From 872ab169e57881e81546afdccb5f825e885c2474 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 15:06:03 -0700 Subject: [PATCH] Challenge inactive MCP credentials and verify OAuth refresh grants --- packages/api/src/mcp-oauth-auth.ts | 97 +++++++++++ packages/api/src/mcp-oauth-scopes.ts | 38 ++++ packages/api/src/protected-api.ts | 31 +++- packages/api/src/worker.ts | 11 ++ packages/api/test/mcp-events.postgres.test.ts | 13 +- .../test/mcp-oauth-renewal.postgres.test.ts | 162 ++++++++++++++++++ packages/api/vitest.config.ts | 2 + scripts/oauth-runtime.mjs | 11 +- 8 files changed, 351 insertions(+), 14 deletions(-) create mode 100644 packages/api/src/mcp-oauth-auth.ts create mode 100644 packages/api/src/mcp-oauth-scopes.ts create mode 100644 packages/api/test/mcp-oauth-renewal.postgres.test.ts diff --git a/packages/api/src/mcp-oauth-auth.ts b/packages/api/src/mcp-oauth-auth.ts new file mode 100644 index 00000000..470cc5fe --- /dev/null +++ b/packages/api/src/mcp-oauth-auth.ts @@ -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 }; +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; +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 { + 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( + `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 { + 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, reportProviderRejection: boolean) { + let finish!: () => void; + const providerFinished = new Promise(resolve => { finish = resolve; }); + let transaction: Promise | 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; + } +} diff --git a/packages/api/src/mcp-oauth-scopes.ts b/packages/api/src/mcp-oauth-scopes.ts new file mode 100644 index 00000000..4c423cf2 --- /dev/null +++ b/packages/api/src/mcp-oauth-scopes.ts @@ -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(); +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"); +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 { + 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( + "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; +} diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 458f8276..abb874ec 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -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, readEventDeliveryDiagnosticsInput, readEventOccurrencesInput, subscribeEventInput, unsubscribeEventInput } from "./mcp-event-contracts"; import { appRegistrationInput, appRegistrationUpdate } from "./apps-contracts"; import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads"; @@ -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>["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") { @@ -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; @@ -96,8 +112,10 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (listenerAuth.oauthGrantId) { const token = await env.OAUTH_PROVIDER?.unwrapToken(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. }; @@ -274,7 +292,10 @@ export class ProtectedApiHandler extends WorkerEntrypoint { 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(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}; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index e27a04bb..fc91bd6b 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -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"; @@ -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({ ...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; diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index 9b5f62e7..546a5949 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -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_/); @@ -438,13 +438,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); diff --git a/packages/api/test/mcp-oauth-renewal.postgres.test.ts b/packages/api/test/mcp-oauth-renewal.postgres.test.ts new file mode 100644 index 00000000..5bf9c965 --- /dev/null +++ b/packages/api/test/mcp-oauth-renewal.postgres.test.ts @@ -0,0 +1,162 @@ +import { expect, it, vi } from "vitest"; +import { createHash, randomBytes } from "node:crypto"; +import worker from "../src/worker"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ + WorkerEntrypoint: class { constructor(readonly ctx: unknown, readonly env: unknown) {} }, + DurableObject: class {}, +})); + +const database = process.env.AUTH_TEST_DATABASE_URL; +const credentials = (token: string) => ({ Authorization: "Bearer " + token }); +const payload = async (response: Response) => { + const body = await response.text(); + return JSON.parse(response.headers.get("Content-Type")?.includes("text/event-stream") + ? body.split("\n").find(line => line.startsWith("data: "))!.slice(6) : body); +}; + +it.skipIf(!database)("challenges an expired bearer, refreshes the existing grant, and renews its MCP subscription", async () => { + const f = await loadingFixture(database!); + try { + const h = await harness(f); + const token = await h.authorize(); + const source = await f.seedEventTrigger(); + const subscription = { name: "factorize.occurrence", arguments: { event_id: source.definitionId }, + delivery: { url: "https://receiver.example.com/notify", mode: "webhook", secret: "whsec_" + randomBytes(32).toString("base64") } }; + const consumed = vi.fn(async (_url: string, init: RequestInit) => { + const { challenge } = JSON.parse(String(init.body)); + return Response.json({ challenge }); + }); + vi.stubGlobal("fetch", consumed); + const subscribe = (access: string, ttlMs: number) => h.rpc(access, "events/subscribe", { ...subscription, ttlMs }); + const first = await subscribe(token.access_token, 300_000); + expect(first.status, await first.clone().text()).toBe(200); + const initialSubscription = await payload(first); + const result = initialSubscription.result; + expect(result, JSON.stringify(initialSubscription)).toBeTruthy(); + const oldRow = (await f.db.pool.query("SELECT id,grant_id,expires_at FROM app.mcp_event_subscriptions")).rows[0]; + expect(oldRow?.id).toBeTruthy(); + + const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + (token.expires_in + 2) * 1000); + const expired = await h.rpc(token.access_token, "tools/call", { name: "list_triggers", arguments: {} }); + expect(expired.status).toBe(401); + expect(expired.headers.get("WWW-Authenticate")).toBe(`Bearer error="invalid_token", resource_metadata="${f.env.APP_ORIGIN}/.well-known/oauth-protected-resource/mcp"`); + const refresh = await h.refresh(token.refresh_token); + expect(refresh.status, await refresh.clone().text()).toBe(200); + const renewed = await refresh.json() as {access_token: string; refresh_token: string}; + const list = await h.rpc(renewed.access_token, "tools/call", { name: "list_triggers", arguments: {} }); + expect(list.status).toBe(200); + expect((await payload(list)).result.structuredContent.items).toHaveLength(1); + const next = await subscribe(renewed.access_token, 600_000); + expect(next.status, await next.clone().text()).toBe(200); + expect((await payload(next)).result).toBeTruthy(); + const rows = (await f.db.pool.query("SELECT id,grant_id,expires_at FROM app.mcp_event_subscriptions")).rows; + expect(rows).toHaveLength(1); + expect(rows[0].id).toBe(oldRow.id); + expect(rows[0].grant_id).toBe(oldRow.grant_id); + expect(rows[0].expires_at.getTime()).toBeGreaterThan(oldRow.expires_at.getTime()); + expect(consumed).toHaveBeenCalledTimes(1); + clock.mockRestore(); + + const narrow = await h.refresh(renewed.refresh_token, "team:read"); + expect(narrow.status).toBe(200); + const restricted = await narrow.json() as { access_token: string; refresh_token: string }; + const forbidden = await h.rpc(restricted.access_token, "tools/call", { name: "list_triggers", arguments: {} }); + expect(forbidden.status).toBe(403); + expect(forbidden.headers.get("WWW-Authenticate")).toContain('error="insufficient_scope", scope="triggers:read"'); + expect((await h.rpc(restricted.access_token, "tools/list", {})).status).toBe(200); + const badBusinessOperation = await h.rpc(renewed.access_token, "tools/call", { name: "get_event", arguments: { eventId: crypto.randomUUID() } }); + expect(badBusinessOperation.status).toBe(200); + expect((await payload(badBusinessOperation)).result.isError).toBe(true); + + await f.db.pool.query("UPDATE app.members SET session_version=session_version+1 WHERE tenant_id=$1 AND user_id=$2", [f.tenantId, f.userId]); + expect((await h.rpc(renewed.access_token, "tools/list", {})).status).toBe(401); + const inactive = await h.refresh(restricted.refresh_token); + expect(inactive.status).toBe(400); + expect(await inactive.json()).toMatchObject({ error: "invalid_grant" }); + } finally { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!database)("keeps a revoked authorization rejected by the resource and token endpoints", async () => { + const f = await loadingFixture(database!); + try { + const h = await harness(f); + const token = await h.authorize(); + const listing = await h.request("/api/v1/access/authorized-clients", "GET", undefined, { Cookie: f.cookie }); + const [grant] = await listing.json() as {grantId: string}[]; + await f.db.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,revoked_at) + VALUES($1,'oauth',$2,$3,$4,now())`, [f.tenantId, grant.grantId, f.userId, f.auth.sessionVersion]); + const beforeProviderCleanup = await h.refresh(token.refresh_token); + expect(beforeProviderCleanup.status).toBe(400); + expect(await beforeProviderCleanup.json()).toMatchObject({ error: "invalid_grant" }); + expect((await h.rpc(token.access_token, "tools/list", {})).status).toBe(401); + const revoked = await h.request(`/api/v1/access/authorizations/${grant.grantId}`, "DELETE", undefined, { Cookie: f.cookie, Origin: f.env.APP_ORIGIN }); + expect(revoked.status).toBe(200); + expect((await h.rpc(token.access_token, "tools/list", {})).status).toBe(401); + const refresh = await h.refresh(token.refresh_token); + expect(refresh.status).toBe(400); + expect(await refresh.json()).toMatchObject({ error: "invalid_grant" }); + expect((await f.db.pool.query("SELECT revoked_at FROM app.agent_identities WHERE subject=$1", [grant.grantId])).rows[0].revoked_at).toBeInstanceOf(Date); + } finally { + await f.cleanup(); + } +}); + +async function harness(f: Awaited>) { + delete f.env.OAUTH_PROVIDER; + const records = new Map(); + f.env.OAUTH_KV = { + async get(key: string, format: { type?: string } | string) { + const item = records.get(key); + return item ? (typeof format === "string" ? format : format?.type) === "json" ? JSON.parse(item.value) : item.value : null; + }, + async put(key: string, value: string, options?: { metadata?: unknown }) { records.set(key, { value, metadata: options?.metadata }); }, + async delete(key: string) { records.delete(key); }, + async list({ prefix }: { prefix?: string } = {}) { + return { list_complete: true, keys: [...records.entries()].filter(([key]) => key.startsWith(prefix ?? "")).map(([name, item]) => ({ name, metadata: item.metadata })) }; + }, + } as unknown as KVNamespace; + const origin = f.env.APP_ORIGIN; + const request = (path: string, method: string, body?: string, headers?: HeadersInit) => { + const requestHeaders = new Headers(headers); + requestHeaders.set("Host", new URL(origin).host); + return worker.fetch(new Request(origin + path, { method, headers: requestHeaders, body }), f.env, { waitUntil() {} } as unknown as ExecutionContext); + }; + const json = (path: string, data: unknown, headers = {}) => request(path, "POST", JSON.stringify(data), { "Content-Type": "application/json", ...headers }); + const registration = await json("/oauth/register", { client_name: "Renewal fixture", redirect_uris: ["http://127.0.0.1/callback"], + token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] }); + expect(registration.status, await registration.clone().text()).toBe(201); + const { client_id } = await registration.json() as {client_id: string}; + const tokenRequest = (params: Record) => request("/oauth/token", "POST", + new URLSearchParams({ client_id, resource: origin + "/mcp", ...params }).toString(), { "Content-Type": "application/x-www-form-urlencoded" }); + const authorize = async () => { + const verifier = randomBytes(32).toString("base64url"); + const redirect_uri = "http://127.0.0.1/callback", scopes = ["team:read", "triggers:read"]; + const authorizationQuery = new URLSearchParams({ response_type: "code", client_id, redirect_uri, resource: origin + "/mcp", scope: scopes.join(" "), + state: "fixture", code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256" }).toString(); + const owner = { Cookie: f.cookie, Origin: origin }; + const preview = await json("/api/v1/oauth/consent/preview", { authorizationQuery }, owner); + expect(preview.status, await preview.clone().text()).toBe(200); + const { request, signature } = await preview.json() as {request:string; signature:string}; + const consent = await json("/api/v1/oauth/consent/decision", { request, signature, decision: "allow", scopes }, owner); + expect(consent.status, await consent.clone().text()).toBe(200); + const { redirectTo } = await consent.json() as {redirectTo:string}; + const exchanged = await tokenRequest({ grant_type: "authorization_code", code: new URL(redirectTo).searchParams.get("code")!, redirect_uri, code_verifier: verifier }); + expect(exchanged.status, await exchanged.clone().text()).toBe(200); + return exchanged.json() as Promise<{ access_token: string; refresh_token: string; expires_in: number }>; + }; + const rpc = (access: string, method: string, params: Record) => json("/mcp", + { jsonrpc: "2.0", id: 1, method, params: { ...params, _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": { name: "fixture", version: "1" }, + "io.modelcontextprotocol/clientCapabilities": {}, + } } }, { ...credentials(access), Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method, + ...(typeof params.name === "string" && method === "tools/call" ? { "Mcp-Name": params.name } : {}) }); + const refresh = (refresh_token: string, scope?: string) => tokenRequest({ grant_type: "refresh_token", refresh_token, ...(scope ? { scope } : {}) }); + return { authorize, rpc, refresh, request }; +} diff --git a/packages/api/vitest.config.ts b/packages/api/vitest.config.ts index 8ba7dea5..52f17af9 100644 --- a/packages/api/vitest.config.ts +++ b/packages/api/vitest.config.ts @@ -4,6 +4,8 @@ import { BalancedValidationSequencer } from "./validation-sequencer"; export default defineConfig({ test: { + // The real OAuth provider imports the Worker entrypoint shim in protocol tests. + server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, // Isolated database fixtures spend part of their time waiting on PostgreSQL I/O. maxWorkers: Number(process.env.FACTORIZE_VITEST_WORKERS ?? Math.min(availableParallelism() + 1, 4)), hookTimeout: 30_000, diff --git a/scripts/oauth-runtime.mjs b/scripts/oauth-runtime.mjs index e645e4d6..177c67a5 100644 --- a/scripts/oauth-runtime.mjs +++ b/scripts/oauth-runtime.mjs @@ -189,8 +189,11 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo const saved = await change(edit); assert.equal(saved.status, 200, saved.text); assert.equal((await change(edit)).status, 409); - const blocked = await rpc('tools/call', {name:'list_triggers',arguments:{}}, 9); - assert.ok(blocked.error || blocked.result?.isError); + const challengeRequest = credentials => json('/mcp', { jsonrpc: '2.0', id: 9, method: 'tools/call', params: {name:'list_triggers',arguments:{}} }, + { ...credentials, Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-11-25' }); + const blocked = await challengeRequest(bearer); + assert.equal(blocked.status, 403, blocked.text); + assert.match(blocked.headers['www-authenticate'], /insufficient_scope.*scope="triggers:read"/); const reflect = async (credentials = bearer) => (await rpc('tools/call', {name:'get_api_reflection',arguments:{}}, 10, credentials)).result.structuredContent; assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'requestable'); @@ -240,7 +243,7 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo assert.equal((await form('/oauth/token', poll)).json.error, 'expired_token'); await db.query('UPDATE app.members SET session_version=2 WHERE tenant_id=$1 AND user_id=$2', [tenantId,userId]); assert.equal((await send('/api/v1/triggers', 'GET', undefined, bearer)).status, 401); - const revoked = await rpc('tools/call', { name: 'list_triggers', arguments: {} }, 4); assert.ok(revoked.error || revoked.result?.isError); + const revoked = await challengeRequest(bearer); assert.equal(revoked.status, 401); assert.match(revoked.headers['www-authenticate'], /invalid_token/); assert.equal((await send('/api/v1/triggers', 'GET', undefined, restBearer)).status, 401); - const revokedDevice = await rpc('tools/call', { name: 'list_triggers', arguments: {} }, 7, { Authorization: 'Bearer '+deviceToken.json.access_token }); assert.ok(revokedDevice.error || revokedDevice.result?.isError); + const revokedDevice = await challengeRequest({ Authorization: 'Bearer '+deviceToken.json.access_token }); assert.equal(revokedDevice.status, 401); }