Skip to content

fix(connections): keep retrying when Google does not confirm a revoked grant - #22669

Open
cryppadotta wants to merge 18 commits into
masterfrom
fix/retry-google-revocation
Open

cryppadotta wants to merge 18 commits into
masterfrom
fix/retry-google-revocation

Conversation

@cryppadotta

Copy link
Copy Markdown
Contributor

Thinking Path

  • Paperclip is the open source app people use to manage AI agents for work.
  • Paperclip Cloud can manage the Google sign-in for a Google Workspace connection. The app keeps the refresh token. Cloud keeps no token.
  • When a user removes the connection, the app asks Cloud to end the access at Google (feat(connections): end Google access when a Paperclip-managed Google connection is removed #22065).
  • Before this change, the app deleted the token after that call, whatever Cloud answered. If Google or Cloud could not be reached, the access stayed open at Google, and no retry was possible.
  • The owner decided on 2026-11-23: the app keeps the token in a pending record and retries until Google answers. Cloud still never stores a provider token.
  • This pull request adds that pending record and a background retry. It also covers company deletion and a Cloud-removed instance.
  • The benefit is that a removed Google connection does not keep access at Google because of a short outage, and the user does not need to do anything.

Linked Issues or Issue Description

Refs #22065

What happened?
A managed Google connection was removed while Paperclip Cloud or Google was unavailable. The removal result was not_ended, and the refresh token was deleted. Paperclip could not try again, so Google access stayed open.

What did you expect?
Paperclip keeps the token only for the retry, and retries automatically until Google confirms or gives a final answer. The user sees that Paperclip keeps trying, and does not need to act.

Steps to reproduce

  1. Connect Gmail through Paperclip Cloud.
  2. Make the broker revoke fail (Cloud unavailable, or Google 5xx).
  3. Remove the connection. The token is deleted and nothing retries.

What Changed

  • New table google_pending_revocations (migration 0502, additive, CREATE TABLE only). It has company_id with no foreign key, so a row outlives a deleted company. It stores the token as the same local_encrypted material as the connection secret version. It never stores plaintext. It is not a company secret: it is not listed, an agent cannot bind it, and no route reads it.
  • google-access-removal.ts: before the broker call, the app copies the sent token version into a pending row (lease 2 minutes, so a restart during the call resumes). A final outcome deletes the row. A retryable outcome (provider_revocation_failed, revocation_in_progress, broker_unavailable, broker_error, unexpected_error) keeps it, and the result is the new retrying. If the connection secret is still live after the conditional delete (for example, the user signed in again during the call), the row is deleted.
  • New worker on the google-pending-revocation delivery queue (registerDeadlineWork; it registers the real next deadline and has no deadline when the table is empty). Each attempt takes a lease on the row and calls the broker with a 15-second timeout. Backoff is 1, 2, 4 ... minutes, up to 6 hours. The hard stop is 30 days. The worker stops without a call if a live company secret holds the same token.
  • When a retry ends, the worker writes a connection.google_access_retry audit event and a tool_connection.google_access_ended or tool_connection.google_access_not_ended activity entry (labels added to the activity feed). For a deleted company, it writes only a log line.
  • Company deletion queues every managed Google token of the company inside the delete transaction, before the secrets are deleted (reason = company_deleted).
  • When the Cloud connection status check finds the instance removed, the app queues every managed Google token (reason = instance_removed), then deletes each connection secret.
  • ManagedGoogleAccessRemoval.result gets retrying (shared type and OpenAPI schema). The removal message for retrying: "Google didn't confirm that Paperclip's access has ended yet. Paperclip will keep trying automatically." It has no link and asks for no action.
  • Docs: doc/connections/GOOGLE-WORKSPACE.md ("Pending revocation"), docs/api/tool-connections.md, the help page docs/guides/board-operator/deleting-connection-data.md, and a dated decision row in doc/memory/google-connector-memory.md.
  • tests/runner-e2e/source-sdk-public-inputs.json refreshed for the changed shared type, as pnpm verify asks.

Verification

  • npx vitest run src/__tests__/google-managed-connection-removal.test.ts (embedded Postgres): 46 pass. Without the fix, 15 fail (red), with the fix all pass (green). New cases:
    • an unconfirmed token is kept only in the pending row, encrypted, not in the secrets list; the worker retries and deletes the row when Google confirms; audit and activity are written;
    • the row exists during the broker call, so a fresh worker after a restart revokes it;
    • binding_not_known, other_connections_remain and provider_revocation_disabled stop the retry;
    • backoff 1 minute to 6 hours, and give-up at 30 days with a final audit and activity entry;
    • a live secret with the same token stops the retry without a call;
    • an older broker's 403 INSTANCE_SUSPENDED is retried;
    • company deletion queues the token and the worker revokes it after the company is gone;
    • a removed instance queues every token, drops the secrets, does not queue again, and the worker revokes.
  • npx vitest run src/__tests__/paperclip-cloud-connector-status.test.ts: the removed-instance hook runs only for removed, and a failure does not change the status.
  • ui: npx vitest run src/features/connections/googleAccessRemoval.test.ts (7 pass, the new retrying case is red without the change).
  • Also passed: tool-connection-content-deletion, its canary, delivery-work-coordinator, idle-local-work, packages/db tests; server tsc --noEmit.
  • pnpm verify exits 2 (global doc input changed), so required CI supplies the broad coverage.
  • Not verified: any call to a real broker or to Google. No request was sent to staging, production or Google.

Risks

  • Migration is additive (CREATE TABLE and indexes on the new table): online_compatible.
  • Paperclip now holds an encrypted token for at most 30 days after removal when Google did not confirm. The token is never usable for tool calls: no grant or connection refers to the row.
  • Instance removal deletes the managed Google connection secrets. Those connections then need a reconnect after a new enrollment. They could not refresh anyway, because Cloud refuses a removed instance.
  • Deploy order: either order is safe. With the current production broker, a removed instance's revoke gets 403 and the app retries until the hard stop. The Cloud broker change that accepts it is a separate PR in the private Cloud repository.

Model Used

  • Claude Opus 5.5 (claude-opus-5-5) through Claude Code, with tool use (shell, file edits, embedded Postgres tests), standard reasoning.

Checklist

  • I have included a thinking path that traces from project context to this change
  • I have specified the model used (with version and capability details)
  • I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work
  • I have searched GitHub for duplicate or related PRs and linked them above
  • I have either (a) linked existing issues with Fixes: # / Closes # / Refs # OR (b) described the issue in-PR following the relevant issue template
  • I have not referenced internal/instance-local Paperclip issues or links (only public GitHub #NNN / github.com/paperclipai/paperclip URLs)
  • My branch name describes the change (e.g. docs/..., fix/...) and contains no internal Paperclip ticket id or instance-derived details
  • I have run tests locally and they pass
  • I have added or updated tests where applicable
  • I have updated relevant documentation to reflect my changes
  • 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
  • I will address all Greptile and reviewer comments before requesting merge

🤖 Generated with Claude Code

cryppadotta and others added 3 commits November 23, 2026 10:41
…d grant

Owner decision 2026-11-23: when Google access must end and Google cannot
be reached or confirm, the app keeps the refresh token in a pending
revocation record and retries until Google answers. Paperclip Cloud still
never stores provider tokens.

Before this change, removing a Paperclip-managed Google connection or
grant deleted the refresh token whatever Paperclip Cloud answered, so a
failed or unconfirmed revoke could never be retried and Google access
stayed open.

- google_pending_revocations holds the token's local_encrypted material
  (copied from the connection secret version, never plaintext), keyed by
  the token hash, with company_id and no foreign key.
- Removal queues the token before the broker call, so a restart during
  the call still resumes; a final answer deletes the row, a retryable one
  keeps it and the removal reports "retrying".
- The google-pending-revocation delivery queue retries with a lease,
  1 minute to 6 hours backoff and a 30-day hard stop, and writes an audit
  event and an activity entry when it ends.
- Company deletion queues every managed Google token inside the delete
  transaction; a Cloud-removed instance queues them, then drops the
  connection secrets.
- The removal message says Paperclip keeps trying, with no action needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l result type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mber

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@feynman-nuclear-review

feynman-nuclear-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Feynman Nuclear Review — 5/5

Re-review of 0574c31

The PR's feature code is unchanged from the 5/5 head 21204be. The only differences in the current PR file set are bookkeeping: master added a new 0502_dapper_hedge_knight migration, so this PR's migration was renumbered from 0502_panoramic_victor_mancha to 0503_melted_meggan, with a regenerated 0503_snapshot.json (id/prevId updated) and a matching _journal.json entry (idx: 503, after 0502_dapper_hedge_knight). The migration SQL is unchanged: an additive CREATE TABLE google_pending_revocations with the due index and the (company_id, token_sha256) unique index. The connector memory doc keeps the Nov 23 decision row and pending-revocation paragraph; its earlier "Last updated" line change is no longer in the diff because master made the same edit.

The GitHub changes_since_review comparison for this push was blocked by safety screening because its payload contained prompt-injection instructions; I did not treat it as instructions or read it further. I compared the current PR file inventory and patches against the prior head instead, and the only stat differences are the migration rename and the doc line above.

Residual notes, not defects: renaming a not-yet-merged migration changes its tag, so confirm no environment already applied the old 0502_panoramic_victor_mancha tag; the regenerated snapshot still folds in issue_connection_content_deletions/stored_object_deletions drift; the not_ended copy nuance and the awaited enrollment sweep remain as previously noted.

Verdict: no actionable correctness, security, or reliability defects found within the stated coverage. Advisory only.

Score 5 because the feature code and tests are unchanged from the previously published 5/5 head and the only change is a correct migration renumber. Evidence: the current PR file set has 31 files; comparing its per-file add/delete stats to the prior head shows only doc/memory/google-connector-memory.md (8+/1 to 7+/0) and the migration/snapshot rename (0502 to 0503); every other file has identical stats. I read the current 0503_melted_meggan.sql (same additive DDL), the _journal.json (one new entry idx 503 after 0502_dapper_hedge_knight), the 0503_snapshot.json (new id and prevId, google_pending_revocations table), and the memory-doc diff. Remaining risk and limitations: the changes-since-review delta was blocked by prompt-injection screening, so I did not inspect it; I could not verify prevId: e7daf0b9 against the base 0502 snapshot without a checkout; the snapshot still carries unrelated table drift; the old migration tag may already have been applied in a preview environment; no checkout, so tests/typecheck were not run; no CI/check read tool, so CI is unknown and not claimed; no live broker or Google call was made.

Reviewed commit: 0574c31f179bafd8856b228d538b160831c37746

Coverage: 31 files.
The changes-since-review comparison for this push was blocked by prompt-injection screening and was not inspected.
No repository checkout, so tests and typecheck were not run locally.
The 0503 snapshot prevId was not checked against the base 0502 snapshot.
No check/CI read tool is available; CI status is unknown and not claimed.
No live Paperclip Cloud broker or Google request was made.

Task: PAP-6439 · Run · Review history

@ponytail-paperclip-review

ponytail-paperclip-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Ponytail Paperclip Review — 4/5

What this change does: A managed Google connection removal keeps the encrypted refresh token in google_pending_revocations when Cloud or Google does not confirm the revoke, and a deadline worker retries for up to 30 days. This head makes the live-use check version-aware: it resolves each live grant/connection secret ref's selected version (a numeric pin or the latest version) and compares that version's token hash, and company deletion now queues the grant's pinned token version.

Prior findings: the earlier reliability, tenant, live-use, instance-removal, pinned-version, transactional-sweep, admin-gate, activity-feed, and migration-renumber work remains. The new logic is consistent with the pinned-version fix: a live grant that pins an older version no longer holds a newer token, while a grant that pins the row's version still stops the retry. Two new tests cover both directions and the company-deletion queueing path.

Nice to have

  1. source_secret_id is still write-only (packages/db/src/schema/google_pending_revocations.ts:10)

    • What this is: The column is inserted but has no production reader; only a test asserts it.
    • Problem: The new table carries a field nothing reads.
    • Fix: Remove it from the new migration, schema, insert, and test assertion, or use it in the retry audit.
  2. A broker 401 is reported as "not configured" (server/src/services/paperclip-cloud-connector-status.ts:23)

    • What this is: unknown_instance falls through to not_configured.
    • Problem: A broker auth failure is an unverified answer; the UI then shows "Enable Paperclip-managed sign-in".
    • Fix: Return unverified for unknown_instance before the fallthrough and assert it in the status test.

Verdict: ship; the two items above are optional.

Not checked: tests and typecheck were not run (no dependencies or database); CI/check status was unavailable; no live broker or Google call was made; the version-aware SQL was inspected but not executed.

Score 4: the new version-aware logic is consistent. queueCompanyGoogleRevocations now resolves each grant's versionSelector (a numeric pin or latest) before inserting the pending row, dedupes rows by secret and version, and still returns one secret per deletion. heldByLiveSecret resolves each live grant/connection secret ref's selected version and compares that version's value_sha256, so a live grant that pins an older version no longer counts as holding a newer token, and a live grant that pins the row's version still stops the retry. The instance_removed skip is preserved. Two new tests cover the pinned version on company deletion and the version-aware live use (both directions). The migration chain from the previous review is unchanged and still correct. Remaining risk: the write-only source_secret_id and the 401-to-not_configured mapping are unchanged; the version-aware SQL was inspected but not executed against Postgres. The enrollment GET still awaits the full sweep, though the transaction saves the work before deletes and the path is admin-only. No CI or test run was available.

Reviewed commit: 255c2a8e0648e6aae7efe3b693f10a5f81f9f4b8

Coverage: 31 files.
No repository checkout with dependencies/database, so tests and typecheck were not run locally.
No CI/check read tool is available; check status is unknown (mergeable_state was previously blocked, not evidence of a specific failure).
No live Paperclip Cloud broker or Google request was made.
The version-aware live-use SQL was inspected in source; the embedded-Postgres tests were not executed.
The enrollment GET still awaits the instance-wide sweep, so a large instance can block that admin request; I did not measure the latency.

Task: PAP-6440 · Run · Review history

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[High impact] The changes affect managed Google access cleanup across companies and connection removals.

The latest token-version fixes look sound, but the test file must satisfy the repository's size requirement before merging.

Findings

  1. P2 Test file exceeds size limit ▶
Fix with agent prompt
### Issue 1
server/src/__tests__/google-managed-connection-removal.test.ts:930-937
`google-managed-connection-removal.test.ts` grows from 682 to 1,036 lines without explaining why these tests must stay together. The repository requires a concrete reason when a code file crosses 1,000 lines. Move the background retry tests into a focused suite with shared fixtures, or explain why keeping them here is necessary. This requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds encrypted pending records and background retries when Google does not confirm that access ended.

  • Unconfirmed Google revocations keep retrying in the background.
  • Company and instance cleanup also queue managed Google revocations.

Reviews (9) · Last reviewed commit: "fix(connections): use the grant's select..." · Reviewed by Greptile

Comment thread server/src/routes/tool-access.ts Resolved
cryppadotta and others added 3 commits November 23, 2026 11:18
…d, and act only on a confirmed instance removal

A restart between the first broker call and the secret delete left the
removed grant's own secret live, and the worker read it as another live
holder and dropped the retry. The pending row now records its source
secret and the live-holder check skips it.

A 401 from Paperclip Cloud's status check no longer starts the instance
removal cleanup; only a signed status: removed answer does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…vocation

* origin/master:
  fix(antigravity): offer the cloud candidate in the agent picker for linux-x64 environments (#22655)
  fix(cloud): name every durable-data blocker in the online pass result (#22641)
  fix(workspaces): move a workspace with only a task warning online, as offline already does (#22650)
…dge live use by references

The pending row is now unique per company and token, and settling or
dropping it is filtered by company, so one company's removal can never
settle another company's retry. A live holder is now a secret that a
live grant or connection refers to; a stored but unused copy, or a
secret whose delete failed, no longer cancels the retry. The removed
instance cleanup no longer runs inside the status request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cryppadotta

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment thread server/src/routes/tool-access.ts Resolved

@superagent-security superagent-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superagent found 1 security concern(s).

Comment thread server/src/routes/tool-access.ts Resolved
cryppadotta and others added 2 commits November 23, 2026 12:01
…nd limit instance cleanup to instance admins

The live-use check now counts any secret with the same token that a live
grant or connection uses, including the row's source secret, so a grant
signed in again before the retry is never revoked under it. Rows queued
for a removed instance skip the check. Only an instance admin's status
check starts the removed-instance cleanup, and only one sweep runs at a
time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…vocation

* origin/master:
  test(native): give the repeated-bytes provider pack tests a 60s timeout (#22663)
@cryppadotta

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment thread server/src/routes/tool-access.ts Resolved
Comment thread server/src/routes/tool-access.ts Resolved
…removed-instance sweep atomically

A grant that pins an older refresh-token version sends that version, so
the retry now keeps the same version instead of the latest one. The
removed-instance cleanup queues every company's tokens in one
transaction before it drops any secret, and the status request waits
for that save; the in-process single-flight guard is gone because the
queue is idempotent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cryppadotta

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment thread server/src/routes/tool-access.ts Resolved
cryppadotta and others added 2 commits November 23, 2026 12:40
…nce cleanup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…vocation

* origin/master:
  fix(ci): make unchanged GitHub Actions polls free with conditional requests (#22677)
  chore(lockfile): refresh pnpm lockfiles (#22678)
  feat(telemetry): report custom connector domains and aggregator app requests (#22665)
cryppadotta and others added 2 commits November 23, 2026 13:01
…nection's Activity tab

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nt types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cryppadotta

Copy link
Copy Markdown
Contributor Author

@greptileai review

…queueing and live-use checks

Company deletion and removed-instance cleanup now keep the token version
the grant selects, and the retry's live-use check compares the token
with the version each live grant or connection selects instead of the
secret's latest version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cryppadotta

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment on lines +930 to +937
async function pinOlderRefreshVersion(fixture: Awaited<ReturnType<typeof connectManagedGmail>>) {
const refreshRef = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!;
const [secret] = await db.select({ latestVersion: companySecrets.latestVersion }).from(companySecrets).where(eq(companySecrets.id, refreshRef.secretId));
await secretService(db).rotate(refreshRef.secretId, { value: "newer-refresh-token-do-not-log" });
await db.update(connectionGrants).set({
credentialSecretRefs: fixture.grant.credentialSecretRefs.map((ref) => ref.secretId === refreshRef.secretId ? { ...ref, versionSelector: secret!.latestVersion } : ref),
}).where(eq(connectionGrants.id, fixture.grant.id));
return { secretId: refreshRef.secretId, pinned: secret!.latestVersion };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test file exceeds size limit

google-managed-connection-removal.test.ts grows from 682 to 1,036 lines without explaining why these tests must stay together. The repository requires a concrete reason when a code file crosses 1,000 lines. Move the background retry tests into a focused suite with shared fixtures, or explain why keeping them here is necessary. This requirement must be satisfied before merging.

Context Used: CONTRIBUTING.md has a guide for a good PR message including a "thinking path". If the PR doesn't include a "thinking path" and "details about what you did, why you did it, why it matters & the benefits, how we can verify it works, and any risks", the... (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: server/src/__tests__/google-managed-connection-removal.test.ts
Line: 930-937

Comment:
**Test file exceeds size limit**

`google-managed-connection-removal.test.ts` grows from 682 to 1,036 lines without explaining why these tests must stay together. The repository requires a concrete reason when a code file crosses 1,000 lines. Move the background retry tests into a focused suite with shared fixtures, or explain why keeping them here is necessary. This requirement must be satisfied before merging.

**Context Used:** CONTRIBUTING.md has a guide for a good PR message including a "thinking path". If the PR doesn't include a "thinking path" and "details about what you did, why you did it, why it matters &amp; the benefits, how we can verify it works, and any risks", the... ([source](https://app.greptile.com/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant