From bb2ed5ab81d2d12b2ae24a2d3086d0a404f5f129 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:21:50 +0000 Subject: [PATCH] fix(oauth): Match resource indicators that differ only by query or trailing slash Protected resource metadata echoes the query of the URL a client dials, so clients disagree about whether `?utm_source=plugin`, `?codemode=false`, or a trailing slash belongs in the RFC 8707 resource. A login in one form followed by a code exchange or refresh in the other failed with `invalid_target` ("Requested resource was not included in the authorization request"), and tokens bound to one form failed on `/mcp` with "Token audience does not match resource server". Add a `resourceMatchCanonical` option to the workers-oauth-provider patch that compares scheme, host, port, and path for both checks, and enable it. The `/mcp/{org}/{project}` path binding is unchanged. Co-Authored-By: David Cramer <23610+dcramer@users.noreply.github.com> --- docs/cloudflare/oauth-architecture.md | 12 + packages/mcp-cloudflare/src/server/index.ts | 7 + .../resource-indicator.integration.test.ts | 208 ++++++++++++++++++ ...flare__workers-oauth-provider@0.10.3.patch | 99 ++++++++- pnpm-lock.yaml | 6 +- 5 files changed, 327 insertions(+), 5 deletions(-) create mode 100644 packages/mcp-cloudflare/src/server/oauth/resource-indicator.integration.test.ts diff --git a/docs/cloudflare/oauth-architecture.md b/docs/cloudflare/oauth-architecture.md index 6df04ec1b..61de15f00 100644 --- a/docs/cloudflare/oauth-architecture.md +++ b/docs/cloudflare/oauth-architecture.md @@ -418,6 +418,18 @@ response keeps the exact protected-resource query string in the RFC 8707 `resource` parameter, while emitting a query-free `issuer` so the document remains valid RFC 8414 metadata. +Because metadata echoes the query, clients disagree about whether a query such +as `?utm_source=plugin` or `?codemode=false`, or a trailing slash, is part of +the resource. A login can name `/mcp?utm_source=plugin` and a later code +exchange or refresh name `/mcp`. The provider runs with +`resourceMatchCanonical: true`, so the token endpoint compares the requested +and granted resources, and `/mcp` compares a token's audience to the request +URL, by scheme, host, port, and path only. The query and trailing slashes are +ignored; the `/mcp/{org}/{project}` path binding is unchanged. The option is +provided by the same version-specific pnpm patch as `clientIdMetadataDocuments`. +When upgrading the provider, port it and run +`pnpm --filter @sentry/mcp-cloudflare exec vitest run src/server/oauth/resource-indicator.integration.test.ts`. + When a constrained OAuth request includes `resource=/mcp/{org}` or `resource=/mcp/{org}/{project}`, the approval page surfaces that scope to the user as a "Session scope" banner before permissions are granted. diff --git a/packages/mcp-cloudflare/src/server/index.ts b/packages/mcp-cloudflare/src/server/index.ts index 35fc9f3ca..da6918699 100644 --- a/packages/mcp-cloudflare/src/server/index.ts +++ b/packages/mcp-cloudflare/src/server/index.ts @@ -348,6 +348,13 @@ const wrappedOAuthProvider = { // handled in authorization-server-metadata.ts. clientIdMetadataDocumentEnabled: true, clientIdMetadataDocuments: CLIENT_ID_METADATA_DOCUMENTS, + // Our PRM echoes the query of the URL a client dials (`?utm_source=`, + // `?codemode=`), and clients disagree about whether that query and a + // trailing slash belong in the RFC 8707 resource. A login in one form + // and a token or refresh request in the other must not fail with + // `invalid_target` or an audience mismatch. Path (org/project) binding + // still applies. Provided by our workers-oauth-provider patch. + resourceMatchCanonical: true, tokenExchangeCallback: (options) => tokenExchangeCallback(options, env, request, clientFamily), scopesSupported: Object.keys(SCOPES), diff --git a/packages/mcp-cloudflare/src/server/oauth/resource-indicator.integration.test.ts b/packages/mcp-cloudflare/src/server/oauth/resource-indicator.integration.test.ts new file mode 100644 index 000000000..7e129216a --- /dev/null +++ b/packages/mcp-cloudflare/src/server/oauth/resource-indicator.integration.test.ts @@ -0,0 +1,208 @@ +import { createExecutionContext, env } from "cloudflare:test"; +import { getOAuthApi } from "@cloudflare/workers-oauth-provider"; +import { describe, expect, it } from "vitest"; +import { SCOPES } from "../../constants"; +import { createPkcePair } from "../../test-utils/pkce"; +import app from "../app"; +import handler from "../index"; +import mcpHandler from "../lib/mcp-handler"; +import type { Env, WorkerProps } from "../types"; +import { CLIENT_ID_METADATA_DOCUMENTS } from "./client-metadata"; + +// Clients disagree about whether the RFC 8707 `resource` carries the query +// string of the configured MCP URL (`?utm_source=plugin`, `?codemode=false`) +// or a trailing slash. A login with one form followed by a token request with +// the other must not fail with `invalid_target`, and the issued token must +// still work on the MCP URL the client dials. + +const ORIGIN = "https://mcp.sentry.dev"; +const REDIRECT_URI = "http://127.0.0.1:43127/callback"; +const workerEnv = { + ...(env as Record), + CF_VERSION_METADATA: { id: "test-version-id" }, +} as Env; + +function createOAuthApi() { + return getOAuthApi( + { + apiRoute: "/mcp", + apiHandler: mcpHandler, + defaultHandler: app, + authorizeEndpoint: "/oauth/authorize", + tokenEndpoint: "/oauth/token", + clientRegistrationEndpoint: "/oauth/register", + clientIdMetadataDocumentEnabled: true, + clientIdMetadataDocuments: CLIENT_ID_METADATA_DOCUMENTS, + scopesSupported: Object.keys(SCOPES), + }, + workerEnv, + ); +} + +async function authorize(resource: string) { + const oauthApi = createOAuthApi(); + const client = await oauthApi.createClient({ + clientName: "resource indicator test client", + redirectUris: [REDIRECT_URI], + tokenEndpointAuthMethod: "none", + }); + const { codeVerifier, codeChallenge } = await createPkcePair(); + const url = new URL("/oauth/authorize", ORIGIN); + for (const [name, value] of Object.entries({ + response_type: "code", + client_id: client.clientId, + redirect_uri: REDIRECT_URI, + scope: "org:read", + state: "test-state", + resource, + code_challenge: codeChallenge, + code_challenge_method: "S256", + })) { + url.searchParams.set(name, value); + } + const request = await oauthApi.parseAuthRequest(new Request(url)); + const { redirectTo } = await oauthApi.completeAuthorization({ + request, + userId: "test-user-123", + metadata: {}, + scope: ["org:read"], + props: { + id: "test-user-123", + clientId: client.clientId, + accessToken: "upstream-access-token", + refreshToken: "upstream-refresh-token", + accessTokenExpiresAt: Date.now() + 60 * 60 * 1000, + scope: "org:read", + grantedSkills: ["inspect"], + } satisfies WorkerProps, + revokeExistingGrants: false, + }); + const code = new URL(redirectTo).searchParams.get("code"); + if (!code) throw new Error("Authorization did not issue a code"); + return { clientId: client.clientId, code, codeVerifier }; +} + +function requestToken(parameters: Record) { + return handler.fetch( + new Request(`${ORIGIN}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(parameters).toString(), + }), + workerEnv, + createExecutionContext(), + ); +} + +async function exchangeCode( + authorization: Awaited>, + resource: string, +) { + return await requestToken({ + grant_type: "authorization_code", + client_id: authorization.clientId, + redirect_uri: REDIRECT_URI, + code: authorization.code, + code_verifier: authorization.codeVerifier, + resource, + }); +} + +function callMcp(path: string, accessToken: string) { + return handler.fetch( + new Request(`${ORIGIN}${path}`, { + method: "POST", + headers: { + Authorization: `Bearer ${accessToken}`, + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "resource-indicator-test", version: "1.0.0" }, + }, + }), + }), + workerEnv, + createExecutionContext(), + ); +} + +async function expectAccepted(path: string, accessToken: string) { + const response = await callMcp(path, accessToken); + expect(response.status).toBe(200); + await response.body?.cancel(); +} + +describe("RFC 8707 resource indicators that differ only by query or trailing slash", () => { + it("exchanges a code when the login carried the query and the token request does not", async () => { + const authorization = await authorize(`${ORIGIN}/mcp?utm_source=plugin`); + const response = await exchangeCode(authorization, `${ORIGIN}/mcp`); + expect(response.status).toBe(200); + const tokens = await response.json<{ access_token: string }>(); + await expectAccepted("/mcp?utm_source=plugin", tokens.access_token); + await expectAccepted("/mcp", tokens.access_token); + }); + + it("refreshes when the refresh request adds a query the login did not have", async () => { + const authorization = await authorize(`${ORIGIN}/mcp`); + const exchange = await exchangeCode(authorization, `${ORIGIN}/mcp`); + expect(exchange.status).toBe(200); + const { refresh_token } = await exchange.json<{ refresh_token: string }>(); + + const refresh = await requestToken({ + grant_type: "refresh_token", + client_id: authorization.clientId, + refresh_token, + resource: `${ORIGIN}/mcp?codemode=false`, + }); + expect(refresh.status).toBe(200); + const tokens = await refresh.json<{ access_token: string }>(); + await expectAccepted("/mcp", tokens.access_token); + await expectAccepted("/mcp?codemode=false", tokens.access_token); + }); + + it("exchanges a code when only a trailing slash differs", async () => { + const authorization = await authorize(`${ORIGIN}/mcp/`); + const response = await exchangeCode(authorization, `${ORIGIN}/mcp`); + expect(response.status).toBe(200); + const tokens = await response.json<{ access_token: string }>(); + await expectAccepted("/mcp", tokens.access_token); + }); + + it("accepts an existing token whose audience carries a query on the bare MCP URL", async () => { + const authorization = await authorize(`${ORIGIN}/mcp?utm_source=plugin`); + const response = await exchangeCode( + authorization, + `${ORIGIN}/mcp?utm_source=plugin`, + ); + expect(response.status).toBe(200); + const tokens = await response.json<{ access_token: string }>(); + await expectAccepted("/mcp", tokens.access_token); + }); + + it("still rejects a token request for a different MCP path", async () => { + const authorization = await authorize(`${ORIGIN}/mcp/sentry`); + const response = await exchangeCode(authorization, `${ORIGIN}/mcp/other`); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: "invalid_target" }); + }); + + it("still rejects a token scoped to one organization on another organization's URL", async () => { + const authorization = await authorize( + `${ORIGIN}/mcp/sentry?utm_source=plugin`, + ); + const response = await exchangeCode(authorization, `${ORIGIN}/mcp/sentry`); + expect(response.status).toBe(200); + const tokens = await response.json<{ access_token: string }>(); + const other = await callMcp("/mcp/other", tokens.access_token); + expect(other.status).toBe(401); + expect(other.headers.get("WWW-Authenticate")).toContain("Invalid audience"); + await other.body?.cancel(); + }); +}); diff --git a/patches/@cloudflare__workers-oauth-provider@0.10.3.patch b/patches/@cloudflare__workers-oauth-provider@0.10.3.patch index 7b5bf4843..44a407add 100644 --- a/patches/@cloudflare__workers-oauth-provider@0.10.3.patch +++ b/patches/@cloudflare__workers-oauth-provider@0.10.3.patch @@ -1,5 +1,5 @@ diff --git a/dist/oauth-provider.d.ts b/dist/oauth-provider.d.ts -index 01141b6b4e708a7f40b32667ed8dd9cf33592888..33c099916cedc3666a5330675f1b3dc88d60a5c1 100644 +index 01141b6b4e708a7f40b32667ed8dd9cf33592888..a702879d22e030ede1271a972d5abd2d5e0a6ba1 100644 --- a/dist/oauth-provider.d.ts +++ b/dist/oauth-provider.d.ts @@ -684,6 +684,12 @@ interface OAuthProviderOptions { @@ -15,10 +15,43 @@ index 01141b6b4e708a7f40b32667ed8dd9cf33592888..33c099916cedc3666a5330675f1b3dc8 /** * When true, requested-vs-granted resource validation compares origins only * (scheme + host + port) instead of exact URIs. This allows an origin-only +@@ -697,6 +703,14 @@ interface OAuthProviderOptions { + * multi-tenant deployments. Prefer configuring `resourceMetadata.resource`. + */ + resourceMatchOriginOnly?: boolean; ++ /** ++ * When true, requested-vs-granted resource validation and access-token audience ++ * checks compare scheme, host, port and path, ignoring the query component and ++ * trailing slashes. Clients disagree about whether the resource carries the ++ * query of the configured server URL, so a login and a later token request can ++ * name the same resource in two forms. Path binding is unchanged. ++ */ ++ resourceMatchCanonical?: boolean; + /** + * Optional metadata for RFC 9728 OAuth 2.0 Protected Resource Metadata. + * Controls the response served at /.well-known/oauth-protected-resource. diff --git a/dist/oauth-provider.js b/dist/oauth-provider.js -index c15348c226f1064f6c277f45f10740b9266219e9..43b4d2bc3fca7aa844722c57c895c68951b76d55 100644 +index c15348c226f1064f6c277f45f10740b9266219e9..66099c2ee0257afed31fb8daf61b261f8df7e572 100644 --- a/dist/oauth-provider.js +++ b/dist/oauth-provider.js +@@ -2693,7 +2693,7 @@ var OAuthProviderImpl = class { + if (tokenData.audience) { + const requestUrl = new URL(request.url); + const resourceServer = `${requestUrl.protocol}//${requestUrl.host}${requestUrl.pathname}${requestUrl.search}`; +- if (!(Array.isArray(tokenData.audience) ? tokenData.audience : [tokenData.audience]).some((aud) => audienceMatches(resourceServer, aud))) return this.createErrorResponse("invalid_token", { ++ if (!(Array.isArray(tokenData.audience) ? tokenData.audience : [tokenData.audience]).some((aud) => audienceMatches(resourceServer, aud, !!this.options.resourceMatchCanonical))) return this.createErrorResponse("invalid_token", { + description: "Token audience does not match resource server", + statusCode: 401, + headers: { "WWW-Authenticate": this.buildWwwAuthenticateHeader(resourceMetadataUrl, "invalid_token", "Invalid audience") } +@@ -2727,7 +2727,7 @@ var OAuthProviderImpl = class { + if (ext.audience) { + const requestUrl = new URL(request.url); + const resourceServer = `${requestUrl.protocol}//${requestUrl.host}${requestUrl.pathname}${requestUrl.search}`; +- if (!(Array.isArray(ext.audience) ? ext.audience : [ext.audience]).some((aud) => audienceMatches(resourceServer, aud))) return this.createErrorResponse("invalid_token", { ++ if (!(Array.isArray(ext.audience) ? ext.audience : [ext.audience]).some((aud) => audienceMatches(resourceServer, aud, !!this.options.resourceMatchCanonical))) return this.createErrorResponse("invalid_token", { + description: "Token audience does not match resource server", + statusCode: 401, + headers: { "WWW-Authenticate": this.buildWwwAuthenticateHeader(resourceMetadataUrl, "invalid_token", "Invalid audience") } @@ -2806,6 +2806,11 @@ var OAuthProviderImpl = class { } if (!this.hasGlobalFetchStrictlyPublic()) throw new Error(`CIMD is enabled but 'global_fetch_strictly_public' compatibility flag is not set.`); @@ -31,3 +64,65 @@ index c15348c226f1064f6c277f45f10740b9266219e9..43b4d2bc3fca7aa844722c57c895c689 return await fetchClientIdMetadataDocument(clientId, this.serverCapabilities); } catch (error) { console.warn(`CIMD fetch failed for ${clientId}:`, error instanceof Error ? error.message : error); +@@ -2836,10 +2841,11 @@ var OAuthProviderImpl = class { + throw new OAuthError("invalid_target", { description: "The authorization grant is not bound to the configured resource" }); + } + const originOnly = !!this.options.resourceMatchOriginOnly; ++ const canonical = !!this.options.resourceMatchCanonical; + if (resourceWasProvided && grantResourceWasStored) { + const requestedResources = Array.isArray(requestedResource) ? requestedResource : [requestedResource]; + const grantedResources = Array.isArray(grantedResource) ? grantedResource : [grantedResource]; +- for (const requested of requestedResources) if (!grantedResources.some((granted) => resourceMatches(requested, granted, originOnly))) throw new OAuthError("invalid_target", { description: "Requested resource was not included in the authorization request" }); ++ for (const requested of requestedResources) if (!grantedResources.some((granted) => resourceMatches(requested, granted, originOnly, canonical))) throw new OAuthError("invalid_target", { description: "Requested resource was not included in the authorization request" }); + } + return requestedAudience ?? grantedAudience; + } +@@ -3135,19 +3141,27 @@ function validateResourceUri(uri) { + * @param audienceValue - The audience value from token + * @returns true if they match, false otherwise + */ +-function audienceMatches(resourceServerUrl, audienceValue) { ++function audienceMatches(resourceServerUrl, audienceValue, canonical = false) { + try { + const resource = new URL(resourceServerUrl); + const audience = new URL(audienceValue); + if (resource.origin !== audience.origin) return false; +- if (audience.search && resource.search !== audience.search) return false; +- if (audience.pathname === "/" || audience.pathname === "") return true; +- return resource.pathname === audience.pathname || resource.pathname.startsWith(audience.pathname + "/"); ++ if (!canonical && audience.search && resource.search !== audience.search) return false; ++ const audiencePath = canonical ? canonicalResourcePath(audience) : audience.pathname; ++ if (audiencePath === "/" || audiencePath === "") return true; ++ return resource.pathname === audiencePath || resource.pathname.startsWith(audiencePath + "/"); + } catch { + return false; + } + } + /** ++* Path of a resource indicator without trailing slashes, so `/mcp/` and `/mcp` ++* name the same resource. The root path stays `/`. ++*/ ++function canonicalResourcePath(url) { ++ return url.pathname.replace(/\/+$/, "") || "/"; ++} ++/** + * Parses and validates the resource parameter from a token request (RFC 8707) + * Handles single string or array of strings (from multiple form parameters) + * @param value - The resource parameter value from the request body +@@ -3169,10 +3183,13 @@ function isExactResource(value, configuredResource) { + * When originOnly is true, compares only the origin (scheme + host + port), + * allowing path-aware resources to match origin-only grants. + */ +-function resourceMatches(requested, granted, originOnly) { +- if (!originOnly) return requested === granted; ++function resourceMatches(requested, granted, originOnly, canonical = false) { ++ if (!originOnly && !canonical) return requested === granted; + try { +- return new URL(requested).origin === new URL(granted).origin; ++ const requestedUrl = new URL(requested); ++ const grantedUrl = new URL(granted); ++ if (requestedUrl.origin !== grantedUrl.origin) return false; ++ return originOnly || canonicalResourcePath(requestedUrl) === canonicalResourcePath(grantedUrl); + } catch { + return requested === granted; + } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b076b3c7..a3ee071ae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -387,7 +387,7 @@ packageExtensionsChecksum: sha256-PIoL2jn0sFpFHgcMKW97dNeqBXVNxH6qFIzsWIBFOMY= pnpmfileChecksum: sha256-Ov3KZHuKeE0QxRj4zRZgvSDmIYPKMRpTDJcVa6X3RPs= patchedDependencies: - '@cloudflare/workers-oauth-provider@0.10.3': 34910b67929c1888b1492384c514d6baeedc4a439f66e21375dee5af404834f8 + '@cloudflare/workers-oauth-provider@0.10.3': b344570966186aa3fd016da543e99aabf3abd9a7b1cb6ba1ad038239e4305efa '@stricli/core@1.2.8': c1d70807ac8f612d2e942650da25753076478898ece26cbdef5af377bedcbadc importers: @@ -875,7 +875,7 @@ importers: version: 3.0.232(react@19.2.8)(zod@4.6.7) '@cloudflare/workers-oauth-provider': specifier: 'catalog:' - version: 0.10.3(patch_hash=34910b67929c1888b1492384c514d6baeedc4a439f66e21375dee5af404834f8) + version: 0.10.3(patch_hash=b344570966186aa3fd016da543e99aabf3abd9a7b1cb6ba1ad038239e4305efa) '@modelcontextprotocol/server': specifier: 'catalog:' version: 2.4.0 @@ -9722,7 +9722,7 @@ snapshots: '@cloudflare/workerd-windows-64@1.20261101.1': optional: true - '@cloudflare/workers-oauth-provider@0.10.3(patch_hash=34910b67929c1888b1492384c514d6baeedc4a439f66e21375dee5af404834f8)': {} + '@cloudflare/workers-oauth-provider@0.10.3(patch_hash=b344570966186aa3fd016da543e99aabf3abd9a7b1cb6ba1ad038239e4305efa)': {} '@cloudflare/workers-types@4.20260405.1': {}