Skip to content

Commit b2e2203

Browse files
authored
Merge pull request #436 from GenerationSoftware/codex/mcp-oauth-renewal
Fix MCP OAuth renewal and transport challenges
2 parents facb991 + a7936c7 commit b2e2203

8 files changed

Lines changed: 351 additions & 14 deletions

File tree

‎packages/api/src/mcp-oauth-auth.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { OAuthError, type TokenExchangeCallbackOptions } from "@cloudflare/workers-oauth-provider";
2+
import { normalizeScopes } from "./access-tokens";
3+
import { applyConnectionScopes, type ConnectionScopePolicy } from "./oauth-connection-settings";
4+
import { databaseFor, type DatabaseClient } from "./postgres/database";
5+
import { lockOAuthPolicy } from "./oauth-reconnect";
6+
import { lockMcpEventGrant } from "./postgres/mcp-event-outbox";
7+
import type { Env, OAuthProps } from "./types";
8+
9+
type Rejection = "invalid_token" | "token_expired" | "membership_inactive" | "session_mismatch" | "grant_revoked" | "grant_mismatch" | "refresh_rejected";
10+
type Policy = ConnectionScopePolicy & { user_id: string; session_version: number; revoked_at: Date | null; integration_overrides: Record<string, string | false> };
11+
export function authDiagnostic(stage: "resource" | "refresh", reason: Rejection) {
12+
console.warn("factorize.mcp_oauth_rejected", { stage, reason });
13+
}
14+
export function mcpOAuthChallenge(env: Env, reason?: Rejection, scopes?: readonly string[]) {
15+
if (reason) authDiagnostic("resource", reason);
16+
const attributes = ['resource_metadata="' + env.APP_ORIGIN + '/.well-known/oauth-protected-resource/mcp"'];
17+
if (scopes) attributes.unshift('error="insufficient_scope"', 'scope="' + scopes.join(" ") + '"');
18+
else if (reason) attributes.unshift('error="invalid_token"');
19+
return Response.json({ error: { code: scopes ? "insufficient_scope" : "invalid_token" } }, {
20+
status: scopes ? 403 : 401, headers: { "Cache-Control": "no-store", "WWW-Authenticate": "Bearer " + attributes.join(", ") },
21+
});
22+
}
23+
type GrantIdentity = Pick<OAuthProps, "tenantId" | "userId" | "sessionVersion">;
24+
type Inspection = { policy?: Policy; reason?: Rejection };
25+
const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
26+
export async function inspectOAuthGrant(sql: DatabaseClient, auth: GrantIdentity, grantId: string, lock = false): Promise<Inspection> {
27+
if (!auth || !uuid.test(auth.tenantId) || !uuid.test(auth.userId) || !Number.isSafeInteger(auth.sessionVersion) || !grantId) {
28+
return { reason: "grant_mismatch" as const };
29+
}
30+
const { rows } = await sql.query<{ role: string; session_version: number }>(
31+
`SELECT m.role,m.session_version FROM app.members m JOIN app.auth_users u ON u.id=m.user_id
32+
WHERE m.tenant_id=$1 AND m.user_id=$2 AND u.email_verified${lock ? " FOR SHARE OF m,u" : ""}`, [auth.tenantId, auth.userId]);
33+
const member = rows[0];
34+
if (member?.role !== "owner") return { reason: "membership_inactive" as const };
35+
if (member.session_version !== auth.sessionVersion) return { reason: "session_mismatch" as const };
36+
const policy = (await sql.query<Policy>(
37+
`SELECT user_id,session_version,revoked_at,disabled_scopes,scope_overrides,integration_overrides
38+
FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2`, [auth.tenantId, grantId])).rows[0];
39+
if (policy?.revoked_at) return { reason: "grant_revoked" as const };
40+
if (policy && (policy.user_id !== auth.userId || policy.session_version !== auth.sessionVersion)) return { reason: "grant_mismatch" as const };
41+
return { policy };
42+
}
43+
44+
export function oauthResourceAuthorization(env: Env, auth: OAuthProps, grantId: string): Promise<Inspection> {
45+
if (!auth.oauthExpiresAt || !Number.isFinite(auth.oauthExpiresAt) || auth.oauthExpiresAt <= Date.now() / 1000) {
46+
return Promise.resolve({ reason: "token_expired" as const });
47+
}
48+
return inspectOAuthGrant(databaseFor(env).pool, auth, grantId);
49+
}
50+
51+
type TokenHook = (options: TokenExchangeCallbackOptions) => Promise<{ accessTokenScope: string[] } | void>;
52+
function invalidRefresh(reason: Rejection): never {
53+
authDiagnostic("refresh", reason);
54+
throw new OAuthError("invalid_grant", { description: "The authorization is no longer active." });
55+
}
56+
57+
// The provider validates the refresh credential and client before invoking
58+
// the hook. Only then acquire application locks, keeping them through the
59+
// provider's rotation and token writes. Revocation shares this grant lock.
60+
export async function withRefreshAdmission(env: Env, run: (hook: TokenHook) => Promise<Response>, reportProviderRejection: boolean) {
61+
let finish!: () => void;
62+
const providerFinished = new Promise<void>(resolve => { finish = resolve; });
63+
let transaction: Promise<void> | undefined;
64+
const onExchange: TokenHook = options => {
65+
if (options.grantType !== "refresh_token") return Promise.resolve();
66+
const props = options.props as OAuthProps | undefined;
67+
if (!props || !Array.isArray(props.scopes) || props.scopes.some(scope => typeof scope !== "string") || props.userId !== options.userId || !uuid.test(props.tenantId) || !options.grantId) invalidRefresh("grant_mismatch");
68+
return new Promise((accept, reject) => {
69+
let admitted = false;
70+
transaction = databaseFor(env).transaction(async sql => {
71+
await lockOAuthPolicy(sql, props);
72+
await lockMcpEventGrant(sql, props.tenantId, options.grantId);
73+
const result = await inspectOAuthGrant(sql, props, options.grantId, true);
74+
if ("reason" in result && result.reason) invalidRefresh(result.reason);
75+
const consent = new Set(normalizeScopes(props.scopes));
76+
const requested = normalizeScopes(options.requestedScope).filter(scope => consent.has(scope));
77+
admitted = true;
78+
accept({ accessTokenScope: applyConnectionScopes(requested, result.policy) });
79+
await providerFinished;
80+
}).catch(error => {
81+
if (admitted) throw error;
82+
reject(error);
83+
});
84+
});
85+
};
86+
try {
87+
const response = await run(onExchange);
88+
if (reportProviderRejection && response.status === 400 && !transaction) {
89+
const payload = await response.clone().json<{error?: string}>().catch(() => null);
90+
if (payload?.error === "invalid_grant") authDiagnostic("refresh", "refresh_rejected");
91+
}
92+
return response;
93+
} finally {
94+
finish();
95+
await transaction;
96+
}
97+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { connectionAccess, requiredIntegrationScope, type AgentIntegration, type ConnectionPolicy } from "./agent-integration-access";
2+
import { databaseFor } from "./postgres/database";
3+
import type { Env, OAuthProps } from "./types";
4+
5+
const requirements = new Map<string, string>();
6+
function tools(scope: string, names: string) { for (const name of names.split(" ")) requirements.set(name, scope); }
7+
tools("triggers:read", "list_events get_event read_event_delivery_diagnostics read_event_occurrences list_event_occurrences list_triggers get_trigger list_trigger_webhook_activity list_webhook_deliveries get_webhook_delivery get_event_processing_acknowledgments set_event_processing_acknowledgments acknowledge_events replay_unacknowledged_events");
8+
tools("triggers:write", "create_event update_event delete_event create_trigger update_trigger delete_trigger enable_trigger disable_trigger fire_trigger test_trigger_webhook_conditions");
9+
tools("integrations:read", "list_exe_connections list_github_installations list_cloudflare_tail_integrations");
10+
tools("vms:read", "list_vms");
11+
tools("vms:edit", "grant_vm_permissions revoke_vm_permissions");
12+
tools("apps:manage", "list_apps get_app create_app update_app");
13+
tools("proxy:use", "request_api read_api_response query_api_response create_payload append_payload_chunk finalize_payload import_attachment fetch_payload get_api_operation read_api_operation cancel_api_operation");
14+
15+
export async function mcpMissingScopes(env: Env, auth: OAuthProps, body: unknown, policy: ConnectionPolicy): Promise<string[] | null> {
16+
if (!body || typeof body !== "object") return null;
17+
const { jsonrpc, id, method, params } = body as { jsonrpc?: unknown; id?: unknown; method?: unknown; params?: any };
18+
if (jsonrpc !== "2.0" || !(typeof id === "string" || typeof id === "number")) return null;
19+
const name = method === "tools/call" ? params?.name : undefined;
20+
const uri = params?.uri;
21+
const resourceRead = method === "resources/read" || method === "resources/subscribe";
22+
const methodNeedsRead = method === "events/list" || method === "events/subscribe" || method === "events/unsubscribe" ||
23+
(resourceRead && typeof uri === "string" && uri.startsWith("factorize://events/")) ||
24+
(method === "subscriptions/listen" && Array.isArray(params?.notifications?.resourceSubscriptions) &&
25+
params.notifications.resourceSubscriptions.some((item: unknown) => typeof item === "string" && item.startsWith("factorize://events/")));
26+
const scope = typeof name === "string" ? requirements.get(name) : methodNeedsRead ? "triggers:read" :
27+
resourceRead && typeof uri === "string" && uri.startsWith("proxy://responses/") ? "proxy:use" : undefined;
28+
if (scope && !auth.scopes.includes(scope)) return [scope];
29+
30+
// Only local Factorize integration policy may request additional OAuth
31+
// scopes. Blocked integrations and upstream errors stay normal tool errors.
32+
const integration = params?.arguments?.integration;
33+
if ((name !== "request_api" && name !== "fetch_payload") || typeof integration !== "string" ||
34+
!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(integration)) return null;
35+
const row = (await databaseFor(env).pool.query<AgentIntegration>(
36+
"SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [auth.tenantId, integration])).rows[0];
37+
return row && connectionAccess(row, auth.scopes, policy) === "requestable" ? ["proxy:use", requiredIntegrationScope(row)] : null;
38+
}

‎packages/api/src/protected-api.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import { mcpOAuthChallenge, oauthResourceAuthorization } from "./mcp-oauth-auth";
2+
import { mcpMissingScopes } from "./mcp-oauth-scopes";
3+
import { applyConnectionScopes } from "./oauth-connection-settings";
4+
import { initialIntegrationOverrides } from "./oauth-reconnect";
15
import { listEventsInput, getProcessingAcknowledgmentsInput, setProcessingAcknowledgmentsInput, acknowledgeEventsInput, replayUnacknowledgedEventsInput, readEventDeliveryDiagnosticsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts";
26
import { appRegistrationInput, appRegistrationUpdate } from "./apps-contracts";
37
import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads";
@@ -70,12 +74,18 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
7074
};
7175
try {
7276
const url = new URL(request.url), path = url.pathname;
73-
if (auth?.oauthGrantId) {
77+
let oauthPolicy: Awaited<ReturnType<typeof oauthResourceAuthorization>>["policy"];
78+
if (auth?.authMethod === "oauth" && auth.oauthGrantId && path === "/mcp") {
79+
const status = await oauthResourceAuthorization(env, auth, auth.oauthGrantId);
80+
if ("reason" in status && status.reason) return timed(mcpOAuthChallenge(env, status.reason));
81+
oauthPolicy = status.policy;
82+
auth = { ...auth, scopes: applyConnectionScopes(auth.scopes, oauthPolicy) };
83+
} else if (auth?.oauthGrantId) {
7484
auth = { ...auth, scopes: await effectiveConnectionScopes(env, auth, auth.scopes) };
7585
if (path.startsWith("/api/v1/agent/") && !auth.scopes.includes("proxy:use")) throw new ServiceError(403, "insufficient_scope", "The proxy:use scope is required.");
7686
}
7787
if (path === "/mcp") {
78-
if (!auth) throw new ServiceError(401, "invalid_token", "Unauthorized");
88+
if (!auth) return timed(mcpOAuthChallenge(env));
7989
const mcpService = new ApiService(env, auth);
8090
mcpSignals.set(mcpService,request.signal);
8191
if (request.method === "POST") {
@@ -85,6 +95,12 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
8595
}));
8696
let body: any;
8797
try { body = await new Response(limited).json(); } catch(error) { if(error instanceof ServiceError) throw error; throw new ServiceError(400,"invalid_request","Request body must be valid JSON."); }
98+
if (auth.authMethod === "oauth" && auth.oauthGrantId) {
99+
const missing = await mcpMissingScopes(env, auth, body, oauthPolicy ?? {
100+
disabled_scopes: [], integration_overrides: initialIntegrationOverrides(auth.initialIntegrationDenials),
101+
});
102+
if (missing) return timed(mcpOAuthChallenge(env, undefined, missing));
103+
}
88104
mcpBodies.set(request,body);
89105
if (body?.method === "subscriptions/listen" && body.params?.notifications?.resourceSubscriptions) {
90106
const listenerAuth = auth;
@@ -96,8 +112,10 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
96112
if (listenerAuth.oauthGrantId) {
97113
const token = await env.OAUTH_PROVIDER?.unwrapToken<OAuthProps>(request.headers.get("Authorization")?.slice(7) ?? "");
98114
if (token?.grantId !== listenerAuth.oauthGrantId || token.expiresAt <= Date.now()/1000) return false;
99-
const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(listenerAuth.scopes).includes(scope));
100-
return (await effectiveConnectionScopes(env, listenerAuth, tokenScopes)).includes(requiredScope);
115+
const status = await oauthResourceAuthorization(env, { ...listenerAuth, oauthExpiresAt: token.expiresAt }, token.grantId);
116+
if ("reason" in status && status.reason) return false;
117+
const tokenScopes = normalizeScopes(token.scope).filter(scope => listenerAuth.scopes.includes(scope));
118+
return applyConnectionScopes(tokenScopes, status.policy).includes(requiredScope);
101119
}
102120
return listenerAuth.scopes.includes(requiredScope); // The database read rechecks owner membership and key activity.
103121
};
@@ -286,7 +304,10 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
286304
if (auth.authMethod === "oauth" || auth.authMethod === undefined) {
287305
const authorization = request.headers.get("Authorization"), credential = authorization?.startsWith("Bearer ") ? authorization.slice(7) : "";
288306
const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken<OAuthProps>(credential) : null;
289-
if (!token || token.userId !== auth.userId || !token.grant?.clientId) return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401});
307+
if (!token || token.userId !== auth.userId || !token.grant?.clientId) {
308+
if (new URL(request.url).pathname === "/mcp") return mcpOAuthChallenge(this.env, "invalid_token");
309+
return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401});
310+
}
290311
// Props describe original consent. The presented token may be narrowed.
291312
const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope));
292313
auth = {...auth, authMethod: "oauth", scopes: tokenScopes, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt};

