Skip to content

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

TypeScript

feat(control-api): honour asProfile at runtime (coherence, no resource, scopes on authorize/refresh)

Diego Zacariasa689efdd00c1
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 836fcdb94..a23a003e7 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.798",
+ "version": "0.1.799",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.798",
+ "version": "0.1.799",
"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.json
index 710ed78e6..b5f61f66e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.798",
+ "version": "0.1.799",
"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/authorizeUrlHelper.ts b/control-api/src/oauth/authorizeUrlHelper.ts
index 6d6ffbe04..ab5704f89 100644
--- a/control-api/src/oauth/authorizeUrlHelper.ts
+++ b/control-api/src/oauth/authorizeUrlHelper.ts
@@ -172,7 +172,7 @@ async function mintAuthorizeUrl(
// Remote lane (`source:'remote'`): the authorize URL is built from the pinned
// discovery-derived `authorizationEndpoint` with a PUBLIC client_id (`decl.id`,
// backfilled for every mode — DEC-23), mandatory PKCE S256, and RFC 8707
- // `resource`. No secret material rides the URL and no K8s Secret is read.
+ // `resource` unless the authorization-server profile omits it. No secret material rides the URL and no K8s Secret is read.
if (decl.remote) {
const state = signOAuthState(deps.stateSecret, stateInput)
const codeChallenge = computeCodeChallengeS256(deriveCodeVerifier(deps.stateSecret, state))
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 429437331..5024c7586 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -3,6 +3,7 @@ import type { PinnedTransport } from '../http/pinnedFetch.js'
import { pinnedFetch } from '../http/pinnedFetch.js'
import type { DnsResolver } from '../http/validateMcpServerSpec.js'
import { rootLogger } from '../observability/logger.js'
+import type { AsProfileId } from './asProfiles.js'
import { getDynamicClient } from './dynamicClientStore.js'
import {
type RemoteOAuthSpecIncoherence,
@@ -63,7 +64,7 @@ export type ServerOAuthSecretSource =
export interface RemoteClientRouting {
authorizationEndpoint: string
tokenEndpoint: string
- /** RFC 8707 resource indicator, echoed in authorize + token/refresh. */
+ /** RFC 8707 resource indicator; absent when the authorization-server profile does not send it. */
resource?: string
clientMode: 'public' | 'confidential'
/** D-8: token in the body vs Authorization header (mcp-host concern; carried for parity). */
@@ -77,6 +78,8 @@ export interface RemoteClientRouting {
* it must match this value rather than being ignored.
*/
issuer?: string
+ /** Closed authorization-server profile pinned on the CR; drives the wire (asProfiles.ts). */
+ asProfile?: AsProfileId
}
/**
diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.ts
index 0cf1b9810..1c18b5287 100644
--- a/control-api/src/oauth/mcpServerOAuthSpec.ts
+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts
@@ -12,6 +12,14 @@
* (`buildMcpServerGrantKey`), so the rule lives here once.
*/
import { rootLogger } from '../observability/logger.js'
+import {
+ detectAsProfile,
+ isAsProfileId,
+ profileHasResourceScope,
+ profileScopeViolation,
+ remoteWireForProfile,
+ withProfileScopes,
+} from './asProfiles.js'
import type {
GenericClientRouting,
OAuthClientDecl,
@@ -46,6 +54,7 @@ export interface McpServerOAuthDecl {
bearerInBody?: unknown
supportsRefresh?: unknown
issForCallback?: unknown
+ asProfile?: unknown
// Generic self-hosted lane (`source:'generic'`, DEC-28). Untrusted CR data →
// every field is validated before use; a malformed generic block fails closed.
refreshEndpoint?: unknown
@@ -67,6 +76,7 @@ export interface McpServerOAuthSpecInput {
// server belongs to", mcpserver.yaml). It is the AUTHORITATIVE Context of a
// context-identity server — the shared grant coordinate — never the body.
contextRef?: unknown
+ remote?: { baseUrl?: unknown }
}
}
@@ -240,13 +250,16 @@ export type RemoteOAuthSpecIncoherence =
| 'bearer_in_body'
| 'cimd_without_issuer_binding'
| 'as_endpoints_cross_site'
+ | 'as_profile_issuer_mismatch'
+ | 'scope_audience_mismatch'
/**
* A remote `spec.oauth` the admission rules reject but that reached the apiserver
* anyway (CRD applied after the object, or a write that bypassed validation, e.g. by
* kubectl/GitOps). The phase using it refuses it with this specific error instead of
* degrading to a generic failure: the CRD-mirror reasons (`public_client_with_secret_refs`,
- * `bearer_in_body`) in consent and token issuance alike; the per-server callback
+ * `bearer_in_body`, `as_profile_issuer_mismatch`) and the profile's scope audience
+ * (`scope_audience_mismatch`) in consent and token issuance alike; the per-server callback
* reasons (`cimd_without_issuer_binding`, `as_endpoints_cross_site`) only in consent
* (authorize-URL minting and the callback), so grants already obtained keep serving.
*/
@@ -270,6 +283,7 @@ export type RemoteOAuthCoherencePhase = 'consent' | 'token'
function remoteOAuthSpecIncoherence(
oauth: McpServerOAuthDecl,
+ baseUrl: unknown,
phase: RemoteOAuthCoherencePhase
): RemoteOAuthSpecIncoherence | null {
if (
@@ -279,6 +293,31 @@ function remoteOAuthSpecIncoherence(
return 'public_client_with_secret_refs'
}
if (oauth.bearerInBody === true) return 'bearer_in_body'
+ // A profile stops sending RFC 8707 `resource`, so it is only honoured on the issuer it
+ // is recognised from; anywhere else it would strip the audience binding of another AS.
+ if (
+ oauth.asProfile !== undefined &&
+ (!isAsProfileId(oauth.asProfile) ||
+ typeof oauth.issuer !== 'string' ||
+ detectAsProfile(oauth.issuer)?.id !== oauth.asProfile)
+ ) {
+ return 'as_profile_issuer_mismatch'
+ }
+ // Without `resource` the scopes alone pick the token's audience, and the scopes or the
+ // base URL can be edited after the install (API or kubectl). The hard audience rules
+ // are therefore re-checked against the base URL in force now. GUID scopes the platform
+ // cannot tie to the host pass: writing the CR is the operator's confirmation.
+ if (oauth.asProfile === 'entra-v2') {
+ const scopes = withProfileScopes(normalizeScopes(oauth.scopes) ?? [], 'entra-v2')
+ if (
+ typeof baseUrl !== 'string' ||
+ !URL.canParse(baseUrl) ||
+ profileScopeViolation('entra-v2', baseUrl, scopes) !== null ||
+ !profileHasResourceScope('entra-v2', baseUrl, scopes)
+ ) {
+ return 'scope_audience_mismatch'
+ }
+ }
// The per-server rules defend the authorization response (which AS minted a code, and
// where it is redeemed). A grant already obtained is sealed to this CR's uid and its
// endpoints are immutable, so a refresh only ever returns to the token endpoint that
@@ -318,7 +357,8 @@ function asEndpointsOnIssuerSite(oauth: McpServerOAuthDecl): boolean {
/**
* Runtime mirror of the remote-carril coherence rules of the McpServer CRD
- * (REMOTE-SECRET-PAIRING for `public`, REMOTE-BEARER-HEADER) and of the install's
+ * (REMOTE-SECRET-PAIRING for `public`, REMOTE-BEARER-HEADER, AS-PROFILE-ISSUER), of the
+ * install's scope-audience rules for an authorization-server profile, and of the install's
* per-server callback rules (no CIMD client and same-site AS endpoints when the AS
* does not return `iss`, which the CRD cannot express). Throws
* {@link RemoteOAuthSpecIncoherentError} for a remote server whose shape no
@@ -336,7 +376,7 @@ export function assertRemoteOAuthSpecCoherent(
): void {
const oauth = server.spec?.oauth
if (!oauth || readOAuthLane(oauth) !== 'remote') return
- const reason = remoteOAuthSpecIncoherence(oauth, phase)
+ const reason = remoteOAuthSpecIncoherence(oauth, server.spec?.remote?.baseUrl, phase)
if (!reason) return
const name = server.metadata?.name
log.warn(
@@ -359,8 +399,14 @@ function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting |
const tokenEndpoint = oauth.tokenEndpoint
if (typeof authorizationEndpoint !== 'string' || authorizationEndpoint.length === 0) return null
if (typeof tokenEndpoint !== 'string' || tokenEndpoint.length === 0) return null
+ const asProfile = isAsProfileId(oauth.asProfile) ? oauth.asProfile : undefined
+ // The CR keeps the PRM's `resource` for audit even when the profile does not send it.
const resource =
- typeof oauth.resource === 'string' && oauth.resource.length > 0 ? oauth.resource : undefined
+ remoteWireForProfile(asProfile).sendResource &&
+ typeof oauth.resource === 'string' &&
+ oauth.resource.length > 0
+ ? oauth.resource
+ : undefined
const issForCallback =
typeof oauth.issForCallback === 'string' && oauth.issForCallback.length > 0
? oauth.issForCallback
@@ -376,6 +422,7 @@ function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting |
supportsRefresh: oauth.supportsRefresh === true,
issForCallback,
...(issuer ? { issuer } : {}),
+ ...(asProfile ? { asProfile } : {}),
}
}
@@ -530,7 +577,9 @@ export function resolveServerOAuthSubject(
// `remote` before any provider-adapter lookup. `'remote'` is the persisted /
// displayed label.
provider: 'remote',
- scopes: normalizeScopes(oauth.scopes),
+ // With a profile the required scopes ride every authorize and refresh, even when
+ // the CR (edited after the install) dropped them.
+ scopes: withProfileScopes(normalizeScopes(oauth.scopes) ?? [], remote.asProfile),
backgroundAccess: oauth.backgroundAccess === true,
remote,
secretSource,
diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.ts
index 15a793e4f..25bfe9493 100644
--- a/control-api/src/oauth/providers.ts
+++ b/control-api/src/oauth/providers.ts
@@ -667,16 +667,24 @@ export function buildRemoteTokenRequest(
return appendResource(standardTokenRequest(tokenEndpoint, input), resource)
}
+/** Append the space-joined `scope` param to an already form-encoded body. */
+function appendScope(request: TokenRequest, scopes?: readonly string[]): TokenRequest {
+ if (!scopes || scopes.length === 0) return request
+ return { ...request, body: `${request.body}&scope=${encodeURIComponent(scopes.join(' '))}` }
+}
+
/**
* Build a remote refresh POST against a discovered `tokenEndpoint`, public client
- * (omits `client_secret` when absent), appending RFC 8707 `resource` when given.
+ * (omits `client_secret` when absent), appending `scope` and then RFC 8707 `resource`
+ * when given. Without either the body is the standard refresh body.
*/
export function buildRemoteRefreshRequest(
tokenEndpoint: string,
input: RefreshTokenInput,
- resource?: string
+ resource?: string,
+ scopes?: readonly string[]
): TokenRequest {
- return appendResource(standardRefreshRequest(tokenEndpoint, input), resource)
+ return appendResource(appendScope(standardRefreshRequest(tokenEndpoint, input), scopes), resource)
}
/** Remote token responses are standard OAuth2 — reuse the baked parser. */
diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.ts
index 31c9710cb..7dd5e4e24 100644
--- a/control-api/src/oauth/tokenHelper.ts
+++ b/control-api/src/oauth/tokenHelper.ts
@@ -1,6 +1,7 @@
import type { DbClient } from '../db.js'
import type { PinnedTransport } from '../http/pinnedFetch.js'
import type { DnsResolver } from '../http/validateMcpServerSpec.js'
+import { remoteWireForProfile } from './asProfiles.js'
import {
type OAuthClientDecl,
RecipeNotFoundError,
@@ -316,7 +317,10 @@ async function refreshRemoteGrant(
clientId: credResult.cred.clientId,
clientSecret: credResult.cred.clientSecret,
},
- remote.resource
+ remote.resource,
+ // Entra's refresh token is valid for every consented API, so without `scope` the
+ // refreshed token's audience would not be pinned to this server.
+ remoteWireForProfile(remote.asProfile).refreshWithScope ? decl.scopes : undefined
)
const posted = await postRemoteTokenForm(
remote.tokenEndpoint,
diff --git a/control-api/test/fixtures/perServerInstall.ts b/control-api/test/fixtures/perServerInstall.ts
index abb76cc48..ca191701b 100644
--- a/control-api/test/fixtures/perServerInstall.ts
+++ b/control-api/test/fixtures/perServerInstall.ts
@@ -12,18 +12,22 @@
*/
import express from 'express'
import request from 'supertest'
+import { config } from '../../src/config.js'
import type { DbClient } from '../../src/db.js'
import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
import type { K8sGateway } from '../../src/k8s.js'
import { type DiscoveryResult, discoverRemoteOAuth } from '../../src/oauth/discovery.js'
import { probeMcpTransport } from '../../src/oauth/mcpTransportProbe.js'
import { createAdminRemoteMcpRouter } from '../../src/routes/admin/remoteMcp.js'
-import type { MockGateway } from '../mockGateway.js'
+import { MockGateway } from '../mockGateway.js'
import {
DCR_PUBLIC_REGISTRATION_RESPONSE,
+ ENTRA_TENANT_AUTHORITY,
+ ENTRA_WORKIQ_PILOT,
type RecordedDcrCall,
makeDcrTransport,
makeDiscoveryTransport,
+ makeInMemoryDynamicClientsDb,
} from './remoteOAuthDiscovery.js'
export const PUBLIC_IP = '93.184.216.34'
@@ -31,12 +35,14 @@ const resolvePublic = async () => [PUBLIC_IP]
/** Run the real discovery client over a probe fixture. */
export async function discoverPilot(
- pilot: Parameters<typeof makeDiscoveryTransport>[0]
+ pilot: Parameters<typeof makeDiscoveryTransport>[0],
+ opts: Parameters<typeof discoverRemoteOAuth>[2] = {}
): Promise<DiscoveryResult> {
- const outcome = await discoverRemoteOAuth(pilot.mcpUrl, {
- transport: makeDiscoveryTransport(pilot),
- resolveDns: resolvePublic,
- })
+ const outcome = await discoverRemoteOAuth(
+ pilot.mcpUrl,
+ { transport: makeDiscoveryTransport(pilot), resolveDns: resolvePublic },
+ opts
+ )
if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
return outcome.result
}
@@ -106,3 +112,61 @@ export async function installRemoteServer(opts: {
const res = await request(app).post('/admin/mcp-servers/remote').send(opts.body)
return { status: res.status, body: res.body as Record<string, unknown>, dcrCalls: calls }
}
+
+/** The two scope forms Work IQ accepts: the GUID its PRM advertises and its App ID URI. */
+export const WORKIQ_GUID_SCOPE = 'fdcc1f02-fc51-4226-8753-f668596af7f7/WorkIQAgent.Ask'
+export const WORKIQ_URL_SCOPE = 'api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask'
+
+/** The McpServer CR as the install persists it, read back from the gateway. */
+export interface InstalledMcpServer {
+ metadata: { name: string; uid: string }
+ spec: {
+ contextRef: string
+ auth: { type: string }
+ remote: { baseUrl: string }
+ oauth: Record<string, unknown>
+ } & Record<string, unknown>
+}
+
+/**
+ * Install Work IQ through the real route — discovery with the tenant authority, the
+ * `entra-v2` profile, pre-registered client — and return the CR the saga wrote. This is
+ * the only producer of a CR carrying `asProfile`, so runtime suites start from it and
+ * any edit they make on top is the direct write (API or kubectl) they model.
+ */
+export async function installWorkIqServer(
+ opts: { scopes?: string[]; serverName?: string; contextRef?: string } = {}
+): Promise<InstalledMcpServer> {
+ const serverName = opts.serverName ?? 'workiq'
+ const contextRef = opts.contextRef ?? 'ctx-a'
+ const namespace = config.mcpServersNamespace
+ const gateway = new MockGateway(namespace)
+ await seedContext(gateway, namespace, contextRef)
+ const discovery = await discoverPilot(ENTRA_WORKIQ_PILOT, {
+ hasPreRegisteredClient: true,
+ authorizationServer: ENTRA_TENANT_AUTHORITY,
+ })
+ const savedCallbackBaseUrl = config.oauthCallbackBaseUrl
+ config.oauthCallbackBaseUrl = 'https://control.example.com'
+ try {
+ const res = await installRemoteServer({
+ gateway,
+ db: makeInMemoryDynamicClientsDb().db,
+ discovery,
+ body: {
+ serverName,
+ contextRef,
+ baseUrl: ENTRA_WORKIQ_PILOT.mcpUrl,
+ mode: 'pre-registered',
+ clientId: '11111111-2222-3333-4444-555555555555',
+ clientSecret: 'entra-client-secret',
+ authorizationServer: ENTRA_TENANT_AUTHORITY,
+ scopes: opts.scopes ?? [WORKIQ_GUID_SCOPE],
+ },
+ })
+ if (res.status !== 201) throw new Error(`Work IQ install failed: ${JSON.stringify(res.body)}`)
+ } finally {
+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl
+ }
+ return (await gateway.getResource('mcpservers', serverName, namespace)) as InstalledMcpServer
+}
diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.ts
index 164cb987a..b4eed2db3 100644
--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts
+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts
@@ -310,7 +310,7 @@ export const ENTRA_TENANT_OIDC_JSON =
export const ENTRA_UNKNOWN_TENANT_OIDC_400_JSON =
'{"error":"invalid_tenant","error_description":"AADSTS90002: Tenant \'00000000-0000-0000-0000-000000000001\' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant. Trace ID: fd7c437e-5de4-418f-a92d-2542f3ff1e00 Correlation ID: f396dc2b-aa03-4985-b73a-a44d76d054af Timestamp: 2026-10-21 14:15:01Z","error_codes":[90002],"timestamp":"2026-10-21 14:15:01Z","trace_id":"fd7c437e-5de4-418f-a92d-2542f3ff1e00","correlation_id":"f396dc2b-aa03-4985-b73a-a44d76d054af","error_uri":"https://login.microsoftonline.com/error?code=90002"}'
-const ENTRA_TENANT_AUTHORITY =
+export const ENTRA_TENANT_AUTHORITY =
'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0'
/** OIDC metadata both Entra pilots serve: the real tenant, `organizations` and an unknown tenant. */
diff --git a/control-api/test/oauth.authorizeUrl.remote.test.ts b/control-api/test/oauth.authorizeUrl.remote.test.ts
index 59f9e3e11..db2c0affe 100644
--- a/control-api/test/oauth.authorizeUrl.remote.test.ts
+++ b/control-api/test/oauth.authorizeUrl.remote.test.ts
@@ -4,6 +4,11 @@ import type { McpServerOAuthReader, McpServerOAuthSubject } from '../src/oauth/c
import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'
import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import {
+ type InstalledMcpServer,
+ WORKIQ_URL_SCOPE,
+ installWorkIqServer,
+} from './fixtures/perServerInstall.js'
import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
/**
@@ -86,3 +91,57 @@ describe('buildAuthorizeUrl — remote mcp subject (DEC-23)', () => {
expect(secretRead).not.toHaveBeenCalled()
})
})
+
+describe('buildAuthorizeUrl — entra-v2 profile (I5, I7)', () => {
+ const ENTRA_AUTHORIZE =
+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/authorize'
+ let workIq: InstalledMcpServer
+
+ beforeAll(async () => {
+ workIq = await installWorkIqServer({ scopes: [WORKIQ_URL_SCOPE] })
+ })
+
+ async function authorizeUrlFor(server: InstalledMcpServer): Promise<URL> {
+ const resolved = resolveServerOAuthSubject(server, 'consent')
+ if (!resolved) throw new Error('fixture: the Work IQ CR did not resolve')
+ const secretRead = vi.fn(async () => ({}))
+ const result = await buildAuthorizeUrl(
+ {
+ subjectKind: 'mcp',
+ mcpServerName: server.metadata.name,
+ oauthClientId: String(server.spec.oauth.id),
+ userId: 'user-9',
+ grantKind: 'user',
+ background: false,
+ redirectUri: `https://control.example.com/api/v1/oauth-callback/remote/${server.metadata.name}`,
+ },
+ {
+ recipeReader: { read: vi.fn(async () => null) },
+ mcpServerReader: { read: vi.fn(async () => ({ namespace: MCP_NS, ...resolved })) },
+ secretReader: { read: secretRead } as unknown as BuildAuthorizeUrlDeps['secretReader'],
+ stateSecret: STATE_SECRET,
+ }
+ )
+ if (result.kind !== 'ok') throw new Error(`authorize-url failed: ${result.kind}`)
+ expect(secretRead).not.toHaveBeenCalled()
+ return new URL(result.authorizeUrl)
+ }
+
+ it('no resource, PKCE S256 and offline_access in scope', async () => {
+ expect(workIq.spec.oauth.resource).toBe('https://workiq.svc.cloud.microsoft/mcp')
+ const url = await authorizeUrlFor(workIq)
+ expect(`${url.origin}${url.pathname}`).toBe(ENTRA_AUTHORIZE)
+ expect(url.searchParams.has('resource')).toBe(false)
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256')
+ expect(url.searchParams.get('scope')).toBe(`${WORKIQ_URL_SCOPE} offline_access`)
+ })
+
+ it('a CR edited to drop offline_access still asks for it', async () => {
+ const edited: InstalledMcpServer = {
+ ...workIq,
+ spec: { ...workIq.spec, oauth: { ...workIq.spec.oauth, scopes: [WORKIQ_URL_SCOPE] } },
+ }
+ const url = await authorizeUrlFor(edited)
+ expect(url.searchParams.get('scope')).toBe(`${WORKIQ_URL_SCOPE} offline_access`)
+ })
+})
diff --git a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts
index 027fe7609..6a567aae6 100644
--- a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts
+++ b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts
@@ -7,6 +7,11 @@ import {
} from '../src/oauth/mcpServerOAuthSpec.js'
import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import {
+ type InstalledMcpServer,
+ WORKIQ_URL_SCOPE,
+ installWorkIqServer,
+} from './fixtures/perServerInstall.js'
import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
/**
@@ -208,3 +213,57 @@ describe('normalizeMcpServerOwnerDecl (refresh reader) does not diverge from the
expect(normalized?.spec?.oauthClients?.[0]?.secretSource).toEqual({ kind: 'dcr-store' })
})
})
+
+describe('remote lane with the entra-v2 profile (CR from the real Work IQ install, T1)', () => {
+ const WORKIQ_RESOURCE = 'https://workiq.svc.cloud.microsoft/mcp'
+ let workIq: InstalledMcpServer
+
+ beforeAll(async () => {
+ workIq = await installWorkIqServer({ scopes: [WORKIQ_URL_SCOPE] })
+ })
+
+ /** The installed CR with `spec.oauth.scopes` rewritten, as an API or kubectl edit would. */
+ function withScopes(scopes: string[]): McpServerOAuthSpecInput {
+ return { ...workIq, spec: { ...workIq.spec, oauth: { ...workIq.spec.oauth, scopes } } }
+ }
+
+ it('the installed CR pins the profile and keeps the PRM resource for audit', () => {
+ expect(workIq.spec.oauth.asProfile).toBe('entra-v2')
+ expect(workIq.spec.oauth.resource).toBe(WORKIQ_RESOURCE)
+ expect(workIq.spec.oauth.scopes).toEqual([WORKIQ_URL_SCOPE, 'offline_access'])
+ })
+
+ for (const phase of ['consent', 'token'] as const) {
+ it(`${phase}: the routing carries the profile and no resource`, () => {
+ const r = resolveServerOAuthSubject(workIq, phase)
+ expect(r?.decl.remote?.asProfile).toBe('entra-v2')
+ expect(r?.decl.remote?.resource).toBeUndefined()
+ expect(r?.decl.scopes).toEqual([WORKIQ_URL_SCOPE, 'offline_access'])
+ })
+
+ it(`${phase}: decl.scopes requests offline_access even when the CR no longer has it`, () => {
+ const r = resolveServerOAuthSubject(withScopes([WORKIQ_URL_SCOPE]), phase)
+ expect(r?.decl.scopes).toEqual([WORKIQ_URL_SCOPE, 'offline_access'])
+ })
+ }
+
+ it('the refresh reader (normalizeMcpServerOwnerDecl) gets the same decl (D4)', () => {
+ const decl = normalizeMcpServerOwnerDecl(withScopes([WORKIQ_URL_SCOPE]) as never)?.spec
+ ?.oauthClients?.[0]
+ expect(decl?.scopes).toEqual([WORKIQ_URL_SCOPE, 'offline_access'])
+ expect(decl?.remote?.resource).toBeUndefined()
+ expect(decl?.remote?.asProfile).toBe('entra-v2')
+ })
+
+ it('without a profile the routing still carries resource and the CR scopes as-is (I6)', () => {
+ const oauth = buildRemoteOAuthSpec(discovery(), {
+ clientMode: 'public',
+ grantScope: 'user',
+ cimdClientId: CIMD_SELF,
+ }) as unknown as Record<string, unknown>
+ const r = resolveServerOAuthSubject(serverFrom(oauth), 'consent')
+ expect(r?.decl.scopes).toEqual(oauth.scopes)
+ expect(r?.decl.remote?.resource).toBe(`${LINEAR}/mcp`)
+ expect(r?.decl.remote && 'asProfile' in r.decl.remote).toBe(false)
+ })
+})
diff --git a/control-api/test/oauth.providers.remote.test.ts b/control-api/test/oauth.providers.remote.test.ts
index de534553d..7b5f25dbd 100644
--- a/control-api/test/oauth.providers.remote.test.ts
+++ b/control-api/test/oauth.providers.remote.test.ts
@@ -80,6 +80,42 @@ describe('buildRemoteRefreshRequest (public client, RFC 8707)', () => {
const req = buildRemoteRefreshRequest(TOKEN_ENDPOINT, { refreshToken: 'RT', clientId: 'CID' })
expect(req.body).toBe('grant_type=refresh_token&refresh_token=RT&client_id=CID')
})
+
+ it('appends scope, space-joined, when scopes are given', () => {
+ const req = buildRemoteRefreshRequest(
+ TOKEN_ENDPOINT,
+ { refreshToken: 'RT', clientId: 'CID' },
+ undefined,
+ ['a', 'offline_access']
+ )
+ expect(req.body).toBe(
+ 'grant_type=refresh_token&refresh_token=RT&client_id=CID&scope=a%20offline_access'
+ )
+ })
+
+ it('puts scope before resource when both are given', () => {
+ const req = buildRemoteRefreshRequest(
+ TOKEN_ENDPOINT,
+ { refreshToken: 'RT', clientId: 'CID', clientSecret: 'SEC' },
+ RESOURCE,
+ ['api://workiq.svc.cloud.microsoft/WorkIQAgent.Ask', 'offline_access']
+ )
+ expect(req.body).toBe(
+ 'grant_type=refresh_token&refresh_token=RT&client_id=CID&client_secret=SEC&scope=api%3A%2F%2Fworkiq.svc.cloud.microsoft%2FWorkIQAgent.Ask%20offline_access&resource=https%3A%2F%2Fmcp.notion.com'
+ )
+ })
+
+ it('an empty scope list leaves the body byte-identical to the resource-only body', () => {
+ const withEmpty = buildRemoteRefreshRequest(
+ TOKEN_ENDPOINT,
+ { refreshToken: 'RT', clientId: 'CID' },
+ RESOURCE,
+ []
+ )
+ expect(withEmpty.body).toBe(
+ 'grant_type=refresh_token&refresh_token=RT&client_id=CID&resource=https%3A%2F%2Fmcp.notion.com'
+ )
+ })
})
describe('parseRemoteTokenResponse', () => {
diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.ts
index ca53bf20f..aa1333fd8 100644
--- a/control-api/test/oauth.remoteSpecCoherence.test.ts
+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts
@@ -14,6 +14,12 @@ import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'
import { membership, seedAllowlistedContext } from './fixtures/contextAllowlist.js'
+import {
+ type InstalledMcpServer,
+ WORKIQ_GUID_SCOPE,
+ WORKIQ_URL_SCOPE,
+ installWorkIqServer,
+} from './fixtures/perServerInstall.js'
import {
ATLASSIAN_V2_PILOT,
DROPBOX_PILOT,
@@ -94,14 +100,44 @@ let bodyDiscovery: DiscoveryResult
// Real Atlassian v2: CIMD + DCR, no RFC 9207, every endpoint on atlassian.com.
let perServerDiscovery: DiscoveryResult
let crossSiteDiscovery: DiscoveryResult
+let notionDiscovery: DiscoveryResult
+// Work IQ as the real install writes it (entra-v2 profile), once per scope form.
+let workIqGuid: InstalledMcpServer
+let workIqUrl: InstalledMcpServer
beforeAll(async () => {
headerDiscovery = await discover(PILOTS.sentry)
bodyDiscovery = await discover(bodyOnlyPilot())
perServerDiscovery = await discover(ATLASSIAN_V2_PILOT)
crossSiteDiscovery = await discover(dropboxWithRfc9207())
+ notionDiscovery = await discover(PILOTS.notion)
+ workIqGuid = await installWorkIqServer({ scopes: [WORKIQ_GUID_SCOPE] })
+ workIqUrl = await installWorkIqServer({ scopes: [WORKIQ_URL_SCOPE] })
})
+const EVIL_BASE_URL = 'https://evil.example/mcp'
+
+/** The `spec.remote` the install wrote for Work IQ. */
+function workIqRemote(): Record<string, unknown> {
+ return { ...workIqGuid.spec.remote }
+}
+
+/** The installed Work IQ `spec.oauth` with its scopes rewritten by a direct write. */
+function workIqWithScopes(scopes: string[]): Record<string, unknown> {
+ return { ...workIqGuid.spec.oauth, scopes }
+}
+
+/** A Notion pre-registered CR with the profile stamped on it: no producer, a direct write. */
+function profileOnNotionOAuth(): Record<string, unknown> {
+ const oauth = buildRemoteOAuthSpec(notionDiscovery, {
+ clientMode: 'confidential',
+ grantScope: 'user',
+ clientSecretName: 'srv-oauth-client',
+ preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,
+ }) as unknown as Record<string, unknown>
+ return { ...oauth, asProfile: 'entra-v2' }
+}
+
function publicWithRefsOAuth(): Record<string, unknown> {
const oauth = buildRemoteOAuthSpec(headerDiscovery, {
clientMode: 'confidential',
@@ -171,7 +207,16 @@ function crossSiteRegistrationOAuth(): Record<string, unknown> {
}
}
-const INCOHERENT = [
+/** `spec.remote` of a case: `undefined` omits the block; a function builds it. */
+type RemoteOf = (() => Record<string, unknown>) | undefined
+
+const INCOHERENT: ReadonlyArray<{
+ label: string
+ oauth: () => Record<string, unknown>
+ remote?: RemoteOf
+ reason: string
+ consentOnly: boolean
+}> = [
// CRD mirrors: refused in consent and token issuance alike.
{
label: 'public + secret refs',
@@ -211,16 +256,107 @@ const INCOHERENT = [
reason: 'as_endpoints_cross_site',
consentOnly: true,
},
-] as const
+ // AS-PROFILE-ISSUER mirror: a profile only on the Entra tenant issuer it comes from.
+ {
+ label: 'asProfile entra-v2 on the Notion issuer',
+ oauth: profileOnNotionOAuth,
+ remote: () => ({ baseUrl: PILOTS.notion.mcpUrl }),
+ reason: 'as_profile_issuer_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'unknown asProfile on the Entra issuer',
+ oauth: () => ({ ...workIqGuid.spec.oauth, asProfile: 'other' }),
+ remote: workIqRemote,
+ reason: 'as_profile_issuer_mismatch',
+ consentOnly: false,
+ },
+ // Hard audience rules of the profile, against the base URL in force.
+ {
+ label: 'entra-v2 with the Microsoft Graph GUID scope',
+ oauth: () => workIqWithScopes(['00000003-0000-0000-c000-000000000000/Mail.Read']),
+ remote: workIqRemote,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 with a Microsoft Graph URL scope',
+ oauth: () => workIqWithScopes(['https://graph.microsoft.com/x']),
+ remote: workIqRemote,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 with an unprefixed scope (read as Graph)',
+ oauth: () => workIqWithScopes(['Mail.Read']),
+ remote: workIqRemote,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 with sign-in scopes only (a Graph token)',
+ oauth: () => workIqWithScopes(['offline_access']),
+ remote: workIqRemote,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ // profileScopeViolation reports an empty scope as '', so a truthiness test misses it.
+ label: 'entra-v2 with an empty scope ahead of a Graph URL scope',
+ oauth: () => workIqWithScopes(['', 'https://graph.microsoft.com/x']),
+ remote: workIqRemote,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ // Same, with the server's own scope after it: only a `!== null` test catches this one,
+ // since the resource-scope rule is satisfied.
+ label: 'entra-v2 with an empty scope ahead of the server URL scope',
+ oauth: () => ({ ...workIqUrl.spec.oauth, scopes: ['', WORKIQ_URL_SCOPE] }),
+ remote: () => ({ ...workIqUrl.spec.remote }),
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 URL-form scope after baseUrl moved to another host',
+ oauth: () => ({ ...workIqUrl.spec.oauth }),
+ remote: () => ({ ...workIqUrl.spec.remote, baseUrl: EVIL_BASE_URL }),
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 without spec.remote',
+ oauth: () => ({ ...workIqGuid.spec.oauth }),
+ remote: undefined,
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+ {
+ label: 'entra-v2 with an unparseable baseUrl',
+ oauth: () => ({ ...workIqGuid.spec.oauth }),
+ remote: () => ({ ...workIqGuid.spec.remote, baseUrl: 'not a url' }),
+ reason: 'scope_audience_mismatch',
+ consentOnly: false,
+ },
+]
function crFrom(
name: string,
- oauth: Record<string, unknown>
+ oauth: Record<string, unknown>,
+ remote?: Record<string, unknown>
): McpServerOAuthSpecInput & {
metadata: { name: string }
spec: Record<string, unknown>
} {
- return { metadata: { name }, spec: { contextRef: CONTEXT, auth: { type: 'oauth' }, oauth } }
+ return {
+ metadata: { name },
+ spec: { contextRef: CONTEXT, auth: { type: 'oauth' }, oauth, ...(remote ? { remote } : {}) },
+ }
+}
+
+/** The CR of an INCOHERENT case. */
+function caseCr(name: string, c: (typeof INCOHERENT)[number]) {
+ return crFrom(name, c.oauth(), c.remote?.())
}
function thrownBy(fn: () => unknown): { code?: unknown; reason?: unknown } | undefined {
@@ -252,37 +388,36 @@ describe('resolver mirror of the remote CRD coherence rules', () => {
for (const c of INCOHERENT) {
it(`${c.label}: resolveServerOAuthSubject(consent) throws remote_oauth_spec_incoherent`, () => {
- const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'consent'))
+ const err = thrownBy(() => resolveServerOAuthSubject(caseCr('srv', c), 'consent'))
expect(err?.code).toBe('remote_oauth_spec_incoherent')
expect(err?.reason).toBe(c.reason)
})
if (c.consentOnly) {
it(`${c.label}: resolveServerOAuthSubject(token) still resolves the subject`, () => {
- const r = resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'token')
+ const r = resolveServerOAuthSubject(caseCr('srv', c), 'token')
expect(r?.decl.id).toBe(c.oauth().id)
expect(r?.decl.remote?.tokenEndpoint).toBe(c.oauth().tokenEndpoint)
})
it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) keeps accepting it`, () => {
- const decl = normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never)?.spec
- ?.oauthClients?.[0]
+ const decl = normalizeMcpServerOwnerDecl(caseCr('srv', c) as never)?.spec?.oauthClients?.[0]
expect(decl?.remote?.tokenEndpoint).toBe(c.oauth().tokenEndpoint)
})
} else {
it(`${c.label}: resolveServerOAuthSubject(token) throws too`, () => {
- const err = thrownBy(() => resolveServerOAuthSubject(crFrom('srv', c.oauth()), 'token'))
+ const err = thrownBy(() => resolveServerOAuthSubject(caseCr('srv', c), 'token'))
expect(err?.reason).toBe(c.reason)
})
it(`${c.label}: the refresh reader (normalizeMcpServerOwnerDecl) refuses it too`, () => {
- const err = thrownBy(() => normalizeMcpServerOwnerDecl(crFrom('srv', c.oauth()) as never))
+ const err = thrownBy(() => normalizeMcpServerOwnerDecl(caseCr('srv', c) as never))
expect(err?.code).toBe('remote_oauth_spec_incoherent')
})
}
it(`${c.label}: resolveServerOAuth still yields the grant coordinate (revoke, sweep)`, () => {
- const r = resolveServerOAuth(crFrom('srv', c.oauth()))
+ const r = resolveServerOAuth(caseCr('srv', c))
expect(r?.oauthClientId).toBe(c.oauth().id)
expect(r?.grantScope).toBe('user')
expect(r?.contextRef).toBe(CONTEXT)
@@ -332,6 +467,61 @@ describe('resolver mirror of the remote CRD coherence rules', () => {
})
})
+describe('entra-v2 runtime audience: what stays coherent', () => {
+ const PHASES = ['consent', 'token'] as const
+ const AUDIENCE_BREAKERS = [
+ ['00000003-0000-0000-c000-000000000000/Mail.Read'],
+ ['https://graph.microsoft.com/x'],
+ ['Mail.Read'],
+ ['offline_access'],
+ ]
+
+ for (const phase of PHASES) {
+ it(`${phase}: both installed Work IQ CRs resolve as written`, () => {
+ for (const cr of [workIqGuid, workIqUrl]) {
+ expect(resolveServerOAuthSubject(cr, phase)?.decl.remote?.asProfile).toBe('entra-v2')
+ }
+ })
+
+ it(`${phase}: an unknown GUID scope is coherent (writing the CR is the confirmation)`, () => {
+ const cr = crFrom(
+ 'srv',
+ workIqWithScopes(['11111111-2222-3333-4444-555555555555/Tools.Read']),
+ workIqRemote()
+ )
+ expect(resolveServerOAuthSubject(cr, phase)?.decl.id).toBe(workIqGuid.spec.oauth.id)
+ })
+
+ // A GUID-form scope is not tied to the base URL, so moving the base URL to another
+ // host goes unnoticed; this pins that limit rather than leaving it implicit.
+ it(`${phase}: the Work IQ GUID scope with baseUrl moved to another host stays coherent`, () => {
+ const cr = crFrom(
+ 'srv',
+ { ...workIqGuid.spec.oauth },
+ {
+ ...workIqGuid.spec.remote,
+ baseUrl: EVIL_BASE_URL,
+ }
+ )
+ expect(resolveServerOAuthSubject(cr, phase)?.decl.id).toBe(workIqGuid.spec.oauth.id)
+ })
+
+ it(`${phase}: without a profile the same scopes are coherent (I6)`, () => {
+ const preRegistered = buildRemoteOAuthSpec(headerDiscovery, {
+ clientMode: 'confidential',
+ grantScope: 'user',
+ clientSecretName: 'srv-oauth-client',
+ preRegisteredClientId: PRE_REGISTERED_CLIENT_ID,
+ }) as unknown as Record<string, unknown>
+ expect(preRegistered.asProfile).toBeUndefined()
+ for (const scopes of [...AUDIENCE_BREAKERS, ['', 'https://graph.microsoft.com/x']]) {
+ const cr = crFrom('srv', { ...preRegistered, scopes })
+ expect(resolveServerOAuthSubject(cr, phase)?.decl.scopes).toEqual(scopes)
+ }
+ })
+ }
+})
+
describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_incoherent', () => {
let gateway: MockGateway
let app: ReturnType<typeof createApp>
@@ -354,8 +544,16 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
config.mcpOauthBrokerEnabled = originalBrokerEnabled
})
- async function seed(name: string, oauth: Record<string, unknown>): Promise<string> {
- const created = (await gateway.createResource('mcpservers', crFrom(name, oauth), MCP_NS)) as {
+ async function seed(
+ name: string,
+ oauth: Record<string, unknown>,
+ remote?: Record<string, unknown>
+ ): Promise<string> {
+ const created = (await gateway.createResource(
+ 'mcpservers',
+ crFrom(name, oauth, remote),
+ MCP_NS
+ )) as {
metadata: { uid: string }
}
// The server is enabled in CONTEXT's allowlist (written by the real
@@ -373,7 +571,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
for (const c of INCOHERENT) {
it(`${c.label}: POST /internal/mcp-oauth/authorize-url → 409, no URL minted`, async () => {
- await seed('srv', c.oauth())
+ await seed('srv', c.oauth(), c.remote?.())
const res = await request(app)
.post('/api/v1/internal/mcp-oauth/authorize-url')
.set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)
@@ -384,7 +582,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
})
it(`${c.label}: authorize-url for a non-member → 403, configuration not disclosed`, async () => {
- await seed('srv', c.oauth())
+ await seed('srv', c.oauth(), c.remote?.())
membership(mockPoolQuery, { contexts: { 'user-2': ['ctx-other'] } })
const res = await request(app)
.post('/api/v1/internal/mcp-oauth/authorize-url')
@@ -397,7 +595,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
it(`${c.label}: POST /mcp-oauth/user-token → ${c.consentOnly ? '200, the stored token is served' : '409 even with a fresh stored token'}`, async () => {
const oauth = c.oauth()
- const uid = await seed('srv', oauth)
+ const uid = await seed('srv', oauth, c.remote?.())
mockPoolQuery.mockImplementation((sql: unknown) => {
const text = typeof sql === 'string' ? sql : ''
if (text.includes('FROM oauth_grants')) {
@@ -445,7 +643,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
it(`${c.label}: GET /oauth-callback/remote → 409, nothing persisted`, async () => {
const oauth = c.oauth()
- await seed('srv', oauth)
+ await seed('srv', oauth, c.remote?.())
const state = signOAuthState(config.oauthStateHmacSecret, {
subjectKind: 'mcp',
mcpServerName: 'srv',
@@ -470,7 +668,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
// binding check or exchange, whichever remote callback the AS used.
it(`${c.label}: GET /oauth-callback/remote/srv → 409, nothing persisted`, async () => {
const oauth = c.oauth()
- await seed('srv', oauth)
+ await seed('srv', oauth, c.remote?.())
const state = signOAuthState(config.oauthStateHmacSecret, {
subjectKind: 'mcp',
mcpServerName: 'srv',
@@ -492,7 +690,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i
})
it(`${c.label}: DELETE /internal/mcp-oauth/grant still revokes (204)`, async () => {
- await seed('srv', c.oauth())
+ await seed('srv', c.oauth(), c.remote?.())
const res = await request(app)
.delete('/api/v1/internal/mcp-oauth/grant')
.set('Authorization', `Bearer ${RPC_PROXY_TOKEN}`)
diff --git a/control-api/test/oauth.tokenHelper.remote.test.ts b/control-api/test/oauth.tokenHelper.remote.test.ts
index eafcb50d9..406ea17cd 100644
--- a/control-api/test/oauth.tokenHelper.remote.test.ts
+++ b/control-api/test/oauth.tokenHelper.remote.test.ts
@@ -5,6 +5,12 @@ import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
import * as store from '../src/oauth/store.js'
import { getAccessToken } from '../src/oauth/tokenHelper.js'
import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import {
+ type InstalledMcpServer,
+ WORKIQ_GUID_SCOPE,
+ installWorkIqServer,
+} from './fixtures/perServerInstall.js'
import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
/**
@@ -113,7 +119,10 @@ describe('getAccessToken — remote refresh is IP-pinned (DEC-17)', () => {
expect(calls).toHaveLength(1)
expect(calls[0].url).toBe(TOKEN_ENDPOINT)
expect(calls[0].connectedIP).toBe(VALIDATED_IP)
- expect(calls[0].body).toContain('grant_type=refresh_token')
+ // I6: without a profile the body is the pre-profile one — resource, never scope.
+ expect(calls[0].body).toBe(
+ `grant_type=refresh_token&refresh_token=REMOTE-RT&client_id=${encodeURIComponent(CLIENT_ID)}&resource=${encodeURIComponent(notion.resource)}`
+ )
expect(refreshSpy).toHaveBeenCalledWith(
expect.anything(),
ENCRYPTION_KEY,
@@ -144,3 +153,70 @@ describe('getAccessToken — no-refresh derived from metadata (D-8, fail-closed)
vi.restoreAllMocks()
})
})
+
+describe('getAccessToken — entra-v2 refresh wire (I5, I7)', () => {
+ const ENTRA_TOKEN_ENDPOINT =
+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token'
+ let workIq: InstalledMcpServer
+
+ beforeAll(async () => {
+ workIq = await installWorkIqServer({ scopes: [WORKIQ_GUID_SCOPE] })
+ })
+
+ async function refreshWith(server: InstalledMcpServer) {
+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())
+ vi.spyOn(store, 'refreshOAuthGrantTokens').mockResolvedValue({ updated: true } as never)
+ const { transport, calls } = recordingTransport(
+ JSON.stringify({ access_token: 'NEW-AT', expires_in: 3600 })
+ )
+ const owner = normalizeMcpServerOwnerDecl(server as never)
+ if (!owner) throw new Error('fixture: the Work IQ CR did not resolve')
+ const clientIdRef = server.spec.oauth.clientIdRef as { name: string; key: string }
+ const clientSecretRef = server.spec.oauth.clientSecretRef as { name: string; key: string }
+ const result = await getAccessToken(
+ { ...KEY, recipeName: server.metadata.name, oauthClientId: String(server.spec.oauth.id) },
+ {
+ db: { query: async () => ({ rows: [] }) } as never,
+ recipeReader: { read: async () => owner },
+ secretReader: {
+ read: async () => ({
+ [clientIdRef.key]: String(server.spec.oauth.id),
+ [clientSecretRef.key]: 'entra-client-secret',
+ }),
+ },
+ fetchFn: (async () => {
+ throw new Error('remote refresh must NOT use fetchFn')
+ }) as unknown as typeof fetch,
+ encryptionKey: ENCRYPTION_KEY,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ }
+ )
+ vi.restoreAllMocks()
+ return { result, calls }
+ }
+
+ it('the POSTed refresh body carries scope with offline_access and no resource', async () => {
+ expect(workIq.spec.oauth.resource).toBe('https://workiq.svc.cloud.microsoft/mcp')
+ const { result, calls } = await refreshWith(workIq)
+ expect(result).toMatchObject({ kind: 'ok', accessToken: 'NEW-AT' })
+ expect(calls).toHaveLength(1)
+ expect(calls[0].url).toBe(ENTRA_TOKEN_ENDPOINT)
+ const body = new URLSearchParams(calls[0].body ?? '')
+ expect(body.get('grant_type')).toBe('refresh_token')
+ expect(body.get('scope')).toBe(`${WORKIQ_GUID_SCOPE} offline_access`)
+ expect(body.has('resource')).toBe(false)
+ expect(calls[0].body).not.toContain('resource=')
+ })
+
+ it('a CR edited to drop offline_access still refreshes with it', async () => {
+ const edited: InstalledMcpServer = {
+ ...workIq,
+ spec: { ...workIq.spec, oauth: { ...workIq.spec.oauth, scopes: [WORKIQ_GUID_SCOPE] } },
+ }
+ const { calls } = await refreshWith(edited)
+ expect(new URLSearchParams(calls[0].body ?? '').get('scope')).toBe(
+ `${WORKIQ_GUID_SCOPE} offline_access`
+ )
+ })
+})