diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 9465e47f..0b43a584 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -3511,6 +3511,8 @@ export interface operations { clientName: string; scopes: string[]; selectedScopes: string[]; + unavailableSavedScopes: string[]; + reconnect: boolean; request: string; signature: string; expiresAt: string; diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index 058249ce..e27f7db0 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -1,3 +1,4 @@ +import { initialIntegrationOverrides } from "./oauth-reconnect"; import { activeVmAuthorization } from "./vm-auth"; import { connectionAccess, requiredIntegrationScope, type AgentIntegration, type ConnectionPolicy } from "./agent-integration-access"; export { connectionAccess, requiredIntegrationScope, type AgentIntegration } from "./agent-integration-access"; @@ -78,9 +79,9 @@ export class AgentApiService { if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) { kind = "oauth"; subject = auth.oauthGrantId; } else throw invalidIdentity(); - const row = (await this.database.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version) - VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject - RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!; + const row = (await this.database.pool.query(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,integration_overrides) + VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject + RETURNING id,user_id,session_version,revoked_at,integration_overrides,disabled_scopes`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion, JSON.stringify(initialIntegrationOverrides(auth.initialIntegrationDenials))])).rows[0]!; if (row.revoked_at || row.user_id !== auth.userId || row.session_version !== auth.sessionVersion) throw invalidIdentity(); return {id: row.id, kind, policy: row, scopes: auth.scopes}; } diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index f3f19523..73495186 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,3 +1,4 @@ +import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect"; import { lockMcpEventGrant } from "./postgres/mcp-event-outbox"; import { eventPayloadSchema, eventProtocolName, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput } from "./mcp-event-contracts"; import { subscribeMcpEvent, unsubscribeMcpEvent } from "./mcp-event-subscriptions"; @@ -620,7 +621,9 @@ export class ApiService { if (scopes.includes(integration.requiredScope)) delete integrationOverrides[integration.id]; else if (edit.integrationOverrides?.[integration.id] === false || (integration.available && integration.policy !== "disabled")) integrationOverrides[integration.id] = false; } - const result = await databaseFor(this.env).pool.query(` + const result = await databaseFor(this.env).transaction(async sql => { + await lockOAuthPolicy(sql, this.auth); + return sql.query(` INSERT INTO app.agent_identities AS i(tenant_id,kind,subject,user_id,session_version,disabled_scopes,scope_overrides,integration_overrides,permissions_revision) SELECT $1,'oauth',$2,$3,$4,'{}',$5,$6,1 WHERE coalesce($7::integer,0)=0 OR EXISTS (SELECT 1 FROM app.agent_identities WHERE tenant_id=$1 AND kind='oauth' AND subject=$2) @@ -628,6 +631,7 @@ export class ApiService { integration_overrides=excluded.integration_overrides,permissions_revision=i.permissions_revision+1 WHERE i.revoked_at IS NULL AND i.user_id=excluded.user_id AND ($7 IS NULL OR i.permissions_revision=$7) RETURNING permissions_revision`, [this.auth.tenantId, grantId, this.auth.userId, this.auth.sessionVersion, [...new Set(scopes)], JSON.stringify(integrationOverrides), edit.expectedRevision ?? client.revision]); + }); if (!result.rowCount) throw new ServiceError(409, "conflict", "Connection permissions changed. Reload permissions."); return { ok: true }; } @@ -645,16 +649,17 @@ export class ApiService { const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope, `${row.name} integration access`])); return publicValue(z.array(authorizedClient), grants.map(grant => { const row = byGrant.get(grant.id), grantedScopes = normalizeScopes(grant.scope); + const integrationOverrides = row?.integration_overrides ?? initialIntegrationOverrides(grant.metadata?.initialIntegrationDenials); const baseScopes = row?.scope_overrides ?? grantedScopes.filter(scope => !row?.disabled_scopes.includes(scope)); const baselineScopes = integrations.filter(integration => integration.policy === "baseline" && integration.available).map(integration => integration.requiredScope); const scopes = [...new Set([...baseScopes,...baselineScopes])].filter(scope => { const id = scope.match(integrationScopePattern)?.[1]; - return !row?.disabled_scopes.includes(scope) && (!id || row?.integration_overrides?.[id] !== false); + return !row?.disabled_scopes.includes(scope) && (!id || integrationOverrides[id] !== false); }); const availableScopes = [...new Set([...globallyAvailable, ...scopes])]; return { grantId: grant.id, clientId: grant.clientId, clientName: row?.display_name ?? byId.get(grant.clientId)?.clientName ?? grant.clientId, appName: byId.get(grant.clientId)?.clientName ?? grant.clientId, availableScopes, scopeLabels, scopes, revision: row?.permissions_revision ?? 0, - integrationOverrides: row?.integration_overrides ?? {}, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), + integrationOverrides, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }; })); } @@ -665,6 +670,7 @@ export class ApiService { do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId,{limit:100,cursor}); found ||= page.items.some(grant=>grant.id===grantId && (grant.metadata as any)?.tenantId===this.auth.tenantId); cursor=page.cursor; } while(cursor && !found); if(!found) throw new ServiceError(404,"not_found","Authorization not found"); await databaseFor(this.env).transaction(async sql => { + await lockOAuthPolicy(sql, this.auth); await lockMcpEventGrant(sql, this.auth.tenantId, grantId); await sql.query(`UPDATE app.mcp_event_subscriptions SET status='stopped',previous_encrypted_secret=NULL,rotated_at=NULL WHERE tenant_id=$1 AND user_id=$2 AND grant_id=$3 AND status='active'`, [this.auth.tenantId, this.auth.userId, grantId]); diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 3a54fab8..bd74fd03 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -3,7 +3,7 @@ import { integrationConsentLabels } from "./agent-api"; import { ACCESS_SCOPES } from "./access-tokens"; import { connectionFor, originalBrowser, startConnection, connectionDestination } from "./oauth-continuation"; import { inspectDevice, decideDevice, deviceConsentSignature, safeEqual } from "./device-oauth"; -import { consentPreview, consentDecision, consentPreviewInput, consentDecisionInput } from "./consent-api"; +import { ConsentPreviewError, consentPreview, consentDecision, consentPreviewInput, consentDecisionInput } from "./consent-api"; import { serialize } from "hono/utils/cookie"; import { z } from "zod"; import { AuthRepository } from "./postgres/auth-repository"; @@ -135,8 +135,11 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (!session) return failure(401, "Sign in before authorizing a client."); try { const data = action === "consent-preview" ? await consentPreview(env, session, consentPreviewInput.parse(input), request) : await consentDecision(env, session, consentDecisionInput.parse(input)); - return data ? authJson(data) : failure(400, "This authorization request is invalid, expired, or already completed. Start a new connection from your MCP client."); - } catch { return failure(400, "This authorization request could not be validated. Return to the browser where you started connecting, or start a new connection from your MCP client."); } + return data ? authJson(data) : failure(400, "This approval is no longer current. Reload the request and review the permissions again. If the connection link has expired or was already used, start Reconnect in your MCP client."); + } catch (error) { + if (error instanceof ConsentPreviewError) return failure(400, error.message); + return failure(400, "Factorize couldn't validate this connection. Start Reconnect in your MCP client and use the fresh authorization link."); + } } if (action === "logout") { if (session) await new IdentityRepository(databaseFor(env), session.tenantId).revoke(session.userId); diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index 01f185ef..14e35403 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -7,12 +7,22 @@ import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; import type { Env, OAuthProps } from "./types"; import type { Session } from "./session"; +import { integrationForScope, lockOAuthPolicy, reconnectPreferences, type ReconnectRevision } from "./oauth-reconnect"; import { AGENT_SCOPES, normalizeScopes } from "./access-tokens"; export const consentPreviewInput = z.object({ authorizationQuery: z.string().min(1).max(8192) }).strict(); export const consentDecisionInput = z.object({ request: z.string().min(1).max(16384), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]), scopes: z.array(z.string()) }).strict(); -export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), selectedScopes: z.array(z.string()), request: z.string(), signature: z.string(), expiresAt: z.string(), integrationLabels: z.array(z.object({ scope: z.string(), name: z.string(), description: z.string().nullable() })).optional() }); +export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), selectedScopes: z.array(z.string()), unavailableSavedScopes: z.array(z.string()), reconnect: z.boolean(), request: z.string(), signature: z.string(), expiresAt: z.string(), integrationLabels: z.array(z.object({ scope: z.string(), name: z.string(), description: z.string().nullable() })).optional() }); export const consentDecisionResponse = z.object({ redirectTo: z.string() }); const supported: readonly string[] = AGENT_SCOPES; +export class ConsentPreviewError extends Error {} +type ConsentEnvelope = { + parsed: AuthRequest; + expiresAt: number; + nonce: string; + connection?: string; + allowedScopes?: string[]; + policyVersion: ReconnectRevision | null; +}; const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))); const decode = (value: string) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)))); const binding = (payload: string, session: Session) => `${payload}.${session.tenantId}.${session.userId}.${session.sessionVersion}`; @@ -23,41 +33,77 @@ export async function consentPreview(env: Env, session: Session, input: z.infer< const connectionId = url.searchParams.get("connection"); const connection = connectionId ? await connectionFor(env, connectionId) : null; if (connectionId) { - if (!connection || connection.kind !== "callback" || !browserRequest || !await originalBrowser(browserRequest, env, connection) || connection.user_id && connection.user_id !== session.userId) return null; + if (!connection || connection.kind !== "callback") { + throw new ConsentPreviewError("This connection link expired or was already used. Start Reconnect in your MCP client and open its new authorization link."); + } + if (!browserRequest || !await originalBrowser(browserRequest, env, connection) || connection.user_id && connection.user_id !== session.userId) { + throw new ConsentPreviewError("Open the new authorization link in the browser and Factorize account where you started connecting. If that browser is unavailable, start Reconnect again in your MCP client."); + } url.searchParams.delete("connection"); - if (url.pathname + url.search !== connection.destination) return null; + if (url.pathname + url.search !== connection.destination) throw new ConsentPreviewError("This link does not match the pending connection. Start Reconnect again in your MCP client."); await databaseFor(env).pool.query("UPDATE app.oauth_connections SET user_id=$2 WHERE id=$1 AND (user_id IS NULL OR user_id=$2)", [connection.id, session.userId]); } const parsed = await env.OAUTH_PROVIDER.parseAuthRequest(new Request(url)); const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); - if (!client) return null; + if (!client || !matchesRegisteredRedirect(parsed.redirectUri, client.redirectUris) || parsed.responseType !== "code" || !parsed.codeChallenge || parsed.codeChallengeMethod !== "S256") { + throw new ConsentPreviewError("The client registration or callback could not be verified. Start Reconnect again from your MCP client."); + } + if (parsed.scope.some(scope => !supported.includes(scope) && !isIntegrationScope(scope))) { + throw new ConsentPreviewError("The client requested an unsupported Factorize permission. Update the scope request in your MCP client, then reconnect."); + } + const scopedRequest = url.searchParams.has("scope"); + // Omitted scope means Factorize can offer its ordinary owner-selectable + // scopes. An explicit scope parameter is always an upper bound, even if empty. + const scopes = normalizeScopes(scopedRequest ? parsed.scope : supported); + const integrationLabels = await integrationConsentLabels(env, session.tenantId, scopes); + const preferences = await reconnectPreferences(env, session, parsed); + const defaultPreset = preferences ? undefined : (await databaseFor(env).pool.query<{scopes:string[]}>( + "SELECT scopes FROM app.permission_presets WHERE tenant_id=$1 AND is_default=true", [session.tenantId], + )).rows[0]; + const preferredScopes = preferences?.preferredScopes ?? defaultPreset?.scopes ?? (scopedRequest ? scopes : []); + const selectedScopes = scopes.filter(scope => preferredScopes.includes(scope)); + const unavailableSavedScopes = preferences?.preferredScopes.filter(scope => !scopes.includes(scope)) ?? []; const expiresAt = Math.min(session.exp, Math.floor(Date.now() / 1000) + 600, connection ? Math.floor(connection.expires_at.getTime() / 1000) : Infinity); await databaseFor(env).pool.query("DELETE FROM app.oauth_consent_previews WHERE expires_at !supported.includes(scope) && !isIntegrationScope(scope))) return null; - const requestedScopes = parsed.scope; - const integrationLabels = await integrationConsentLabels(env, session.tenantId, requestedScopes); - const scopes = normalizeScopes(requestedScopes); - const defaultPreset = (await databaseFor(env).pool.query<{scopes:string[]}>("SELECT scopes FROM app.permission_presets WHERE tenant_id=$1 AND is_default=true", [session.tenantId])).rows[0]; - const selectedScopes = defaultPreset ? scopes.filter(scope => defaultPreset.scopes.includes(scope)) : scopes; - return { integrationLabels, clientName: client.clientName ?? "this client", scopes, selectedScopes, request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; + const request = encode({ parsed, expiresAt, nonce, connection: connectionId ?? undefined, allowedScopes: scopes, policyVersion: preferences?.version ?? null } satisfies ConsentEnvelope); + return { integrationLabels, clientName: client.clientName ?? "this client", scopes, selectedScopes, unavailableSavedScopes, + reconnect: !!preferences, request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; } export async function consentDecision(env: Env, session: Session, input: z.infer) { if (!env.OAUTH_PROVIDER || !equal(input.signature, await hmac(binding(input.request, session), env.SESSION_SIGNING_SECRET))) return null; - let envelope: { parsed: AuthRequest; expiresAt: number; nonce: string; connection?: string }; + let envelope: ConsentEnvelope; try { envelope = decode(input.request); } catch { return null; } if (!Number.isFinite(envelope.expiresAt) || envelope.expiresAt <= Math.floor(Date.now() / 1000)) return null; const parsed = envelope.parsed; // Revalidate client registration and redirect URI before grant issuance. const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); if (!client || !matchesRegisteredRedirect(parsed.redirectUri, client.redirectUris)) return null; - const allowed = new Set(normalizeScopes(parsed.scope.filter(scope => supported.includes(scope) || isIntegrationScope(scope)))); + const allowed = new Set(normalizeScopes(envelope.allowedScopes ?? parsed.scope)); const selected = normalizeScopes(input.scopes); const issuedScopes = selected; if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !(AGENT_SCOPES as readonly string[]).includes(scope) && !isIntegrationScope(scope))) return null; return databaseFor(env).transaction(async transaction => { + const initialIntegrationDenials = new Set(); + if (input.decision === "allow") { + await lockOAuthPolicy(transaction, session); + const current = await reconnectPreferences(env, session, parsed, transaction); + // Refuse stale approvals without consuming the preview or connection. A + // new review must display the latest settings before consent can proceed. + if (envelope.policyVersion === undefined || + envelope.policyVersion?.grantId !== current?.version.grantId || + envelope.policyVersion?.revision !== current?.version.revision) return null; + const selectedIntegrations = new Set(issuedScopes.map(integrationForScope)); + for (const id of current?.deniedIntegrations ?? []) initialIntegrationDenials.add(id); + // An unchecked integration is an explicit denial even when the global + // baseline could otherwise grant it via proxy:use alone. + for (const scope of allowed) { + const id = integrationForScope(scope); + if (id && !selectedIntegrations.has(id)) initialIntegrationDenials.add(id); + } + for (const id of selectedIntegrations) if (id) initialIntegrationDenials.delete(id); + } const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]); if (!preview.rows.length) return null; if (envelope.connection) { @@ -66,8 +112,9 @@ export async function consentDecision(env: Env, session: Session, input: z.infer } if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; } await integrationConsentLabels(env, session.tenantId, issuedScopes); - const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: issuedScopes, authMethod: "oauth" }; - const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: issuedScopes, props, revokeExistingGrants: false }); + const denied = initialIntegrationDenials.size ? { initialIntegrationDenials: [...initialIntegrationDenials] } : {}; + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: issuedScopes, authMethod: "oauth", ...denied }; + const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId, ...denied }, scope: issuedScopes, props, revokeExistingGrants: false }); return { redirectTo }; }); } diff --git a/packages/api/src/oauth-reconnect.ts b/packages/api/src/oauth-reconnect.ts new file mode 100644 index 00000000..101fb31b --- /dev/null +++ b/packages/api/src/oauth-reconnect.ts @@ -0,0 +1,74 @@ +import type { GrantSummary, AuthRequest } from "@cloudflare/workers-oauth-provider"; +import { integrationScopePattern } from "./agent-api-contracts"; +import { normalizeScopes } from "./access-tokens"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { matchesRegisteredRedirect } from "./oauth-continuation"; +import type { Env } from "./types"; +import type { Session } from "./session"; + +type ReconnectPolicy = { + subject: string; + disabled_scopes: string[]; + scope_overrides: string[] | null; + integration_overrides: Record; + revoked_at: Date | null; + permissions_revision: number; +}; + +export function initialIntegrationOverrides(ids: unknown): Record { + return Object.fromEntries(Array.isArray(ids) ? ids.filter((id): id is string => + typeof id === "string" && integrationScopePattern.test(`integration:${id}:1`)).map(id => [id, false]) : []); +} + +export function integrationForScope(scope: string) { + return integrationScopePattern.exec(scope)?.[1]; +} + +export type ReconnectRevision = { grantId: string; revision: number }; + +export async function lockOAuthPolicy(db: DatabaseClient, session: Pick) { + // Consent does not have a grant ID yet. Use the owner/team key shared with + // permission edits and revocation, including before an identity row exists. + await db.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`oauth-policy:${session.tenantId}:${session.userId}`]); +} + +export async function reconnectPreferences(env: Env, session: Session, request: AuthRequest, db?: DatabaseClient) { + if (!env.OAUTH_PROVIDER) return null; + const grants: GrantSummary[] = []; + const now = Math.floor(Date.now() / 1000); + let cursor: string | undefined; + // A URL client ID may be shared across multiple client installations. Keep + // its defaults tied to the same exact redirect as the provider does. + const exactRedirect = /^https?:\/\//.test(request.clientId); + do { + const page = await env.OAUTH_PROVIDER.listUserGrants(session.userId, { cursor, limit: 100 }); + grants.push(...page.items.filter(grant => + grant.userId === session.userId && grant.clientId === request.clientId && + grant.metadata?.tenantId === session.tenantId && (!grant.expiresAt || grant.expiresAt > now) && + (exactRedirect ? grant.redirectUri === request.redirectUri : + !grant.redirectUri || matchesRegisteredRedirect(request.redirectUri, [grant.redirectUri])), + + )); + cursor = page.cursor; + } while (cursor); + if (!grants.length) return null; + const { rows } = await (db ?? databaseFor(env).pool).query( + `SELECT subject,disabled_scopes,scope_overrides,integration_overrides,revoked_at,permissions_revision + FROM app.agent_identities WHERE tenant_id=$1 AND user_id=$2 AND kind='oauth' AND subject=ANY($3)`, + [session.tenantId, session.userId, grants.map(grant => grant.id)], + ); + const policies = new Map(rows.map(row => [row.subject, row])); + const grant = grants.sort((a, b) => b.createdAt-a.createdAt || b.id.localeCompare(a.id)) + .find(item => !policies.get(item.id)?.revoked_at); + if (!grant) return null; + const policy = policies.get(grant.id); + const overrides = policy?.integration_overrides ?? initialIntegrationOverrides(grant.metadata?.initialIntegrationDenials); + return { + version: { grantId: grant.id, revision: policy?.permissions_revision ?? 0 } satisfies ReconnectRevision, + preferredScopes: normalizeScopes(policy?.scope_overrides ?? grant.scope).filter(scope => { + const integration = integrationForScope(scope); + return !policy?.disabled_scopes.includes(scope) && (!integration || overrides[integration] !== false); + }), + deniedIntegrations: Object.keys(overrides).filter(id => overrides[id] === false), + }; +} diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index c1013db2..663d736e 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -40,6 +40,8 @@ export type OAuthProps = { /** Stable identifier for the OAuth authorization grant; never a bearer token. */ oauthGrantId?: string; oauthClientId?: string; + /** Explicit integration denials carried to this grant at browser consent. */ + initialIntegrationDenials?: string[]; /** Expiry of the presented, verified OAuth access token. */ oauthExpiresAt?: number; vmGrantId?: string; diff --git a/packages/api/src/vm-permissions.ts b/packages/api/src/vm-permissions.ts index 85bac938..825a10b7 100644 --- a/packages/api/src/vm-permissions.ts +++ b/packages/api/src/vm-permissions.ts @@ -4,6 +4,7 @@ import { integrationScopePattern } from "./agent-api-contracts"; import { AgentApiError } from "./agent-api-error"; import type { Database, DatabaseClient } from "./postgres/database"; import type { OAuthProps } from "./types"; +import { initialIntegrationOverrides } from "./oauth-reconnect"; import { z } from "zod"; export const vmPermissionSource = z.union([ @@ -75,7 +76,7 @@ export async function resolveVmPermissions(db: DatabaseClient, auth: OAuthProps, const integration = integrations.get(scope); if (!integration || !integration.available || integration.policy === "disabled" || !effective.has("proxy:use")) throw forbidden(); if (auth.authMethod === "oauth") { - if (connectionAccess(integration, [...effective], policy ?? { disabled_scopes: [], integration_overrides: {} }) !== "granted") throw forbidden(); + if (connectionAccess(integration, [...effective], policy ?? { disabled_scopes: [], integration_overrides: initialIntegrationOverrides(auth.initialIntegrationDenials) }) !== "granted") throw forbidden(); } else if (!effective.has(scope)) { throw forbidden(); } diff --git a/packages/api/test/consent-api.test.ts b/packages/api/test/consent-api.test.ts index e34af803..6b064c20 100644 --- a/packages/api/test/consent-api.test.ts +++ b/packages/api/test/consent-api.test.ts @@ -4,10 +4,19 @@ import { decideDevice, deviceAuthorization, inspectDevice } from "../src/device- import type { Env } from "../src/types"; const session = { tenantId: "tenant", userId: "owner", email: "owner@example.test", sessionVersion: 2, exp: Math.floor(Date.now() / 1000) + 3600 }; const parsed = { responseType: "code", clientId: "client", redirectUri: "https://client.test/callback", scope: ["team:read", "triggers:read", "integrations:read", "triggers:read", "triggers:write", "triggers:write", "triggers:write"], state: "state", codeChallenge: "challenge", codeChallengeMethod: "S256", resource: "https://factorize.test/mcp", issuer: "https://factorize.test" }; -function fixture(defaultPreset?: string[]) { +const queryWithScope = { authorizationQuery: "client_id=client&scope=fixture" }; +const deniedId = "18a2410e-ea09-4fe0-af8a-719c0c91e6e2"; +const integrationScope = `integration:${deniedId}:1`; +function fixture(defaultPreset?: string[], reconnect?: { approved: string[]; saved: string[]; denied?: boolean; revision?: number }) { const values = new Map(); const used = new Set(); const query = vi.fn(async (sql: string, args: unknown[]) => { + if (sql.includes("pg_advisory_xact_lock")) return { rows: [] }; + if (sql.includes("FROM app.agent_identities")) return { rows: reconnect ? [{ + subject: "previous-grant", scope_overrides: reconnect.saved, disabled_scopes: [], integration_overrides: reconnect.denied ? { [deniedId]: false } : {}, revoked_at: null, permissions_revision: reconnect.revision ?? 1, + }] : [] }; + if (sql.includes("FROM app.agent_integrations")) return { rows: [{ id: deniedId, epoch: 1, available: true, policy: "baseline", name: "Fixture integration", description: null }] }; + if (sql.includes("FROM app.oauth_connections")) return { rows: [] }; if (sql.startsWith("SELECT scopes FROM app.permission_presets")) return { rows: defaultPreset ? [{ scopes: defaultPreset }] : [] }; if (sql.startsWith("INSERT INTO app.oauth_consent_previews") || sql.startsWith("DELETE FROM app.oauth_consent_previews")) return { rows: [] }; @@ -17,13 +26,15 @@ function fixture(defaultPreset?: string[]) { used.add(id); return { rows: [{ id }] }; }); - const oauth = { parseAuthRequest: vi.fn(async () => parsed), lookupClient: vi.fn(async () => ({ clientId: "client", clientName: "External client", redirectUris: [parsed.redirectUri], tokenEndpointAuthMethod: "none" })), completeAuthorization: vi.fn(async (_options: unknown) => ({ redirectTo: parsed.redirectUri + "?code=authorized&state=state" })) }; + const oauth = { parseAuthRequest: vi.fn(async () => parsed), listUserGrants: vi.fn(async () => ({ items: reconnect ? [{ + id: "previous-grant", clientId: parsed.clientId, userId: session.userId, metadata: { tenantId: session.tenantId }, redirectUri: parsed.redirectUri, scope: reconnect.approved, createdAt: Math.floor(Date.now() / 1000) - 60, + }] : [] })), lookupClient: vi.fn(async () => ({ clientId: "client", clientName: "External client", redirectUris: [parsed.redirectUri], tokenEndpointAuthMethod: "none" })), completeAuthorization: vi.fn(async (_options: unknown) => ({ redirectTo: parsed.redirectUri + "?code=authorized&state=state" })) }; const env = { DATABASE: { pool: { query }, transaction: async (work: any) => work({ query }) }, APP_ORIGIN: "https://factorize.test", SESSION_SIGNING_SECRET: "test-signing", OAUTH_PROVIDER: oauth, OAUTH_KV: { get: async (key: string, type?: string) => { const value = values.get(key); return value ? type === "json" ? JSON.parse(value) : value : null; }, put: async (key: string, value: string) => { values.set(key, value); }, delete: async (key: string) => { values.delete(key); } } } as unknown as Env; return { env, oauth }; } describe("static consent support", () => { it("binds expiring decisions to owner, tenant and session version; enforces requested scopes and current registered redirects", async () => { - const { env, oauth } = fixture(), preview = (await consentPreview(env, session, { authorizationQuery: "client_id=client&redirect_uri=https%3A%2F%2Fclient.test%2Fcallback" }))!; + const { env, oauth } = fixture(), preview = (await consentPreview(env, session, queryWithScope))!; expect(preview.clientName).toBe("External client"); expect(preview.selectedScopes).toEqual(preview.scopes); const input = { request: preview.request, signature: preview.signature, decision: "allow" as const, scopes: ["team:read", "triggers:read", "integrations:read"] }; @@ -38,7 +49,7 @@ describe("static consent support", () => { }); it("issues the approved default preset scopes", async () => { const { env, oauth } = fixture(["team:read"]); - const preview = (await consentPreview(env, session, { authorizationQuery: "client_id=client" }))!; + const preview = (await consentPreview(env, session, queryWithScope))!; expect(preview.selectedScopes).toEqual(["team:read"]); const input = { request: preview.request, signature: preview.signature, decision: "allow" as const, scopes: preview.selectedScopes }; expect((await consentDecision(env, session, input))?.redirectTo).toContain("code=authorized"); @@ -49,12 +60,95 @@ describe("static consent support", () => { it("expires consent bindings and preserves state and issuer on denial", async () => { const { env } = fixture(); vi.useFakeTimers(); - try { const preview = (await consentPreview(env, session, { authorizationQuery: "client_id=client" }))!; + try { const preview = (await consentPreview(env, session, queryWithScope))!; const input = { request: preview.request, signature: preview.signature, decision: "deny" as const, scopes: [] }; const redirect = new URL((await consentDecision(env, session, input))!.redirectTo); expect(redirect.searchParams.get("state")).toBe("state"); expect(redirect.searchParams.get("iss")).toBe(env.APP_ORIGIN); expect(redirect.searchParams.get("error")).toBe("access_denied"); vi.advanceTimersByTime(601_000); expect(await consentDecision(env, session, input)).toBeNull(); } finally { vi.useRealTimers(); } }); + it("carries saved scope additions into a new owner-approved grant without replacing the old grant", async () => { + const reconnect = { approved: ["team:read"], saved: ["team:read", "triggers:write"] }; + const { env, oauth } = fixture(["integrations:read"], reconnect); + const preview = (await consentPreview(env, session, queryWithScope))!; + expect(preview).toMatchObject({ reconnect: true, selectedScopes: ["team:read", "triggers:write"], unavailableSavedScopes: [] }); + const input = { request: preview.request, signature: preview.signature, decision: "allow" as const, scopes: preview.selectedScopes }; + expect((await consentDecision(env, session, input))?.redirectTo).toContain("code=authorized"); + expect(oauth.completeAuthorization).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + scope: ["team:read", "triggers:write"], props: expect.objectContaining({ scopes: ["team:read", "triggers:write"] }), revokeExistingGrants: false, + })); + expect(reconnect.approved).toEqual(["team:read"]); + }); + + it("limits explicit requests and offers owner choices when the client omits scope", async () => { + const { env, oauth } = fixture(undefined, { approved: ["team:read"], saved: ["team:read", "triggers:write"] }); + oauth.parseAuthRequest.mockResolvedValue({ ...parsed, scope: ["team:read"] }); + const limited = (await consentPreview(env, session, queryWithScope))!; + expect(limited).toMatchObject({ scopes: ["team:read"], selectedScopes: ["team:read"], unavailableSavedScopes: ["triggers:write"] }); + oauth.parseAuthRequest.mockResolvedValue({ ...parsed, scope: [] }); + const selectable = (await consentPreview(env, session, { authorizationQuery: "client_id=client" }))!; + expect(selectable.scopes).toEqual(expect.arrayContaining(["team:read", "triggers:read", "triggers:write"])); + expect(selectable.selectedScopes).toEqual(["team:read", "triggers:write"]); + const chosen = ["team:read", "triggers:read", "triggers:write"]; + await consentDecision(env, session, { request: selectable.request, signature: selectable.signature, decision: "allow", scopes: chosen }); + expect(oauth.completeAuthorization).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + request: expect.objectContaining({ scope: [] }), scope: chosen, props: expect.objectContaining({ scopes: chosen }), + })); + }); + + it("carries an explicit integration block through reconnect until the owner selects its scope", async () => { + const { env, oauth } = fixture(undefined, { approved: ["proxy:use", integrationScope], saved: ["proxy:use", integrationScope], denied: true }); + oauth.parseAuthRequest.mockResolvedValue({ ...parsed, scope: ["proxy:use", integrationScope] }); + const unchanged = (await consentPreview(env, session, queryWithScope))!; + expect(unchanged.scopes).toContain(integrationScope); + expect(unchanged.selectedScopes).toEqual(["proxy:use"]); + await consentDecision(env, session, { request: unchanged.request, signature: unchanged.signature, decision: "allow", scopes: unchanged.selectedScopes }); + expect(oauth.completeAuthorization).toHaveBeenNthCalledWith(1, expect.objectContaining({ + scope: ["proxy:use"], metadata: { tenantId: session.tenantId, initialIntegrationDenials: [deniedId] }, + props: expect.objectContaining({ initialIntegrationDenials: [deniedId] }), + })); + const changed = (await consentPreview(env, session, queryWithScope))!; + await consentDecision(env, session, { request: changed.request, signature: changed.signature, decision: "allow", scopes: changed.scopes }); + expect(oauth.completeAuthorization).toHaveBeenNthCalledWith(2, expect.objectContaining({ + scope: ["proxy:use", integrationScope], metadata: { tenantId: session.tenantId }, + })); + }); + + it("records displayed baseline integrations left unchecked as explicit denials", async () => { + const { env, oauth } = fixture(undefined, { approved: ["proxy:use", integrationScope], saved: ["proxy:use", integrationScope] }); + oauth.parseAuthRequest.mockResolvedValue({ ...parsed, scope: ["proxy:use", integrationScope] }); + const preview = await consentPreview(env, session, queryWithScope); + expect(preview.selectedScopes).toEqual(["proxy:use", integrationScope]); + const result = await consentDecision(env, session, { request: preview.request, signature: preview.signature, decision: "allow", scopes: ["proxy:use"] }); + expect(result?.redirectTo).toContain("code=authorized"); + expect(oauth.completeAuthorization).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + scope: ["proxy:use"], props: expect.objectContaining({ initialIntegrationDenials: [deniedId] }), + })); + }); + + it("requires a fresh consent review after a saved permission edit", async () => { + const saved = { approved: ["proxy:use", integrationScope], saved: ["proxy:use", integrationScope], denied: true, revision: 1 }; + const { env, oauth } = fixture(undefined, saved); + oauth.parseAuthRequest.mockResolvedValue({ ...parsed, scope: ["proxy:use", integrationScope] }); + const original = await consentPreview(env, session, queryWithScope); + saved.revision += 1; + const refreshed = await consentPreview(env, session, queryWithScope); + const approve = (preview: typeof original) => consentDecision(env, session, { + request: preview.request, signature: preview.signature, decision: "allow", scopes: preview.selectedScopes, + }); + await expect(approve(original)).resolves.toBeNull(); + expect(oauth.completeAuthorization).not.toHaveBeenCalled(); + await expect(approve(refreshed)).resolves.toMatchObject({ redirectTo: expect.stringContaining("code=authorized") }); + expect(oauth.completeAuthorization).toHaveBeenCalledTimes(1); + }); + + it("gives an actionable expired-link response and accepts a fresh authorization", async () => { + const { env } = fixture(); + await expect(consentPreview(env, session, { + authorizationQuery: queryWithScope.authorizationQuery + "&connection=ab57c1b7-bdeb-45ae-a933-45686266070f", + })).rejects.toThrow("Start Reconnect in your MCP client"); + await expect(consentPreview(env, session, queryWithScope)).resolves.toMatchObject({ clientName: "External client" }); + }); + it("inspects only public device metadata and keeps grant/code state server-owned", async () => { const { env, oauth } = fixture(); delete env.DATABASE; const form = new FormData(); form.set("client_id", "client"); form.set("scope", "team:read triggers:read integrations:read"); const issued = await (await deviceAuthorization(new Request(env.APP_ORIGIN + "/oauth/device_authorization", { method: "POST", body: form }), env, oauth as any, ["team:read", "triggers:read", "integrations:read"])).json() as any; diff --git a/packages/api/test/oauth-onboarding.postgres.test.ts b/packages/api/test/oauth-onboarding.postgres.test.ts index a5f85373..d0f276fe 100644 --- a/packages/api/test/oauth-onboarding.postgres.test.ts +++ b/packages/api/test/oauth-onboarding.postgres.test.ts @@ -10,6 +10,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun let f: Awaited>, emails: string[] = []; const grant = vi.fn(async ({ request }: any) => ({ redirectTo: `${request.redirectUri}?code=grant&state=${request.state}` })); const oauth = { + listUserGrants: async () => ({ items: [] }), lookupClient: async (id: string) => id === "client" ? { clientId: id, clientName: "MCP CLI", redirectUris: ["http://127.0.0.1/callback"], tokenEndpointAuthMethod: "none" } : null, parseAuthRequest: async (request: Request) => { const q = new URL(request.url).searchParams; diff --git a/packages/api/test/protocol-api.postgres.test.ts b/packages/api/test/protocol-api.postgres.test.ts index b5695646..9c141857 100644 --- a/packages/api/test/protocol-api.postgres.test.ts +++ b/packages/api/test/protocol-api.postgres.test.ts @@ -12,10 +12,10 @@ describe.skipIf(!url)("cookie protocol APIs against PostgreSQL", { timeout: 30_0 try { const parsed = { responseType: "code", clientId: "client", redirectUri: "https://external.test/callback", scope: ["team:read", "triggers:read", "integrations:read"], state: "state", codeChallenge: "challenge", codeChallengeMethod: "S256", resource: f.env.APP_ORIGIN + "/mcp", issuer: f.env.APP_ORIGIN }; await f.db.pool.query("INSERT INTO app.permission_presets(tenant_id,id,name,scopes,is_default) VALUES($1,$2,'Read only',ARRAY['triggers:read'],true)",[f.tenantId,crypto.randomUUID()]); - const oauth = { parseAuthRequest: async () => parsed, lookupClient: async () => ({ clientId: "client", clientName: "CLI", redirectUris: [parsed.redirectUri] }), completeAuthorization: vi.fn(async (_input: unknown) => ({ redirectTo: parsed.redirectUri + "?code=issued" })) }; + const oauth = { listUserGrants: async () => ({ items: [] }), parseAuthRequest: async () => parsed, lookupClient: async () => ({ clientId: "client", clientName: "CLI", redirectUris: [parsed.redirectUri] }), completeAuthorization: vi.fn(async (_input: unknown) => ({ redirectTo: parsed.redirectUri + "?code=issued" })) }; f.env.OAUTH_PROVIDER = oauth as any; const request = (path: string, body: unknown, cookie = f.cookie) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { method: "POST", headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body) }), f.env, null, {} as ExecutionContext); - const previewResponse = await request("/api/v1/oauth/consent/preview", { authorizationQuery: "client_id=client" }); expect(previewResponse.status).toBe(200); const preview = await previewResponse.json() as any; + const previewResponse = await request("/api/v1/oauth/consent/preview", { authorizationQuery: "client_id=client&scope=team%3Aread+triggers%3Aread+integrations%3Aread" }); expect(previewResponse.status).toBe(200); const preview = await previewResponse.json() as any; expect(preview.selectedScopes).toEqual(["triggers:read"]); expect(preview.scopes).toEqual(parsed.scope); const input = { request: preview.request, signature: preview.signature, scopes: ["team:read", "triggers:read", "integrations:read"], decision: "allow" }; expect((await request("/api/v1/oauth/consent/decision", input)).status).toBe(200); expect(oauth.completeAuthorization).toHaveBeenCalledTimes(1); diff --git a/packages/api/test/vm-permissions.postgres.test.ts b/packages/api/test/vm-permissions.postgres.test.ts index 14d984a8..6bb10b46 100644 --- a/packages/api/test/vm-permissions.postgres.test.ts +++ b/packages/api/test/vm-permissions.postgres.test.ts @@ -103,6 +103,10 @@ describe.skipIf(!url)("VM grant persistence and delegation", () => { await expect(resolveVmPermissions(f.db.pool, auth, { scopes: ["triggers:read", "triggers:write"] })).rejects.toMatchObject({ status: 403 }); expect(await resolveVmPermissions(f.db.pool, auth, { scopes: [scope, "triggers:read"] })).toEqual({ scopes: [scope, "triggers:read"], presetId: null }); + const freshGrant = { ...auth, oauthGrantId: "fresh-client", initialIntegrationDenials: [integrationId] }; + await expect(resolveVmPermissions(f.db.pool, freshGrant, { scopes: [scope] })).rejects.toMatchObject({ status: 403 }); + await expect(resolveVmPermissions(f.db.pool, freshGrant, { scopes: ["triggers:read"] })).resolves.toMatchObject({ scopes: ["triggers:read"] }); + const repository = new VmGrantRepository(f.db.pool, f.tenantId); const vmScopes = ["vms:edit", "proxy:use", "triggers:read"]; const target = { provider_id: integrationId, provider_kind: "fly" as const, provider_epoch: 1, vm: "machine", vm_app: "app" }; diff --git a/packages/app/src/features/auth/consent.tsx b/packages/app/src/features/auth/consent.tsx index 5570d41c..71ee5cce 100644 --- a/packages/app/src/features/auth/consent.tsx +++ b/packages/app/src/features/auth/consent.tsx @@ -3,12 +3,61 @@ import { useState } from "react"; import { useQuery, useMutation } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf } from "./session"; + export function ConsentScreen() { - const authorizationQuery = location.search.slice(1), [selected, setSelected] = useState(null); - const preview = useQuery({ queryKey: ["consent", authorizationQuery], queryFn: async ({ signal }) => { const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 0, retry: false }); - const scopes = selected ?? preview.data?.selectedScopes ?? preview.data?.scopes ?? []; - const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } }); - return

