From b133d5a7cc92b7999b8bf07360721e1a826326b9 Mon Sep 17 00:00:00 2001 From: matthewhenry1 <31288868+matthewhenry1@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:32:58 -0500 Subject: [PATCH] fix(auth): a new CIMD authorization keeps the user's other grants A CIMD client ID and its redirect URI are shared by every connection a hosted client holds (one metadata URL, one callback), so the provider's default grant replacement revoked a user's other live connections whenever they authorized again. Their next refresh failed with 'Grant not found'. Registered (DCR) clients get a client ID per install and keep replacement. --- src/auth/oauth-handler.ts | 9 +++++ tests/auth/cimd.test.ts | 71 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/src/auth/oauth-handler.ts b/src/auth/oauth-handler.ts index 426f73313..32af16d57 100644 --- a/src/auth/oauth-handler.ts +++ b/src/auth/oauth-handler.ts @@ -39,6 +39,11 @@ interface AuthEnv extends Env { OAUTH_PROVIDER: OAuthHelpers } +/** The provider has already validated the client; only a CIMD client ID is an https URL. */ +function isClientIdMetadataDocumentUrl(clientId: string): boolean { + return clientId.startsWith('https://') +} + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The OAuth provider attaches this helper binding at runtime. const env = cloudflareEnv as AuthEnv const ALLOWED_SCOPES = new Set(ALL_SCOPES) @@ -372,6 +377,10 @@ export function createAuthHandlers() { const { redirectTo } = await env.OAUTH_PROVIDER.completeAuthorization({ request: oauthReqInfo, userId: identity.user.id, + // A CIMD client ID and its callback are shared by every connection a hosted client + // holds, so replacing "existing" grants revokes the user's other live connections. + // Registered clients get a client ID per install and keep replacement. + revokeExistingGrants: !isClientIdMetadataDocumentUrl(oauthReqInfo.clientId), metadata: { label: identity.user.email }, scope: grantedScopes(oauthReqInfo.scope, upstreamScope), props: { diff --git a/tests/auth/cimd.test.ts b/tests/auth/cimd.test.ts index 925f669df..1241faf97 100644 --- a/tests/auth/cimd.test.ts +++ b/tests/auth/cimd.test.ts @@ -72,6 +72,60 @@ function useCloudflareAuthSuccess(): void { ) } +/** Run the full CIMD authorization and code exchange, returning the issued refresh token. */ +async function authorizeAndExchange(): Promise { + const authorization = await exports.default.fetch(new Request(authorizeUrl())) + const handle = (await authorization.text()).match(/name="handle" value="([^"]+)"/)?.[1] + const approval = await exports.default.fetch( + new Request(`${MCP_ORIGIN}/authorize`, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Cookie: cookiesFrom(authorization) + }, + body: new URLSearchParams({ handle: handle!, scopes: 'user:read' }).toString(), + redirect: 'manual' + }) + ) + const upstreamState = new URL(approval.headers.get('location')!).searchParams.get('state') + const callback = await exports.default.fetch( + new Request( + `${MCP_ORIGIN}/oauth/callback?code=authcode&state=${encodeURIComponent(upstreamState!)}`, + { headers: { Cookie: cookiesFrom(approval) }, redirect: 'manual' } + ) + ) + const code = new URL(callback.headers.get('location')!).searchParams.get('code') + const tokenResponse = await exports.default.fetch( + new Request(`${MCP_ORIGIN}/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code: code!, + client_id: CIMD_CLIENT_ID, + redirect_uri: REDIRECT_URI, + code_verifier: DOWNSTREAM_CODE_VERIFIER, + resource: MCP_RESOURCE + }).toString() + }) + ) + expect(tokenResponse.status).toBe(200) + return ((await tokenResponse.json()) as { refresh_token: string }).refresh_token +} + +function refreshRequest(refreshToken: string): Request { + return new Request(`${MCP_ORIGIN}/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + client_id: CIMD_CLIENT_ID, + resource: MCP_RESOURCE + }).toString() + }) +} + afterEach(async () => { await clearKv(env.OAUTH_KV) }) @@ -170,6 +224,23 @@ describe('Client ID Metadata Documents', () => { expect((await env.OAUTH_KV.list({ prefix: 'client:' })).keys).toHaveLength(0) }) + it('keeps an earlier grant when the same user authorizes the same CIMD client again', async () => { + // A hosted CIMD client (one client ID, one callback) can hold several independent + // connections for one Cloudflare user; a new one must not revoke the others. + server.use(http.get(CIMD_CLIENT_ID, () => HttpResponse.json(cimdMetadata()))) + useCloudflareAuthSuccess() + + const first = await authorizeAndExchange() + const second = await authorizeAndExchange() + expect(first.split(':')[1]).not.toBe(second.split(':')[1]) + expect((await env.OAUTH_KV.list({ prefix: 'grant:' })).keys).toHaveLength(2) + + const firstRefresh = await exports.default.fetch(refreshRequest(first)) + expect(firstRefresh.status).toBe(200) + const secondRefresh = await exports.default.fetch(refreshRequest(second)) + expect(secondRefresh.status).toBe(200) + }) + it('returns a local retryable error when metadata cannot be fetched', async () => { const unavailableClientId = 'https://unavailable.example.com/oauth/client.json' server.use(http.get(unavailableClientId, () => new HttpResponse(null, { status: 502 })))