‎packages/api/src/worker.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { mcpOAuthChallenge, withRefreshAdmission } from "./mcp-oauth-auth";
12
import { pruneTotp } from "./totp";
23
import { googleSignInCallback } from "./auth-api";
34
import { clearExpiredGoogleSignIns, googleCallbackPath } from "./google-sign-in";
@@ -152,8 +153,18 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext)
152153
const clone = request.clone();
153154
const form = await clone.formData().catch(() => null);
154155
if (form?.get("grant_type") === DEVICE_GRANT) return deviceToken(request, env, oauth, ctx);
156+
return withRefreshAdmission(env, tokenExchangeCallback =>
157+
new OAuthProvider<Env>({ ...providerOptions(env), tokenExchangeCallback }).fetch(request, env, ctx),
158+
form?.get("grant_type") === "refresh_token");
155159
}
156160
const response = await oauth.fetch(request, env, ctx);
161+
if (url.pathname === "/mcp" && response.status === 401) {
162+
// The provider rejects these before handing off to Factorize. Only its
163+
// fixed OAuth fields are inspected, not any credential or arbitrary error.
164+
const error = await response.clone().json<{error?: unknown; error_description?: unknown}>().catch(() => null);
165+
if (error?.error === "invalid_token") return mcpOAuthChallenge(env, error.error_description === "Access token expired" ? "token_expired" : "invalid_token");
166+
if (!request.headers.has("Authorization")) return mcpOAuthChallenge(env);
167+
}
157168
if (url.pathname === "/.well-known/oauth-authorization-server") return addDeviceMetadata(response, env.APP_ORIGIN);
158169
return response;
159170
} } satisfies ExportedHandler<Env>;