Authorize {preview.data?.clientName ?? "a client"}

{preview.isPending &&

Validating authorization request…

}{preview.error &&

{preview.error.message}

} - {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Trigger writes may cause future schedule/webhook/lifecycle execution. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

} + const authorizationQuery = location.search.slice(1); + const [selection, setSelection] = useState<{ request: string; scopes: string[] }>(); + const preview = useQuery({ + queryKey: ["consent", authorizationQuery], + queryFn: async ({ signal }) => { + const { data, error } = await api.POST("/api/v1/oauth/consent/preview", { signal, body: { authorizationQuery } }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, + staleTime: Infinity, + retry: false, + }); + const data = preview.data; + const scopes = data && selection?.request === data.request ? selection.scopes : (data?.selectedScopes ?? data?.scopes ?? []); + const decision = useMutation({ + retry: false, + mutationFn: async (value: "allow" | "deny") => { + if (!data) throw new Error("Load the authorization request first."); + const { data: result, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: data.request, signature: data.signature, decision: value, scopes } }); + if (!result || error) throw new Error(messageOf(error)); + location.assign(result.redirectTo); + }, + }); + const reload = () => { + setSelection(undefined); + decision.reset(); + void preview.refetch(); + }; + return +

{data?.reconnect ? "Reconnect" : "Authorize"} {data?.clientName ?? "a client"}

