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
97 changes: 97 additions & 0 deletions packages/api/src/mcp-oauth-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { OAuthError, type TokenExchangeCallbackOptions } from "@cloudflare/workers-oauth-provider";
import { normalizeScopes } from "./access-tokens";
import { applyConnectionScopes, type ConnectionScopePolicy } from "./oauth-connection-settings";
import { databaseFor, type DatabaseClient } from "./postgres/database";
import { lockOAuthPolicy } from "./oauth-reconnect";
import { lockMcpEventGrant } from "./postgres/mcp-event-outbox";
import type { Env, OAuthProps } from "./types";

type Rejection = "invalid_token" | "token_expired" | "membership_inactive" | "session_mismatch" | "grant_revoked" | "grant_mismatch" | "refresh_rejected";
type Policy = ConnectionScopePolicy & { user_id: string; session_version: number; revoked_at: Date | null; integration_overrides: Record<string, string | false> };
export function authDiagnostic(stage: "resource" | "refresh", reason: Rejection) {
console.warn("factorize.mcp_oauth_rejected", { stage, reason });
}
export function mcpOAuthChallenge(env: Env, reason?: Rejection, scopes?: readonly string[]) {
if (reason) authDiagnostic("resource", reason);
const attributes = ['resource_metadata="' + env.APP_ORIGIN + '/.well-known/oauth-protected-resource/mcp"'];
if (scopes) attributes.unshift('error="insufficient_scope"', 'scope="' + scopes.join(" ") + '"');
else if (reason) attributes.unshift('error="invalid_token"');
return Response.json({ error: { code: scopes ? "insufficient_scope" : "invalid_token" } }, {
status: scopes ? 403 : 401, headers: { "Cache-Control": "no-store", "WWW-Authenticate": "Bearer " + attributes.join(", ") },
});
}
type GrantIdentity = Pick<OAuthProps, "tenantId" | "userId" | "sessionVersion">;
type Inspection = { policy?: Policy; reason?: Rejection };
const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
export async function inspectOAuthGrant(sql: DatabaseClient, auth: GrantIdentity, grantId: string, lock = false): Promise<Inspection> {
if (!auth || !uuid.test(auth.tenantId) || !uuid.test(auth.userId) || !Number.isSafeInteger(auth.sessionVersion) || !grantId) {
return { reason: "grant_mismatch" as const };
}
const { rows } = await sql.query<{ role: string; session_version: number }>(
`SELECT m.role,m.session_version FROM app.members m JOIN app.auth_users u ON u.id=m.user_id
WHERE m.tenant_id=$1 AND m.user_id=$2 AND u.email_verified${lock ? " FOR SHARE OF m,u" : ""}`, [auth.tenantId, auth.userId]);
const member = rows[0];
if (member?.role !== "owner") return { reason: "membership_inactive" as const };
if (member.session_version !== auth.sessionVersion) return { reason: "session_mismatch" as const };
const policy = (await sql.query<Policy>(
`SELECT user_id,session_version,revoked_at,disabled_scopes,scope_overrides,integration_overrides
FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2`, [auth.tenantId, grantId])).rows[0];
if (policy?.revoked_at) return { reason: "grant_revoked" as const };
if (policy && (policy.user_id !== auth.userId || policy.session_version !== auth.sessionVersion)) return { reason: "grant_mismatch" as const };
return { policy };
}

export function oauthResourceAuthorization(env: Env, auth: OAuthProps, grantId: string): Promise<Inspection> {
if (!auth.oauthExpiresAt || !Number.isFinite(auth.oauthExpiresAt) || auth.oauthExpiresAt <= Date.now() / 1000) {
return Promise.resolve({ reason: "token_expired" as const });
}
return inspectOAuthGrant(databaseFor(env).pool, auth, grantId);
}

type TokenHook = (options: TokenExchangeCallbackOptions) => Promise<{ accessTokenScope: string[] } | void>;
function invalidRefresh(reason: Rejection): never {
authDiagnostic("refresh", reason);
throw new OAuthError("invalid_grant", { description: "The authorization is no longer active." });
}

// The provider validates the refresh credential and client before invoking
// the hook. Only then acquire application locks, keeping them through the
// provider's rotation and token writes. Revocation shares this grant lock.
export async function withRefreshAdmission(env: Env, run: (hook: TokenHook) => Promise<Response>, reportProviderRejection: boolean) {
let finish!: () => void;
const providerFinished = new Promise<void>(resolve => { finish = resolve; });
let transaction: Promise<void> | undefined;
const onExchange: TokenHook = options => {
if (options.grantType !== "refresh_token") return Promise.resolve();
const props = options.props as OAuthProps | undefined;
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");
return new Promise((accept, reject) => {
let admitted = false;
transaction = databaseFor(env).transaction(async sql => {
await lockOAuthPolicy(sql, props);
await lockMcpEventGrant(sql, props.tenantId, options.grantId);
const result = await inspectOAuthGrant(sql, props, options.grantId, true);
if ("reason" in result && result.reason) invalidRefresh(result.reason);
const consent = new Set(normalizeScopes(props.scopes));
const requested = normalizeScopes(options.requestedScope).filter(scope => consent.has(scope));
admitted = true;
accept({ accessTokenScope: applyConnectionScopes(requested, result.policy) });
await providerFinished;
}).catch(error => {
if (admitted) throw error;
reject(error);
});
});
};
try {
const response = await run(onExchange);
if (reportProviderRejection && response.status === 400 && !transaction) {
const payload = await response.clone().json<{error?: string}>().catch(() => null);
if (payload?.error === "invalid_grant") authDiagnostic("refresh", "refresh_rejected");
}
return response;
} finally {
finish();
await transaction;
}
}
38 changes: 38 additions & 0 deletions packages/api/src/mcp-oauth-scopes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { connectionAccess, requiredIntegrationScope, type AgentIntegration, type ConnectionPolicy } from "./agent-integration-access";
import { databaseFor } from "./postgres/database";
import type { Env, OAuthProps } from "./types";

