diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 7571e18b2ea..8aac435e157 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -8794,6 +8794,57 @@ describeEmbeddedPostgres("tool access service", () => { } }); + it("answers a rate-limited managed GitHub sign-in start with 429 and retry guidance", async () => { + const company = await createCompany(db); + const userId = `github-rate-limited-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGitHubConnector(company.id, userId); + connector.startAuthorization = vi.fn(async () => { + throw new PaperclipCloudConnectorError( + "Paperclip Cloud connector rejected the request (operation=session, status=429, reason=RATE_LIMITED)", + "CONNECTOR_REQUEST_FAILED", + 429, + Date.now() + 30_000, + "RATE_LIMITED", + ); + }); + const githubDefinition = getConnectableAppDefinition("github")!; + const previousOwnershipAvailability = + githubDefinition.ownershipAvailability; + githubDefinition.ownershipAvailability = { + ...previousOwnershipAvailability, + platform_shared: true, + }; + try { + const app = createRouteApp( + db, + boardSessionActor(company.id, "owner", userId), + undefined, + { paperclipCloudConnector: connector }, + ); + const connected = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ + galleryKey: "github", + connectionMethodKey: "managed", + grantKind: "user", + name: "GitHub", + }); + + expect(connector.startAuthorization).toHaveBeenCalled(); + expect(connected.status).toBe(429); + expect(connected.body).toMatchObject({ + error: "GitHub sign-in is busy right now. Try again in a moment.", + code: "paperclip_cloud_connector_rate_limited", + }); + expect(connected.body.details.retryAfterSeconds).toBeGreaterThan(0); + expect(connected.body.details.retryAfterSeconds).toBeLessThanOrEqual(30); + expect(JSON.stringify(connected.body)).not.toContain("RATE_LIMITED"); + } finally { + githubDefinition.ownershipAvailability = previousOwnershipAvailability; + } + }); + it.each(["user", "organization"] as const)("builds one Workspace catalog from actual partial consent for a %s grant", async (grantKind) => { const company = await createCompany(db); const userId = `workspace-member-${randomUUID()}`; diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 3dedf46c813..aae8a71d8cd 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -13,8 +13,8 @@ import type { Db } from "@paperclipai/db"; import { companies, agents, connectionGrants, issueThreadInteractions, toolConnections, toolOauthStates } from "@paperclipai/db"; import type { ConnectionGrantKind, ToolOAuthStartResult } from "@paperclipai/shared"; import { getConnectableAppDefinition } from "@paperclipai/shared"; -import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; -import { isPaperclipCloudConnectorStrategy, paperclipCloudConnectorConsentAllowed, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { badRequest, conflict, forbidden, notFound, tooManyRequests, unprocessable } from "../../../errors.js"; +import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, paperclipCloudConnectorConsentAllowed, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { deriveVercelConnectSubject, vercelConnectCallbackUrl, VercelConnectClientError, type VercelConnectClient } from "../../vercel-connect.js"; import type { ConnectionSetupPolicy } from "../connections/setup-policy.js"; @@ -36,6 +36,18 @@ type Dependencies = { assertOAuthEndpointUrl: ReturnType["assertOAuthEndpointUrl"]; }; +function cloudConnectorStartHttpError(error: unknown, providerName: string, at: Date): unknown { + if (!(error instanceof PaperclipCloudConnectorError)) return error; + if (error.status !== 429 && error.brokerReason !== "RATE_LIMITED") return error; + const retryAfterSeconds = error.retryAt === undefined + ? undefined + : Math.max(1, Math.ceil((error.retryAt - at.getTime()) / 1000)); + return tooManyRequests(`${providerName} sign-in is busy right now. Try again in a moment.`, { + code: "paperclip_cloud_connector_rate_limited", + ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }), + }); +} + export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies) { const { now, getConnectionRow, setupPolicy, fixedPersonalIdentityForReconnect, currentCloudConnector, vercelConnect, ensureOAuthClient, oauthEndpointsForConnection, assertOAuthEndpointUrl } = dependencies; const { assertConnectorConnectionSetupEnabled, assertExperimentalConnectorSetupEnabled } = setupPolicy; @@ -395,16 +407,21 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies returnUri.pathname = "/api/tools/oauth/cloud-connector/callback"; returnUri.search = ""; returnUri.hash = ""; - const session = await cloudConnector.startAuthorization({ - subject: authorizationSubjectAgentId - ? `agent:${authorizationSubjectAgentId}` - : subjectUserId!, - companyId, - profile: managedProfile.id, - ...(managedProfile.id === "workspace.all" ? { scopes: requestedScopes! } : {}), - returnUri: returnUri.toString(), - returnState: state, - }); + let session; + try { + session = await cloudConnector.startAuthorization({ + subject: authorizationSubjectAgentId + ? `agent:${authorizationSubjectAgentId}` + : subjectUserId!, + companyId, + profile: managedProfile.id, + ...(managedProfile.id === "workspace.all" ? { scopes: requestedScopes! } : {}), + returnUri: returnUri.toString(), + returnState: state, + }); + } catch (error) { + throw cloudConnectorStartHttpError(error, providerName, now()); + } const remoteExpiry = new Date(session.expiresAt); const expiresAt = Number.isFinite(remoteExpiry.getTime()) ? new Date(