‎packages/api/test/mcp-events.postgres.test.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,8 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl
179179
const crossTenant = await diagnosis(otherMatch.occurrence!.id);
180180
expect(crossTenant.isError).toBe(true);
181181
expect(crossTenant.content).toEqual(missing.content);
182-
expect((await diagnosis(empty, { ...auth, scopes: [] })).isError).toBe(true);
183-
expect((await diagnosis(empty, { ...auth, userId: crypto.randomUUID() })).isError).toBe(true);
182+
expect((await request("tools/call", { name: "read_event_delivery_diagnostics", arguments: { occurrenceId: empty } }, { ...auth, scopes: [] })).status).toBe(403);
183+
expect((await request("tools/call", { name: "read_event_delivery_diagnostics", arguments: { occurrenceId: empty } }, { ...auth, userId: crypto.randomUUID() })).status).toBe(401);
184184

185185
const subscriptionId = (await subscribe()).message.result.id;
186186
expect(subscriptionId).toMatch(/^sub_/);
@@ -576,13 +576,16 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl
576576
await new IdentityRepository(f.db, f.otherTenant).upsertOwner(f.userId, "owner@example.test");
577577
const other = { ...f.auth, tenantId: f.otherTenant };
578578
expect((await read({ occurrenceId: rotated.occurrenceId }, other)).isError).toBe(true);
579-
expect((await read({ occurrenceId: rotated.occurrenceId }, { ...auth, scopes: [] })).isError).toBe(true);
579+
expect((await request("tools/call", { name: "read_event_occurrences", arguments: { occurrenceId: rotated.occurrenceId } }, { ...auth, scopes: [] })).status).toBe(403);
580580
});
581581

582582
it("rejects failed verification, forbidden destinations, unauthorized calls and cross-tenant names", async () => {
583583
const input = { name, delivery: { mode: "webhook", url: receiver, secret: secret(key) } };
584-
expect((await request("events/list", {}, { ...auth, scopes: [] })).message.error.code).toBe(-32024);
585-
expect((await request("events/subscribe", input, { ...auth, scopes: [] })).message.error.code).toBe(-32024);
584+
for (const [method, params] of [["events/list", {}], ["events/subscribe", input]] as const) {
585+
const denied = await request(method, params, { ...auth, scopes: [] });
586+
expect(denied.status).toBe(403);
587+
expect(denied.message.error.code).toBe("insufficient_scope");
588+
}
586589
const other = await f.seedEventTrigger(f.otherTenant);
587590
expect((await request("events/subscribe", { ...input, name: `factorize.event.${other.definitionId}` })).message.error).toMatchObject({ code: -32023 });
588591
expect((await request("events/list", {}, auth, { "Mcp-Method": "events/unsubscribe" })).status).toBe(400);

0 commit comments

Comments
 (0)