+ {preview.isFetching &&

Validating authorization request…

} + {preview.error &&

{preview.error.message}

} + {data && !preview.isError && !preview.isFetching && <> +

{data.reconnect ? "Review your saved choices and select the permissions to grant to the new token. Existing tokens won’t gain permissions." : "Select the workspace permissions to grant to this client."} Write does not imply read. Trigger writes can cause future schedule or webhook processing.

+ {!!data.unavailableSavedScopes?.length &&

The client did not request these saved permissions: {data.unavailableSavedScopes.join(", ")}. To grant them, update the client’s scope request and reconnect again.

} +
+ Permissions + {data.scopes.map(scope => { + const integration = data.integrationLabels?.find(label => label.scope === scope); + return ; + })} +
+

Request expires {data.expiresAt}.

+ + + } + {decision.error &&

{decision.error.message}

} + {(decision.isError || preview.isError) && }
; } diff --git a/packages/app/src/features/settings/client-permissions.tsx b/packages/app/src/features/settings/client-permissions.tsx index 673dc9c6..80861aef 100644 --- a/packages/app/src/features/settings/client-permissions.tsx +++ b/packages/app/src/features/settings/client-permissions.tsx @@ -24,5 +24,5 @@ export function ClientPermissions({ client: initialClient, close }: { client: Au const { error } = await api.PUT("/api/v1/access/authorizations/{grantId}/permissions", { params: { path: { grantId: client.grantId } }, body: { scopes: allowed, expectedRevision: client.revision, ...(Object.keys(integrationOverrides).length && { integrationOverrides }) } }); if (error) throw new Error(messageOf(error)); }, onSuccess: close, onSettled: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); - return