const requirements = new Map<string, string>();
function tools(scope: string, names: string) { for (const name of names.split(" ")) requirements.set(name, scope); }
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");
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");
tools("integrations:read", "list_exe_connections list_github_installations list_cloudflare_tail_integrations");
tools("vms:read", "list_vms");
tools("vms:edit", "grant_vm_permissions revoke_vm_permissions");
tools("apps:manage", "list_apps get_app create_app update_app");
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");

export async function mcpMissingScopes(env: Env, auth: OAuthProps, body: unknown, policy: ConnectionPolicy): Promise<string[] | null> {
if (!body || typeof body !== "object") return null;
const { jsonrpc, id, method, params } = body as { jsonrpc?: unknown; id?: unknown; method?: unknown; params?: any };
if (jsonrpc !== "2.0" || !(typeof id === "string" || typeof id === "number")) return null;
const name = method === "tools/call" ? params?.name : undefined;
const uri = params?.uri;
const resourceRead = method === "resources/read" || method === "resources/subscribe";
const methodNeedsRead = method === "events/list" || method === "events/subscribe" || method === "events/unsubscribe" ||
(resourceRead && typeof uri === "string" && uri.startsWith("factorize://events/")) ||
(method === "subscriptions/listen" && Array.isArray(params?.notifications?.resourceSubscriptions) &&
params.notifications.resourceSubscriptions.some((item: unknown) => typeof item === "string" && item.startsWith("factorize://events/")));
const scope = typeof name === "string" ? requirements.get(name) : methodNeedsRead ? "triggers:read" :
resourceRead && typeof uri === "string" && uri.startsWith("proxy://responses/") ? "proxy:use" : undefined;
if (scope && !auth.scopes.includes(scope)) return [scope];

// Only local Factorize integration policy may request additional OAuth
// scopes. Blocked integrations and upstream errors stay normal tool errors.
const integration = params?.arguments?.integration;
if ((name !== "request_api" && name !== "fetch_payload") || typeof integration !== "string" ||
!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(integration)) return null;
const row = (await databaseFor(env).pool.query<AgentIntegration>(
"SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [auth.tenantId, integration])).rows[0];
return row && connectionAccess(row, auth.scopes, policy) === "requestable" ? ["proxy:use", requiredIntegrationScope(row)] : null;
}
31 changes: 26 additions & 5 deletions packages/api/src/protected-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { mcpOAuthChallenge, oauthResourceAuthorization } from "./mcp-oauth-auth";
import { mcpMissingScopes } from "./mcp-oauth-scopes";
import { applyConnectionScopes } from "./oauth-connection-settings";
import { initialIntegrationOverrides } from "./oauth-reconnect";
import { listEventsInput, getProcessingAcknowledgmentsInput, setProcessingAcknowledgmentsInput, acknowledgeEventsInput, replayUnacknowledgedEventsInput, readEventDeliveryDiagnosticsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts";
import { appRegistrationInput, appRegistrationUpdate } from "./apps-contracts";
import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads";
Expand Down Expand Up @@ -70,12 +74,18 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
};
try {
const url = new URL(request.url), path = url.pathname;
if (auth?.oauthGrantId) {
let oauthPolicy: Awaited<ReturnType<typeof oauthResourceAuthorization>>["policy"];
if (auth?.authMethod === "oauth" && auth.oauthGrantId && path === "/mcp") {
const status = await oauthResourceAuthorization(env, auth, auth.oauthGrantId);
if ("reason" in status && status.reason) return timed(mcpOAuthChallenge(env, status.reason));
oauthPolicy = status.policy;
auth = { ...auth, scopes: applyConnectionScopes(auth.scopes, oauthPolicy) };
} else if (auth?.oauthGrantId) {
auth = { ...auth, scopes: await effectiveConnectionScopes(env, auth, auth.scopes) };
if (path.startsWith("/api/v1/agent/") && !auth.scopes.includes("proxy:use")) throw new ServiceError(403, "insufficient_scope", "The proxy:use scope is required.");
}
if (path === "/mcp") {
if (!auth) throw new ServiceError(401, "invalid_token", "Unauthorized");
if (!auth) return timed(mcpOAuthChallenge(env));
const mcpService = new ApiService(env, auth);
mcpSignals.set(mcpService,request.signal);
if (request.method === "POST") {
Expand All @@ -85,6 +95,12 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
}));
let body: any;
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."); }
if (auth.authMethod === "oauth" && auth.oauthGrantId) {
const missing = await mcpMissingScopes(env, auth, body, oauthPolicy ?? {
disabled_scopes: [], integration_overrides: initialIntegrationOverrides(auth.initialIntegrationDenials),
});
if (missing) return timed(mcpOAuthChallenge(env, undefined, missing));
}
mcpBodies.set(request,body);
if (body?.method === "subscriptions/listen" && body.params?.notifications?.resourceSubscriptions) {
const listenerAuth = auth;
Expand All @@ -96,8 +112,10 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
if (listenerAuth.oauthGrantId) {
const token = await env.OAUTH_PROVIDER?.unwrapToken<OAuthProps>(request.headers.get("Authorization")?.slice(7) ?? "");
if (token?.grantId !== listenerAuth.oauthGrantId || token.expiresAt <= Date.now()/1000) return false;
const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(listenerAuth.scopes).includes(scope));
return (await effectiveConnectionScopes(env, listenerAuth, tokenScopes)).includes(requiredScope);
const status = await oauthResourceAuthorization(env, { ...listenerAuth, oauthExpiresAt: token.expiresAt }, token.grantId);
if ("reason" in status && status.reason) return false;
const tokenScopes = normalizeScopes(token.scope).filter(scope => listenerAuth.scopes.includes(scope));
return applyConnectionScopes(tokenScopes, status.policy).includes(requiredScope);
}
return listenerAuth.scopes.includes(requiredScope); // The database read rechecks owner membership and key activity.
};
Expand Down Expand Up @@ -286,7 +304,10 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
if (auth.authMethod === "oauth" || auth.authMethod === undefined) {
const authorization = request.headers.get("Authorization"), credential = authorization?.startsWith("Bearer ") ? authorization.slice(7) : "";
const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken<OAuthProps>(credential) : null;
if (!token || token.userId !== auth.userId || !token.grant?.clientId) return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401});
if (!token || token.userId !== auth.userId || !token.grant?.clientId) {
if (new URL(request.url).pathname === "/mcp") return mcpOAuthChallenge(this.env, "invalid_token");
return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401});
}
// Props describe original consent. The presented token may be narrowed.
const tokenScopes = normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope));
auth = {...auth, authMethod: "oauth", scopes: tokenScopes, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt};
Expand Down
11 changes: 11 additions & 0 deletions packages/api/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { mcpOAuthChallenge, withRefreshAdmission } from "./mcp-oauth-auth";
import { pruneTotp } from "./totp";
import { googleSignInCallback } from "./auth-api";
import { clearExpiredGoogleSignIns, googleCallbackPath } from "./google-sign-in";
Expand Down Expand Up @@ -152,8 +153,18 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext)
const clone = request.clone();
const form = await clone.formData().catch(() => null);
if (form?.get("grant_type") === DEVICE_GRANT) return deviceToken(request, env, oauth, ctx);
return withRefreshAdmission(env, tokenExchangeCallback =>
new OAuthProvider<Env>({ ...providerOptions(env), tokenExchangeCallback }).fetch(request, env, ctx),
form?.get("grant_type") === "refresh_token");
}
const response = await oauth.fetch(request, env, ctx);
if (url.pathname === "/mcp" && response.status === 401) {
// The provider rejects these before handing off to Factorize. Only its
// fixed OAuth fields are inspected, not any credential or arbitrary error.
const error = await response.clone().json<{error?: unknown; error_description?: unknown}>().catch(() => null);
if (error?.error === "invalid_token") return mcpOAuthChallenge(env, error.error_description === "Access token expired" ? "token_expired" : "invalid_token");
if (!request.headers.has("Authorization")) return mcpOAuthChallenge(env);
}
if (url.pathname === "/.well-known/oauth-authorization-server") return addDeviceMetadata(response, env.APP_ORIGIN);
return response;
} } satisfies ExportedHandler<Env>;
Expand Down
13 changes: 8 additions & 5 deletions packages/api/test/mcp-events.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl
const crossTenant = await diagnosis(otherMatch.occurrence!.id);
expect(crossTenant.isError).toBe(true);
expect(crossTenant.content).toEqual(missing.content);
expect((await diagnosis(empty, { ...auth, scopes: [] })).isError).toBe(true);
expect((await diagnosis(empty, { ...auth, userId: crypto.randomUUID() })).isError).toBe(true);
expect((await request("tools/call", { name: "read_event_delivery_diagnostics", arguments: { occurrenceId: empty } }, { ...auth, scopes: [] })).status).toBe(403);
expect((await request("tools/call", { name: "read_event_delivery_diagnostics", arguments: { occurrenceId: empty } }, { ...auth, userId: crypto.randomUUID() })).status).toBe(401);

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

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