Skip to content

The open-source app everyone uses to manage agents at work

fix(connections): keep Cloud refresh reauthorization diagnostics (#17362)

Devin Foley3c4050e3ad03
diff --git a/doc/connections/GMAIL.md b/doc/connections/GMAIL.md
index 6b9ed00d17..fb29d5cd04 100644
--- a/doc/connections/GMAIL.md
+++ b/doc/connections/GMAIL.md
@@ -386,6 +386,7 @@ seven-day testing-token expiry.
| The managed method is unavailable | Confirm the exact profile is in `CLOUD_HARNESS_CONNECTOR_GOOGLE_ENABLED_PROFILES` and its client id and secret reference are configured. |
| Login starts asking for Gmail | Stop the rollout. The login and Gmail clients or route namespaces have been mixed. |
| Connector is unavailable | Keep the grant in `needs_reauthorization` or an actionable unavailable state. Never use a login token or another environment's client. |
+| Refresh reports `reason=PROVIDER_REAUTHORIZATION_REQUIRED` | The provider revoked, expired, or already rotated the grant, or the grant no longer matches the profile. Paperclip marks it `needs_reauthorization`; the user reconnects. `reason=PROVIDER_OPERATION_FAILED` is a provider or Cloud outage; retry later. |
## References
diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts
index 97183dbc97..38c49754c4 100644
--- a/server/src/__tests__/tool-access-service.test.ts
+++ b/server/src/__tests__/tool-access-service.test.ts
@@ -95,7 +95,7 @@ import { errorHandler } from "../middleware/index.js";
import * as sentry from "../sentry.js";
import { HttpError } from "../errors.js";
import type { VercelConnectClient } from "../services/vercel-connect.js";
-import { invalidatePaperclipCloudConnectorCapabilities, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
+import { invalidatePaperclipCloudConnectorCapabilities, PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
const externalDatabaseUrl = process.env.PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL?.trim();
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -9495,6 +9495,36 @@ describeEmbeddedPostgres("tool access service", () => {
}
});
+ it("marks a managed grant for reconnection when the provider rejects its refresh", async () => {
+ const company = await createCompany(db);
+ await createAgent(db, company.id);
+ const userId = `managed-refresh-rejected-${randomUUID()}`;
+ await grantBoardUser(db, company.id, userId, [], "owner");
+ const actor = { actorType: "user" as const, actorId: userId };
+ const connector = fakeGmailConnector(company.id, userId);
+ const service = createTestToolAccessService(db, { paperclipCloudConnector: connector });
+ const definition = getConnectableAppDefinition("gmail")!;
+ const availability = definition.ownershipAvailability;
+ definition.ownershipAvailability = { ...availability, platform_shared: true };
+ mockToolsList([]);
+ try {
+ const connected = await service.connectGalleryApp(company.id, { galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind: "user", name: "Managed rejected refresh" }, actor);
+ const started = await service.startOAuth(company.id, connected.connectionId, { redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor });
+ await service.completePaperclipCloudConnectorCallback({ state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "initial", actor });
+ const [grant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connected.connectionId), eq(connectionGrants.subjectUserId, userId)));
+ vi.mocked(connector.refresh).mockRejectedValueOnce(new PaperclipCloudConnectorError(
+ "Paperclip Cloud connector rejected the request (operation=refresh, status=409, reason=PROVIDER_REAUTHORIZATION_REQUIRED)",
+ "REAUTHORIZATION_REQUIRED",
+ 409,
+ ));
+ await expect(service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: connected.connectionId, grantId: grant.id, forceRefresh: true, actor }))
+ .rejects.toMatchObject({ status: 422, details: { code: "oauth_reauthorization_required" } });
+ expect((await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))[0].status).toBe("needs_reauthorization");
+ } finally {
+ definition.ownershipAvailability = availability;
+ }
+ });
+
it("orders managed reconnect with refresh and rejects superseded secret writes", async () => {
const company = await createCompany(db);
await createAgent(db, company.id);
diff --git a/server/src/services/fixtures/cloud-connector-refresh-reauthorization.json b/server/src/services/fixtures/cloud-connector-refresh-reauthorization.json
new file mode 100644
index 0000000000..cdff2302c6
--- /dev/null
+++ b/server/src/services/fixtures/cloud-connector-refresh-reauthorization.json
@@ -0,0 +1,6 @@
+{
+ "status": 409,
+ "body": {
+ "error": "PROVIDER_REAUTHORIZATION_REQUIRED"
+ }
+}
diff --git a/server/src/services/paperclip-cloud-connector.test.ts b/server/src/services/paperclip-cloud-connector.test.ts
index 29229c8439..07bd0bb119 100644
--- a/server/src/services/paperclip-cloud-connector.test.ts
+++ b/server/src/services/paperclip-cloud-connector.test.ts
@@ -32,6 +32,9 @@ const subject = "user_test";
const originRejectionContract = JSON.parse(readFileSync(
new URL("./fixtures/cloud-connector-origin-rejection.json", import.meta.url), "utf8",
)) as { status: number; body: { error: string } };
+const refreshReauthorizationContract = JSON.parse(readFileSync(
+ new URL("./fixtures/cloud-connector-refresh-reauthorization.json", import.meta.url), "utf8",
+)) as { status: number; body: { error: string } };
function rawPrivateKey(key: KeyObject): string {
const jwk = key.export({ format: "jwk" }) as { d?: string };
@@ -142,6 +145,24 @@ describe("Paperclip Cloud connector", () => {
});
});
+ it("asks for reconnection when the provider rejects a refresh grant", async () => {
+ const connector = createPaperclipCloudConnector({
+ config: config().config,
+ request: vi.fn(async () => Response.json(refreshReauthorizationContract.body, {
+ status: refreshReauthorizationContract.status,
+ })) as typeof fetch,
+ });
+ const error = await connector.refresh({
+ subject, companyId, profile: "gmail.read", refreshToken: "refresh-secret",
+ }).catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(PaperclipCloudConnectorError);
+ expect(error).toMatchObject({
+ code: "REAUTHORIZATION_REQUIRED", status: 409,
+ message: "Paperclip Cloud connector rejected the request (operation=refresh, status=409, reason=PROVIDER_REAUTHORIZATION_REQUIRED)",
+ });
+ expect(JSON.stringify(error)).not.toContain("refresh-secret");
+ });
+
it("keeps the original status when the error body stream fails", async () => {
const response = new Response(new ReadableStream({
start(controller) { controller.error(new Error("DO_NOT_REPORT")); },
diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts
index b84c9c709a..b1461d3e14 100644
--- a/server/src/services/paperclip-cloud-connector.ts
+++ b/server/src/services/paperclip-cloud-connector.ts
@@ -144,7 +144,7 @@ const BROKER_REJECTION_REASONS = new Set([
"REQUEST_EXPIRED", "REQUEST_REPLAYED", "SIGNATURE_REJECTED",
"AUDIENCE_MISMATCH", "OPERATION_MISMATCH", "PAYLOAD_MISMATCH",
"MALFORMED_REQUEST", "UNSUPPORTED_ALGORITHM", "RATE_LIMITED",
- "PROVIDER_OPERATION_FAILED",
+ "PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED",
]);
const UNKNOWN_BROKER_REASON = "UNKNOWN_BROKER_ERROR";