Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): send the profile scopes on the entra-v2 code exchange (F3-S1)
Diego Zacarias45950c1de3a9
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex b49557aac..a9fdad0d2 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.801",+ "version": "0.1.802","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.801",+ "version": "0.1.802","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 02383214b..6c23d7b9d 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.801",+ "version": "0.1.802","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/callback.ts b/control-api/src/oauth/callback.tsindex 5024c7586..aa617ae2e 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -3,7 +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 { type AsProfileId, remoteWireForProfile } from './asProfiles.js'import { getDynamicClient } from './dynamicClientStore.js'import {type RemoteOAuthSpecIncoherence,@@ -989,7 +989,11 @@ async function exchangeRemoteAuthCode(redirectUri: grant.redirectUri,codeVerifier,},- remote.resource+ remote.resource,+ // The authorize request's `scope` travels through the browser and can be edited;+ // without `scope` on the redemption Entra issues the token for whatever that leg+ // asked for, so the CR's scopes are what pin the audience here.+ remoteWireForProfile(remote.asProfile).scopeOnTokenRequests ? decl.scopes : undefined)const posted = await postRemoteTokenForm(remote.tokenEndpoint,diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.tsindex 25bfe9493..33674fbea 100644--- a/control-api/src/oauth/providers.ts+++ b/control-api/src/oauth/providers.ts@@ -657,14 +657,16 @@ export function buildRemoteAuthorizeUrl(/*** Build a remote token-exchange POST against a discovered `tokenEndpoint`, as a* public client (omits `client_secret` when `input.clientSecret` is absent — the- * standard builder already drops it) and appending RFC 8707 `resource` when given.+ * standard builder already drops it), appending `scope` and then RFC 8707 `resource`+ * when given. Without either the body is the standard exchange body.*/export function buildRemoteTokenRequest(tokenEndpoint: string,input: TokenExchangeInput,- resource?: string+ resource?: string,+ scopes?: readonly string[]): TokenRequest {- return appendResource(standardTokenRequest(tokenEndpoint, input), resource)+ return appendResource(appendScope(standardTokenRequest(tokenEndpoint, input), scopes), resource)}/** Append the space-joined `scope` param to an already form-encoded body. */diff --git a/control-api/test/fixtures/perServerInstall.ts b/control-api/test/fixtures/perServerInstall.tsindex ca191701b..e1fde81f0 100644--- a/control-api/test/fixtures/perServerInstall.ts+++ b/control-api/test/fixtures/perServerInstall.ts@@ -135,13 +135,20 @@ export interface InstalledMcpServer {* 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 } = {}+ opts: {+ scopes?: string[]+ serverName?: string+ contextRef?: string+ /** A gateway the suite already seeded with `contextRef`; a fresh one otherwise. */+ gateway?: MockGateway+ db?: DbClient+ } = {}): 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 gateway = opts.gateway ?? new MockGateway(namespace)+ if (!opts.gateway) await seedContext(gateway, namespace, contextRef)const discovery = await discoverPilot(ENTRA_WORKIQ_PILOT, {hasPreRegisteredClient: true,authorizationServer: ENTRA_TENANT_AUTHORITY,@@ -151,7 +158,7 @@ export async function installWorkIqServer(try {const res = await installRemoteServer({gateway,- db: makeInMemoryDynamicClientsDb().db,+ db: opts.db ?? makeInMemoryDynamicClientsDb().db,discovery,body: {serverName,diff --git a/control-api/test/oauth.callbackRemotePerServer.test.ts b/control-api/test/oauth.callbackRemotePerServer.test.tsindex 69badd9a3..6d185ff12 100644--- a/control-api/test/oauth.callbackRemotePerServer.test.ts+++ b/control-api/test/oauth.callbackRemotePerServer.test.ts@@ -15,10 +15,13 @@ import {type McpServerOAuthSpecInput,resolveServerOAuthSubject,} from '../src/oauth/mcpServerOAuthSpec.js'+import { deriveCodeVerifier } from '../src/oauth/pkce.js'import { signOAuthState } from '../src/oauth/state.js'import {+ WORKIQ_URL_SCOPE,discoverPilot,installRemoteServer,+ installWorkIqServer,seedContext,withRfc9207,} from './fixtures/perServerInstall.js'@@ -253,6 +256,47 @@ describe('per-server callback — success', () => {})})+describe('per-server callback — the code exchange body (I5, I6)', () => {+ it('entra-v2: the exchange sends the CR scopes plus offline_access, the verifier and no resource', async () => {+ // The CR as the Work IQ install writes it, read back by the production subject reader.+ const cr = await installWorkIqServer({ scopes: [WORKIQ_URL_SCOPE], gateway, db })+ expect(cr.spec.oauth.resource).toBe('https://workiq.svc.cloud.microsoft/mcp')+ const h = harness()+ const state = await stateFor(cr.metadata.name)++ const result = await handleOAuthCallback(+ { target: perServer(cr.metadata.name), code: 'CODE', state },+ h.deps+ )++ expect(result.kind).toBe('ok')+ expect(h.tokenPosts).toHaveLength(1)+ expect(h.tokenPosts[0].url).toBe(+ 'https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/v2.0/token'+ )+ const body = new URLSearchParams(h.tokenPosts[0].body)+ expect(body.get('grant_type')).toBe('authorization_code')+ expect(body.get('scope')).toBe(`${WORKIQ_URL_SCOPE} offline_access`)+ expect(body.get('code_verifier')).toBe(deriveCodeVerifier(STATE_SECRET, state))+ expect(body.has('resource')).toBe(false)+ expect(h.tokenPosts[0].body).not.toContain('resource=')+ })++ it('without a profile (Notion) the exchange body is unchanged: resource, no scope', async () => {+ const srv = await installPreRegistered('hubspot')+ const resource = String((await oauthOf(srv.name)).resource)+ const h = harness()+ const state = await stateFor(srv.name)++ await handleOAuthCallback({ target: perServer(srv.name), code: 'CODE', state }, h.deps)++ expect(h.tokenPosts).toHaveLength(1)+ expect(h.tokenPosts[0].body).toBe(+ `grant_type=authorization_code&code=CODE&client_id=client-hubspot&client_secret=secret-hubspot&redirect_uri=${encodeURIComponent(srv.redirectUri)}&code_verifier=${deriveCodeVerifier(STATE_SECRET, state)}&resource=${encodeURIComponent(resource)}`+ )+ })+})+describe('per-server callback — a code for one server never binds to another (I2)', () => {it('DCR: /remote/a/<nonceA> with the state of b → binding_mismatch, b never read, no exchange', async () => {const a = await installDcr('server-a')diff --git a/control-api/test/oauth.providers.remote.test.ts b/control-api/test/oauth.providers.remote.test.tsindex 7b5f25dbd..57574d83e 100644--- a/control-api/test/oauth.providers.remote.test.ts+++ b/control-api/test/oauth.providers.remote.test.ts@@ -64,6 +64,36 @@ describe('buildRemoteTokenRequest (public client, RFC 8707)', () => {})})+describe('buildRemoteTokenRequest — scopes (entra-v2 code exchange)', () => {+ const INPUT = {+ code: 'CODE',+ clientId: 'CID',+ redirectUri: 'https://cb.example.com/remote',+ codeVerifier: 'VER',+ }+ const STANDARD =+ 'grant_type=authorization_code&code=CODE&client_id=CID&redirect_uri=https%3A%2F%2Fcb.example.com%2Fremote&code_verifier=VER'++ it('appends scope, space-joined, when scopes are given', () => {+ const req = buildRemoteTokenRequest(TOKEN_ENDPOINT, INPUT, undefined, ['a', 'offline_access'])+ expect(req.body).toBe(`${STANDARD}&scope=a%20offline_access`)+ })++ it('puts scope before resource when both are given', () => {+ const req = buildRemoteTokenRequest(TOKEN_ENDPOINT, INPUT, RESOURCE, ['a', 'offline_access'])+ expect(req.body).toBe(+ `${STANDARD}&scope=a%20offline_access&resource=https%3A%2F%2Fmcp.notion.com`+ )+ })++ it('without scopes (absent or empty) the body is byte-identical', () => {+ expect(buildRemoteTokenRequest(TOKEN_ENDPOINT, INPUT).body).toBe(STANDARD)+ expect(buildRemoteTokenRequest(TOKEN_ENDPOINT, INPUT, RESOURCE, []).body).toBe(+ `${STANDARD}&resource=https%3A%2F%2Fmcp.notion.com`+ )+ })+})+describe('buildRemoteRefreshRequest (public client, RFC 8707)', () => {it('omits client_secret and appends resource', () => {const req = buildRemoteRefreshRequest(