diff --git a/doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md b/doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md index 143fbc273cb..972e72783b8 100644 --- a/doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md +++ b/doc/connections/GOOGLE-WORKSPACE-SERVICE-CONSENT.md @@ -24,11 +24,18 @@ and Slides have their respective editor scopes. Gmail uses `gmail.compose` for draft creation; Google permits sending under that scope, but Paperclip's closed tool allowlist still excludes sending. +Every selectable combination stays inside the 14 scopes submitted for Google +verification, kept as an explicit list in `GOOGLE_WORKSPACE_SUBMITTED_SCOPES`. +The server rejects an authorization request that carries any other scope. On +callback and refresh it ignores any other scope Google reports, on both the +managed and the customer-owned path. + Both customer OAuth and managed Cloud OAuth bind the request to durable OAuth state. The broker must support nonempty `workspace.all` scope subsets, preserve them in the provider URL and encrypted claim binding, and reject unknown scopes. -Other managed profiles retain their exact-set contract. Ship that broker change -before updating tenant apps; an older broker rejects narrowed requests safely. +Refresh now signs the 14 as its binding, so the app must be deployed before the +broker narrows its `workspace.all` registry to the 14. Other managed profiles +retain their exact-set contract. Only provider-reported consent enables tools. Callback and refresh cap effective permissions to the saved request, including read-only implications of broader diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index 265dfed88d0..ef4dde80f49 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -80,11 +80,26 @@ client pair; that client's Cloud project must have every applicable MCP API and preview enrollment. Do not remove legacy enabled profiles while their grants are in use. This code change does not enable the broker profile or deploy any stack. -The signed request and envelope authentication bind the exact selected request; -the legacy 21-scope profile remains supported for old clients. The encrypted -credential payload preserves Google's actual nonempty -subset. Missing scope evidence and scopes outside that reviewed union fail closed -on authorization and refresh. Individual legacy profiles retain exact matching. +The signed request and envelope authentication bind the exact selected request. +Refresh binds the 14 scopes submitted for Google verification +(`GOOGLE_WORKSPACE_SUBMITTED_SCOPES`), which the broker accepts as a subset of +its registry. The encrypted credential payload preserves Google's actual +nonempty subset. An authorization request with any scope outside the 14 is +rejected. Callback and refresh use one contract on both managed and +customer-owned OAuth: Paperclip caps Google's reported scopes to the 14 and to +the saved request, and continues. A scope outside the 14 (for example a former +Chat, Contacts, Directory, profile or `calendar.readonly` grant) is ignored and +never enables an action. Only missing scope evidence or an empty result needs +reconnecting, and reconnecting with a new service choice always works. +Individual legacy profiles retain exact matching. + +Paperclip's own Google client never starts consent for a profile outside the +14: `gmail.archive` (`gmail.modify`), `chat.read`, `chat.write`, `people.read` +and `workspace-search.read`. Their Apps methods are no longer offered for new +setup even when the broker advertises them, and reconnecting a saved connection +on one of them is refused. Saved connections keep resolving their method, +refreshing and running. Customer-owned OAuth methods for those services are +unchanged. For the new `google/workspace.all` profile only, HKDF info is SHA-256(AAD) to remain below Node's 1024-byte limit. AES-GCM still authenticates the complete AAD; legacy envelope key derivation is unchanged. diff --git a/packages/shared/src/google-workspace-connectors.test.ts b/packages/shared/src/google-workspace-connectors.test.ts index 56ce31604a1..b92d1c51f4a 100644 --- a/packages/shared/src/google-workspace-connectors.test.ts +++ b/packages/shared/src/google-workspace-connectors.test.ts @@ -5,7 +5,9 @@ import { googleWorkspaceGrantedScopes, googleWorkspaceToolTarget, isGoogleWorkspaceToolGranted, googleWorkspaceServiceGranted, isGoogleWorkspaceScopeGrant, googleWorkspaceSelectedScopes, googleWorkspaceEffectiveScopes, GOOGLE_WORKSPACE_DEFAULT_SELECTION, - googleWorkspaceDraftRequestedScopes, + googleWorkspaceDraftRequestedScopes, GOOGLE_WORKSPACE_SERVICE_GROUPS, GOOGLE_WORKSPACE_SUBMITTED_SCOPES, + GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS, googleWorkspaceProfileWithinSubmittedScopes, + type GoogleWorkspaceServiceSelection, } from "./google-workspace-connectors.js"; const scope = (value: string) => `https://www.googleapis.com/auth/${value}`; @@ -43,23 +45,51 @@ describe("combined Google Workspace consent", () => { expect(isGoogleWorkspaceToolGranted("docs__read_doc", effective)).toBe(true); expect(googleWorkspaceEffectiveScopes([scope("documents")], [scope("documents.readonly")])).toEqual([scope("documents.readonly")]); }); - it("requests the existing union with one profile and preserves legacy definitions", () => { - const expected = [...new Set(Object.entries(profiles).filter(([key]) => key !== "workspace.all" && key !== "gmail.archive").flatMap(([, value]) => value.scopes))]; - expect(profiles["workspace.all"].scopes).toEqual(expected); - expect(expected).toHaveLength(21); - expect(expected).not.toContain(scope("gmail.modify")); + it("limits every selectable service combination to the 14 scopes submitted for Google verification", () => { + const submitted = [ + "gmail.readonly", "gmail.compose", + "drive.readonly", "drive.file", + "documents.readonly", "documents", + "spreadsheets.readonly", "spreadsheets", + "presentations.readonly", "presentations", + "calendar.calendarlist.readonly", "calendar.events.readonly", "calendar.events.freebusy", "calendar.events", + ].map(scope); + expect([...GOOGLE_WORKSPACE_SUBMITTED_SCOPES].sort()).toEqual([...submitted].sort()); + let selections: GoogleWorkspaceServiceSelection[] = [{}]; + for (const group of GOOGLE_WORKSPACE_SERVICE_GROUPS) { + selections = selections.flatMap((selection) => [selection, { ...selection, [group.id]: "read" }, { ...selection, [group.id]: "write" }]); + } + expect(selections).toHaveLength(27); + const union = new Set(); + for (const selection of selections) { + const selected = googleWorkspaceSelectedScopes(selection); + for (const value of selected) expect(submitted, JSON.stringify(selection)).toContain(value); + selected.forEach((value) => union.add(value)); + } + expect([...union].sort()).toEqual([...submitted].sort()); + expect([...profiles["workspace.all"].scopes].sort()).toEqual([...submitted].sort()); const app = getConnectableAppDefinition("google-workspace")!; expect(app.methods).toHaveLength(2); expect(app.methods.filter((method) => method.connectorProfile)).toHaveLength(1); - for (const method of app.methods) expect(method.defaults?.scopesHint).toEqual(expected.filter(scope => !/chat|contacts|directory|userinfo|\/calendar.readonly$/.test(scope))); + for (const method of app.methods) expect([...method.defaults!.scopesHint!].sort()).toEqual([...submitted].sort()); for (const profile of Object.values(GOOGLE_WORKSPACE_SERVICES)) expect(getConnectableAppDefinition(profiles[profile].appSlug)).not.toBeNull(); }); + it("marks only profiles inside the submitted scopes as usable with Paperclip's Google client", () => { + const outside = GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS.filter((profile) => !googleWorkspaceProfileWithinSubmittedScopes(profile)); + expect(outside).toEqual(["gmail.archive", "chat.read", "chat.write", "people.read", "workspace-search.read"]); + }); + it("accepts a nonempty subset but not missing or unrequested permissions", () => { expect(isGoogleWorkspaceScopeGrant([scope("documents")])).toBe(true); + expect(isGoogleWorkspaceScopeGrant(GOOGLE_WORKSPACE_SUBMITTED_SCOPES)).toBe(true); expect(isGoogleWorkspaceScopeGrant([])).toBe(false); expect(isGoogleWorkspaceScopeGrant([scope("chat.memberships.readonly")])).toBe(false); expect(isGoogleWorkspaceScopeGrant([scope("gmail.send")])).toBe(false); + for (const legacy of ["chat.spaces.readonly", "chat.messages.readonly", "chat.messages.create", "directory.readonly", + "userinfo.profile", "contacts.readonly", "calendar.readonly", "gmail.modify"]) { + expect(isGoogleWorkspaceScopeGrant([scope("documents"), scope(legacy)]), legacy).toBe(false); + } }); it("declining Gmail leaves Drive available without enabling Gmail or Docs", () => { diff --git a/packages/shared/src/google-workspace-connectors.ts b/packages/shared/src/google-workspace-connectors.ts index 212243767bb..dc3cf14356a 100644 --- a/packages/shared/src/google-workspace-connectors.ts +++ b/packages/shared/src/google-workspace-connectors.ts @@ -100,14 +100,25 @@ const SERVICE_PROFILES: Readonly id !== "gmail.archive").flatMap(([, profile]) => profile.scopes))]), + "workspace.all": def("google-workspace", "https://workspacemcp.googleapis.com/mcp/v1", GOOGLE_WORKSPACE_SUBMITTED_SCOPES), }; +export function googleWorkspaceProfileWithinSubmittedScopes(profile: GoogleWorkspaceConnectorProfileId): boolean { + return GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes.every((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope)); +} + export const GOOGLE_WORKSPACE_SERVICES = { gmail: "gmail.draft", drive: "drive.write", docs: "docs.write", sheets: "sheets.write", slides: "slides.write", calendar: "calendar.write", chat: "chat.write", @@ -176,9 +187,12 @@ export function isGoogleWorkspaceToolGranted(name: string, scopes: readonly stri return Boolean(target && target.requiredScopes.every((alternatives) => alternatives.some((scope) => scopes.includes(scope)))); } +export function googleWorkspaceSubmittedScopesIn(scopes: readonly string[]): string[] { + return [...new Set(scopes.filter((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope)))]; +} + export function isGoogleWorkspaceScopeGrant(scopes: readonly string[]): boolean { - const allowed = GOOGLE_WORKSPACE_CONNECTOR_PROFILES["workspace.all"].scopes; - return scopes.length > 0 && scopes.every((scope) => allowed.includes(scope)); + return scopes.length > 0 && scopes.every((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope)); } export function googleWorkspaceServiceGranted(service: GoogleWorkspaceService, scopes: readonly string[]): boolean { diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index e9ebcd72090..cdc1d3ab7d5 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -64,6 +64,7 @@ import { GITHUB_CONNECTOR_PROFILES, GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, + googleWorkspaceProfileWithinSubmittedScopes, googleWorkspaceSelectedScopes, GOOGLE_WORKSPACE_DEFAULT_SELECTION, getAvailableConnectionMethod, @@ -6013,13 +6014,12 @@ describeEmbeddedPostgres("tool access service", () => { const archivePilotGmail = archivePilot.body.apps.find( (app: { slug: string }) => app.slug === "gmail", ); - expect(archivePilotGmail.ownershipAvailability.platform_shared).toBe(true); + expect(archivePilotGmail.ownershipAvailability.platform_shared).toBe(false); expect( archivePilotGmail.methods.map((method: { key: string }) => method.key), ).toEqual([ "customer-read-oauth", "customer-draft-oauth", - "paperclip-archive", "customer-archive-oauth", ]); }); @@ -7977,7 +7977,7 @@ describeEmbeddedPostgres("tool access service", () => { expect(updated.transportConfig).toEqual(updated.config); }); - it.each(GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS.flatMap((profile) => [ + it.each(GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS.filter(googleWorkspaceProfileWithinSubmittedScopes).flatMap((profile) => [ ["local_trusted", "private", "http://127.0.0.1:3102"] as const, ["authenticated", "public", "https://tenant.paperclip.app"] as const, ].map(([deploymentMode, deploymentExposure, origin]) => ({ profile, deploymentMode, deploymentExposure, origin }))))( @@ -8019,7 +8019,7 @@ describeEmbeddedPostgres("tool access service", () => { expect(JSON.stringify(getConnectableAppDefinition(slug))).toBe(definitionBefore); }); - it.each(GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS)("connects advertised Workspace %s with a Cloud-delivered environment identity", async (profile) => { + it.each(GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS.filter(googleWorkspaceProfileWithinSubmittedScopes))("connects advertised Workspace %s with a Cloud-delivered environment identity", async (profile) => { const slug = GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].appSlug; const methodKey = getConnectableAppDefinition(slug)!.methods.find((method) => method.connectorProfile === profile)!.key; const company = await createCompany(db); @@ -8091,6 +8091,59 @@ describeEmbeddedPostgres("tool access service", () => { expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); }); + it.each(GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS.filter((profile) => !googleWorkspaceProfileWithinSubmittedScopes(profile)))( + "refuses new managed setup for advertised %s, whose scopes were not submitted for verification", async (profile) => { + const slug = GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].appSlug; + const methodKey = getConnectableAppDefinition(slug)!.methods.find((method) => method.connectorProfile === profile)!.key; + const company = await createCompany(db); + const userId = "board-user"; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGoogleWorkspaceConnector(company.id, userId, profile); + const app = createRouteApp(db, boardSessionActor(company.id, "owner", userId), undefined, { paperclipCloudConnector: connector }); + const gallery = await request(app).get(`/api/companies/${company.id}/tools/gallery`); + expect(gallery.body.apps.find((entry: { slug: string }) => entry.slug === slug)?.methods + .map((method: { key: string }) => method.key) ?? []).not.toContain(methodKey); + const response = await request(app).post(`/api/companies/${company.id}/tools/apps/connect`).send({ + galleryKey: slug, connectionMethodKey: methodKey, grantKind: "user", name: `Legacy ${slug}`, + }); + expect(response.status).toBe(422); + expect(connector.startAuthorization).not.toHaveBeenCalled(); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }, + ); + + it("keeps a saved Paperclip-managed Gmail archive connection refreshing but never asks Google to consent again", async () => { + const company = await createCompany(db); + const userId = `gmail-archive-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGoogleWorkspaceConnector(company.id, userId, "gmail.draft"); + const service = createTestToolAccessService(db, { paperclipCloudConnector: connector }); + const actor = { actorType: "user" as const, actorId: userId }; + mockToolsList([]); + const connected = await service.connectGalleryApp(company.id, { + galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind: "user", name: "Gmail archive", + }, 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: "archive-claim", actor, + }); + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + const config = { ...row.config, connectionMethodKey: "paperclip-archive", + oauth: { ...(row.config.oauth as Record), connectorProfile: "gmail.archive" } }; + await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, row.id)); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, row.id)); + vi.mocked(connector.startAuthorization).mockClear(); + + await service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: row.id, grantId: grant.id, forceRefresh: true, actor }); + expect(connector.refresh).toHaveBeenCalledWith(expect.objectContaining({ profile: "gmail.archive" })); + await expect(service.startOAuth(company.id, row.id, { + redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor, + })).rejects.toMatchObject({ status: 422, details: { code: "paperclip_cloud_connector_scope_not_offered" } }); + expect(connector.startAuthorization).not.toHaveBeenCalled(); + }); + it("completes brokered Gmail OAuth with a single database connection", async () => { const company = await createCompany(db); const userId = `gmail-member-${randomUUID()}`; @@ -8869,6 +8922,52 @@ describeEmbeddedPostgres("tool access service", () => { expect(gmail.status).toBe("disabled"); }); + it.each(["managed", "customer"] as const)("caps a %s callback that also reports an unrequested legacy scope", async (mode) => { + const fixture = await connectWorkspace(mode, ["documents.readonly", "gmail.readonly", "chat.messages.readonly", "calendar.readonly"]); + const [grant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, fixture.connected.connectionId), eq(connectionGrants.status, "active"))); + expect(grant.providerTenant?.oauth?.scopes).toEqual([ + "https://www.googleapis.com/auth/documents.readonly", "https://www.googleapis.com/auth/gmail.readonly", + ]); + const tools = await fixture.gateway.listToolsForSession(fixture.session.token); + expect(tools.map((tool) => tool.upstreamToolName).sort()).toEqual(["docs__read_doc", "gmail__get_message"]); + }); + + it.each(["managed", "customer"] as const)("keeps a %s grant on its submitted scopes when refresh also reports a legacy scope", async (mode) => { + const fixture = await connectWorkspace(mode); + const tool = (await fixture.gateway.listToolsForSession(fixture.session.token)).find((item) => item.upstreamToolName === "docs__read_doc")!; + fixture.expireNextCall(["https://www.googleapis.com/auth/documents.readonly", "https://www.googleapis.com/auth/gmail.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/calendar.readonly"]); + await fixture.gateway.executeTool({ sessionToken: fixture.session.token, tool: tool.name, parameters: {} }).catch(() => undefined); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, fixture.connected.connectionId)); + expect(grant.status).toBe("active"); + expect(grant.providerTenant?.oauth?.scopes).toEqual([ + "https://www.googleapis.com/auth/documents.readonly", "https://www.googleapis.com/auth/gmail.readonly", + ]); + const tools = await fixture.gateway.listToolsForSession(fixture.session.token); + expect(tools.map((item) => item.upstreamToolName).sort()).toEqual(["docs__read_doc", "gmail__get_message"]); + await expect(fixture.gateway.executeTool({ sessionToken: fixture.session.token, tool: tool.name, parameters: {} })).resolves.toMatchObject({ status: "completed" }); + }); + + it.each(["managed", "customer"] as const)("reconnects a %s grant whose refresh reported only legacy scopes", async (mode) => { + const fixture = await connectWorkspace(mode); + const tool = (await fixture.gateway.listToolsForSession(fixture.session.token)).find((item) => item.upstreamToolName === "docs__read_doc")!; + fixture.expireNextCall(["https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/chat.messages.readonly"]); + await expect(fixture.gateway.executeTool({ sessionToken: fixture.session.token, tool: tool.name, parameters: {} })).rejects.toMatchObject({ reasonCode: "oauth_reauthorization_required" }); + const [stale] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, fixture.connected.connectionId)); + expect(stale.status).toBe("needs_reauthorization"); + const redirectUri = mode === "managed" ? "https://paperclip.example/api/tools/oauth/cloud-connector/callback" : "https://paperclip.example/api/tools/oauth/callback"; + const started = await fixture.service.startOAuth(fixture.company.id, fixture.connected.connectionId, { + redirectUri, actor: fixture.actor, workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION, + }); + const state = new URL(started.authorizationUrl).searchParams.get("state")!; + if (mode === "managed") await fixture.service.completePaperclipCloudConnectorCallback({ state, claimId: "reconnect", actor: fixture.actor }); + else await fixture.service.completeOAuthCallback({ state, code: "reconnect", redirectUri, actor: fixture.actor }); + const [grant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, fixture.connected.connectionId), eq(connectionGrants.status, "active"))); + expect(grant.providerTenant?.oauth?.scopes).toEqual([ + "https://www.googleapis.com/auth/documents.readonly", "https://www.googleapis.com/auth/gmail.readonly", + ]); + }); + it("keeps healthy service tools visible during a partial outage and restores recovered services", async () => { const fixture = await connectWorkspace("managed"); fixture.unavailable.add("gmailmcp.googleapis.com"); @@ -8925,7 +9024,8 @@ describeEmbeddedPostgres("tool access service", () => { await expect(fixture.gateway.executeTool({ sessionToken: fixture.session.token, tool: gmail.name, parameters: {} })).resolves.toMatchObject({ status: "completed" }); }); - it.each((["managed", "customer"] as const).flatMap((mode) => [undefined, [], ["https://www.googleapis.com/auth/gmail.send"]].map((scopes) => ({ mode, scopes }))))( + it.each((["managed", "customer"] as const).flatMap((mode) => [undefined, [], ["https://www.googleapis.com/auth/gmail.send"], + ["https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/chat.messages.readonly"]].map((scopes) => ({ mode, scopes }))))( "fails closed on invalid refreshed permissions ($mode, $scopes)", async ({ mode, scopes }) => { const fixture = await connectWorkspace(mode); const tool = (await fixture.gateway.listToolsForSession(fixture.session.token)).find((item) => item.upstreamToolName === "docs__read_doc")!; diff --git a/server/src/services/paperclip-cloud-connector.test.ts b/server/src/services/paperclip-cloud-connector.test.ts index e8e3767cd1f..7b1bcf0bf46 100644 --- a/server/src/services/paperclip-cloud-connector.test.ts +++ b/server/src/services/paperclip-cloud-connector.test.ts @@ -8,11 +8,17 @@ import { sign, type KeyObject, } from "node:crypto"; -import { SLACK_MANAGER_SCOPES } from "@paperclipai/shared"; +import { + APP_DEFINITIONS, + GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS, + GOOGLE_WORKSPACE_SUBMITTED_SCOPES, + SLACK_MANAGER_SCOPES, +} from "@paperclipai/shared"; import { describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; import { + appWithPaperclipCloudConnectorAvailability, createPaperclipCloudConnector, invalidatePaperclipCloudConnectorCapabilities, GMAIL_CONNECTOR_SCOPES, @@ -74,7 +80,7 @@ describe("Paperclip Cloud connector", () => { await expect(connector.claim({ subject, companyId, profile: "workspace.all", claimId: "test-claim", redemptionId: "test-state" })).resolves.toEqual(credentials); sealed = seal(credentials, keys.sealPublicKey, "access", keys.config, "workspace.all"); await expect(connector.refresh({ subject, companyId, profile: "workspace.all", refreshToken: "test-refresh" })).resolves.toEqual(credentials); - for (const invalid of [[], [...scopes, "https://www.googleapis.com/auth/gmail.send"]]) { + for (const invalid of [[], ["https://www.googleapis.com/auth/gmail.send"]]) { credentials.scopes = invalid; sealed = seal(credentials, keys.sealPublicKey, "initial", keys.config, "workspace.all"); await expect(connector.claim({ subject, companyId, profile: "workspace.all", claimId: "test-claim", redemptionId: "test-state" })).rejects.toMatchObject({ code: "REAUTHORIZATION_REQUIRED" }); @@ -241,21 +247,87 @@ describe("Paperclip Cloud connector", () => { } }); - it.each(["chat.read", "chat.write"] as const)("signs reduced Chat scopes for %s", async (profile) => { + it.each(["gmail.archive", "chat.read", "chat.write", "people.read", "workspace-search.read"] as const)( + "never asks Paperclip's Google client for %s, whose scopes were not submitted for verification", async (profile) => { + const request = vi.fn(async () => Response.json({ confirmationUrl: "https://my.example.test/connections/confirm?session=legacy", expiresAt: "2099-01-01T00:00:00Z" })); + const connector = createPaperclipCloudConnector({ config: config().config, request: request as typeof fetch }); + await expect(connector.startAuthorization({ subject, companyId, profile, + returnUri: "https://paperclip.example.test/api/tools/oauth/cloud-connector/callback", returnState: "legacy-state" })) + .rejects.toMatchObject({ code: "CONNECTOR_CONFIG_INVALID" }); + expect(request).not.toHaveBeenCalled(); + }, + ); + + it.each(["calendar.readonly", "chat.messages.readonly", "contacts.readonly", "gmail.modify"])( + "rejects a unified Workspace request that adds %s before reaching the broker", async (extra) => { + const request = vi.fn(async () => Response.json({})); + const connector = createPaperclipCloudConnector({ config: config().config, request: request as typeof fetch }); + await expect(connector.startAuthorization({ subject, companyId, profile: "workspace.all", + scopes: ["https://www.googleapis.com/auth/gmail.readonly", `https://www.googleapis.com/auth/${extra}`], + returnUri: "https://paperclip.example.test/api/tools/oauth/cloud-connector/callback", returnState: "workspace-state" })) + .rejects.toMatchObject({ code: "CONNECTOR_CONFIG_INVALID" }); + expect(request).not.toHaveBeenCalled(); + }, + ); + + it("binds unified Workspace refresh to the submitted scopes and caps reported permissions to them", async () => { const keys = config(); - const scopes = ["chat.spaces.readonly", "chat.messages.readonly", ...(profile === "chat.write" ? ["chat.messages.create"] : [])] - .map((scope) => `https://www.googleapis.com/auth/${scope}`); + const credentials = { v: 1, accessToken: "test-access", refreshToken: "test-refresh", tokenType: "Bearer", + accessTokenExpiresAt: null, refreshTokenExpiresAt: null, scopes: ["https://www.googleapis.com/auth/documents"], subject, companyId, instanceId, + environment: keys.config.environment, provider: "google", profile: "workspace.all" }; + let sealed = seal(credentials, keys.sealPublicKey, "access", keys.config, "workspace.all"); + const signedScopes: unknown[] = []; const request = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { const body = JSON.parse(String(init?.body)); - const claims = JSON.parse(Buffer.from(body.request.split(".")[1], "base64url").toString("utf8")); - expect(claims.prf).toBe(profile); - expect(claims.scp).toEqual(scopes); - return Response.json({ confirmationUrl: "https://my.example.test/connections/confirm?session=chat", expiresAt: "2099-01-01T00:00:00Z" }); + signedScopes.push(JSON.parse(Buffer.from(body.request.split(".")[1], "base64url").toString("utf8")).scp); + return Response.json({ sealed }); }); const connector = createPaperclipCloudConnector({ config: keys.config, request: request as typeof fetch }); - await connector.startAuthorization({ subject, companyId, profile, - returnUri: "https://paperclip.example.test/api/tools/oauth/cloud-connector/callback", returnState: "chat-state" }); - expect(request).toHaveBeenCalledOnce(); + await expect(connector.refresh({ subject, companyId, profile: "workspace.all", refreshToken: "test-refresh" })).resolves.toEqual(credentials); + expect([...signedScopes[0] as string[]].sort()).toEqual([...GOOGLE_WORKSPACE_SUBMITTED_SCOPES].sort()); + for (const legacy of ["calendar.readonly", "chat.messages.readonly", "userinfo.profile", "gmail.send"]) { + credentials.scopes = ["https://www.googleapis.com/auth/documents", `https://www.googleapis.com/auth/${legacy}`]; + sealed = seal(credentials, keys.sealPublicKey, "access", keys.config, "workspace.all"); + await expect(connector.refresh({ subject, companyId, profile: "workspace.all", refreshToken: "test-refresh" })) + .resolves.toMatchObject({ scopes: ["https://www.googleapis.com/auth/documents"] }); + sealed = seal(credentials, keys.sealPublicKey, "initial", keys.config, "workspace.all"); + await expect(connector.claim({ subject, companyId, profile: "workspace.all", claimId: "test-claim", redemptionId: "test-state" })) + .resolves.toMatchObject({ scopes: ["https://www.googleapis.com/auth/documents"] }); + credentials.scopes = [`https://www.googleapis.com/auth/${legacy}`]; + sealed = seal(credentials, keys.sealPublicKey, "access", keys.config, "workspace.all"); + await expect(connector.refresh({ subject, companyId, profile: "workspace.all", refreshToken: "test-refresh" })) + .rejects.toMatchObject({ code: "REAUTHORIZATION_REQUIRED" }); + } + }); + + it("offers new managed Google setup only for methods inside the submitted scopes", () => { + const submitted = new Set(GOOGLE_WORKSPACE_SUBMITTED_SCOPES); + const savedConnectionsOnly = [ + "gmail/paperclip-archive", + "google-chat/paperclip-read", "google-chat/paperclip-write", + "google-people/paperclip-read", + "google-workspace-search/paperclip-read", + ]; + const managedGoogle = APP_DEFINITIONS.flatMap((app) => app.methods + .filter((method) => method.oauthStrategy === "paperclip_cloud_connector" + && (GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS as readonly string[]).includes(method.connectorProfile ?? "")) + .map((method) => ({ app, method, id: `${app.slug}/${method.key}` }))); + expect(managedGoogle.length).toBeGreaterThan(savedConnectionsOnly.length); + expect(managedGoogle.filter(({ method }) => (method.defaults?.scopesHint ?? []).some((value) => !submitted.has(value))) + .map(({ id }) => id)).toEqual(savedConnectionsOnly); + for (const app of APP_DEFINITIONS) { + const offered = appWithPaperclipCloudConnectorAvailability(app, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + for (const method of offered.methods.filter((candidate) => candidate.oauthStrategy === "paperclip_cloud_connector")) { + expect(savedConnectionsOnly).not.toContain(`${app.slug}/${method.key}`); + for (const value of method.defaults?.scopesHint ?? []) expect(submitted, `${app.slug}/${method.key}`).toContain(value); + } + } + const gmail = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "gmail")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + expect(gmail.methods.map((method) => method.key)).toEqual([ + "paperclip-read", "customer-read-oauth", "paperclip-draft", "customer-draft-oauth", "customer-archive-oauth", + ]); + const chat = appWithPaperclipCloudConnectorAvailability(APP_DEFINITIONS.find((app) => app.slug === "google-chat")!, [...GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS]); + expect(chat.ownershipAvailability?.platform_shared).toBe(false); }); it("signs selected Workspace scopes without substituting the full profile", async () => { diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index 5020a506266..cfcabde5cff 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -20,6 +20,8 @@ import { isGitHubConnectorProfileId, isGoogleWorkspaceConnectorProfileId, isGoogleWorkspaceScopeGrant, + googleWorkspaceProfileWithinSubmittedScopes, + googleWorkspaceSubmittedScopesIn, type GitHubConnectorProfileId, type GoogleWorkspaceConnectorProfileId, } from "@paperclipai/shared"; @@ -396,6 +398,7 @@ export function createPaperclipCloudConnector(input: { if (credentials.profile !== profile) { throw new PaperclipCloudConnectorError("Paperclip Cloud connector profile binding did not match", "CONNECTOR_BINDING_MISMATCH"); } + if (profile === "workspace.all") credentials.scopes = googleWorkspaceSubmittedScopesIn(credentials.scopes); if (!(profile === "workspace.all" ? isGoogleWorkspaceScopeGrant(credentials.scopes) : sameStringSet(credentials.scopes, definition.scopes))) { throw new PaperclipCloudConnectorError("Paperclip Cloud scope grant did not match", "REAUTHORIZATION_REQUIRED"); } @@ -521,6 +524,9 @@ export function createPaperclipCloudConnector(input: { }, async startAuthorization(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; returnUri: string; returnState: string }) { const profile = values.profile ?? "gmail.draft"; + if (!paperclipCloudConnectorConsentAllowed(profile)) { + throw new PaperclipCloudConnectorError("This permission set is not offered through Paperclip's Google app", "CONNECTOR_CONFIG_INVALID"); + } const response = await call("session", { ...values, profile }); if (typeof response.confirmationUrl !== "string" || typeof response.expiresAt !== "string") { throw new PaperclipCloudConnectorError("Paperclip Cloud connector returned an invalid session", "CONNECTOR_BAD_RESPONSE"); @@ -735,7 +741,8 @@ export function appWithPaperclipCloudConnectorAvailability( const enabledProfiles = new Set(profiles); const methods = app.methods.filter((method) => !isPaperclipCloudConnectorStrategy(method.oauthStrategy) - || Boolean(method.connectorProfile && enabledProfiles.has(method.connectorProfile)) + || Boolean(method.connectorProfile && enabledProfiles.has(method.connectorProfile) + && paperclipCloudConnectorConsentAllowed(method.connectorProfile)) ); return { ...app, @@ -748,6 +755,10 @@ export function appWithPaperclipCloudConnectorAvailability( }; } +export function paperclipCloudConnectorConsentAllowed(profile: string): boolean { + return !isGoogleWorkspaceConnectorProfileId(profile) || googleWorkspaceProfileWithinSubmittedScopes(profile); +} + let capabilityCache: { key: string; expiresAt: number; profiles: PaperclipCloudConnectorProfileId[] } | null = null; let capabilityCacheGeneration = 0; diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 77488796912..3dedf46c813 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -14,7 +14,7 @@ import { companies, agents, connectionGrants, issueThreadInteractions, toolConne import type { ConnectionGrantKind, ToolOAuthStartResult } from "@paperclipai/shared"; import { getConnectableAppDefinition } from "@paperclipai/shared"; import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; -import { isPaperclipCloudConnectorStrategy, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { isPaperclipCloudConnectorStrategy, 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"; @@ -348,6 +348,12 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies if (!managedProfile) throw badRequest("This app has an invalid managed connector profile"); const providerName = galleryEntry?.name ?? "Google Workspace"; + if (!paperclipCloudConnectorConsentAllowed(managedProfile.id)) { + throw unprocessable( + `${providerName} can no longer be connected through Paperclip with these permissions. Connect Google Workspace, or set up ${providerName} with your own Google OAuth app.`, + { code: "paperclip_cloud_connector_scope_not_offered" }, + ); + } const cloudConnector = currentCloudConnector(); if (!cloudConnector) { throw unprocessable( diff --git a/server/src/services/tool-access/oauth/cloud-callback.ts b/server/src/services/tool-access/oauth/cloud-callback.ts index ebba51b0b92..bfe6d1fc345 100644 --- a/server/src/services/tool-access/oauth/cloud-callback.ts +++ b/server/src/services/tool-access/oauth/cloud-callback.ts @@ -8,7 +8,7 @@ import type { ActorInfo } from "../types.js"; import { oauthConfig, normalizeOauthScopes } from "./metadata.js"; import { connectionMethodForConnection } from "../connection-methods.js"; import { loadGitHubGrantMetadata } from "../github-access-discovery.js"; -import { googleWorkspaceEffectiveScopes, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, gte, ne } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -131,8 +131,8 @@ export function createCloudOAuthCallback(db: Db, dependencies: Dependencies) { ...(profile.id === "workspace.all" && stateRow.requestedScopes ? { scopes: stateRow.requestedScopes } : {}), }); if (profile.id === "workspace.all") { - const requested = normalizeOauthScopes(stateRow.requestedScopes); - credentials.scopes = googleWorkspaceEffectiveScopes(requested, credentials.scopes); + const requested = googleWorkspaceSubmittedScopesIn(normalizeOauthScopes(stateRow.requestedScopes)); + credentials.scopes = googleWorkspaceEffectiveScopes(requested, googleWorkspaceSubmittedScopesIn(credentials.scopes)); if (!isGoogleWorkspaceScopeGrant(credentials.scopes)) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" }); } const refreshToken = credentials.refreshToken; diff --git a/server/src/services/tool-access/oauth/direct-callback.ts b/server/src/services/tool-access/oauth/direct-callback.ts index 2b5484abbff..17404dc6002 100644 --- a/server/src/services/tool-access/oauth/direct-callback.ts +++ b/server/src/services/tool-access/oauth/direct-callback.ts @@ -8,7 +8,7 @@ import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from ". import { normalizeOAuthProviderError, oauthProviderErrorMessage } from "./provider-errors.js"; import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./metadata.js"; import { connectionMethodForConnection } from "../connection-methods.js"; -import { googleWorkspaceEffectiveScopes, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, ne } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -154,12 +154,9 @@ export function createDirectOAuthCallback(db: Db, dependencies: Dependencies) { code: input.code, resource: endpoints.resource, }); - if (sourceTemplateKey === "google-workspace" && !isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) { - throw unprocessable("Google did not return a supported permission grant. Reconnect and choose the Google services you want to use.", { code: "oauth_scope_grant_invalid" }); - } if (sourceTemplateKey === "google-workspace") { - token.scope = googleWorkspaceEffectiveScopes(authorizedScopes, normalizeOauthScopes(token.scope)).join(" "); - if (!token.scope) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" }); + token.scope = googleWorkspaceEffectiveScopes(googleWorkspaceSubmittedScopesIn(authorizedScopes), googleWorkspaceSubmittedScopesIn(normalizeOauthScopes(token.scope))).join(" "); + if (!isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" }); } const connectedAt = now(); const expiresAt = token.expiresIn diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index 1754f2c43be..d521137af4d 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -4,7 +4,7 @@ import type { ActorInfo, DbTransaction } from "../types.js"; import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from "./client.js"; import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./metadata.js"; -import { googleWorkspaceEffectiveScopes, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; +import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -149,8 +149,8 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo refreshToken: refreshSecret.value, }); if (profile.id === "workspace.all") { - const requested = normalizeOauthScopes(oauthGrantConfig(grant).requestedScopes ?? oauthGrantConfig(grant).scopes); - credentials.scopes = googleWorkspaceEffectiveScopes(requested, credentials.scopes); + const requested = googleWorkspaceSubmittedScopesIn(normalizeOauthScopes(oauthGrantConfig(grant).requestedScopes ?? oauthGrantConfig(grant).scopes)); + credentials.scopes = googleWorkspaceEffectiveScopes(requested, googleWorkspaceSubmittedScopesIn(credentials.scopes)); } if (profile.id === "workspace.all" && !isGoogleWorkspaceScopeGrant(credentials.scopes)) { throw new PaperclipCloudConnectorError("Google did not return verifiable permissions", "REAUTHORIZATION_REQUIRED"); @@ -456,6 +456,9 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo throw error; } + if (connection.config.sourceTemplateKey === "google-workspace") { + token.scope = googleWorkspaceSubmittedScopesIn(normalizeOauthScopes(token.scope)).join(" "); + } if (connection.config.sourceTemplateKey === "google-workspace" && !isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) { await db.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: now() }) diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index b1a79860e2e..64c19e79a26 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -260,8 +260,8 @@ "packages/shared/src/github-connectors.ts": "b8448b1eddac9a9d1308b94e4d136c761cbd4a00", "packages/shared/src/github-skill-repository.ts": "b00a9963472723bcb7fcd433aae442f75d7a138b", "packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734", - "packages/shared/src/google-workspace-connectors.test.ts": "56ce31604a18761e72bb648b1e6e4361eccc14eb", - "packages/shared/src/google-workspace-connectors.ts": "212243767bb35d116c801d9444be84e47b0777d6", + "packages/shared/src/google-workspace-connectors.test.ts": "b92d1c51f4ac8323528b35bc041073f814acd5c9", + "packages/shared/src/google-workspace-connectors.ts": "dc3cf14356ad8dc04e6b4f7bf13b922af24cc4bf", "packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525", "packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186", "packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66",