From 23ce68a8dce30ed630ccb24e22e305447b98ba8f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:52:20 -0600 Subject: [PATCH] feat(connections): end Google access when a Paperclip-managed Google connection is removed (#22065) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Connectors let agents use Google Workspace through a Google sign-in that Paperclip Cloud manages for the user > - When a user removes a Paperclip-managed Google connection, Paperclip deletes the tokens locally, but the grant stays live at Google > - Google's OAuth review expects that a disconnect ends the app's access, and users expect it too > - Google's revoke ends the user's whole grant to the shared client, so only the Paperclip Cloud broker can decide when it is safe to revoke > - This pull request asks the broker to revoke each removed grant, keeps local removal unconditional, and tells the user the outcome in plain language > - The benefit is that removal ends Google access when no other Paperclip connection needs it, and the user knows what to do when it did not ## Linked Issues or Issue Description **Subsystem affected** Connectors: Paperclip-managed Google Workspace and the legacy per-service Google connections (server removal, shared contracts, connection UI). **Problem or motivation** Removing a Paperclip-managed Google connection or grant was local only. The refresh token was deleted in Paperclip, but Google still listed Paperclip as having access to the account. The docs said so ("Removal is local for managed grants"). **Proposed solution** On removal, send each removed grant's refresh token to the broker's signed `POST /v1/connector/revoke`. The broker revokes at Google only when no other live binding could share the grant. Paperclip records the broker's outcome code and shows one of three plain messages. Local removal never waits on, or fails because of, that call. **Alternatives considered** Call Google's revoke endpoint from the app. This ends the user's whole grant to the shared client and can break their other Google connections, so the broker owns the decision. **Additional context** Older brokers answer 409 `REVOCATION_NOT_AVAILABLE`. The app treats that, a timeout, and a network error as "could not end access at Google" and still removes the connection. ## What Changed - `paperclip-cloud-connector.ts`: `revoke()` takes an optional `timeoutMs`, returns the broker's `outcome` from an allowlist, and keeps `REVOCATION_NOT_AVAILABLE` as an allowed rejection reason. - New `tool-access/connections/google-access-removal.ts`. For a managed Google connection, `prepare()` reads each removed grant's refresh token and returns a `send()` step. `send()` calls the broker for each distinct token, one after another, under one 5-second deadline. Every result and every error (including a Paperclip Cloud client that cannot be created) becomes an outcome code. It never rejects and never logs a token. An unexpected error is logged with the error name only and reported as `unexpected_error`. - Order for removing a whole connection: read the tokens, run the whole local teardown (grants, installs, app profile, gateway tokens, runtime slots, catalog, OAuth state, archive the connection), call the broker, delete the sent refresh-token secrets whatever the outcome, then delete the remaining secrets. A failure anywhere in the teardown makes no broker call. Order for removing one grant: read the token, commit the revocation, call the broker, delete the grant's refresh-token secret. `send()` owns the call and the deletion through an injected secret-removal function. - Owed revocations: a revoked managed Google grant whose refresh-token secret still exists (and that nothing live uses) is sent by every later removal, then the secret is deleted. This covers a process stop after the teardown and before the call, with no new column. Once the secret is deleted, nothing is sent again. - Shared tokens: the shared (organization) sign-in writes the same secret refs to the organization grant and the connection. So revoking an organization grant alone neither calls the broker nor deletes the secret, because the connection still uses that token; removing the connection does both. The same rule applies to any refresh token still used by another live grant or connection. - Audit history: once the broker call settles, a `connection.google_access_removal` audit event records `reasonCode` = result and `providerAccess` (plus `grantId` for a single grant). If that write fails, the removal still succeeds and the failure is logged. - Revoke signs with the subject that consented to the grant (`providerTenant.externalId`, saved by the managed callback from the claim). Grants saved without it fall back to the refresh rule. Refresh is unchanged; see Risks. - `removal.ts` and `grants.ts`: `providerAccess: { provider, result, outcomes }` goes to the responses and to the `tool_connection.archived` and `tool_connection.grant_revoked` activity entries. The tool access audit field `providerRevocation` keeps its Vercel meaning only. - `packages/shared`: `ManagedGoogleAccessRemoval`, `ManagedGoogleRevocationOutcome`, `ConnectionGrantRevocationResult`. - UI: one helper, `connectionRemovalToast`, builds the removal toast (base sentence plus the Google notice, tone and action) for Connectors, Connections and the app page. No codes are shown. - API: `docs/api/tool-connections.md` documents both DELETE responses and `providerAccess`. The OpenAPI registration describes the optional field and its four results. - Docs: `GOOGLE-WORKSPACE.md` (order, owed revocations, decision table), `GMAIL.md`, the Google connector memory note, and the help page on deleting connection data. Decision table, judged over the distinct tokens sent in this removal: | Outcomes | `result` | User message | | --- | --- | --- | | Every token `revoked` | `ended` | "Paperclip's access to this Google account was also ended at Google." | | Any failure-type code: `provider_revocation_failed`, `binding_not_known` (the broker had no record, so Google was not called), `provider_revocation_disabled`, `revocation_in_progress`, `revocation_not_available`, `broker_unavailable`, `broker_error`, `credential_unavailable`, `unexpected_error` | `not_ended` | "Paperclip removed the connection but couldn't end its access at Google. You can remove Paperclip from your Google account's third-party connections." + "Open Google account connections" | | Only `other_connections_remain` | `other_connections_remain` | "Other Paperclip connections still use this Google account, so Google keeps Paperclip's access until you remove those too." | | At least one `revoked`, the rest `other_connections_remain` | `ended_unconfirmed` | "Paperclip's access was ended at Google. If more than one Google account was connected here, check your Google account's third-party connections to be sure." + "Open Google account connections" | Grants record no Google account identity: the managed callback saves `externalId` (the Paperclip subject), `name` (the provider name), and OAuth timing and scopes, and none of the 14 scopes returns an account identifier. So the last row is always `ended_unconfirmed`. This includes two tokens of one user and several agent grants on one Google account. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/google-managed-connection-removal.test.ts src/services/tool-access src/services/paperclip-cloud-connector-revoke.test.ts src/services/paperclip-cloud-connector.test.ts src/__tests__/tool-connection-removal.test.ts src/__tests__/tool-access-service.test.ts src/__tests__/openapi-routes.test.ts` (714 passed) - `pnpm --filter @paperclipai/ui exec vitest run src/features/connections/googleAccessRemoval.test.ts src/pages/apps` (passed) - Server test typecheck (`node server/scripts/typecheck-layers.mjs`) passes. - Red then green: the server tests failed on `master` sources (21), then each review round's new tests failed on the previous head and pass now. They cover: the order on both paths, local failure before the grant commit making no call and the retry sending, cleanup failure after the call making no second call, a process stop between commit and call being sent on retry with the secret deleted after, a Paperclip Cloud client that cannot be created, the consenting subject for an organization grant, sequential sends under one deadline, each row of the decision table (per-agent and same-user cases give `ended_unconfirmed`, a mixed failure gives `not_ended`), the unexpected-error log without a token, no token in any log call, the delete-stored-data option, and a toast test per surface. - Added time, measured locally with a stubbed broker that answers at once: median 22.1 ms against 20.3 ms without the broker step (12 runs each), about 2 ms. With a real broker, one round trip per removed token, capped at 5 seconds in total. - `pnpm verify` exits 2 (a global CI input changed), so required CI supplies the broad coverage. - Not verified against a live broker or a real Google account. ## Risks - A removal of a managed Google connection or grant can take up to 5 seconds longer when the broker is slow. - Refresh subject is not changed in this PR. In the broker (`recordProviderGrant`), a ledger row's subject is fixed when the row is first written, and a refresh under another subject leaves that row untouched. So moving refresh to a new subject could stop updating the row's last-seen time. After 200 days the row would then count as not live, and a later removal elsewhere could revoke at Google while this connection still works. That risk cannot be ruled out from code for rows written before this release, so both refresh paths keep their old rules. The two refresh paths already use different subject orders today: the gateway prefers `connectorSubjectAgentId` and then `connectorSubjectUserId`, while background refresh prefers the grant's own subject. That is pre-existing, and this PR leaves it unchanged. Revoke uses the consenting subject, which matches the claim-time ledger row. When the row was first written by a refresh under a different subject, the broker answers `binding_not_known` and the user gets the warning. - Repeated removals can send an already-removed token again; the broker returns its recorded outcome and changes nothing at Google. - Against an older broker, users see the "could not end access at Google" message, which is accurate. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/connections/GMAIL.md | 13 +- doc/connections/GOOGLE-WORKSPACE.md | 92 ++- doc/memory/google-connector-memory.md | 2 +- docs/api/tool-connections.md | 50 ++ docs/docs.json | 1 + .../deleting-connection-data.md | 2 + packages/shared/src/index.ts | 3 + packages/shared/src/types/index.ts | 3 + packages/shared/src/types/tool-access.ts | 24 + .../google-managed-connection-removal.test.ts | 682 ++++++++++++++++++ .../src/__tests__/tool-access-service.test.ts | 11 +- server/src/routes/openapi.ts | 20 + server/src/routes/tool-access.ts | 2 +- .../slack/setup/development-manager.ts | 1 + .../paperclip-cloud-connector-revoke.test.ts | 80 ++ .../src/services/paperclip-cloud-connector.ts | 20 +- server/src/services/secrets.ts | 26 +- server/src/services/tool-access.ts | 4 +- .../connections/google-access-removal.test.ts | 260 +++++++ .../connections/google-access-removal.ts | 269 +++++++ .../tool-access/connections/grants.ts | 30 +- .../tool-access/connections/removal.ts | 22 +- .../tool-access/oauth/client-settings.ts | 17 + .../tool-access/oauth/grant-refresh.ts | 11 +- .../oauth/managed-connector-subject.test.ts | 21 + .../runner-e2e/source-sdk-public-inputs.json | 6 +- ui/src/api/tools.ts | 3 +- .../connections/googleAccessRemoval.test.ts | 50 ++ .../connections/googleAccessRemoval.ts | 56 ++ ui/src/pages/apps/AppDetail.test.tsx | 22 +- ui/src/pages/apps/AppDetail.tsx | 8 +- ui/src/pages/apps/Browse.test.tsx | 36 + ui/src/pages/apps/Browse.tsx | 20 +- ui/src/pages/apps/Connections.test.tsx | 25 + ui/src/pages/apps/Connections.tsx | 14 +- 35 files changed, 1831 insertions(+), 75 deletions(-) create mode 100644 docs/api/tool-connections.md create mode 100644 server/src/__tests__/google-managed-connection-removal.test.ts create mode 100644 server/src/services/paperclip-cloud-connector-revoke.test.ts create mode 100644 server/src/services/tool-access/connections/google-access-removal.test.ts create mode 100644 server/src/services/tool-access/connections/google-access-removal.ts create mode 100644 server/src/services/tool-access/oauth/managed-connector-subject.test.ts create mode 100644 ui/src/features/connections/googleAccessRemoval.test.ts create mode 100644 ui/src/features/connections/googleAccessRemoval.ts diff --git a/doc/connections/GMAIL.md b/doc/connections/GMAIL.md index fb29d5cd049..58050d11640 100644 --- a/doc/connections/GMAIL.md +++ b/doc/connections/GMAIL.md @@ -247,12 +247,13 @@ deletes the ciphertext on expiry and excludes it from long-term backups. Refresh and supported revoke operations handle plaintext only in memory for one bounded request. -Removing one managed Google profile revokes only the local Paperclip grant. -Paperclip does not call Google's token revocation endpoint for that action. -Google treats revocation as client-wide for the user, so a provider-side revoke -could also invalidate the user's other managed Gmail, Drive, and Calendar -profiles. A future provider-level disconnect must present that all-profiles -effect explicitly. +Removing a managed Google profile asks Paperclip Cloud to revoke the grant. +Google treats revocation as client-wide for the user, so the broker revokes at +Google only when no other live binding it knows of could share the grant, and +otherwise reports that other connections remain. Paperclip commits the local +removal first and calls the broker only after that; the answer never changes +the local result. See "Removing a managed Google connection" in +[GOOGLE-WORKSPACE.md](GOOGLE-WORKSPACE.md). ### Configure each originating Paperclip instance diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index 513432004ed..ee64fd1b2fa 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -130,8 +130,8 @@ instance to the fixed endpoints below. Customer OAuth uses the instance's existi `/api/tools/oauth/callback` instead. Register that exact HTTPS or loopback callback on the customer-owned client. -Removal is local for managed grants: Google's project-wide revocation can break -other connections. Before rollout, verify full and partial consent with an enrolled +Removing a managed connection or grant asks Paperclip Cloud to revoke it (see +"Removing a managed Google connection" below). Before rollout, verify full and partial consent with an enrolled test account, allowed reads/writes, reconnect, refresh and removal. Deterministic tests are not real-provider proof. Combining profiles simplifies onboarding, not Google's per-scope demonstration, justification or security-assessment obligations. @@ -228,10 +228,90 @@ owner when the new method supports that owner. The Paperclip-managed method signs every broker request with one explicit profile. The broker binds that profile into sessions, one-time claims, sealed -token envelopes, and refresh. Per-profile removal is local-only for managed -Google grants. Google's revocation endpoint can invalidate all grants for the -same user and managed client, so Paperclip does not call it while removing one -Workspace profile. +token envelopes, and refresh. + +### Removing a managed Google connection + +Removing a Paperclip-managed Google connection, or one of its per-user, +organization or per-agent grants, sends each removed grant's refresh token to +Paperclip Cloud's signed `POST /v1/connector/revoke`. Revoke signs with the +subject that consented to the grant (`providerTenant.externalId`, saved by the +managed callback), which is the subject of the broker's ledger row from the +claim. Grants saved without it fall back to the subject refresh uses. Refresh +keeps its own existing subject rule. + +The broker removes its record for that token. It revokes at Google only when it +knows of no other live binding that could share the grant, because Google's +revoke ends the user's whole grant to the managed client. A repeated call for a +token it already removed returns the outcome it recorded. Its `outcome` is one +of `revoked`, `other_connections_remain`, `provider_revocation_failed`, +`binding_not_known`, `provider_revocation_disabled` or +`revocation_in_progress`. The app adds `revocation_not_available` (an older +broker's 409), `broker_unavailable` (timeout, network failure or no usable +Cloud client), `broker_error`, `credential_unavailable` and +`unexpected_error`. + +Order for removing a whole connection: read the refresh tokens; run the whole +local teardown (grants, installs, the app-managed profile, gateway tokens and +sessions, runtime slots, catalog status, OAuth state, archive the connection); +then call the broker, one token at a time under one 5-second deadline; then +delete the refresh-token secrets that were sent, whatever the outcome; then +delete the remaining secrets. The broker step never throws, is never retried, +and never changes the local outcome. A failure anywhere in the teardown makes +no broker call and leaves the token in place. + +Order for removing one grant: read the token, commit the grant revocation, +call the broker, then delete the grant's refresh-token secret. + +Deletion is compare-and-delete. Whether the connection owns the secret is +checked first. Then `secrets.remove(secretId, { expectedVersion })` claims the +row in one statement only if it is not deleted and its `latestVersion` still +equals the version that was read, and only then runs the usual provider-side +deletion and row removal. No caller transaction or row lock is held, and the +broker call never runs inside a transaction. A managed Google sign-in that finishes +during the call always writes a new version of the refresh token, so the new +sign-in's token is never deleted, and a later removal sends that new token. A +sign-in that returns no refresh token is refused before anything is written +(`oauth_refresh_missing`), so it cannot reactivate the grant with the old +token. During a whole- +connection removal a sign-in cannot complete after the teardown: the teardown +deletes the connection's OAuth states, and the callback must consume its state +in its own transaction. An organization +grant shares its secrets with the connection's own credential (the shared +sign-in writes the same refs to both), so revoking it alone neither calls the +broker nor deletes the secret; removing the connection does both. The same +holds for any refresh-token secret still used by another live grant or +connection. + +A revoked managed Google grant whose refresh-token secret still exists, and is +used by nothing live, is a revocation still owed (for example, the process +stopped after the teardown and before the call). Every later removal of that +grant or connection sends it, then deletes the secret. Once the secret is +gone, nothing is sent again. The token outlives the removal only in that crash +window. + +`providerAccess: { provider, result, outcomes }` is returned with the removal +and recorded in its activity entry, codes only. Once the broker call settles, +the connection's audit history also gets a `connection.google_access_removal` +event with `reasonCode` set to the result and `providerAccess` (plus `grantId` +for a single grant) in its details. This includes owed revocations sent on a +retry. If that write fails, the removal still succeeds and the failure is +logged. The result is judged over the +distinct tokens sent: + +| Outcomes | `result` | Message | +| --- | --- | --- | +| Every token `revoked` | `ended` | Access was ended at Google | +| Any other code (failure, not known, unavailable, error) | `not_ended` | Could not end access; link to https://myaccount.google.com/connections | +| Only `other_connections_remain` | `other_connections_remain` | Other connections keep access | +| At least one `revoked`, the rest `other_connections_remain` | `ended_unconfirmed` | Access was ended; check Google if more than one account was connected; link to the same page | + +The last row is the sequence the broker returns for two tokens of one Google +grant sent one at a time, but two different Google accounts can return it too. +Grants record no Google account identity (none of the 14 scopes returns one), +so the app cannot report `ended` for it. + +Connections on a customer-owned Google OAuth client are removed locally only. | App | Read profile | Write profile | | --- | --- | --- | diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 5bc1a2b047c..6d03b4932fd 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -271,7 +271,7 @@ nested run answers and migrated log originals. | Raw provider traces | Full traffic | No. Admin opt-in, encrypted, expire within 24 hours. | | Feedback exports already sent | Run logs the user chose to share | No. Already outside Paperclip. | | Optional model check for injection screening | If a company turns it on, the full tool result is sent to an OpenRouter model | Not stored by Paperclip. | -| Connection removal | Deletes tokens locally | Does not revoke at Google. | +| Connection removal | Deletes tokens locally | Asks Paperclip Cloud to revoke at Google; it does so only when no other connection could share the grant. Customer-owned clients stay local. | What "Delete data" keeps: the record that each call happened (time, tool, agent, outcome, size, fingerprint), and activity entries with counts only. diff --git a/docs/api/tool-connections.md b/docs/api/tool-connections.md new file mode 100644 index 00000000000..c45df84c029 --- /dev/null +++ b/docs/api/tool-connections.md @@ -0,0 +1,50 @@ +--- +title: Tool Connections +summary: Remove a connection or one of its grants, and read what happened at the provider +--- + +Removing a connection or a grant always completes in Paperclip. The response says what happened at the provider when Paperclip can ask the provider to end access. + +## Remove a Connection + +``` +DELETE /api/tool-connections/{connectionId} +DELETE /api/tool-connections/{connectionId}?deleteStoredContent=true +``` + +The caller needs `connections:configure` for the connection. Only a board user can set `deleteStoredContent=true`. + +The `200` response is the archived connection with a `removal` object. `removal` holds counts of what was torn down, for example `secretsRevoked` and `grantsRevoked`. With `deleteStoredContent=true`, the response also has `contentDeletion`. + +## Remove a Grant + +``` +DELETE /api/tool-connections/{connectionId}/grants/{grantId} +``` + +The caller needs `connections:configure` for the connection, or must be the grant's own user. The `200` response is the revoked grant. + +## Google Access (`providerAccess`) + +For a Google connection that Paperclip Cloud manages, the connection response has `removal.providerAccess` and the grant response has `providerAccess`. Other connections do not have this field. + +```json +{ + "provider": "google", + "result": "ended", + "outcomes": ["revoked"] +} +``` + +`result` is one of: + +| `result` | Meaning | +| --- | --- | +| `ended` | Google ended Paperclip's access for every removed grant. | +| `ended_unconfirmed` | Google ended access for at least one removed grant, and the others reported other connections. Paperclip cannot tell whether they were the same Google account. | +| `other_connections_remain` | Other Paperclip connections still use this Google account, so Google keeps the access. | +| `not_ended` | Paperclip could not end the access at Google for at least one removed grant. The user can remove it at https://myaccount.google.com/connections. | + +`outcomes` has one code for each refresh token Paperclip sent, in order. The codes are for diagnosis, not for display. + +A failure to end access at Google does not undo the local removal. On both routes the local removal completes first, then Paperclip asks Paperclip Cloud to end access at Google, and it never retries in the request. Revoking an organization grant whose token the connection itself still uses does not end access at Google and has no `providerAccess`; removing the connection does. The activity entry for the removal records the same `providerAccess`, and the connection's audit history gets a `connection.google_access_removal` event with it. diff --git a/docs/docs.json b/docs/docs.json index 55989359f45..5c818919af0 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -130,6 +130,7 @@ "api/costs", "api/secrets", "api/tool-gateway-tokens", + "api/tool-connections", "api/activity", "api/dashboard" ] diff --git a/docs/guides/board-operator/deleting-connection-data.md b/docs/guides/board-operator/deleting-connection-data.md index 831a8db2ca1..5c431ce9e9a 100644 --- a/docs/guides/board-operator/deleting-connection-data.md +++ b/docs/guides/board-operator/deleting-connection-data.md @@ -32,6 +32,8 @@ You need permission to manage the connection. 2. Select **Also delete data read through this connection**. 3. Select **Remove connection**. +For a Google connection that Paperclip set up for you, removing the connection also asks Google to end Paperclip's access to that Google account. The message after removal tells you whether access was ended. If other Paperclip connections still use the same Google account, Google keeps Paperclip's access until you remove those too. If Paperclip could not end access at Google, remove Paperclip from your Google account's [third-party connections](https://myaccount.google.com/connections). Connections that use your own Google OAuth app are removed only in Paperclip. + Deletion starts right away and continues in the background. It finishes even if Paperclip restarts while it runs. If a step fails, for example because file storage is unavailable, Paperclip keeps the request open and tries again until every step succeeds. It reports the deletion as finished only then. The connection's page shows when the data was last deleted. ## What is deleted diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6a606abbcc6..0ee8c415f1d 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1561,6 +1561,9 @@ export type { ToolConnectionInstallTargetType, ToolConnectionRemovalResult, ToolConnectionRemovalSummary, + ManagedGoogleAccessRemoval, + ManagedGoogleRevocationOutcome, + ConnectionGrantRevocationResult, ToolConnectionStoredContent, ToolConnectionStoredContentCounts, ToolConnectionContentDeletion, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 9c93d353993..e753d49a5cb 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -562,6 +562,9 @@ export type { ToolConnectionInstallTargetType, ToolConnectionRemovalResult, ToolConnectionRemovalSummary, + ManagedGoogleAccessRemoval, + ManagedGoogleRevocationOutcome, + ConnectionGrantRevocationResult, ToolConnectionStoredContent, ToolConnectionStoredContentCounts, ToolConnectionContentDeletion, diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 6c091a9bd1a..978cac1aca7 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -427,8 +427,32 @@ export interface ToolConnectionRemovalSummary { appSubjectCleanup: "not_applicable" | "manage_in_vercel"; manageUrl: string; } | null; + providerAccess?: ManagedGoogleAccessRemoval | null; } +export type ManagedGoogleRevocationOutcome = + | "revoked" + | "other_connections_remain" + | "provider_revocation_failed" + | "binding_not_known" + | "provider_revocation_disabled" + | "revocation_in_progress" + | "revocation_not_available" + | "broker_unavailable" + | "broker_error" + | "credential_unavailable" + | "unexpected_error"; + +export interface ManagedGoogleAccessRemoval { + provider: "google"; + result: "ended" | "ended_unconfirmed" | "other_connections_remain" | "not_ended"; + outcomes: ManagedGoogleRevocationOutcome[]; +} + +export type ConnectionGrantRevocationResult = ConnectionGrant & { + providerAccess?: ManagedGoogleAccessRemoval | null; +}; + export interface ToolConnectionRemovalResult { connection: ToolConnection; removal: ToolConnectionRemovalSummary; diff --git a/server/src/__tests__/google-managed-connection-removal.test.ts b/server/src/__tests__/google-managed-connection-removal.test.ts new file mode 100644 index 00000000000..2ef0c5050fa --- /dev/null +++ b/server/src/__tests__/google-managed-connection-removal.test.ts @@ -0,0 +1,682 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, + authUsers, + companies, + companyMemberships, + companySecretBindings, + companySecrets, + companySecretVersions, + connectionGrants, + connectionTokenIssuances, + createDb, + secretAccessEvents, + toolAccessAuditEvents, + toolApplications, + toolCatalogEntries, + toolConnectionContentDeletions, + toolConnectionInstalls, + toolConnections, + toolOauthStates, + toolProfileBindings, + toolProfileEntries, + toolProfiles, + userSecretDeclarations, + userSecretDefinitions, +} from "@paperclipai/db"; +import { and, eq, isNull, ne } from "drizzle-orm"; +import { GOOGLE_WORKSPACE_CONNECTOR_PROFILES } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { toolAccessService } from "../services/tool-access.js"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { errorHandler } from "../middleware/index.js"; +import { logger } from "../middleware/logger.js"; +import { PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js"; +import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +const REFRESH_TOKEN = "gmail-refresh-token-do-not-log"; + +function fakeConnector(companyId: string, userId: string) { + const credentials = { + v: 1 as const, + accessToken: "gmail-access-token", + refreshToken: REFRESH_TOKEN, + tokenType: "Bearer", + accessTokenExpiresAt: new Date(Date.now() + 3_600_000).toISOString(), + refreshTokenExpiresAt: null, + scopes: [...GOOGLE_WORKSPACE_CONNECTOR_PROFILES["gmail.draft"].scopes], + subject: userId, + companyId, + instanceId: "test-instance", + environment: "development" as const, + provider: "google" as const, + profile: "gmail.draft" as const, + }; + return { + getCapabilities: vi.fn(async () => ["gmail.draft" as const]), + startAuthorization: vi.fn(async ({ returnState }: { returnState: string }) => ({ + authorizationUrl: `https://accounts.google.com/o/oauth2/v2/auth?state=${encodeURIComponent(returnState)}`, + expiresAt: new Date(Date.now() + 600_000).toISOString(), + })), + claim: vi.fn(async ({ subject }: { subject: string }) => subject === userId + ? credentials + : { ...credentials, subject, refreshToken: `${subject}-refresh-do-not-log`, accessToken: `${subject}-access` }), + refresh: vi.fn(async () => credentials), + revoke: vi.fn(async (_values: { subject: string; token: string }): Promise<{ outcome?: string }> => ({ outcome: "revoked" })), + }; +} + +function toolsListFetch() { + return vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const body = JSON.parse(String(init?.body)); + if (body.method === "notifications/initialized") return new Response(null, { status: 202 }); + return Response.json({ jsonrpc: "2.0", id: body.id, + result: body.method === "initialize" ? { protocolVersion: "2025-06-18" } : { tools: [] } }); + }); +} + +describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-google-removal-"); + db = createDb(tempDb.connectionString, { maxConnections: 4 }); + await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: true }); + }, 20_000); + + afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + await db.delete(toolConnectionContentDeletions); + await db.delete(toolOauthStates); + await db.delete(connectionTokenIssuances); + await db.delete(connectionGrants); + await db.delete(secretAccessEvents); + await db.delete(companySecretBindings); + await db.delete(userSecretDeclarations); + await db.delete(companySecretVersions); + await db.delete(companySecrets); + await db.delete(userSecretDefinitions); + await db.delete(activityLog); + await db.delete(toolAccessAuditEvents); + await db.delete(toolConnectionInstalls); + await db.delete(toolProfileBindings); + await db.delete(toolProfileEntries); + await db.delete(toolProfiles); + await db.delete(toolCatalogEntries); + await db.delete(toolConnections); + await db.delete(toolApplications); + await db.delete(companyMemberships); + await db.delete(companies); + await db.delete(authUsers); + }); + + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await tempDb?.cleanup(); + }); + + async function connectManagedGmail(grantKind: "user" | "organization" = "user") { + const [company] = await db.insert(companies).values({ + name: `Google removal ${randomUUID()}`, + issuePrefix: `GR${randomUUID().slice(0, 6).toUpperCase()}`, + }).returning(); + const userId = `google-removal-${randomUUID()}`; + await db.insert(companyMemberships).values({ + companyId: company!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner", + }); + const connector = fakeConnector(company!.id, userId); + const cloudConnector = connector as unknown as PaperclipCloudConnector; + const service = toolAccessService(db, { + paperclipCloudConnector: cloudConnector, + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], + remoteHttpRequest: async (url, init) => fetch(url, init), + }); + const actor = { actorType: "user" as const, actorId: userId }; + toolsListFetch(); + const connected = await service.connectGalleryApp(company!.id, { + galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind, name: "Gmail", + }, 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: "removal-claim", actor, + }); + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { + type: "board", userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null, + isInstanceAdmin: false, source: "session", companyIds: [company!.id], + memberships: [{ companyId: company!.id, membershipRole: "owner", status: "active" }], + }; + next(); + }); + app.use("/api", toolAccessRoutes(db, { + paperclipCloudConnector: cloudConnector, + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], + remoteHttpRequest: async (url, init) => fetch(url, init), + })); + app.use(errorHandler); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId)); + return { company: company!, userId, connector, app, service, connectionId: connected.connectionId, grant: grant! }; + } + + async function googleAudit(connectionId: string) { + const rows = await db.select().from(toolAccessAuditEvents).where(and( + eq(toolAccessAuditEvents.connectionId, connectionId), eq(toolAccessAuditEvents.action, "connection.google_access_removal"))); + return rows.map((row) => ({ reasonCode: row.reasonCode, providerAccess: (row.details as Record).providerAccess })); + } + + async function liveSecretCount(companyId: string) { + return (await db.select({ id: companySecrets.id }).from(companySecrets) + .where(and(eq(companySecrets.companyId, companyId), isNull(companySecrets.deletedAt)))).length; + } + + it.each([ + ["revoked", "ended"], + ["other_connections_remain", "other_connections_remain"], + ["provider_revocation_failed", "not_ended"], + ["binding_not_known", "not_ended"], + ["provider_revocation_disabled", "not_ended"], + ["revocation_in_progress", "not_ended"], + ] as const)("asks Cloud to end Google access and reports %s as %s", async (outcome, result) => { + const fixture = await connectManagedGmail(); + fixture.connector.revoke.mockResolvedValue({ outcome }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(fixture.connector.revoke).toHaveBeenCalledWith({ + subject: fixture.userId, companyId: fixture.company.id, profile: "gmail.draft", token: REFRESH_TOKEN, timeoutMs: expect.any(Number), + }); + const [{ timeoutMs }] = fixture.connector.revoke.mock.calls[0] as unknown as [{ timeoutMs: number }]; + expect(timeoutMs).toBeGreaterThan(4_000); + expect(timeoutMs).toBeLessThanOrEqual(5_000); + expect(response.body.removal.providerAccess).toEqual({ provider: "google", result, outcomes: [outcome] }); + const [entry] = await db.select().from(activityLog).where(and( + eq(activityLog.companyId, fixture.company.id), eq(activityLog.action, "tool_connection.archived"))); + expect(entry!.details).toMatchObject({ providerAccess: { provider: "google", result, outcomes: [outcome] } }); + expect(JSON.stringify(entry!.details)).not.toContain(REFRESH_TOKEN); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: result, providerAccess: { provider: "google", result, outcomes: [outcome] } }]); + }); + + it.each([ + ["revoked", "ended"], + ["other_connections_remain", "other_connections_remain"], + ["binding_not_known", "not_ended"], + ] as const)("records %s for a single grant in the audit history and keeps the existing audit field", async (outcome, result) => { + const fixture = await connectManagedGmail(); + fixture.connector.revoke.mockResolvedValue({ outcome }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: result, providerAccess: { provider: "google", result, outcomes: [outcome] } }]); + const [revoked] = await db.select().from(toolAccessAuditEvents).where(and( + eq(toolAccessAuditEvents.connectionId, fixture.connectionId), eq(toolAccessAuditEvents.action, "connection_grant.revoked"))); + expect(revoked!.details).toMatchObject({ providerRevocation: "not_applicable" }); + expect(revoked!.details).not.toHaveProperty("providerAccess"); + }); + + it("still removes the connection when the audit record of the Google result cannot be written", async () => { + const fixture = await connectManagedGmail(); + const insert = db.insert.bind(db); + vi.spyOn(db, "insert").mockImplementation(((table: unknown) => { + if (table === toolAccessAuditEvents) throw new Error("audit unavailable"); + return insert(table as never); + }) as never); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] }); + }); + + it.each([ + ["an older broker", new PaperclipCloudConnectorError("rejected", "REAUTHORIZATION_REQUIRED", 409, undefined, "REVOCATION_NOT_AVAILABLE"), "revocation_not_available"], + ["a broker timeout", new PaperclipCloudConnectorError("Paperclip Cloud connector is unavailable", "CONNECTOR_UNAVAILABLE"), "broker_unavailable"], + ["a network error", new TypeError("fetch failed"), "broker_error"], + ] as const)("still removes the connection locally after %s", async (_label, error, outcome) => { + const fixture = await connectManagedGmail(); + fixture.connector.revoke.mockRejectedValue(error); + const logged: unknown[] = []; + for (const level of ["trace", "debug", "info", "warn", "error", "fatal"] as const) { + vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => { logged.push(args); }) as never); + } + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(response.body.status).toBe("archived"); + expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "not_ended", outcomes: [outcome] }); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + expect(connection!.credentialSecretRefs).toEqual([]); + expect(JSON.stringify(logged)).not.toContain(REFRESH_TOKEN); + }); + + it("ends access at Google only after every local access path is closed", async () => { + const fixture = await connectManagedGmail(); + const seen: Array<{ connection?: string; grant?: string; installs: number; refreshStored: boolean }> = []; + const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + fixture.connector.revoke.mockImplementation(async () => { + const [row] = await db.select({ status: toolConnections.status, enabled: toolConnections.enabled }).from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, fixture.connectionId)); + const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt))); + seen.push({ connection: row?.enabled ? row.status : `${row?.status}:disabled`, grant: grantRow?.status, installs: installs.length, refreshStored: Boolean(refresh) }); + return { outcome: "revoked" }; + }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(seen).toEqual([{ connection: "archived:disabled", grant: "revoked", installs: 0, refreshStored: true }]); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); + + it("revokes a single grant at Google only after the grant is marked revoked", async () => { + const fixture = await connectManagedGmail(); + const seen: Array = []; + fixture.connector.revoke.mockImplementation(async () => { + const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + seen.push(grantRow?.status); + return { outcome: "revoked" }; + }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + expect(seen).toEqual(["revoked"]); + }); + + it("makes no broker call when the local grant revocation fails", async () => { + const fixture = await connectManagedGmail(); + vi.spyOn(db, "transaction").mockRejectedValue(new Error("local removal failed")); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(500); + expect(fixture.connector.revoke).not.toHaveBeenCalled(); + }); + + it("makes no broker call when the teardown fails, keeps the token, and the retry sends it once", async () => { + const fixture = await connectManagedGmail(); + const transaction = vi.spyOn(db, "transaction").mockRejectedValue(new Error("teardown failed")); + + const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(failed.status).toBe(500); + expect(fixture.connector.revoke).not.toHaveBeenCalled(); + expect(await liveSecretCount(fixture.company.id)).toBeGreaterThan(0); + + transaction.mockRestore(); + const retried = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(retried.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(retried.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] }); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + + const again = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(again.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + }); + + it("sends a revocation still owed when the process stopped after the teardown and before the call", async () => { + const fixture = await connectManagedGmail(); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id)); + await db.update(toolConnections).set({ status: "archived", enabled: false }).where(eq(toolConnections.id, fixture.connectionId)); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); + + it("sends a revocation still owed when the process stopped after the grants were revoked", async () => { + const fixture = await connectManagedGmail(); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id)); + const seen: number[] = []; + fixture.connector.revoke.mockImplementation(async () => { + seen.push(await liveSecretCount(fixture.company.id)); + return { outcome: "revoked" }; + }); + const logged: unknown[] = []; + for (const level of ["trace", "debug", "info", "warn", "error", "fatal"] as const) { + vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => { logged.push(args); }) as never); + } + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: REFRESH_TOKEN })); + expect(seen[0]).toBeGreaterThan(0); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] }); + expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: "ended", providerAccess: { provider: "google", result: "ended", outcomes: ["revoked"] } }]); + expect(JSON.stringify(logged)).not.toContain(REFRESH_TOKEN); + }); + + it("makes no broker call when removal fails before the grants are revoked, and the retry sends them", async () => { + const fixture = await connectManagedGmail(); + const update = db.update.bind(db); + let failedOnce = false; + vi.spyOn(db, "update").mockImplementation(((table: unknown) => { + if (table === connectionGrants && !failedOnce) { + failedOnce = true; + throw new Error("grant revocation failed"); + } + return update(table as never); + }) as never); + + const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(failed.status).toBe(500); + expect(fixture.connector.revoke).not.toHaveBeenCalled(); + + const retried = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(retried.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: REFRESH_TOKEN })); + expect(retried.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] }); + }); + + it.each(["connection", "grant"] as const)("still completes the local %s removal when the Paperclip Cloud client cannot be created", async (path) => { + const fixture = await connectManagedGmail(); + vi.stubEnv("PAPERCLIP_ID_CONNECTOR_INSTANCE_ID", "legacy-instance"); + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { + type: "board", userId: fixture.userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null, + isInstanceAdmin: false, source: "session", companyIds: [fixture.company.id], + memberships: [{ companyId: fixture.company.id, membershipRole: "owner", status: "active" }], + }; + next(); + }); + app.use("/api", toolAccessRoutes(db, { + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], + remoteHttpRequest: async (url, init) => fetch(url, init), + })); + app.use(errorHandler); + + const response = await request(app).delete(path === "connection" + ? `/api/tool-connections/${fixture.connectionId}` + : `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + const providerAccess = path === "connection" ? response.body.removal.providerAccess : response.body.providerAccess; + expect(providerAccess).toEqual({ provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] }); + const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + expect(grantRow!.status).toBe("revoked"); + }); + + it("revokes an organization grant under the user who consented after the connection-wide subject changed", async () => { + const fixture = await connectManagedGmail("organization"); + expect(fixture.grant.kind).toBe("organization"); + const otherUserId = `google-removal-other-${randomUUID()}`; + await db.insert(companyMemberships).values({ + companyId: fixture.company.id, principalType: "user", principalId: otherUserId, status: "active", membershipRole: "owner", + }); + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + const config = { ...row!.config, oauth: { ...(row!.config.oauth as Record), connectorSubjectUserId: otherUserId } }; + await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, fixture.connectionId)); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + const sent = fixture.connector.revoke.mock.calls.map(([values]) => [values.subject, values.token]); + expect(sent).toEqual([[fixture.userId, REFRESH_TOKEN]]); + }); + + it("keeps the delete-stored-data option working alongside the Google outcome", async () => { + const fixture = await connectManagedGmail(); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}?deleteStoredContent=true`); + + expect(response.status).toBe(200); + expect(response.body.contentDeletion).toBeTruthy(); + expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] }); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); + + it("revokes only the removed grant at Google and records the outcome", async () => { + const fixture = await connectManagedGmail(); + fixture.connector.revoke.mockResolvedValue({ outcome: "other_connections_remain" }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + expect(response.body.status).toBe("revoked"); + expect(response.body.providerAccess).toEqual({ provider: "google", result: "other_connections_remain", outcomes: ["other_connections_remain"] }); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ subject: fixture.userId, token: REFRESH_TOKEN })); + const [entry] = await db.select().from(activityLog).where(and( + eq(activityLog.companyId, fixture.company.id), eq(activityLog.action, "tool_connection.grant_revoked"))); + expect(entry!.details).toMatchObject({ providerAccess: { outcomes: ["other_connections_remain"] } }); + expect(await googleAudit(fixture.connectionId)).toEqual([ + { reasonCode: "other_connections_remain", providerAccess: { provider: "google", result: "other_connections_remain", outcomes: ["other_connections_remain"] } }, + ]); + + const repeated = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + expect(repeated.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + + const removal = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(removal.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(removal.body.removal.providerAccess).toBeUndefined(); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); + + async function signInAgain(fixture: Awaited>, refreshToken: string | null) { + const actor = { actorType: "user" as const, actorId: fixture.userId }; + const started = await fixture.service.startOAuth(fixture.company.id, fixture.connectionId, { + redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor, + }); + const claimed = await fixture.connector.claim({ subject: fixture.userId }); + fixture.connector.claim.mockResolvedValueOnce({ ...claimed, refreshToken } as typeof claimed); + return () => fixture.service.completePaperclipCloudConnectorCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: `again-${randomUUID()}`, actor, + }); + } + + it.each(["connection", "grant"] as const)("deletes the sent token at the secret provider on %s removal", async (path) => { + const fixture = await connectManagedGmail(); + const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + const [refresh] = await db.select({ key: companySecrets.key, provider: companySecrets.provider }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId)); + expect(refresh!.provider).toBe("local_encrypted"); + const providerDelete = vi.spyOn(localEncryptedProvider, "deleteOrArchive"); + + const response = await request(fixture.app).delete(path === "connection" + ? `/api/tool-connections/${fixture.connectionId}` + : `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + const deletedKeys = providerDelete.mock.calls.map(([input]) => (input as { context: { secretKey: string } }).context.secretKey); + expect(deletedKeys.filter((key) => key.startsWith(refresh!.key))).toHaveLength(1); + const [row] = await db.select({ id: companySecrets.id }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId)); + expect(row).toBeUndefined(); + if (path === "connection") expect(response.body.removal.secretsRevoked).toBe(2); + }); + + it.each(["connection", "grant"] as const)("completes a %s removal on a database pool of one connection", async (path) => { + const fixture = await connectManagedGmail(); + const single = createDb(tempDb!.connectionString, { maxConnections: 1 }); + try { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { + type: "board", userId: fixture.userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null, + isInstanceAdmin: false, source: "session", companyIds: [fixture.company.id], + memberships: [{ companyId: fixture.company.id, membershipRole: "owner", status: "active" }], + }; + next(); + }); + app.use("/api", toolAccessRoutes(single, { + paperclipCloudConnector: fixture.connector as unknown as PaperclipCloudConnector, + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], + remoteHttpRequest: async (url, init) => fetch(url, init), + })); + app.use(errorHandler); + const url = path === "connection" + ? `/api/tool-connections/${fixture.connectionId}` + : `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`; + const outcome = await Promise.race([ + request(app).delete(url).then((response) => response.status), + new Promise((resolve) => setTimeout(() => resolve("timed out"), 15_000)), + ]); + expect(outcome).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt))); + expect(refresh).toBeUndefined(); + } finally { + await single.$client.end({ timeout: 1 }); + } + }, 30_000); + + it("keeps the new token when the user signs in again while Paperclip Cloud answers a grant removal", async () => { + const fixture = await connectManagedGmail(); + let finishSignIn: (() => Promise) | null = null; + fixture.connector.revoke.mockImplementation(async () => { + await finishSignIn!(); + return { outcome: "revoked" }; + }); + finishSignIn = await signInAgain(fixture, "fresh-refresh-token-do-not-log"); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + expect(grantRow!.status).toBe("active"); + fixture.connector.refresh.mockClear(); + await fixture.service.refreshOAuthGrantCredentials({ + companyId: fixture.company.id, connectionId: fixture.connectionId, grantId: fixture.grant.id, forceRefresh: true, + actor: { actorType: "user", actorId: fixture.userId }, + }); + expect(fixture.connector.refresh).toHaveBeenCalledWith(expect.objectContaining({ refreshToken: "fresh-refresh-token-do-not-log" })); + }); + + async function liveRefsToMissingSecrets(companyId: string) { + const live = new Set((await db.select({ id: companySecrets.id }).from(companySecrets) + .where(and(eq(companySecrets.companyId, companyId), isNull(companySecrets.deletedAt)))).map((row) => row.id)); + const grants = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), ne(connectionGrants.status, "revoked"))); + const connections = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), ne(toolConnections.status, "archived"))); + return [ + ...grants.flatMap((grant) => grant.credentialSecretRefs), + ...connections.flatMap((connection) => [...connection.credentialSecretRefs, ...connection.credentialRefs]), + ].filter((ref) => !live.has(ref.secretId)); + } + + it("refuses a managed Google sign-in that returns no refresh token and leaves the grant unchanged", async () => { + const fixture = await connectManagedGmail(); + + await expect((await signInAgain(fixture, null))()).rejects.toMatchObject({ details: { code: "oauth_refresh_missing" } }); + + const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + expect(grantRow!.status).toBe("active"); + expect(grantRow!.credentialSecretRefs).toEqual(fixture.grant.credentialSecretRefs); + expect(await liveRefsToMissingSecrets(fixture.company.id)).toEqual([]); + }); + + it("still deletes the old refresh token when a sign-in without one is refused while Paperclip Cloud answers a grant removal", async () => { + const fixture = await connectManagedGmail(); + const oldRefreshId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + const finishSignIn = await signInAgain(fixture, null); + let signIn: unknown = null; + fixture.connector.revoke.mockImplementation(async () => { + signIn = await finishSignIn().then(() => "completed", (error: { details?: { code?: string } }) => error.details?.code); + return { outcome: "revoked" }; + }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + expect(signIn).toBe("oauth_refresh_missing"); + const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + expect(grantRow!.status).toBe("revoked"); + const [oldRefresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(eq(companySecrets.id, oldRefreshId)); + expect(oldRefresh).toBeUndefined(); + expect(await liveRefsToMissingSecrets(fixture.company.id)).toEqual([]); + }); + + it("refuses a sign-in for a connection that was removed while Paperclip Cloud answered", async () => { + const fixture = await connectManagedGmail(); + const finishSignIn = await signInAgain(fixture, "late-refresh-token-do-not-log"); + let lateSignIn: unknown = null; + fixture.connector.revoke.mockImplementation(async () => { + lateSignIn = await finishSignIn().then(() => "completed", () => "refused"); + return { outcome: "revoked" }; + }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(lateSignIn).toBe("refused"); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); + + it("sends the new token of a grant that was signed in again after an owed revocation", async () => { + const fixture = await connectManagedGmail(); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id)); + await (await signInAgain(fixture, "renewed-refresh-token-do-not-log"))(); + const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id)); + expect(grantRow!.status).toBe("active"); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + + expect(response.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: "renewed-refresh-token-do-not-log" })); + }); + + it("keeps the refresh token when its version changes while Paperclip Cloud answers", async () => { + const fixture = await connectManagedGmail(); + const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + fixture.connector.revoke.mockImplementation(async () => { + const [row] = await db.select({ latestVersion: companySecrets.latestVersion }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId)); + await db.update(companySecrets).set({ latestVersion: row!.latestVersion + 1 }).where(eq(companySecrets.id, refreshSecretId)); + return { outcome: "revoked" }; + }); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + + expect(response.status).toBe(200); + const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt))); + expect(refresh).toBeTruthy(); + }); + + it("neither ends access at Google nor deletes the token when revoking an organization grant the connection still uses", async () => { + const fixture = await connectManagedGmail("organization"); + const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId; + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId)); + const shared = [...row!.credentialSecretRefs, ...row!.credentialRefs].some((ref) => ref.secretId === refreshSecretId); + expect(shared).toBe(true); + + const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`); + expect(response.status).toBe(200); + expect(response.body.providerAccess).toBeUndefined(); + expect(fixture.connector.revoke).not.toHaveBeenCalled(); + const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt))); + expect(refresh).toBeTruthy(); + + const removal = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); + expect(removal.status).toBe(200); + expect(fixture.connector.revoke).toHaveBeenCalledTimes(1); + expect(await liveSecretCount(fixture.company.id)).toBe(0); + }); +}); diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 0440e6f652e..7571e18b2ea 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -194,7 +194,7 @@ function fakeGoogleWorkspaceConnector( })), claim: vi.fn(async () => credentials), refresh: vi.fn(async () => credentials), - revoke: vi.fn(async () => undefined), + revoke: vi.fn(async () => ({})), } satisfies Partial as unknown as PaperclipCloudConnector; } @@ -233,7 +233,7 @@ function fakeGitHubConnector( })), claim: vi.fn(async () => credentials), refresh: vi.fn(async () => credentials), - revoke: vi.fn(async () => undefined), + revoke: vi.fn(async () => ({})), setWebhookBinding: vi.fn(async () => undefined), leaseEvents: vi.fn(async () => null), acknowledgeEvents: vi.fn(async () => 0), @@ -8264,7 +8264,10 @@ describeEmbeddedPostgres("tool access service", () => { await expect( service.revokeConnectionGrant(connected.connectionId, grant!.id, actor), ).resolves.toMatchObject({ status: "revoked" }); - expect(connector.revoke).not.toHaveBeenCalled(); + expect(connector.revoke).toHaveBeenCalledTimes(1); + expect(connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ + subject: userId, profile: "gmail.draft", token: "gmail-refresh-token", + })); } finally { if (deadline) clearTimeout(deadline); await callbackDb.$client.end({ timeout: 0 }).catch(() => undefined); @@ -14399,7 +14402,7 @@ describeEmbeddedPostgres("tool access service", () => { expiresAt: new Date(Date.now() + 600_000).toISOString(), })), claim: vi.fn(async () => credentials), refresh: vi.fn(async () => credentials), - revoke: vi.fn(async () => undefined), + revoke: vi.fn(async () => ({})), } satisfies Partial as unknown as PaperclipCloudConnector; const service = createTestToolAccessService(db, { paperclipCloudConnector: connector }); const custom = await service.connectGalleryApp(company.id, { diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 1e10c07ea01..19e87bd6507 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -12482,6 +12482,12 @@ registerCurrentRoute({ summary: "Revoke a personal tool connection grant delegation", }); +const managedGoogleAccessRemovalSchema = z.object({ + provider: z.literal("google"), + result: z.enum(["ended", "ended_unconfirmed", "other_connections_remain", "not_ended"]), + outcomes: z.array(z.string()).describe("One diagnostic code per refresh token sent to Paperclip Cloud, in order."), +}).describe("Present only for a Google connection managed by Paperclip Cloud. A failure to end access at Google does not undo the local removal."); + registerCurrentRoute({ "x-paperclip-transport": "rest", "x-paperclip-connection-management": "connections:configure", @@ -12489,6 +12495,13 @@ registerCurrentRoute({ path: "/api/tool-connections/{connectionId}/grants/{grantId}", tags: ["tool-access"], summary: "Revoke a tool connection grant", + description: "Revokes the grant locally, then, for a Google connection managed by Paperclip Cloud, asks Paperclip Cloud to end the grant's access at Google and reports the result in providerAccess.", + responses: { + 200: r.ok(z.object({ providerAccess: managedGoogleAccessRemovalSchema.optional() }).passthrough()), + 401: r.unauthorized, + 403: r.forbidden, + 404: r.notFound, + }, }); registerCurrentRoute({ @@ -12574,7 +12587,14 @@ registerCurrentRoute({ path: "/api/tool-connections/{connectionId}", tags: ["tool-access"], summary: "Archive a tool connection", + description: "Removes the connection and its credentials. For a Google connection managed by Paperclip Cloud, removal.providerAccess reports whether access was ended at Google.", query: z.object({ deleteStoredContent: z.enum(["true", "false"]).optional() }), + responses: { + 200: r.ok(z.object({ removal: z.object({ providerAccess: managedGoogleAccessRemovalSchema.optional() }).passthrough() }).passthrough()), + 401: r.unauthorized, + 403: r.forbidden, + 404: r.notFound, + }, }); registerCurrentRoute({ diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 71d4c3fe42b..2ac4ed49052 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -2008,7 +2008,7 @@ function connectorEnrollmentPrincipal(req: Request): string { action: "tool_connection.grant_revoked", entityType: "connection_grant", entityId: grant.id, - details: { connectionId: connection.id, kind: grant.kind }, + details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}) }, }); res.json(grant); }); diff --git a/server/src/services/connectors/slack/setup/development-manager.ts b/server/src/services/connectors/slack/setup/development-manager.ts index d4e71fd868a..d3b19ee5813 100644 --- a/server/src/services/connectors/slack/setup/development-manager.ts +++ b/server/src/services/connectors/slack/setup/development-manager.ts @@ -68,6 +68,7 @@ export function developmentSlackManager( async revoke(values) { try { await api("auth.revoke", {}, values.token); } catch { throw providerFailure("slack_manager_reauthorize"); } + return {}; }, }; } diff --git a/server/src/services/paperclip-cloud-connector-revoke.test.ts b/server/src/services/paperclip-cloud-connector-revoke.test.ts new file mode 100644 index 00000000000..e0cc7233f1b --- /dev/null +++ b/server/src/services/paperclip-cloud-connector-revoke.test.ts @@ -0,0 +1,80 @@ +import { createHash, generateKeyPairSync, type KeyObject } from "node:crypto"; +import { describe, expect, it, vi } from "vitest"; +import { createPaperclipCloudConnector, type PaperclipCloudConnectorConfig } from "./paperclip-cloud-connector.js"; + +const companyId = "company_test"; +const subject = "user_test"; + +function rawPrivateKey(key: KeyObject): string { + const jwk = key.export({ format: "jwk" }) as { d?: string }; + if (!jwk.d) throw new Error("missing private key bytes"); + return jwk.d; +} + +function config() { + return { + config: { + baseUrl: "https://my.example.test", + instanceId: "inst_test", + environment: "staging", + signPrivateKey: rawPrivateKey(generateKeyPairSync("ed25519").privateKey), + sealPrivateKey: rawPrivateKey(generateKeyPairSync("x25519").privateKey), + } satisfies PaperclipCloudConnectorConfig, + }; +} + +describe("Paperclip Cloud Google grant revocation", () => { + function decodeClaims(request: string) { + return JSON.parse(Buffer.from(request.split(".")[1]!, "base64url").toString("utf8")); + } + + it("signs the Google profile, sends the refresh token only in the body, and returns the broker outcome", async () => { + const bodies: Array<{ request: string; token: string }> = []; + const request = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body))); + return Response.json({ localBindingRemoved: true, revokedAtProvider: false, outcome: "other_connections_remain" }); + }); + const connector = createPaperclipCloudConnector({ config: config().config, request: request as typeof fetch }); + await expect(connector.revoke({ subject, companyId, profile: "workspace.all", token: "refresh-secret" })) + .resolves.toEqual({ outcome: "other_connections_remain" }); + expect(String(request.mock.calls[0]![0])).toBe("https://my.example.test/v1/connector/revoke"); + const claims = decodeClaims(bodies[0]!.request); + expect(claims).toMatchObject({ op: "revoke", sub: subject, cid: companyId, prv: "google", prf: "workspace.all" }); + expect(claims.sh).toBe(createHash("sha256").update("refresh-secret").digest("base64url")); + expect(bodies[0]!.token).toBe("refresh-secret"); + expect(bodies[0]!.request).not.toContain("refresh-secret"); + }); + + it.each(["revoked", "provider_revocation_failed", "binding_not_known", "provider_revocation_disabled", "revocation_in_progress"])( + "accepts the %s outcome", + async (outcome) => { + const connector = createPaperclipCloudConnector({ config: config().config, + request: vi.fn(async () => Response.json({ outcome })) as typeof fetch }); + await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" })).resolves.toEqual({ outcome }); + }, + ); + + it("drops an unknown outcome", async () => { + const connector = createPaperclipCloudConnector({ config: config().config, + request: vi.fn(async () => Response.json({ outcome: "DO_NOT_REPORT" })) as typeof fetch }); + await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" })).resolves.toEqual({}); + }); + + it("reports an older broker's 409 as revocation not available", async () => { + const connector = createPaperclipCloudConnector({ config: config().config, + request: vi.fn(async () => Response.json({ error: "REVOCATION_NOT_AVAILABLE" }, { status: 409 })) as typeof fetch }); + await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" })) + .rejects.toMatchObject({ status: 409, brokerReason: "REVOCATION_NOT_AVAILABLE" }); + }); + + it("aborts the broker call at the requested timeout", async () => { + const request = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(new Error("aborted"))); + })); + const connector = createPaperclipCloudConnector({ config: config().config, request: request as unknown as typeof fetch }); + const started = Date.now(); + await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t", timeoutMs: 50 })) + .rejects.toMatchObject({ code: "CONNECTOR_UNAVAILABLE" }); + expect(Date.now() - started).toBeLessThan(2_000); + }); +}); diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index cfcabde5cff..a5078c4f3dd 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -160,7 +160,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_REAUTHORIZATION_REQUIRED", + "PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED", "REVOCATION_NOT_AVAILABLE", "SLACK_ENROLLMENT_GENERATION_CHANGED", "SLACK_ENROLLMENT_IDENTITY_CHANGED", "SLACK_ENROLLMENT_CHANGED", "SLACK_ENROLLMENT_UNSETTLED", "SLACK_ENROLLMENT_DISABLED", "SLACK_COMPANY_MISMATCH", "SLACK_EVENTS_UNAVAILABLE", @@ -169,6 +169,12 @@ const BROKER_REJECTION_REASONS = new Set([ ]); const UNKNOWN_BROKER_REASON = "UNKNOWN_BROKER_ERROR"; +export const PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES = [ + "revoked", "other_connections_remain", "provider_revocation_failed", + "binding_not_known", "provider_revocation_disabled", "revocation_in_progress", +] as const; +export type PaperclipCloudGrantRevocationOutcome = typeof PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES[number]; + async function readBrokerRejectionReason(response: Response): Promise { if (response.bodyUsed || response.body?.locked) return UNKNOWN_BROKER_REASON; const reader = response.body?.getReader(); @@ -301,6 +307,7 @@ export function createPaperclipCloudConnector(input: { operation: PaperclipCloudConnectorOperation, claims: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; returnUri?: string; returnState?: string; claimId?: string; redemptionId?: string; eventWakeVersion?: 0 | 1 }, secret?: { field: "refreshToken" | "token" | "binding" | "acknowledgement" | "enrollment" | "operation"; value: string }, + timeoutMs = 15_000, ): Promise { const endpoint = new URL(ENDPOINTS[operation], `${config.baseUrl}/`).toString(); const issuedAt = Math.floor(now() / 1000); @@ -344,7 +351,7 @@ export function createPaperclipCloudConnector(input: { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: encodedBody, - signal: AbortSignal.timeout(15_000), + signal: AbortSignal.timeout(timeoutMs), }); } catch { throw new PaperclipCloudConnectorError("Paperclip Cloud connector is unavailable", "CONNECTOR_UNAVAILABLE"); @@ -588,8 +595,13 @@ export function createPaperclipCloudConnector(input: { profile, ); }, - async revoke(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; token: string }) { - await call("revoke", { ...values, profile: values.profile ?? "gmail.draft" }, { field: "token", value: values.token }); + async revoke(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; token: string; timeoutMs?: number }): Promise<{ outcome?: PaperclipCloudGrantRevocationOutcome }> { + const { timeoutMs, ...claims } = values; + const response = await call("revoke", { ...claims, profile: claims.profile ?? "gmail.draft" }, { field: "token", value: claims.token }, timeoutMs); + const outcome = (response as ConnectorResponse & { outcome?: unknown }).outcome; + return typeof outcome === "string" && (PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES as readonly string[]).includes(outcome) + ? { outcome: outcome as PaperclipCloudGrantRevocationOutcome } + : {}; }, async setWebhookBinding(values: { subject: string; diff --git a/server/src/services/secrets.ts b/server/src/services/secrets.ts index 6c0d8d44e59..11ec3d36fb3 100644 --- a/server/src/services/secrets.ts +++ b/server/src/services/secrets.ts @@ -985,6 +985,7 @@ function assertSelectableProviderConfig(config: { export type RemoveSecretOptions = { /** Runs after the secret is marked deleted and before its row is removed. */ beforeDelete?: (secret: typeof companySecrets.$inferSelect) => Promise; + expectedVersion?: number; }; export function secretService(db: Db | DbTransaction) { @@ -3453,9 +3454,28 @@ export function secretService(db: Db | DbTransaction) { async function removeSecretInternal(secretId: string, options: RemoveSecretOptions = {}) { const preCheckSecret = await getById(secretId); if (!preCheckSecret) return null; - return withAccountHomeSecretMutationLock(undefined, preCheckSecret.companyId, () => - removeSecretUnlocked(secretId, options), - ); + return withAccountHomeSecretMutationLock(undefined, preCheckSecret.companyId, async () => { + if (options.expectedVersion !== undefined) { + const now = new Date(); + const claimed = await db + .update(companySecrets) + .set({ + key: sql`${companySecrets.key} || '__deleted__' || ${companySecrets.id}`, + name: sql`${companySecrets.name} || '__deleted__' || ${companySecrets.id}`, + status: "deleted", + deletedAt: now, + updatedAt: now, + }) + .where(and( + eq(companySecrets.id, secretId), + isNull(companySecrets.deletedAt), + eq(companySecrets.latestVersion, options.expectedVersion), + )) + .returning({ id: companySecrets.id }); + if (claimed.length === 0) return null; + } + return removeSecretUnlocked(secretId, options); + }); } // The body of `removeSecretInternal` above, unchanged. Extracted to a named diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 27984e78e69..d5ae794a920 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -785,8 +785,8 @@ export function toolAccessService( ? createVercelConnectClient() : options.vercelConnectClient; const runtimeSupervisor = createToolRuntimeSupervisor(db, options); - const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect }); - const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, getConnectionRow }); + const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets }); + const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow }); /** * Connection setup resolves connector definitions synchronously. Refresh the * plugin-provided part of the catalog from the plugins table first, so a diff --git a/server/src/services/tool-access/connections/google-access-removal.test.ts b/server/src/services/tool-access/connections/google-access-removal.test.ts new file mode 100644 index 00000000000..5225247469f --- /dev/null +++ b/server/src/services/tool-access/connections/google-access-removal.test.ts @@ -0,0 +1,260 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Db } from "@paperclipai/db"; + +const resolveConnectionGrantSecret = vi.hoisted(() => vi.fn()); +vi.mock("../../connection-credentials.js", () => ({ resolveConnectionGrantSecret })); + +import { createManagedGoogleAccessRemoval, summarizeManagedGoogleAccess } from "./google-access-removal.js"; +import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { logger } from "../../../middleware/logger.js"; + +const companyId = "company-1"; + +function fakeDb(rows: { grants?: unknown[]; connections?: unknown[] } = {}) { + const answer = (columns: Record) => ("secretRefs" in columns ? rows.connections ?? [] + : "refs" in columns ? rows.grants ?? [] + : "latestVersion" in columns ? [{ latestVersion: 1 }] + : "status" in columns ? [{ status: "revoked" }] : []); + const db: Record = { + insert: vi.fn(() => ({ values: vi.fn(async () => undefined) })), + update: vi.fn(() => ({ set: () => ({ where: async () => undefined }) })), + select: vi.fn((columns: Record) => ({ + from: () => ({ + where: () => { + const result = Promise.resolve(answer(columns)); + return Object.assign(result, { for: () => result }); + }, + }), + })), + }; + db.transaction = vi.fn(async (run: (tx: unknown) => Promise) => run(db)); + return db as unknown as Db; +} + +const scope = () => ({ removingConnection: true, removeSecret: vi.fn(async () => true) }); + +function connection(oauth: Record, authKind = "oauth") { + return { id: "connection-1", companyId, authKind, config: { oauth } } as never; +} + +const managedGoogle = { strategy: "paperclip_cloud_connector", connectorProfile: "workspace.all", connectorSubjectUserId: "org-owner" }; + +function grant( + id: string, + kind: string, + subject: { subjectUserId?: string; subjectAgentId?: string; consentSubject?: string }, + refreshSecretId = `${id}-refresh`, +) { + return { + id, companyId, connectionId: "connection-1", kind, + subjectUserId: subject.subjectUserId ?? null, + subjectAgentId: subject.subjectAgentId ?? null, + providerTenant: subject.consentSubject ? { externalId: subject.consentSubject } : null, + credentialSecretRefs: [ + { configPath: "oauth.access_token", secretId: `${id}-access` }, + { configPath: "oauth.refresh_token", secretId: refreshSecretId }, + ], + } as never; +} + +type RevokeValues = Parameters[0]; + +function connectorWith(revoke: (values: RevokeValues) => Promise<{ outcome?: string }>) { + return { revoke: vi.fn(revoke) } as unknown as PaperclipCloudConnector & { revoke: ReturnType }; +} + +async function run( + removal: ReturnType, + oauth: Record, + grants: never[], + authKind?: string, +) { + const prepared = await removal.prepare(connection(oauth, authKind), grants, undefined, scope()); + return prepared ? prepared.send() : null; +} + +describe("managed Google access removal", () => { + beforeEach(() => { + vi.restoreAllMocks(); + resolveConnectionGrantSecret.mockReset(); + resolveConnectionGrantSecret.mockImplementation(async (_db, _connection, _grant, ref: { secretId: string }) => ({ value: `token-for-${ref.secretId}`, latestVersion: 1 })); + }); + + it("revokes per-user, per-agent and organization grants each under the subject that consented", async () => { + const connector = connectorWith(async () => ({ outcome: "revoked" })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, managedGoogle, [ + grant("user-grant", "user", { subjectUserId: "user-1", consentSubject: "user-1" }), + grant("agent-grant", "agent", { subjectAgentId: "agent-1", consentSubject: "agent:agent-1" }), + grant("org-grant", "organization", { consentSubject: "first-consenter" }), + grant("old-org-grant", "organization", {}), + ])).resolves.toEqual({ provider: "google", result: "ended", outcomes: ["revoked", "revoked", "revoked", "revoked"] }); + expect(connector.revoke.mock.calls.map(([values]) => [values.subject, values.token, values.profile])).toEqual([ + ["user-1", "token-for-user-grant-refresh", "workspace.all"], + ["agent:agent-1", "token-for-agent-grant-refresh", "workspace.all"], + ["first-consenter", "token-for-org-grant-refresh", "workspace.all"], + ["org-owner", "token-for-old-org-grant-refresh", "workspace.all"], + ]); + }); + + it("sends a refresh token shared by two grants once", async () => { + const connector = connectorWith(async () => ({ outcome: "revoked" })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await run(removal, managedGoogle, [ + grant("org-grant", "organization", {}, "shared-refresh"), + grant("user-grant", "user", { subjectUserId: "org-owner" }, "shared-refresh"), + ]); + expect(connector.revoke).toHaveBeenCalledTimes(1); + }); + + it("sends two grants of one user one after the other and reports access ended but unconfirmed", async () => { + let inFlight = 0; + let maxInFlight = 0; + const outcomes = ["other_connections_remain", "revoked"]; + const connector = connectorWith(async () => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + await new Promise((resolve) => setTimeout(resolve, 5)); + inFlight -= 1; + return { outcome: outcomes.shift() }; + }); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, managedGoogle, [ + grant("org-grant", "organization", { consentSubject: "user-1" }), + grant("user-grant", "user", { subjectUserId: "user-1", consentSubject: "user-1" }), + ])).resolves.toEqual({ provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] }); + expect(maxInFlight).toBe(1); + expect(connector.revoke.mock.calls.map(([values]) => values.token)).toEqual([ + "token-for-org-grant-refresh", "token-for-user-grant-refresh", + ]); + }); + + it.each([ + "binding_not_known", "provider_revocation_failed", "revocation_in_progress", + ])("reports access not ended when one token was revoked and another reports %s", async (later) => { + const outcomes = ["revoked", later]; + const connector = connectorWith(async () => ({ outcome: outcomes.shift() })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, managedGoogle, [ + grant("a", "user", { consentSubject: "user-1" }), + grant("b", "organization", { consentSubject: "user-1" }), + ])).resolves.toMatchObject({ result: "not_ended" }); + }); + + it.each([ + ["a customer-owned Google client", { strategy: "authorization_code", provider: "google" }, "oauth"], + ["a managed GitHub connection", { strategy: "paperclip_cloud_connector", connectorProfile: "github.code" }, "oauth"], + ["a non-OAuth connection", managedGoogle, "api_key"], + ])("makes no broker call for %s", async (_label, oauth, authKind) => { + const connector = connectorWith(async () => ({ outcome: "revoked" })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, oauth, [grant("user-grant", "user", { subjectUserId: "user-1" })], authKind)).resolves.toBeNull(); + expect(connector.revoke).not.toHaveBeenCalled(); + expect(resolveConnectionGrantSecret).not.toHaveBeenCalled(); + }); + + it("reports access not ended when Paperclip Cloud is not configured or the token is unreadable", async () => { + resolveConnectionGrantSecret.mockRejectedValueOnce(new Error("missing")); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => null }); + await expect(run(removal, managedGoogle, [ + grant("user-grant", "user", { subjectUserId: "user-1" }), + grant("agent-grant", "agent", { subjectAgentId: "agent-1" }), + ])).resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["credential_unavailable", "broker_unavailable"] }); + }); + + it("reports access not ended when creating the Paperclip Cloud client throws", async () => { + const removal = createManagedGoogleAccessRemoval(fakeDb(), { + currentCloudConnector: () => { throw new Error("instance key is invalid"); }, + }); + await expect(run(removal, managedGoogle, [grant("user-grant", "user", { subjectUserId: "user-1" })])) + .resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] }); + }); + + it("logs an unexpected failure without the token and reports access not ended", async () => { + const warn = vi.spyOn(logger, "warn").mockImplementation((() => undefined) as never); + const broken = { ...(grant("user-grant", "user", { subjectUserId: "user-1" }) as object) }; + Object.defineProperty(broken, "credentialSecretRefs", { get() { throw new TypeError("token-for-user-grant-refresh"); } }); + const connector = connectorWith(async () => ({ outcome: "revoked" })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, managedGoogle, [broken as never])) + .resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["unexpected_error"] }); + expect(warn).toHaveBeenCalledTimes(1); + expect(JSON.stringify(warn.mock.calls)).not.toContain("token-for-user-grant-refresh"); + expect(connector.revoke).not.toHaveBeenCalled(); + }); + + it("bounds all broker calls of one removal by a single deadline", async () => { + let clock = 0; + const connector = connectorWith(async (values) => { + clock += values.timeoutMs ?? 0; + return { outcome: "other_connections_remain" }; + }); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector, timeoutMs: 5_000, now: () => clock }); + await expect(run(removal, managedGoogle, [ + grant("a", "user", { consentSubject: "user-1" }), + grant("b", "user", { consentSubject: "user-2" }), + ])).resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["other_connections_remain", "broker_unavailable"] }); + expect(connector.revoke).toHaveBeenCalledTimes(1); + expect(connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 5_000 })); + }); + + it("reports a per-agent connection whose last agent grant was revoked as ended but unconfirmed", async () => { + const outcomes = ["other_connections_remain", "revoked"]; + const connector = connectorWith(async () => ({ outcome: outcomes.shift() })); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + await expect(run(removal, managedGoogle, [ + grant("agent-a", "agent", { subjectAgentId: "a", consentSubject: "agent:a" }), + grant("agent-b", "agent", { subjectAgentId: "b", consentSubject: "agent:b" }), + ])).resolves.toMatchObject({ result: "ended_unconfirmed" }); + }); + + it.each([ + [["revoked", "revoked"], "ended"], + [["broker_unavailable", "revoked"], "not_ended"], + [["other_connections_remain", "binding_not_known"], "not_ended"], + [["revoked", "unexpected_error"], "not_ended"], + [["other_connections_remain", "other_connections_remain"], "other_connections_remain"], + [["other_connections_remain", "revoked"], "ended_unconfirmed"], + [["revoked", "other_connections_remain"], "ended_unconfirmed"], + ] as const)("summarizes %j as %s", (outcomes, result) => { + expect(summarizeManagedGoogleAccess([...outcomes]).result).toBe(result); + }); + it("records each result, including ended_unconfirmed, as its own audit event", async () => { + const values = vi.fn(async () => undefined); + const db = { ...fakeDb(), insert: vi.fn(() => ({ values })) } as unknown as Db; + const outcomes = ["other_connections_remain", "revoked"]; + const connector = connectorWith(async () => ({ outcome: outcomes.shift() })); + const removal = createManagedGoogleAccessRemoval(db, { currentCloudConnector: () => connector }); + const prepared = await removal.prepare(connection(managedGoogle), [ + grant("agent-a", "agent", { subjectAgentId: "a", consentSubject: "agent:a" }), + grant("agent-b", "agent", { subjectAgentId: "b", consentSubject: "agent:b" }), + ], undefined, { ...scope(), grantId: "agent-a" }); + await prepared!.send(); + expect(values).toHaveBeenCalledWith(expect.objectContaining({ + action: "connection.google_access_removal", + reasonCode: "ended_unconfirmed", + details: { grantId: "agent-a", providerAccess: { provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] } }, + })); + expect(JSON.stringify(values.mock.calls)).not.toContain("token-for"); + }); + it("deletes each sent refresh token only after the broker answered, whatever the outcome", async () => { + const order: string[] = []; + const connector = connectorWith(async (values) => { order.push(`revoke:${values.token}`); return { outcome: "provider_revocation_failed" }; }); + const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector }); + const removeSecret = vi.fn(async (secretId: string) => { order.push(`delete:${secretId}`); }); + const prepared = await removal.prepare(connection(managedGoogle), [grant("user-grant", "user", { consentSubject: "user-1" })], undefined, { removingConnection: true, removeSecret }); + await prepared!.send(); + expect(order).toEqual(["revoke:token-for-user-grant-refresh", "delete:user-grant-refresh"]); + }); + + it("neither sends nor deletes a refresh token that a live connection or grant still uses", async () => { + const connector = connectorWith(async () => ({ outcome: "revoked" })); + const db = fakeDb({ connections: [{ id: "connection-1", refs: [], secretRefs: [{ secretId: "org-grant-refresh" }] }] }); + const removal = createManagedGoogleAccessRemoval(db, { currentCloudConnector: () => connector }); + const removeSecret = vi.fn(); + await expect(removal.prepare(connection(managedGoogle), [grant("org-grant", "organization", { consentSubject: "user-1" })], undefined, { removingConnection: false, removeSecret })) + .resolves.toBeNull(); + expect(connector.revoke).not.toHaveBeenCalled(); + expect(removeSecret).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/services/tool-access/connections/google-access-removal.ts b/server/src/services/tool-access/connections/google-access-removal.ts new file mode 100644 index 00000000000..d6dbf365d80 --- /dev/null +++ b/server/src/services/tool-access/connections/google-access-removal.ts @@ -0,0 +1,269 @@ +import type { Db } from "@paperclipai/db"; +import { companySecrets, connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db"; +import { and, eq, inArray, isNull, ne } from "drizzle-orm"; +import type { ManagedGoogleAccessRemoval, ManagedGoogleRevocationOutcome } from "@paperclipai/shared"; +import { logger } from "../../../middleware/logger.js"; +import { resolveConnectionGrantSecret } from "../../connection-credentials.js"; +import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { managedConnectorConsentSubject, managedConnectorProfile } from "../oauth/client-settings.js"; +import { oauthConfig } from "../oauth/metadata.js"; +import type { ActorInfo } from "../types.js"; +import { actorBinding } from "../actor.js"; + +export const MANAGED_GOOGLE_REVOKE_TIMEOUT_MS = 5_000; + +type RemovedGrant = Pick; + +type PreparedRevocation = + | { kind: "call"; subject: string; token: string } + | { kind: "skip"; outcome: ManagedGoogleRevocationOutcome }; + +export type PreparedGoogleAccessRemoval = { + send(): Promise; +}; + +export type GoogleAccessRemovalScope = { + grantId?: string; + removingConnection: boolean; + canRemoveSecret?(secretId: string): Promise; + removeSecret(secretId: string, expectedVersion: number): Promise; +}; + +function refreshSecretId(grant: RemovedGrant): string | null { + return (grant.credentialSecretRefs ?? []).find((ref) => ref.configPath === "oauth.refresh_token")?.secretId ?? null; +} + +function outcomeForError(error: unknown): ManagedGoogleRevocationOutcome { + if (!(error instanceof PaperclipCloudConnectorError)) return "broker_error"; + if (error.code === "CONNECTOR_UNAVAILABLE") return "broker_unavailable"; + if (error.status === 409 && error.brokerReason === "REVOCATION_NOT_AVAILABLE") return "revocation_not_available"; + return "broker_error"; +} + +export function summarizeManagedGoogleAccess(outcomes: ManagedGoogleRevocationOutcome[]): ManagedGoogleAccessRemoval { + const revoked = outcomes.filter((outcome) => outcome === "revoked").length; + const remaining = outcomes.filter((outcome) => outcome === "other_connections_remain").length; + const result: ManagedGoogleAccessRemoval["result"] = revoked + remaining < outcomes.length + ? "not_ended" + : revoked === outcomes.length + ? "ended" + : revoked === 0 + ? "other_connections_remain" + : "ended_unconfirmed"; + return { provider: "google", result, outcomes }; +} + +export function createManagedGoogleAccessRemoval(db: Db, deps: { + currentCloudConnector: () => PaperclipCloudConnector | null; + timeoutMs?: number; + now?: () => number; +}) { + const timeoutMs = deps.timeoutMs ?? MANAGED_GOOGLE_REVOKE_TIMEOUT_MS; + const now = deps.now ?? Date.now; + + async function send( + connection: typeof toolConnections.$inferSelect, + profile: string, + revocations: PreparedRevocation[], + ): Promise { + const outcomes: ManagedGoogleRevocationOutcome[] = []; + let connector: PaperclipCloudConnector | null = null; + let connectorUnavailable = false; + try { + connector = deps.currentCloudConnector(); + } catch { + connectorUnavailable = true; + } + const deadline = now() + timeoutMs; + for (const revocation of revocations) { + if (revocation.kind === "skip") { + outcomes.push(revocation.outcome); + continue; + } + const remaining = deadline - now(); + if (connectorUnavailable || !connector || remaining <= 0) { + outcomes.push("broker_unavailable"); + continue; + } + try { + const { outcome } = await connector.revoke({ + subject: revocation.subject, + companyId: connection.companyId, + profile: profile as Parameters[0]["profile"], + token: revocation.token, + timeoutMs: remaining, + }); + outcomes.push(outcome ?? "broker_error"); + } catch (error) { + outcomes.push(outcomeForError(error)); + } + } + const summary = summarizeManagedGoogleAccess(outcomes); + if (summary.result === "not_ended") { + logger.warn( + { companyId: connection.companyId, connectionId: connection.id, outcomes: summary.outcomes }, + "Paperclip Cloud did not end Google access for a removed connection", + ); + } + return summary; + } + + function unexpectedFailure(connection: typeof toolConnections.$inferSelect, error: unknown): PreparedGoogleAccessRemoval { + logger.warn( + { companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error }, + "Could not prepare ending Google access for a removed connection", + ); + return { send: async () => summarizeManagedGoogleAccess(["unexpected_error"]) }; + } + + async function recordAudit( + connection: typeof toolConnections.$inferSelect, + actor: ActorInfo | undefined, + scope: GoogleAccessRemovalScope, + providerAccess: ManagedGoogleAccessRemoval, + ) { + try { + const binding = actorBinding(actor); + await db.insert(toolAccessAuditEvents).values({ + companyId: connection.companyId, + connectionId: connection.id, + actorType: binding.actorType ?? "system", + actorId: binding.actorId, + action: "connection.google_access_removal", + outcome: providerAccess.result === "not_ended" ? "failure" : "success", + reasonCode: providerAccess.result, + details: { ...(scope.grantId ? { grantId: scope.grantId } : {}), providerAccess }, + }); + } catch (error) { + logger.warn( + { companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error }, + "Could not record the Google access result for a removed connection", + ); + } + } + + async function secretsHeldElsewhere( + connection: typeof toolConnections.$inferSelect, + grants: RemovedGrant[], + secretIds: string[], + removingConnection: boolean, + ): Promise> { + if (secretIds.length === 0) return new Set(); + const wanted = new Set(secretIds); + const removedGrantIds = new Set(grants.map((grant) => grant.id)); + const held = new Set(); + const liveGrants = await db.select({ id: connectionGrants.id, connectionId: connectionGrants.connectionId, refs: connectionGrants.credentialSecretRefs }) + .from(connectionGrants) + .where(and(eq(connectionGrants.companyId, connection.companyId), ne(connectionGrants.status, "revoked"))); + for (const row of liveGrants) { + if (removedGrantIds.has(row.id) || (removingConnection && row.connectionId === connection.id)) continue; + for (const ref of row.refs ?? []) if (wanted.has(ref.secretId)) held.add(ref.secretId); + } + const liveConnections = await db.select({ id: toolConnections.id, refs: toolConnections.credentialRefs, secretRefs: toolConnections.credentialSecretRefs }) + .from(toolConnections) + .where(and(eq(toolConnections.companyId, connection.companyId), ne(toolConnections.status, "archived"))); + for (const row of liveConnections) { + if (removingConnection && row.id === connection.id) continue; + for (const ref of [...(row.refs ?? []), ...(row.secretRefs ?? [])]) if (wanted.has(ref.secretId)) held.add(ref.secretId); + } + return held; + } + + async function deleteSentSecrets( + connection: typeof toolConnections.$inferSelect, + scope: GoogleAccessRemovalScope, + sent: Array<{ secretId: string; version: number }>, + ) { + for (const { secretId, version } of sent) { + try { + if (scope.canRemoveSecret && !(await scope.canRemoveSecret(secretId))) continue; + await scope.removeSecret(secretId, version); + } catch (error) { + logger.warn( + { companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error }, + "Could not delete a refresh token after ending Google access", + ); + } + } + } + + async function prepare( + connection: typeof toolConnections.$inferSelect, + grants: RemovedGrant[], + actor: ActorInfo | undefined, + scope: GoogleAccessRemovalScope, + ): Promise { + const oauth = oauthConfig(connection); + if (connection.authKind !== "oauth" || !isPaperclipCloudConnectorStrategy(oauth.strategy)) return null; + const profile = managedConnectorProfile(typeof oauth.connectorProfile === "string" ? oauth.connectorProfile : undefined); + if (profile?.provider !== "google") return null; + try { + const revokedSecretIds = grants.flatMap((grant) => { + const secretId = grant.status === "revoked" ? refreshSecretId(grant) : null; + return secretId ? [secretId] : []; + }); + const stillStored = new Set(revokedSecretIds.length === 0 ? [] : (await db.select({ id: companySecrets.id }).from(companySecrets) + .where(and(eq(companySecrets.companyId, connection.companyId), inArray(companySecrets.id, revokedSecretIds), isNull(companySecrets.deletedAt)))) + .map((row) => row.id)); + const candidateSecretIds = grants.flatMap((grant) => { + const secretId = refreshSecretId(grant); + return secretId ? [secretId] : []; + }); + const held = await secretsHeldElsewhere(connection, grants, candidateSecretIds, scope.removingConnection); + const seen = new Set(); + const revocations: PreparedRevocation[] = []; + const sentSecrets: Array<{ secretId: string; version: number }> = []; + for (const grant of grants) { + const secretId = refreshSecretId(grant); + const refreshRef = (grant.credentialSecretRefs ?? []).find((ref) => ref.configPath === "oauth.refresh_token"); + if (!secretId || !refreshRef || seen.has(secretId)) continue; + if (grant.status === "revoked" && !stillStored.has(secretId)) continue; + if (held.has(secretId)) continue; + seen.add(secretId); + const subject = managedConnectorConsentSubject(grant, oauth); + if (!subject) { + revocations.push({ kind: "skip", outcome: "credential_unavailable" }); + continue; + } + try { + const { value, latestVersion } = await resolveConnectionGrantSecret(db, connection, grant, refreshRef, { + consumerType: "tool_connection", + consumerId: connection.id, + actorType: actor?.actorType ?? "system", + actorId: actor?.actorId ?? null, + }); + revocations.push({ kind: "call", subject, token: value }); + sentSecrets.push({ secretId, version: latestVersion }); + } catch { + revocations.push({ kind: "skip", outcome: "credential_unavailable" }); + } + } + if (revocations.length === 0) return null; + return { + send: async () => { + let summary: ManagedGoogleAccessRemoval; + try { + summary = await send(connection, profile.id, revocations); + } catch (error) { + summary = await unexpectedFailure(connection, error).send(); + } + await deleteSentSecrets(connection, scope, sentSecrets); + await recordAudit(connection, actor, scope, summary); + return summary; + }, + }; + } catch (error) { + const failed = unexpectedFailure(connection, error); + return { + send: async () => { + const summary = await failed.send(); + await recordAudit(connection, actor, scope, summary); + return summary; + }, + }; + } + } + + return { prepare }; +} diff --git a/server/src/services/tool-access/connections/grants.ts b/server/src/services/tool-access/connections/grants.ts index 572bb0e8856..c45625b06a3 100644 --- a/server/src/services/tool-access/connections/grants.ts +++ b/server/src/services/tool-access/connections/grants.ts @@ -1,16 +1,18 @@ import { notifyGitHubCredentialChange } from "../../github-connection-notifications.js"; +import type { secretService } from "../../secrets.js"; import type { ConnectionManagementContext } from "../../connection-management.js"; import { connectionActorUserId } from "../actor.js"; import { toConnectionGrant } from "./projection.js"; import { actorBinding } from "../actor.js"; import { vercelConnectResourcesFor } from "../vercel-credentials.js"; import type { ActorInfo } from "../types.js"; -import { oauthConfig } from "../oauth/metadata.js"; import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, connectionGrantMembers, connectionGrantDelegations, connectionGrants, authUsers, companyMemberships, toolAccessAuditEvents, toolConnections } from "@paperclipai/db"; import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; -import { isPaperclipCloudConnectorStrategy } from "../../paperclip-cloud-connector.js"; +import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { createManagedGoogleAccessRemoval } from "./google-access-removal.js"; +import type { ConnectionGrantRevocationResult } from "@paperclipai/shared"; import { vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js"; import type { createConnectionCredentialValidation } from "./credential-validation.js"; @@ -18,9 +20,12 @@ type GrantDependencies = { getConnectionRow(idOrUid: string, companyId?: string): Promise; assertSecretRefs: ReturnType; vercelConnect: VercelConnectClient | null; + currentCloudConnector: () => PaperclipCloudConnector | null; + secrets: Pick, "remove">; }; -export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect }: GrantDependencies) { +export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets }: GrantDependencies) { + const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector }); return { listConnectionGrants: async (idOrUid: string, companyId?: string) => { const connection = await getConnectionRow(idOrUid, companyId); @@ -487,7 +492,7 @@ replaceConnectionGrantMembers: async ( idOrUid: string, grantId: string, actor?: ActorInfo, - ) => { + ): Promise => { await actor?.managementContext?.reauthorize(); const connection = await getConnectionRow(idOrUid); const binding = actorBinding(actor); @@ -504,6 +509,11 @@ replaceConnectionGrantMembers: async ( .limit(1); if (!currentGrant) throw notFound("Connection grant not found"); let providerRevocation = "not_applicable"; + const providerAccessRemoval = await managedGoogleAccess.prepare(connection, [currentGrant], actor, { + grantId: currentGrant.id, + removingConnection: false, + removeSecret: (secretId, expectedVersion) => secrets.remove(secretId, { expectedVersion }), + }); if ( connection.credentialSource === "vercel_connect" && connection.externalCredential @@ -527,15 +537,6 @@ replaceConnectionGrantMembers: async ( providerRevocation = "failed"; } } - } else if ( - isPaperclipCloudConnectorStrategy(oauthConfig(connection).strategy) - ) { - // Google revocation is client-wide for a user. The managed Workspace - // profiles intentionally share one Paperclip-owned client, so revoking - // one token here could invalidate unrelated Gmail, Drive, and Calendar - // grants. A per-profile removal is therefore local-only. A future - // provider-level disconnect must warn that it removes every profile. - providerRevocation = "local_only_shared_client"; } const grant = await db.transaction(async (tx) => { await notifyGitHubCredentialChange(tx, connection); @@ -597,6 +598,7 @@ replaceConnectionGrantMembers: async ( return updated; }); if (!grant) throw notFound("Connection grant not found"); + const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null; await db.insert(toolAccessAuditEvents).values({ companyId: connection.companyId, connectionId: connection.id, @@ -607,7 +609,7 @@ replaceConnectionGrantMembers: async ( reasonCode: "grant_revoked", details: { grantId: grant.id, kind: grant.kind, providerRevocation }, }); - return toConnectionGrant(grant); + return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}) }; } }; } diff --git a/server/src/services/tool-access/connections/removal.ts b/server/src/services/tool-access/connections/removal.ts index ae3016de93e..3dd762ef663 100644 --- a/server/src/services/tool-access/connections/removal.ts +++ b/server/src/services/tool-access/connections/removal.ts @@ -3,6 +3,8 @@ import { notifyVoiceChange } from "../../voice/voice-recovery-notifications.js"; import { notifyChatEndpointWork } from "../../chat-work-notifications.js"; import { notifyToolConnectionHealth } from "../../tool-connection-health-notifications.js"; import { toConnection } from "./projection.js"; +import { createManagedGoogleAccessRemoval } from "./google-access-removal.js"; +import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { actorBinding, connectionActorUserId } from "../actor.js"; import { stageSlackCloudEnrollmentIntent } from "../../chat-channels/slack/cloud-enrollment.js"; import { vercelConnectResourcesFor } from "../vercel-credentials.js"; @@ -81,10 +83,12 @@ type RemovalDependencies = { secrets: ReturnType; runtimeSupervisor: Pick, "stopSlot">; vercelConnect: VercelConnectClient | null; + currentCloudConnector: () => PaperclipCloudConnector | null; getConnectionRow(idOrUid: string, companyId?: string): Promise; }; -export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, getConnectionRow }: RemovalDependencies) { +export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow }: RemovalDependencies) { + const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector }); /** * Split the secrets a connection points at into the ones it owns outright and * the ones another consumer still depends on. @@ -262,10 +266,14 @@ async function removeConnection( const grantRows = await db .select({ id: connectionGrants.id, + companyId: connectionGrants.companyId, + connectionId: connectionGrants.connectionId, status: connectionGrants.status, kind: connectionGrants.kind, subjectUserId: connectionGrants.subjectUserId, + subjectAgentId: connectionGrants.subjectAgentId, credentialSecretRefs: connectionGrants.credentialSecretRefs, + providerTenant: connectionGrants.providerTenant, externalCredential: connectionGrants.externalCredential, }) .from(connectionGrants) @@ -276,6 +284,14 @@ async function removeConnection( ), ); const grantsToRevoke = grantRows.filter((row) => row.status !== "revoked"); + let secretsRevoked = 0; + const providerAccessRemoval = await managedGoogleAccess.prepare(connection, grantRows, actor, { + removingConnection: true, + canRemoveSecret: async (secretId) => (await classifyConnectionSecrets(connection, [secretId])).owned.includes(secretId), + removeSecret: async (secretId, expectedVersion) => { + if (await secrets.remove(secretId, { expectedVersion })) secretsRevoked += 1; + }, + }); if (grantsToRevoke.length > 0) { await db .update(connectionGrants) @@ -595,6 +611,8 @@ async function removeConnection( await browserUseService(db, options.remoteHttpRequest).stopBeforeCredentialRemoval(connection.companyId, connection.id); } + const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null; + // Only now, with every access path closed, revoke the credentials. Each // `secrets.remove` marks the row deleted before it calls the provider, so a // provider error leaves an unresolvable secret and a resumable removal @@ -611,7 +629,6 @@ async function removeConnection( connection, candidateSecretIds, ); - let secretsRevoked = 0; for (const secretId of owned) { const removed = await secrets.remove(secretId); if (removed) secretsRevoked += 1; @@ -664,6 +681,7 @@ async function removeConnection( gatewaySessionsRevoked, applicationArchived: archived.applicationArchived, externalCredentialCleanup, + ...(providerAccess ? { providerAccess } : {}), }, }; } diff --git a/server/src/services/tool-access/oauth/client-settings.ts b/server/src/services/tool-access/oauth/client-settings.ts index 1fea19bafd7..b9f5f2aab69 100644 --- a/server/src/services/tool-access/oauth/client-settings.ts +++ b/server/src/services/tool-access/oauth/client-settings.ts @@ -130,6 +130,23 @@ export async function oauthGalleryEntryForConnection( export type ManagedConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId; +export function managedConnectorSubject( + grant: { kind: string; subjectUserId: string | null; subjectAgentId: string | null }, + oauth: Record, +): string | null { + if (grant.kind === "agent" && grant.subjectAgentId) return `agent:${grant.subjectAgentId}`; + if (grant.kind === "user" && grant.subjectUserId) return grant.subjectUserId; + return typeof oauth.connectorSubjectUserId === "string" ? oauth.connectorSubjectUserId : null; +} + +export function managedConnectorConsentSubject( + grant: { kind: string; subjectUserId: string | null; subjectAgentId: string | null; providerTenant?: { externalId?: unknown } | null }, + oauth: Record, +): string | null { + const consentSubject = grant.providerTenant?.externalId; + return typeof consentSubject === "string" && consentSubject ? consentSubject : managedConnectorSubject(grant, oauth); +} + export function managedConnectorProfile(value: string | undefined): { id: ManagedConnectorProfileId; provider: "google" | "github" | "asana"; diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index d521137af4d..b811431f04c 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -16,7 +16,7 @@ import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type P import { actorForSecret, type OAuthCredentialStore } from "./credential-store.js"; import { withoutOAuthRefreshLease, type OAuthRefreshLeases } from "./refresh-leases.js"; -import { managedConnectorProfile, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js"; +import { managedConnectorProfile, managedConnectorSubject, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js"; import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js"; import { singleFlight } from "../single-flight.js"; import { usesClientCredentials } from "./client-credentials.js"; @@ -106,14 +106,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo : undefined, ); const cloudConnector = currentCloudConnector(); - const connectorSubject = - grant.kind === "agent" && grant.subjectAgentId - ? `agent:${grant.subjectAgentId}` - : grant.kind === "user" && grant.subjectUserId - ? grant.subjectUserId - : typeof oauth.connectorSubjectUserId === "string" - ? oauth.connectorSubjectUserId - : null; + const connectorSubject = managedConnectorSubject(grant, oauth); const accessRef = grant.credentialSecretRefs.find( (ref) => ref.configPath === "oauth.access_token", ); diff --git a/server/src/services/tool-access/oauth/managed-connector-subject.test.ts b/server/src/services/tool-access/oauth/managed-connector-subject.test.ts new file mode 100644 index 00000000000..798cae88b7b --- /dev/null +++ b/server/src/services/tool-access/oauth/managed-connector-subject.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { managedConnectorConsentSubject, managedConnectorSubject } from "./client-settings.js"; + +const oauth = { connectorSubjectUserId: "latest-user" }; +const organizationGrant = { kind: "organization", subjectUserId: null, subjectAgentId: null, providerTenant: { externalId: "consenting-user" } }; + +describe("managed connector subjects", () => { + it("keeps refresh on the subject rule it has always used", () => { + expect(managedConnectorSubject(organizationGrant, oauth)).toBe("latest-user"); + expect(managedConnectorSubject({ kind: "agent", subjectUserId: null, subjectAgentId: "a1" }, oauth)).toBe("agent:a1"); + expect(managedConnectorSubject({ kind: "user", subjectUserId: "u1", subjectAgentId: null }, oauth)).toBe("u1"); + }); + + it("revokes under the subject that consented to the grant", () => { + expect(managedConnectorConsentSubject(organizationGrant, oauth)).toBe("consenting-user"); + }); + + it("falls back to the refresh rule for grants saved without a consenting subject", () => { + expect(managedConnectorConsentSubject({ ...organizationGrant, providerTenant: null }, oauth)).toBe("latest-user"); + }); +}); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c745970a1ac..200a590ac5b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "6a606abbcc658563ce236b9b0671cc508b05673f", + "packages/shared/src/index.ts": "0ee8c415f1dc36e4aec1a44b8e2e1a8f59885668", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -412,7 +412,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "9c93d353993d6073389ae6dad752c7b8845377e1", + "packages/shared/src/types/index.ts": "e753d49a5cb6ae09a4b2d62bc7f832012b499c08", "packages/shared/src/types/instance.ts": "d47ae3080fbf096e71c51e707efe7e827a6562c7", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "d594c0037a8d9882dc35d3ecd7cb8c276d7e2831", @@ -435,7 +435,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "6c091a9bd1a6e4daef61ee860df54a4db19cdd80", + "packages/shared/src/types/tool-access.ts": "978cac1aca717b4d41f05b4b099756760b594153", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index 302ca96951b..309315506b3 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -66,6 +66,7 @@ import type { CreateToolTrustRuleFromActionRequest, ToolRedactedValueSummary, ConnectionGrant, + ConnectionGrantRevocationResult, ConnectionGrantKind, ConnectionGrantDelegation, ConnectionGrantsResponse, @@ -410,7 +411,7 @@ export const toolsApi = { `/tool-connections/${connectionId}/grants/${grantId}/delegations/${delegationId}`, ), revokeConnectionGrant: (connectionId: string, grantId: string) => - api.delete(`/tool-connections/${connectionId}/grants/${grantId}`), + api.delete(`/tool-connections/${connectionId}/grants/${grantId}`), // An empty `memberUserIds` is the canonical "all organization members". // Replacement is atomic server-side, so this never partially widens access. replaceConnectionGrantMembers: (connectionId: string, grantId: string, memberUserIds: string[]) => diff --git a/ui/src/features/connections/googleAccessRemoval.test.ts b/ui/src/features/connections/googleAccessRemoval.test.ts new file mode 100644 index 00000000000..438fceccf45 --- /dev/null +++ b/ui/src/features/connections/googleAccessRemoval.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { connectionRemovalToast, GOOGLE_THIRD_PARTY_ACCESS_URL, googleAccessRemovalNotice } from "./googleAccessRemoval"; + +describe("googleAccessRemovalNotice", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("says nothing for connections that are not Paperclip-managed Google", () => { + expect(googleAccessRemovalNotice(undefined)).toBeNull(); + expect(googleAccessRemovalNotice(null)).toBeNull(); + }); + + it("says access was ended at Google", () => { + expect(googleAccessRemovalNotice({ provider: "google", result: "ended", outcomes: ["revoked"] })).toEqual({ + tone: "success", + body: "Paperclip's access to this Google account was also ended at Google.", + }); + }); + + it("says other connections keep Google access", () => { + expect(googleAccessRemovalNotice({ provider: "google", result: "other_connections_remain", outcomes: ["other_connections_remain"] })).toEqual({ + tone: "success", + body: "Other Paperclip connections still use this Google account, so Google keeps Paperclip's access until you remove those too.", + }); + }); + + it("offers Google's own page when access could not be ended, without showing codes", () => { + const open = vi.fn(() => null); + vi.stubGlobal("window", { open }); + const notice = googleAccessRemovalNotice({ provider: "google", result: "not_ended", outcomes: ["revocation_not_available"] }); + expect(notice?.tone).toBe("warn"); + expect(notice?.body).toBe("Paperclip removed the connection but couldn't end its access at Google. You can remove Paperclip from your Google account's third-party connections."); + expect(notice?.body).not.toMatch(/revocation|broker|_/); + notice?.action?.onClick?.(); + expect(open).toHaveBeenCalledWith(GOOGLE_THIRD_PARTY_ACCESS_URL, "_blank", "noopener,noreferrer"); + expect(GOOGLE_THIRD_PARTY_ACCESS_URL).toBe("https://myaccount.google.com/connections"); + }); + it("says access was ended but asks to check when the Google account cannot be confirmed", () => { + const notice = googleAccessRemovalNotice({ provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] }); + expect(notice?.tone).toBe("info"); + expect(notice?.body).toBe("Paperclip's access was ended at Google. If more than one Google account was connected here, check your Google account's third-party connections to be sure."); + expect(notice?.action?.label).toBe("Open Google account connections"); + }); + + it("builds the removal toast with or without a Google outcome", () => { + expect(connectionRemovalToast({ title: "Connection removed", body: "Removed.", providerAccess: undefined })) + .toEqual({ title: "Connection removed", body: "Removed.", tone: "success" }); + expect(connectionRemovalToast({ title: "Connection removed", body: "Removed.", providerAccess: { provider: "google", result: "ended", outcomes: ["revoked"] } })) + .toEqual({ title: "Connection removed", body: "Removed. Paperclip's access to this Google account was also ended at Google.", tone: "success" }); + }); +}); diff --git a/ui/src/features/connections/googleAccessRemoval.ts b/ui/src/features/connections/googleAccessRemoval.ts new file mode 100644 index 00000000000..566bef7d984 --- /dev/null +++ b/ui/src/features/connections/googleAccessRemoval.ts @@ -0,0 +1,56 @@ +import type { ManagedGoogleAccessRemoval } from "@paperclipai/shared"; +import type { ToastAction, ToastInput, ToastTone } from "../../context/ToastContext"; + +export const GOOGLE_THIRD_PARTY_ACCESS_URL = "https://myaccount.google.com/connections"; + +export interface GoogleAccessRemovalNotice { + body: string; + tone: ToastTone; + action?: ToastAction; +} + +const openGoogleAccountConnections: ToastAction = { + label: "Open Google account connections", + onClick: () => { window.open(GOOGLE_THIRD_PARTY_ACCESS_URL, "_blank", "noopener,noreferrer"); }, +}; + +export function googleAccessRemovalNotice( + providerAccess: ManagedGoogleAccessRemoval | null | undefined, +): GoogleAccessRemovalNotice | null { + if (providerAccess?.provider !== "google") return null; + if (providerAccess.result === "ended") { + return { tone: "success", body: "Paperclip's access to this Google account was also ended at Google." }; + } + if (providerAccess.result === "ended_unconfirmed") { + return { + tone: "info", + body: "Paperclip's access was ended at Google. If more than one Google account was connected here, check your Google account's third-party connections to be sure.", + action: openGoogleAccountConnections, + }; + } + if (providerAccess.result === "other_connections_remain") { + return { + tone: "success", + body: "Other Paperclip connections still use this Google account, so Google keeps Paperclip's access until you remove those too.", + }; + } + return { + tone: "warn", + body: "Paperclip removed the connection but couldn't end its access at Google. You can remove Paperclip from your Google account's third-party connections.", + action: openGoogleAccountConnections, + }; +} + +export function connectionRemovalToast(input: { + title: string; + body: string; + providerAccess: ManagedGoogleAccessRemoval | null | undefined; +}): ToastInput { + const notice = googleAccessRemovalNotice(input.providerAccess); + return { + title: input.title, + body: notice ? `${input.body} ${notice.body}` : input.body, + tone: notice?.tone ?? "success", + ...(notice?.action ? { action: notice.action } : {}), + }; +} diff --git a/ui/src/pages/apps/AppDetail.test.tsx b/ui/src/pages/apps/AppDetail.test.tsx index 885a7029f3a..421737f4506 100644 --- a/ui/src/pages/apps/AppDetail.test.tsx +++ b/ui/src/pages/apps/AppDetail.test.tsx @@ -83,7 +83,7 @@ vi.mock("@/api/tools", () => ({ finalizeOAuthAccessMock(companyId, connectionId, input), putConnectionInstalls: (connectionId: string, installs: unknown) => putConnectionInstallsMock(connectionId, installs), - archiveConnection: vi.fn(), + archiveConnection: (connectionId: string) => archiveConnectionMock(connectionId), refreshCatalog: (connectionId: string) => refreshCatalogMock(connectionId), checkConnectionHealth: (connectionId: string) => checkConnectionHealthMock(connectionId), startOAuth: (connectionId: string, input?: unknown) => input === undefined @@ -179,6 +179,7 @@ vi.mock("@/context/BreadcrumbContext", () => ({ })); const pushToastMock = vi.hoisted(() => vi.fn()); +const archiveConnectionMock = vi.hoisted(() => vi.fn()); vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: pushToastMock }), useOptionalToastActions: () => ({ pushToast: pushToastMock }), @@ -612,6 +613,25 @@ describe("AppDetail", () => { expect(Array.from(container.querySelectorAll("button")).some((b) => b.textContent === "Reconnect")).toBe(false); }); + it("tells the user when Google access could not be ended after removing the app", async () => { + getConnectionMock.mockResolvedValue(connection({ transport: "rest_api", config: { sourceTemplateKey: "composio", connectionMethodKey: "api-key" }, enabled: false, healthStatus: "error" })); + archiveConnectionMock.mockResolvedValueOnce({ removal: { providerAccess: { provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] } } }); + await renderAppDetail(); + const danger = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.includes("Danger zone"))!; + await act(async () => danger.click()); + const remove = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.trim() === "Remove app")!; + await act(async () => remove.click()); + const confirm = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.trim() === "Yes, remove it")!; + await act(async () => confirm.click()); + await act(async () => { await Promise.resolve(); }); + expect(pushToastMock).toHaveBeenCalledWith(expect.objectContaining({ + title: "Disconnected", + tone: "warn", + body: expect.stringContaining("couldn't end its access at Google"), + action: expect.objectContaining({ label: "Open Google account connections" }), + })); + }); + it("uses Permissions as the primary connection page and has no Setup tab", () => { expect(APP_TABS.map((tab) => tab.key)).toEqual([ "permissions", diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 2f74105c8d9..ecb3753dc5a 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -38,6 +38,7 @@ import { buildCompanyUserProfileMap } from "@/lib/company-members"; import { installStateFrom, type InstallState } from "@/lib/tool-installs"; import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow"; import { useGoogleWorkspaceServiceGate } from "@/features/connections/GoogleWorkspaceServices"; +import { connectionRemovalToast } from "@/features/connections/googleAccessRemoval"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -324,11 +325,16 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio const agents = agentsQuery.data ?? []; const disconnectRemote = useMutation({ mutationFn: () => toolsApi.archiveConnection(connectionId), - onSuccess: () => { + onSuccess: (removed) => { queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId!) }); queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); queryClient.invalidateQueries({ queryKey: queryKeys.tools.applications(selectedCompanyId!) }); queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId!) }); + pushToast(connectionRemovalToast({ + title: "Disconnected", + body: "The connection was removed and agents can no longer use it.", + providerAccess: removed?.removal?.providerAccess, + })); navigate("/apps"); }, onError: (error) => pushToast({ title: "Couldn't disconnect", body: describeError(error).body, tone: "error" }), diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx index f0016c757c5..1292e9762fd 100644 --- a/ui/src/pages/apps/Browse.test.tsx +++ b/ui/src/pages/apps/Browse.test.tsx @@ -1692,6 +1692,42 @@ describe("Connectors landing page", () => { ); }); + it("tells the user when Paperclip could not end Google access and links to Google's page", async () => { + listApplicationsMock.mockResolvedValue({ applications: [application()] }); + listConnectionsMock.mockResolvedValue({ connections: [connection()] }); + archiveConnectionMock.mockResolvedValueOnce({ + ...connection(), status: "archived", + removal: { providerAccess: { provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] } }, + }); + + await renderBrowse(); + const menuTrigger = container.querySelector('button[aria-label="Manage devinfoley@gmail.com connection"]'); + await act(async () => { + menuTrigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); + }); + await flushReact(); + const removeItem = Array.from(document.body.querySelectorAll('[role="menuitem"]')) + .find((item) => item.textContent?.trim() === "Remove connection"); + await act(async () => { + removeItem?.dispatchEvent(new Event("click", { bubbles: true })); + }); + await flushReact(); + const confirmButton = Array.from(document.body.querySelectorAll("button")) + .find((button) => button.textContent?.trim() === "Remove connection"); + await act(async () => { + confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + + expect(pushToastMock).toHaveBeenCalledWith(expect.objectContaining({ + title: "Connection removed", + tone: "warn", + body: expect.stringContaining("Paperclip removed the connection but couldn't end its access at Google."), + action: expect.objectContaining({ label: "Open Google account connections" }), + })); + expect(JSON.stringify(pushToastMock.mock.calls.at(-1))).not.toContain("broker_unavailable"); + }); + it("retains the confirmed pool revision when a concurrent edit rejects removal", async () => { const app = aiConnectionRouterAppDefinition("example.pool", { name: "AI connection pool", description: "Use saved connections" }); listGalleryMock.mockResolvedValue({ apps: [app] }); diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx index 87f489b1f89..8cd94ced3de 100644 --- a/ui/src/pages/apps/Browse.tsx +++ b/ui/src/pages/apps/Browse.tsx @@ -1,3 +1,4 @@ +import { connectionRemovalToast } from "@/features/connections/googleAccessRemoval"; import { AGGREGATOR_NAMES, aggregatorManagementUrl, isAppAggregator, type AggregatorAppSnapshot, type AggregatorAppsResponse } from "@paperclipai/shared/aggregator-apps"; import type { CatalogSource } from "./CatalogSourceFilters"; import { ConnectorsToolbar } from "./ConnectorsToolbar"; @@ -543,10 +544,11 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne if (!target.poolRevision) throw new Error("Open the confirmation again before removing this pool."); await aiConnectionPoolsApi.remove(selectedCompanyId!, target.id, target.poolRevision); } else { - await toolsApi.archiveConnection(target.id, { deleteStoredContent }); + return toolsApi.archiveConnection(target.id, { deleteStoredContent }); } + return null; }, - onSuccess: (_connection, target) => { + onSuccess: (removed, target) => { queryClient.invalidateQueries({ queryKey: ["email-inboxes", selectedCompanyId!] }); queryClient.invalidateQueries({ queryKey: queryKeys.chatEndpoints.list(selectedCompanyId!), @@ -560,17 +562,17 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId!), }); - pushToast({ - title: "Connection removed", - body: + const body = target.pool ? "The connections in the pool are kept." : target.kind === "chat" ? `${target.providerName} is disconnected. Existing Paperclip tasks remain available.` : target.remainingConnectionCount > 0 ? `${target.providerName} still has ${target.remainingConnectionCount} active ${target.remainingConnectionCount === 1 ? "connection" : "connections"} available to agents.` - : `${target.providerName} is no longer available to agents through this connection. Its saved credentials were deleted.`, - ...(deleteStoredContent && !target.pool && target.kind !== "chat" ? { title: "Connection removed. Deleting its saved data." } : {}), - tone: "success", - }); + : `${target.providerName} is no longer available to agents through this connection. Its saved credentials were deleted.`; + pushToast(connectionRemovalToast({ + title: deleteStoredContent && !target.pool && target.kind !== "chat" ? "Connection removed. Deleting its saved data." : "Connection removed", + body, + providerAccess: removed?.removal?.providerAccess, + })); setConnectionToRemove(null); }, onError: (error) => diff --git a/ui/src/pages/apps/Connections.test.tsx b/ui/src/pages/apps/Connections.test.tsx index 4a57b8745fc..c88424abfc0 100644 --- a/ui/src/pages/apps/Connections.test.tsx +++ b/ui/src/pages/apps/Connections.test.tsx @@ -425,6 +425,31 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => { }); + it("adds the Google outcome to the deletion message", async () => { + listApplicationsMock.mockResolvedValue({ applications: [application({ id: "app-github", name: "GitHub" })] }); + listConnectionsMock.mockResolvedValue({ connections: [connection({ id: "c-github-primary", applicationId: "app-github", name: "GitHub" })] }); + archiveConnectionMock.mockResolvedValueOnce({ + ...connection({ id: "c-github-primary", status: "archived" }), + removal: { providerAccess: { provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] } }, + }); + await renderApps(); + const deleteButton = container.querySelector('button[aria-label="Delete GitHub for the organization connection"]'); + await act(async () => { + deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + const confirmButton = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Delete connection"); + await act(async () => { + confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + expect(pushToastMock).toHaveBeenCalledWith(expect.objectContaining({ + title: "Connection deleted", + tone: "info", + body: expect.stringContaining("If more than one Google account was connected here"), + action: expect.objectContaining({ label: "Open Google account connections" }), + })); + }); + it("reports the remaining active connections after deleting one", async () => { listApplicationsMock.mockResolvedValue({ applications: [application({ id: "app-github", name: "GitHub" })], diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index 75b1a2d7d19..846d98979a5 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -1,3 +1,4 @@ +import { connectionRemovalToast } from "@/features/connections/googleAccessRemoval"; import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow"; import { isRetiredComposioConnection, RETIRED_COMPOSIO_MESSAGE } from "@paperclipai/shared"; import { useEffect, useMemo, useState, type ReactNode } from "react"; @@ -191,17 +192,14 @@ export function Connections() { }) => toolsApi.archiveConnection(target.id), - onSuccess: (_connection, target) => { + onSuccess: (removed, target) => { queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId!) }); queryClient.invalidateQueries({ queryKey: queryKeys.tools.applications(selectedCompanyId!) }); queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId!) }); - pushToast({ - title: "Connection deleted", - body: target.remainingConnectionCount > 0 - ? `${target.appName} still has ${target.remainingConnectionCount} active ${target.remainingConnectionCount === 1 ? "connection" : "connections"} available to agents.` - : `${target.appName} is no longer available to agents and its credentials are deleted. Connecting it again needs a new sign-in or key.`, - tone: "success", - }); + const body = target.remainingConnectionCount > 0 + ? `${target.appName} still has ${target.remainingConnectionCount} active ${target.remainingConnectionCount === 1 ? "connection" : "connections"} available to agents.` + : `${target.appName} is no longer available to agents and its credentials are deleted. Connecting it again needs a new sign-in or key.`; + pushToast(connectionRemovalToast({ title: "Connection deleted", body, providerAccess: removed?.removal?.providerAccess })); setConnectionToDelete(null); }, onError: (error) =>