Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/cloudflare/oauth-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions packages/mcp-cloudflare/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown>),
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<string, string>) {
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<ReturnType<typeof authorize>>,
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();
});
});
99 changes: 97 additions & 2 deletions patches/@cloudflare__workers-oauth-provider@0.10.3.patch
Original file line number Diff line number Diff line change
@@ -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<Env = Cloudflare.Env> {
Expand All @@ -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<Env = Cloudflare.Env> {
* 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.`);
Expand All @@ -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;
}
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading