|
| 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 | +} |
0 commit comments