Removing permissions takes effect immediately. To use permissions its token does not already carry, the client must reconnect and authorize again.

Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; + return

You can add or remove permissions here. Removal takes effect immediately. Additions are saved as choices for this connection: start Reconnect in the MCP client and review the choices in the new consent screen to issue a fresh token.

Agent API scopes{client.availableScopes.map(scope => )}
{save.error &&

{save.error.message}

}
; } diff --git a/packages/app/test/functional/protocol.spec.mjs b/packages/app/test/functional/protocol.spec.mjs index e7b746a7..6b376b96 100644 --- a/packages/app/test/functional/protocol.spec.mjs +++ b/packages/app/test/functional/protocol.spec.mjs @@ -63,3 +63,37 @@ test("device code entry recovers from an expired attempt with a new client code await page.getByRole("button", { name: "Deny device" }).click(); await page.getByRole("status").filter({ hasText: "Authorization denied" }).waitFor(); assert.deepEqual(decision, { userCode: "ABCD-2345", signature: "new-signature", decision: "deny" }); await context.close(); }); + +test("failed reconnect approval reloads the review and never submits a new consent automatically", async () => { + const { context, page } = await setup(); + try { + let previewCount = 0; + const approvals = []; + await page.route("**/api/v1/oauth/consent/preview", route => route.fulfill({ json: { + clientName: "External CLI", reconnect: true, scopes: ["team:read", "triggers:write"], selectedScopes: ["team:read"], + unavailableSavedScopes: ["triggers:read"], request: `request-${++previewCount}`, signature: "signature", + expiresAt: "2026-10-09T12:00:00Z", + } })); + await page.route("**/api/v1/oauth/consent/decision", route => { + approvals.push(route.request().postDataJSON()); + return approvals.length === 1 ? route.fulfill({ status: 400, json: { error: { code: "invalid_request", message: "Reload the request and review the permissions again." } } }) + : route.fulfill({ json: { redirectTo: origin + "/completed?code=issued" } }); + }); + await page.goto(origin + "/authorize?client_id=client&state=fresh&code_challenge=challenge"); + await page.getByRole("heading", { name: "Reconnect External CLI" }).waitFor(); + await page.getByRole("status").filter({ hasText: "The client did not request these saved permissions: triggers:read" }).waitFor(); + await page.getByLabel("triggers:write").check(); + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await page.getByRole("alert").waitFor(); + await page.getByRole("button", { name: "Reload authorization request" }).click(); + assert.equal(await page.getByLabel("triggers:write").isChecked(), false); + assert.equal(approvals.length, 1); + await page.getByRole("button", { name: "Allow", exact: true }).click(); + await page.waitForURL("**/completed?code=issued"); + assert.deepEqual(approvals.map(({ request, scopes }) => [request, scopes]), [ + ["request-1", ["team:read", "triggers:write"]], ["request-2", ["team:read"]], + ]); + } finally { + await context.close(); + } +}); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 247ad3d1..47115125 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -197,6 +197,8 @@ Source: https://docs.factorize.sh/troubleshooting/connection | Symptom | Action | | --- | --- | | Browser consent fails or is cancelled | Sign in to the intended Factorize account, restart authorization from the client, and approve the requested scopes. | +| The authorization link expired or was used | Start **Reconnect** in the MCP client and open its new authorization link. Keep approval in the same browser and Factorize account. If only the consent form expired, reload it and review the choices again. | +| Saved permissions are missing from consent | Open **Clients → Edit permissions** to save your choices, then reconnect the same registered client. If it explicitly requests a scope list, add the missing scopes to that client request. If it omits scope, choose from the Factorize API scopes in the browser. Existing access and refresh tokens cannot gain permissions. | | Client never connects | Confirm `https://app.factorize.sh/mcp`, remote Streamable HTTP and OAuth support. Open the client's MCP status view and authenticate; see [client-specific instructions](https://docs.factorize.sh/mcp/overview). | | `invalid_token` or access disappears | Reauthorize the client. Password reset, password change, or sign-out can invalidate delegated credentials. | | `insufficient_scope` | Reconnect and grant `triggers:read` to discover Events and occurrences, or `triggers:write` to manage Events and Triggers. Add integration scopes only when needed. | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index bc2ad30e..f2d05089 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2479,6 +2479,12 @@ paths: type: array items: type: string + unavailableSavedScopes: + type: array + items: + type: string + reconnect: + type: boolean request: type: string signature: @@ -2507,6 +2513,8 @@ paths: - clientName - scopes - selectedScopes + - unavailableSavedScopes + - reconnect - request - signature - expiresAt diff --git a/packages/docs/troubleshooting/connection.mdx b/packages/docs/troubleshooting/connection.mdx index a1570f58..86c21bd8 100644 --- a/packages/docs/troubleshooting/connection.mdx +++ b/packages/docs/troubleshooting/connection.mdx @@ -6,6 +6,8 @@ description: Recover MCP authorization, scopes, and integration access. | Symptom | Action | | --- | --- | | Browser consent fails or is cancelled | Sign in to the intended Factorize account, restart authorization from the client, and approve the requested scopes. | +| The authorization link expired or was used | Start **Reconnect** in the MCP client and open its new authorization link. Keep approval in the same browser and Factorize account. If only the consent form expired, reload it and review the choices again. | +| Saved permissions are missing from consent | Open **Clients → Edit permissions** to save your choices, then reconnect the same registered client. If it explicitly requests a scope list, add the missing scopes to that client request. If it omits scope, choose from the Factorize API scopes in the browser. Existing access and refresh tokens cannot gain permissions. | | Client never connects | Confirm `https://app.factorize.sh/mcp`, remote Streamable HTTP and OAuth support. Open the client's MCP status view and authenticate; see [client-specific instructions](/mcp/overview). | | `invalid_token` or access disappears | Reauthorize the client. Password reset, password change, or sign-out can invalidate delegated credentials. | | `insufficient_scope` | Reconnect and grant `triggers:read` to discover Events and occurrences, or `triggers:write` to manage Events and Triggers. Add integration scopes only when needed. | diff --git a/scripts/oauth-runtime.mjs b/scripts/oauth-runtime.mjs index a229833d..e88c60d3 100644 --- a/scripts/oauth-runtime.mjs +++ b/scripts/oauth-runtime.mjs @@ -176,8 +176,9 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo const clients = await send('/api/v1/access/authorized-clients', 'GET', undefined, owner); const connection = clients.json.find(client => client.clientId === clientId); assert.equal(connection.clientName, 'Release assistant'); - const integrationId = randomUUID(); + const integrationId = randomUUID(), deniedIntegrationId = randomUUID(); await db.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available) VALUES ($1,$2,'linear','linear','Linear',true)", [tenantId,integrationId]); + await db.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) VALUES ($1,$2,'github','local-fixture','Blocked fixture',true,'baseline')", [tenantId,deniedIntegrationId]); const permissionsPath = '/api/v1/access/authorizations/' + connection.grantId + '/permissions'; const change = (edit, headers = owner) => send(permissionsPath, 'PUT', JSON.stringify(edit), {...headers, 'Content-Type':'application/json'}); const integrationKey = 'integration:' + integrationId + ':1'; @@ -198,11 +199,18 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo freshQuery.set('scope', [...edit.scopes, 'proxy:use'].join(' ')); freshQuery.set('state', 'fixture-reauthorize'); freshQuery.set('code_challenge', createHash('sha256').update(freshVerifier).digest('base64url')); - const freshPreview = await json('/api/v1/oauth/consent/preview', {authorizationQuery: freshQuery.toString()}, owner); + const freshScreen = await send('/authorize?' + freshQuery, 'GET', undefined, owner); + assert.equal(freshScreen.status, 302, freshScreen.text); + const freshUrl = new URL(freshScreen.headers.location); + const freshCookie = freshScreen.headers['set-cookie'][0].split(';')[0]; + const freshOwner = { ...owner, Cookie: cookie + '; ' + freshCookie }; + const freshPreview = await json('/api/v1/oauth/consent/preview', {authorizationQuery: freshUrl.search.slice(1)}, freshOwner); assert.equal(freshPreview.status, 200, freshPreview.text); + assert.equal(freshPreview.json.reconnect, true); + assert.deepEqual(freshPreview.json.selectedScopes, edit.scopes); const freshConsent = await json('/api/v1/oauth/consent/decision', { - request: freshPreview.json.request, signature: freshPreview.json.signature, decision: 'allow', scopes: [...edit.scopes, 'proxy:use'], - }, owner); + request: freshPreview.json.request, signature: freshPreview.json.signature, decision: 'allow', scopes: [...freshPreview.json.selectedScopes, 'proxy:use'], + }, freshOwner); assert.equal(freshConsent.status, 200, freshConsent.text); const freshDestination = new URL(freshConsent.json.redirectTo); assert.equal(freshDestination.searchParams.get('state'), 'fixture-reauthorize'); @@ -212,6 +220,8 @@ export async function checkOAuth({ read: send, stream, db, tenantId, userId, coo }); assert.equal(freshExchange.status, 200, freshExchange.text); const freshBearer = { Authorization: 'Bearer '+freshExchange.json.access_token }; + const reflected = await reflect(freshBearer); + assert.equal(reflected.integrations.find(row => row.id === deniedIntegrationId).access, 'unavailable'); assert.equal((await reflect(freshBearer)).integrations.find(row => row.id === integrationId).access, 'granted'); assert.equal((await change({scopes: originalScopes, expectedRevision: 1})).status, 200); assert.equal((await reflect()).integrations.find(row => row.id === integrationId).access, 'unavailable');