diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index 1aaca09e594..7e87a566189 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -640,6 +640,19 @@ for native onboarding and physical login-process retirement. Cancellation and expiry await retirement before removing the private home. After a server restart, start a new Google sign-in attempt. +Disconnecting a Google Antigravity account, or removing its connection, deletes +the sign-in that Paperclip saved for it. Paperclip does not revoke the sign-in at +Google. The sign-in uses the OAuth client of Google's own Antigravity runtime, not +a Paperclip client, and Google revocation removes the grant for the whole client. +A revoke would also sign the person out of their own Antigravity app or CLI and +out of every other Paperclip connection for that Google account. The disconnect +says that the sign-in stays valid at Google until the person removes it in their +Google account. Paperclip keeps a saved sign-in that another connection or target +still uses. If the delete fails, the grant keeps its reference, and disconnecting +again retries the delete. A reconnect that saves a new version first is never +deleted. The disconnect also releases work held by that account's usage limits in +the same transaction as the grant revocation. + Antigravity task execution remains pending acceptance. Its managed subscription path is local and turn-by-turn: native execution retires before refreshed tokens are verified and saved with generation checks. Remote and warm OAuth execution diff --git a/doc/plans/2026-11-25-antigravity-cloud-rollout.md b/doc/plans/2026-11-25-antigravity-cloud-rollout.md index cc53049f942..7424e9aa1f3 100644 --- a/doc/plans/2026-11-25-antigravity-cloud-rollout.md +++ b/doc/plans/2026-11-25-antigravity-cloud-rollout.md @@ -42,7 +42,7 @@ Copied from the kickoff success criteria. Re-read before saying "done". campaign: staging first and verified, production after. 5. Credentials: a person's Google token placed in a sandbox is scoped to that connection and agent, never logged, never visible to other tasks, and - disconnect revokes it. + disconnect deletes Paperclip's saved copy (no revoke at Google, see G10). 6. Every PR: green checks, Greptile 5/5, merged; deploys watched; staging verified. 7. The ledger records what is and is not proven. @@ -144,7 +144,7 @@ refreshable file credential with write-back to the plugin path today. | G7 | Remote sign-in is refused at save, Test and run start (`server/src/services/native-runtime/antigravity-connection-policy.ts:42-45`, `server/src/routes/agents.ts:3292-3302`, `antigravity-runner-credentials.ts:73-74`). | as cited | Core | | G8 | Warm default conflicts with per-turn only. A plugin environment's `runnerLifecycleMode` wins over the agent's setting (`server/src/services/runner-environment-lifecycle.ts:14-23`, `:92-93`), and the managed Daytona and Unikraft task environments set `warm` (Cloud `src/fleet/materializer.ts:163`, `:175`). Antigravity refuses warm at run start (`antigravity-connection-policy.ts:29-31`), but the save-time check does not pass the lifecycle (`agents.ts:3299`). So an Antigravity agent on those environments would save, then fail every run. | as cited | Core | | G9 | A Cloud user cannot create a Google sign-in. Hosted instances refuse server-host sign-in (`server/src/services/local-ai-login-policy.ts:4-12`, `server/src/routes/ai-connections.ts:153`). Google sign-in is a PKCE flow whose redirect is `http://127.0.0.1:/` on the server (`packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts:47-60`), which a remote browser cannot reach. Cloud's other sign-ins use a login terminal on the computer, and only Codex can read a credential back from it (`packages/plugins/sdk/src/protocol.ts:1120`, `:1167-1180`; `server/src/services/plugin-login-credential.ts:13-23`). | as cited | Core (route, UI) | -| G10 | Disconnect does not revoke at Google. AI connection removal marks the grant revoked in Paperclip only; no Google token revocation exists for AI connections (no `revoke` call in `server/src/services/ai-connections.ts` or `antigravity-auth.ts`). | as cited | Core | +| G10 | Disconnect left the saved sign-in in Paperclip. Decision: Paperclip deletes its saved sign-in on disconnect and removal and does not revoke at Google. The sign-in uses the OAuth client of Google's own Antigravity runtime (`antigravity-auth.ts:12`), and Google revocation "removes all OAuth 2.0 scopes previously granted to a project" (Google OAuth native-app guide, "Token revocation"). A revoke would sign the person out of their own Antigravity app or CLI and out of every other connection for that Google account. | as cited | Core | Closest templates: @@ -252,7 +252,7 @@ Reuse the Claude delivery for the token and the Codex path for write-back: | Token never logged | The credential only travels in typed task credentials and private task environment. The Launcher must reject `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` (exact name) and the `GEMINI_` and `GOOGLE_` prefixes in any configured or project environment, as it does for Copilot's `COPILOT_` prefix. Add a test that searches the run log and Launcher logs for the token after a run. | | Scoped to the run | One task credential per task, bound to the account binding and session (Cloud `task_credentials.go:64-70` `credentialBinding`); per-turn only. | | Not readable by other tasks | Today's mechanism: each agent has its own computer or sandbox (the task drivers declare `requiresAgent: true`, Cloud `extensions/plugin-agent-computer/src/manifest.ts:26-48`), so other agents' tasks never share it. Inside one computer, every task of that agent runs as the **same** UID/GID 1000 on a shared kernel; each task gets its own private mount namespace and user namespace, and `/home/agent` is shared (Cloud `agent-computer/launcher/README.md`, "Namespace isolation" and the task entry row). Same-UID tasks are therefore not a boundary by themselves. The implementation must add: the credential home under the task's private path (`/run/paperclip-runner-tasks/`), never `/home/agent` or a profile slot; removal when the task ends; and proof that a concurrent task of the same agent cannot read it, neither the file nor `/proc//environ` or memory of the Runner process. If that proof fails, pass the token through a file in the private task mount instead of the environment, or run Antigravity tasks one at a time per computer. Keep the cross-task read test as a regression test. Owner: item 9 alone (the Launcher gives the Runner a runtime root under the private task path, so `agentHomeDirectory` is task-private, and item 9's acceptance carries the cross-task read test). | -| Revoked on disconnect | New: on disconnect or reconnect, call Google's token revocation for the stored refresh token, then retire it. Running tasks fail at their next refresh. Record an activity log entry. | +| Deleted on disconnect | On disconnect or removal, delete the saved sign-in and record an activity entry. Do not call Google's revoke: the client is Google's own Antigravity client, so a revoke would also sign the person out of their Antigravity app or CLI and every other connection for that account. The person removes access in their Google account if they want it ended at Google. Running tasks keep their current turn. | ## 4. The qualification flip @@ -330,14 +330,14 @@ in that repository. | 2 | Add Antigravity sign-in task credential with refresh write-back | Core | same files plus `native-session-executor.ts` (write-back sync beside Codex), `antigravity-runner-credentials.ts` | New credential carries only the sanitized sign-in JSON as `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`; a rotated refresh token from a task snapshot is saved only after the account check; a different account is refused; a test proves no token in logs | 1 | B | | 3 | Keep per-turn-only harnesses per-turn on warm plugin environments | Core | `server/src/services/runner-environment-lifecycle.ts`, `server/src/routes/agents.ts` (save check), tests | An Antigravity agent on a plugin environment with `runnerLifecycleMode: "warm"` runs per-turn, or save refuses it in plain words; no run fails with the warm refusal | none | A | | 4 | Hosted Google sign-in (spike, then route and UI) | Core | `server/src/routes/ai-connections.ts`, `server/src/services/local-ai-login.ts`, `local-ai-browser-login.ts`, Runner `antigravity-auth.ts`, UI connection dialog | Spike answers the loopback question first. Then: on an authenticated public instance, a user completes Google sign-in by pasting the redirect; wrong `state`, reused code and another user's attempt are refused; the connection lists models | none | A | -| 5 | Revoke the Google token on disconnect | Core | AI connection removal and reconnect paths in `server/src/services/ai-connections.ts`, activity log | Disconnect calls Google revocation once (retried on network failure), the secret is retired, an activity entry is written, a later run asks to reconnect | none | A | +| 5 | Delete the saved Google sign-in on disconnect (no revoke at Google, see G10) | Core | AI connection removal and grant revocation paths, activity log | Disconnect deletes the saved sign-in (a shared one is kept; a failed delete keeps a retryable reference), the activity entry says in plain words that the sign-in stays valid at Google until the person removes it there, a later run asks to reconnect | none | A | | 6 | Allow Antigravity on plugin Runner-task and remote sign-in targets | Core | `antigravity-release.ts`, `antigravity-connection-probe.ts` (use the plugin probe path, `server/src/services/native-runtime/plugin-runner-probe.ts`), `antigravity-connection-policy.ts`, `antigravity-runner-credentials.ts`, `agents.ts` | Tested against a released-profile fixture (the real profile is still pending when this merges): picker offers Antigravity on a plugin environment; Test runs the plugin probe; save and run accept sign-in on remote targets when 2 is present. The Core sandbox path gets the same sign-in support. Re-verified live in item 12 | 1, 2, 3 | C | | 7 | Qualification runs on a paid key | Core (ledger) | `doc/plans/2026-11-22-antigravity-qualification.md` | All NOT RUN rows in section 4 pass live (24 cells local and Daytona, both lineups, session-load or no claim, attended sign-in journey, image pull time) | paid key (owner) | A (starts when the key exists) | | 8 | Flip Antigravity from pending to qualified | Core | `packages/paperclip-runner` release declaration and generated profiles, capability profile, docs, UI copy | Ledger rule met; the Core image's provider pack includes the closure without a candidate flag; no operator grant needed | 7, 3 | D | | 9 | Run Antigravity on agent computers through ACPX | Cloud | `extensions/plugin-agent-computer/src/harnesses.ts`, `agent-computer/harness/harnesses.json`, `harness.go`, Launcher `task_credentials.go`, `configured_environment.go`, `agent-computer/runtime/select-pack.mjs`, `assemble.mjs`, `pack-manifest.mjs`, `verify*.mjs`, tests (copy Cloud #1696) | Row `antigravity`: driver `acpx`, `acpxAgent: "antigravity"`, `projectAuthProvider: "google"`, credential `task-env` with key sets `GEMINI_API_KEY` or the sign-in key, reserved prefixes `GEMINI_` and `GOOGLE_`, reserved exact key `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` with a negative test (a configured or project environment that sets it is refused), blocked project settings for `.gemini/settings.json` endpoint and key fields, the Runner's runtime root (so `agentHomeDirectory`) in the private task path, with a test that a concurrent task of the same agent cannot read the staged file, `/proc//environ` or Runner memory, per-turn, closure under `provider-assets/antigravity/linux-x64` copied into the ROM. Tests pin the two tables together | 1, 2 (types); ROM content needs 8 | B (code), E (ROM) | | 10 | Pin the Runner ROM to a Core with the flip | Cloud | `agent-computer/runner-source.lock.json`, `runner-pnpm-lock.yaml` | ROM and fleet sandbox image build; closure verified at build; ROM size, build time, boot and first-token time recorded before and after | 8, 9 | E | | 11 | Staging policy campaign | Fleet (operator action, no code) | `env_config` campaign with the full array plus `antigravity_runtime`, canary first | Staging `/api/health` lists the exact array; picker shows Google Antigravity | 10 deployed on staging, 6 deployed | F | -| 12 | Staging acceptance (staging is the canary) | none (verification, ledger update) | ledger | First establish which environment kind staging stacks use (fleet environment defaults, `paperclipComputerDefault`). Then finish line 1, 2 and 5 on staging before any production exposure, both credential routes, Flash and Neon, Paperclip Computer and the managed sandbox; Stop; a restart mid-run resumes; disconnect revokes | 11, 4, 5 | F | +| 12 | Staging acceptance (staging is the canary) | none (verification, ledger update) | ledger | First establish which environment kind staging stacks use (fleet environment defaults, `paperclipComputerDefault`). Then finish line 1, 2 and 5 on staging before any production exposure, both credential routes, Flash and Neon, Paperclip Computer and the managed sandbox; Stop; a restart mid-run resumes; disconnect deletes the saved sign-in | 11, 4, 5 | F | | 13 | Update the Cloud bootstrap default | Cloud | `src/fleet/cloud-harness-availability.ts`, `docs/harness-availability.md` | New stacks born before fleet policy get the same list | 12 | G | | 14 | Production campaign | Fleet (operator action) | as 11, production | Production `/api/health` lists the array; one production run Done | 12, owner go-ahead | G | diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 87b4a095d07..f0c8e72ac41 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1648,6 +1648,7 @@ export type { ToolConnectionRemovalResult, ToolConnectionRemovalSummary, ManagedGoogleAccessRemoval, + AiSignInRemoval, ManagedGoogleRevocationOutcome, ConnectionGrantRevocationResult, ToolConnectionStoredContent, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 60366f78918..e566109a838 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -566,6 +566,7 @@ export type { ToolConnectionRemovalResult, ToolConnectionRemovalSummary, ManagedGoogleAccessRemoval, + AiSignInRemoval, ManagedGoogleRevocationOutcome, ConnectionGrantRevocationResult, ToolConnectionStoredContent, diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index f1f8dfb778e..e517c0282ce 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -429,6 +429,13 @@ export interface ToolConnectionRemovalSummary { manageUrl: string; } | null; providerAccess?: ManagedGoogleAccessRemoval | null; + signInRemoval?: AiSignInRemoval | null; +} + +export interface AiSignInRemoval { + provider: "google"; + savedSignIn: "deleted" | "kept_shared" | "not_deleted"; + providerSignIn: "still_valid"; } export type ManagedGoogleRevocationOutcome = @@ -452,6 +459,7 @@ export interface ManagedGoogleAccessRemoval { export type ConnectionGrantRevocationResult = ConnectionGrant & { providerAccess?: ManagedGoogleAccessRemoval | null; + signInRemoval?: AiSignInRemoval | null; }; export interface ToolConnectionRemovalResult { diff --git a/server/src/__tests__/antigravity-disconnect-sign-in.test.ts b/server/src/__tests__/antigravity-disconnect-sign-in.test.ts new file mode 100644 index 00000000000..c97c0344076 --- /dev/null +++ b/server/src/__tests__/antigravity-disconnect-sign-in.test.ts @@ -0,0 +1,424 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import express from "express"; +import request from "supertest"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { and, eq, isNull, sql } from "drizzle-orm"; +import { + activityLog, + companies, + companyMemberships, + companySecretBindings, + companySecrets, + connectionGrants, + routines, + routineTriggers, + createDb, + toolConnections, + userSecretDeclarations, + userSecretDefinitions, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const control = vi.hoisted(() => ({ failRelease: false })); +vi.mock("../services/heartbeat/provider-limit-wait.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + releaseProviderLimitWaits: async (...args: Parameters) => { + if (control.failRelease) throw new Error("hold release failed"); + return actual.releaseProviderLimitWaits(...args); + }, + }; +}); +vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) })); + +import { aiConnectionService } from "../services/ai-connections.js"; +import { toolAccessService } from "../services/tool-access.js"; +import { secretService } from "../services/secrets.js"; +import { createAntigravitySignInRemoval } from "../services/antigravity-access-removal.js"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { errorHandler } from "../middleware/index.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +const REFRESH_TOKEN = "antigravity-refresh-token-do-not-log"; +const credential = (refreshToken = REFRESH_TOKEN) => JSON.stringify({ + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", + client_secret: "fixture-client-secret", + refresh_token: refreshToken, + token_uri: "https://oauth2.googleapis.com/token", + scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], +}); +const STILL_VALID = { provider: "google", savedSignIn: "deleted", providerSignIn: "still_valid" }; + +describeEmbeddedPostgres("deleting a saved Google Antigravity sign-in on disconnect", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + let home = ""; + + beforeAll(async () => { + home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-antigravity-disconnect-"))); + vi.stubEnv("PAPERCLIP_HOME", home); + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-antigravity-disconnect-"); + db = createDb(tempDb.connectionString, { maxConnections: 4 }); + }, 30_000); + + afterEach(async () => { + control.failRelease = false; + vi.restoreAllMocks(); + await allowDeletion(); + }); + + async function blockDeletion(secretId: string) { + await db.execute(sql.raw(`create or replace function test_block_secret_delete() returns trigger language plpgsql as $$ + begin + if old.id = '${secretId}'::uuid and new.deleted_at is not null then raise exception 'vault unavailable'; end if; + return new; + end $$`)); + await db.execute(sql.raw("drop trigger if exists test_block_secret_delete on company_secrets")); + await db.execute(sql.raw("create trigger test_block_secret_delete before update on company_secrets for each row execute function test_block_secret_delete()")); + } + + async function allowDeletion() { + await db?.execute(sql.raw("drop trigger if exists test_block_secret_delete on company_secrets")); + } + + afterAll(async () => { + vi.unstubAllEnvs(); + await db?.$client.end({ timeout: 1 }); + await tempDb?.cleanup(); + if (home) await rm(home, { recursive: true, force: true }); + }); + + function noNetwork() { + return vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + throw new Error(`Unexpected request to ${String(url)}`); + }); + } + + async function company() { + const [row] = await db.insert(companies).values({ + name: `Antigravity disconnect ${randomUUID()}`, + issuePrefix: `AD${randomUUID().slice(0, 6).toUpperCase()}`, + }).returning(); + const userId = `antigravity-owner-${randomUUID()}`; + await db.insert(companyMemberships).values({ + companyId: row!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner", + }); + return { companyId: row!.id, userId }; + } + + async function connectGoogle(input: { companyId: string; userId: string; ownership: "personal" | "shared"; account: string; refreshToken?: string; connectionId?: string }) { + const saved = await aiConnectionService(db).save(input.companyId, input.userId, { + provider: "google", method: "subscription", ownership: input.ownership, name: `Google ${input.account}`, + loginSessionId: "fixture", agentIds: [], allAgents: true, ...(input.connectionId ? { connectionId: input.connectionId } : {}), + }, credential(input.refreshToken), undefined, undefined, undefined, input.account); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, saved.grantId)); + return { ...saved, secretId: grant!.credentialSecretRefs[0]!.secretId }; + } + + async function liveSecret(companyId: string, secretId: string) { + return (await db.select({ id: companySecrets.id }).from(companySecrets) + .where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.id, secretId), isNull(companySecrets.deletedAt)))).length > 0; + } + + async function grantRow(grantId: string) { + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId)); + return grant!; + } + + function app(companyId: string, userId: string) { + const server = express(); + server.use(express.json()); + server.use((req, _res, next) => { + req.actor = { + type: "board", userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null, + isInstanceAdmin: false, source: "session", companyIds: [companyId], + memberships: [{ companyId, membershipRole: "owner", status: "active" }], + }; + next(); + }); + server.use("/api", toolAccessRoutes(db, {})); + server.use(errorHandler); + return server; + } + + it("deletes the saved sign-in without calling Google, records it in plain words, and lets the owner reconnect", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "alice@example.test" }); + const network = noNetwork(); + + const response = await request(app(companyId, userId)).delete(`/api/tool-connections/${account.connectionId}/grants/${account.grantId}`); + + expect(response.status).toBe(200); + expect(response.body.signInRemoval).toEqual(STILL_VALID); + expect(network).not.toHaveBeenCalled(); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + expect(await grantRow(account.grantId)).toMatchObject({ status: "revoked", credentialSecretRefs: [] }); + const [entry] = await db.select().from(activityLog) + .where(and(eq(activityLog.companyId, companyId), eq(activityLog.action, "tool_connection.grant_revoked"))); + expect(entry?.details).toMatchObject({ signInRemoval: STILL_VALID }); + expect(JSON.stringify(entry?.details)).not.toContain(REFRESH_TOKEN); + + const reconnected = await connectGoogle({ companyId, userId, ownership: "personal", account: "alice@example.test", + refreshToken: "alice-new-refresh-do-not-log", connectionId: account.connectionId }); + expect(reconnected.grantId).toBe(account.grantId); + expect((await grantRow(account.grantId)).status).toBe("active"); + expect(await liveSecret(companyId, reconnected.secretId)).toBe(true); + }); + + it.each([ + ["created by someone else", { createdByUserId: "company-admin" }], + ["deleted", { deletedAt: new Date(), status: "deleted" }], + ["moved to another provider", { provider: "aws_secrets_manager" }], + ] as const)("refuses a personal reconnect when the saved sign-in slot was %s", async (_label, change) => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "olga@example.test" }); + await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + const key = `ai_${account.grantId.replaceAll("-", "_")}`; + await db.update(userSecretDefinitions).set(change).where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, key))); + const [definition] = await db.select().from(userSecretDefinitions) + .where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, key))); + + await expect(connectGoogle({ companyId, userId, ownership: "personal", account: "olga@example.test", + refreshToken: "olga-new-refresh-do-not-log", connectionId: account.connectionId })) + .rejects.toThrow("This account's saved sign-in slot was changed outside this connection"); + + const values = await db.select().from(companySecrets) + .where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.userSecretDefinitionId, definition!.id))); + expect(values).toEqual([]); + expect((await grantRow(account.grantId)).status).toBe("revoked"); + }); + + it("deletes the saved sign-in when the whole connection is removed", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "bob@example.test" }); + const network = noNetwork(); + + const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + + expect(removed.removal.signInRemoval).toEqual(STILL_VALID); + expect(removed.connection.status).toBe("archived"); + expect(network).not.toHaveBeenCalled(); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + }); + + it("keeps a saved sign-in that another grant still references", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "carol@example.test" }); + const other = await connectGoogle({ companyId, userId, ownership: "shared", account: "carol-two@example.test" }); + const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const }; + await db.update(connectionGrants).set({ credentialSecretRefs: [ref] }).where(eq(connectionGrants.id, other.grantId)); + + const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + + expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + expect((await grantRow(other.grantId)).credentialSecretRefs).toEqual([ref]); + expect((await grantRow(account.grantId)).credentialSecretRefs).toEqual([]); + }); + + it("deletes the saved sign-in on connection removal when only grants of that connection reference it", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "mia@example.test" }); + const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const }; + const [second] = await db.insert(connectionGrants).values({ + companyId, connectionId: account.connectionId, kind: "organization", credentialSecretRefs: [ref], createdByUserId: userId, + }).returning(); + + const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + + expect(removed.removal.signInRemoval).toEqual(STILL_VALID); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + expect((await grantRow(second!.id)).status).toBe("revoked"); + }); + + it("keeps the saved sign-in when a grant on another, still active connection references it", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "nia@example.test" }); + const other = await connectGoogle({ companyId, userId, ownership: "shared", account: "nia-two@example.test" }); + const ref = { secretId: account.secretId, configPath: "ai.credential", required: true, versionSelector: "latest" as const }; + await db.update(connectionGrants).set({ credentialSecretRefs: [ref] }).where(eq(connectionGrants.id, other.grantId)); + + const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + + expect(removed.removal.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + }); + + it("reports a failed delete, keeps a retryable reference, and deletes on the next disconnect", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "dana@example.test" }); + await blockDeletion(account.secretId); + + const failed = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + + expect(failed.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "not_deleted" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]); + + await allowDeletion(); + const retried = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + expect(retried.signInRemoval).toEqual(STILL_VALID); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + }); + + it("finishes a delete that failed after the sign-in was already marked deleted", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "ivy@example.test" }); + await db.execute(sql.raw(`create or replace function test_block_secret_purge() returns trigger language plpgsql as $$ + begin + if old.id = '${account.secretId}'::uuid then raise exception 'vault unavailable'; end if; + return old; + end $$`)); + await db.execute(sql.raw("create trigger test_block_secret_purge before delete on company_secrets for each row execute function test_block_secret_purge()")); + let failed; + try { + failed = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + } finally { + await db.execute(sql.raw("drop trigger if exists test_block_secret_purge on company_secrets")); + } + + expect(failed.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "not_deleted" }); + const [halfDeleted] = await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId)); + expect(halfDeleted?.deletedAt).not.toBeNull(); + expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]); + + const retried = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + expect(retried.signInRemoval).toEqual(STILL_VALID); + expect(await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId))).toEqual([]); + expect((await grantRow(account.grantId)).credentialSecretRefs).toEqual([]); + }); + + it("keeps a saved sign-in that another target binds", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "jade@example.test" }); + await db.insert(companySecretBindings).values({ + companyId, secretId: account.secretId, targetType: "agent", targetId: randomUUID(), configPath: "env.GEMINI_HOME", + }); + + const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + + expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + }); + + it("keeps a personal saved sign-in that another target declares", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "personal", account: "kim@example.test" }); + const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, account.secretId)); + await db.insert(userSecretDeclarations).values({ + companyId, userSecretDefinitionId: secret!.userSecretDefinitionId!, targetType: "agent", targetId: randomUUID(), + configPath: "env.GEMINI_HOME", envKey: "GEMINI_HOME", + }); + + const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + + expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + }); + + it("keeps a saved sign-in that a routine trigger uses", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "lee@example.test" }); + const [routine] = await db.insert(routines).values({ companyId, title: "Uses the sign-in" }).returning(); + await db.insert(routineTriggers).values({ companyId, routineId: routine!.id, kind: "webhook", secretId: account.secretId }); + + const revoked = await toolAccessService(db).revokeConnectionGrant(account.connectionId, account.grantId, { actorType: "user", actorId: userId }); + + expect(revoked.signInRemoval).toEqual({ ...STILL_VALID, savedSignIn: "kept_shared" }); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + }); + + it("keeps the reference after a failed delete during connection removal so removing it again finishes", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "erin@example.test" }); + await blockDeletion(account.secretId); + + const failed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + + expect(failed.removal.signInRemoval?.savedSignIn).toBe("not_deleted"); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + expect((await grantRow(account.grantId)).credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]); + + await allowDeletion(); + const retried = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + expect(retried.removal.signInRemoval).toEqual(STILL_VALID); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + }); + + it("never deletes a reconnect that saved a new sign-in while the disconnect was finishing", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "faye@example.test" }); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, account.connectionId)); + const vault = secretService(db); + const removal = createAntigravitySignInRemoval(db, { + secrets: { + remove: async (...args: Parameters) => { + await connectGoogle({ companyId, userId, ownership: "shared", account: "faye@example.test", + refreshToken: "faye-new-refresh-do-not-log", connectionId: account.connectionId }); + return vault.remove(...args); + }, + }, + }); + const prepared = await removal.prepare(connection!, [await grantRow(account.grantId)], { removingConnection: false }); + await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date(), updatedAt: new Date(Date.now() - 1_000) }) + .where(eq(connectionGrants.id, account.grantId)); + + const result = await prepared!.send(); + + expect(result).toBeNull(); + const grant = await grantRow(account.grantId); + expect(grant.status).toBe("active"); + expect(grant.credentialSecretRefs.map((entry) => entry.secretId)).toEqual([account.secretId]); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + expect(await vault.resolveSecretValue(companyId, account.secretId, "latest")).toBe(credential("faye-new-refresh-do-not-log")); + }); + + it("keeps the reference of a reconnect that lands while the connection is being removed", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "hana@example.test" }); + const replacement = await secretService(db).create(companyId, { name: `replacement-${randomUUID()}`, provider: "local_encrypted", value: credential("hana-new-refresh-do-not-log") }, { userId }); + const ref = { secretId: replacement.id, configPath: "ai.credential", required: true, versionSelector: "latest" }; + await db.execute(sql.raw(`create or replace function test_reconnect_on_delete() returns trigger language plpgsql as $$ + begin + if old.id = '${account.secretId}'::uuid then + update connection_grants set status = 'active', revoked_at = null, credential_secret_refs = '${JSON.stringify([ref])}'::jsonb + where id = '${account.grantId}'::uuid; + end if; + return old; + end $$`)); + await db.execute(sql.raw("create trigger test_reconnect_on_delete after delete on company_secrets for each row execute function test_reconnect_on_delete()")); + try { + await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + } finally { + await db.execute(sql.raw("drop trigger if exists test_reconnect_on_delete on company_secrets")); + } + + const grant = await grantRow(account.grantId); + expect(grant.status).toBe("active"); + expect(grant.credentialSecretRefs).toEqual([ref]); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + }); + + it("leaves every grant active and the sign-in saved when releasing held work fails during removal", async () => { + const { companyId, userId } = await company(); + const account = await connectGoogle({ companyId, userId, ownership: "shared", account: "gail@example.test" }); + control.failRelease = true; + + await expect(toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId })) + .rejects.toThrow("hold release failed"); + + expect((await grantRow(account.grantId)).status).toBe("active"); + expect(await liveSecret(companyId, account.secretId)).toBe(true); + + control.failRelease = false; + const removed = await toolAccessService(db).archiveConnection(account.connectionId, companyId, { actorType: "user", actorId: userId }); + expect(removed.removal.signInRemoval).toEqual(STILL_VALID); + expect(await liveSecret(companyId, account.secretId)).toBe(false); + }); +}); diff --git a/server/src/__tests__/google-managed-connection-removal.test.ts b/server/src/__tests__/google-managed-connection-removal.test.ts index a93e24ca01c..634413cba5c 100644 --- a/server/src/__tests__/google-managed-connection-removal.test.ts +++ b/server/src/__tests__/google-managed-connection-removal.test.ts @@ -260,15 +260,20 @@ describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () => 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); + const transaction = db.transaction.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); + vi.spyOn(db, "transaction").mockImplementation(((work: (tx: typeof db) => Promise, ...rest: unknown[]) => + transaction(async (tx) => { + const update = tx.update.bind(tx); + tx.update = ((table: unknown) => { + if (table === connectionGrants && !failedOnce) { + failedOnce = true; + throw new Error("grant revocation failed"); + } + return update(table as never); + }) as never; + return work(tx as unknown as typeof db); + }, ...(rest as []))) as never); const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`); expect(failed.status).toBe(500); diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 8fd6fddca88..3523cb266c7 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -2113,7 +2113,7 @@ function connectorEnrollmentPrincipal(req: Request): string { action: "tool_connection.grant_revoked", entityType: "connection_grant", entityId: grant.id, - details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}) }, + details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}), ...(grant.signInRemoval ? { signInRemoval: grant.signInRemoval } : {}) }, }); res.json(grant); }); diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index ca3d8713e00..e4e7f93f124 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -40,7 +40,7 @@ import { type CreateAiConnection, type AiConnectionLoginIntent, } from "@paperclipai/shared"; -import { forbidden, notFound, unprocessable } from "../errors.js"; +import { conflict, forbidden, notFound, unprocessable } from "../errors.js"; import { aiConnectionConfigurationFailure, aiConnectionCredentialNotSharedFailure } from "./ai-connection-configuration-failure.js"; import { quotaCredentialRecovery, quotaCredentialHash } from "./quota-credential-recovery.js"; import { prepareAntigravityCredentialRecovery } from "./native-runtime/antigravity-runner-credentials.js"; @@ -754,7 +754,13 @@ export function aiConnectionService(db: Db) { { userId }, ); else if (input.ownership === "personal") { - const definition = await secrets.createUserSecretDefinition( + const [existingDefinition] = await tx.select().from(userSecretDefinitions) + .where(and(eq(userSecretDefinitions.companyId, companyId), eq(userSecretDefinitions.key, `ai_${grantId.replaceAll("-", "_")}`))); + if (existingDefinition && (existingDefinition.createdByUserId !== userId || existingDefinition.deletedAt + || existingDefinition.status !== "active" || existingDefinition.provider !== "local_encrypted" + || existingDefinition.providerConfigId || existingDefinition.managedMode !== "paperclip_managed")) + throw conflict("This account's saved sign-in slot was changed outside this connection. Add the account as a new connection."); + const definition = existingDefinition ?? await secrets.createUserSecretDefinition( companyId, { key: `ai_${grantId.replaceAll("-", "_")}`, diff --git a/server/src/services/antigravity-access-removal.ts b/server/src/services/antigravity-access-removal.ts new file mode 100644 index 00000000000..8887be47463 --- /dev/null +++ b/server/src/services/antigravity-access-removal.ts @@ -0,0 +1,156 @@ +import { and, eq } from "drizzle-orm"; +import { + companySecrets, + connectionGrants, + userSecretDefinitions, + type Db, + type toolConnections, +} from "@paperclipai/db"; +import { aiConnectionMetadataSchema, type AiSignInRemoval } from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; +import { findSecretConsumers } from "./connection-secret-consumers.js"; +import { quotaCredentialRecovery } from "./quota-credential-recovery.js"; +import type { secretService } from "./secrets.js"; + +type RemovedGrant = Pick; +type Connection = typeof toolConnections.$inferSelect; +type Target = { grantId: string; secretId: string; expectedVersion: number; definitionId: string | null; state: "live" | "claimed" | "gone" }; +type CredentialResult = AiSignInRemoval["savedSignIn"] | "reconnected"; + +export type PreparedAiSignInRemoval = { + send(): Promise; + retainedGrantIds(): string[]; +}; + +export function isAntigravitySubscriptionConnection(connection: Pick): boolean { + if (connection.connectionPurpose !== "ai") return false; + const metadata = aiConnectionMetadataSchema.safeParse(connection.config?.ai); + return metadata.success && metadata.data.provider === "google" && metadata.data.method === "subscription"; +} + +export function summarizeAiSignInRemoval(results: AiSignInRemoval["savedSignIn"][]): AiSignInRemoval { + const savedSignIn = results.includes("not_deleted") ? "not_deleted" + : results.includes("kept_shared") ? "kept_shared" + : "deleted"; + return { provider: "google", savedSignIn, providerSignIn: "still_valid" }; +} + +export function createAntigravitySignInRemoval(db: Db, deps: { + secrets: Pick, "remove">; +}) { + async function privateSlot(connection: Connection, grant: RemovedGrant, secretId: string): Promise { + const [row] = await db + .select({ + id: companySecrets.id, + name: companySecrets.name, + scope: companySecrets.scope, + latestVersion: companySecrets.latestVersion, + deletedAt: companySecrets.deletedAt, + definitionId: userSecretDefinitions.id, + definitionKey: userSecretDefinitions.key, + }) + .from(companySecrets) + .leftJoin(userSecretDefinitions, eq(userSecretDefinitions.id, companySecrets.userSecretDefinitionId)) + .where(and(eq(companySecrets.companyId, connection.companyId), eq(companySecrets.id, secretId))); + if (!row) return { grantId: grant.id, secretId, expectedVersion: 0, definitionId: null, state: "gone" }; + const personal = grant.kind === "user"; + const claimed = row.deletedAt !== null; + const name = `ai-${grant.id}`; + const owned = personal + ? row.scope === "user" && row.definitionKey === `ai_${grant.id.replaceAll("-", "_")}` + : row.scope === "company" && (row.name === name || (claimed && row.name === `${name}__deleted__${row.id}`)); + if (!owned) return null; + return { + grantId: grant.id, secretId: row.id, expectedVersion: row.latestVersion, + definitionId: personal ? row.definitionId : null, state: claimed ? "claimed" : "live", + }; + } + + async function usedElsewhere(connection: Connection, target: Target, removingConnection: boolean): Promise { + const held = await findSecretConsumers(db, { + companyId: connection.companyId, connectionId: connection.id, secretIds: [target.secretId], + excludeGrantIds: [target.grantId], removingConnection, liveOnly: true, + }); + return held.has(target.secretId); + } + + async function clearRevokedRef(connection: Connection, target: Target) { + const [grant] = await db.select({ refs: connectionGrants.credentialSecretRefs }).from(connectionGrants) + .where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.status, "revoked"))); + if (!grant) return; + const refs = (grant.refs ?? []).filter((ref) => ref.secretId !== target.secretId); + await db.update(connectionGrants) + .set({ credentialSecretRefs: refs, updatedAt: new Date() }) + .where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.status, "revoked"))); + } + + async function stillRevoked(connection: Connection, target: Target) { + const [grant] = await db.select({ status: connectionGrants.status }).from(connectionGrants) + .where(and(eq(connectionGrants.id, target.grantId), eq(connectionGrants.companyId, connection.companyId))); + return grant?.status === "revoked"; + } + + async function secretStillStored(connection: Connection, target: Target) { + const rows = await db.select({ id: companySecrets.id }).from(companySecrets) + .where(and(eq(companySecrets.companyId, connection.companyId), eq(companySecrets.id, target.secretId))); + return rows.length > 0; + } + + async function retire(connection: Connection, target: Target, removingConnection: boolean): Promise { + if (!(await stillRevoked(connection, target))) return "reconnected"; + if (await usedElsewhere(connection, target, removingConnection)) { + await clearRevokedRef(connection, target); + return "kept_shared"; + } + if (target.state === "gone") { + await clearRevokedRef(connection, target); + return "deleted"; + } + const removed = target.state === "claimed" + ? await deps.secrets.remove(target.secretId) + : await deps.secrets.remove(target.secretId, { expectedVersion: target.expectedVersion }); + if (!removed && await secretStillStored(connection, target)) { + return (await stillRevoked(connection, target)) ? "not_deleted" : "reconnected"; + } + await clearRevokedRef(connection, target); + await quotaCredentialRecovery(connection.companyId, target.grantId).clear().catch(() => undefined); + return "deleted"; + } + + async function prepare(connection: Connection, grants: RemovedGrant[], scope: { removingConnection: boolean }): Promise { + if (!isAntigravitySubscriptionConnection(connection)) return null; + const targets: Target[] = []; + for (const grant of grants) { + const ref = (grant.credentialSecretRefs ?? []).find((entry) => entry.configPath === "ai.credential"); + if (!ref) continue; + const target = await privateSlot(connection, grant, ref.secretId); + if (target) targets.push(target); + } + if (targets.length === 0) return null; + const retained: string[] = []; + return { + retainedGrantIds: () => [...retained], + send: async () => { + const results: AiSignInRemoval["savedSignIn"][] = []; + for (const target of targets) { + let result: CredentialResult; + try { + result = await retire(connection, target, scope.removingConnection); + } catch (error) { + logger.warn( + { companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error }, + "Could not delete a disconnected Google sign-in", + ); + result = "not_deleted"; + } + if (result === "reconnected") continue; + if (result === "not_deleted") retained.push(target.grantId); + results.push(result); + } + return results.length > 0 ? summarizeAiSignInRemoval(results) : null; + }, + }; + } + + return { prepare }; +} diff --git a/server/src/services/connection-secret-consumers.ts b/server/src/services/connection-secret-consumers.ts new file mode 100644 index 00000000000..c8bd7ce6af0 --- /dev/null +++ b/server/src/services/connection-secret-consumers.ts @@ -0,0 +1,69 @@ +import { and, eq, inArray, ne, sql, type SQL } from "drizzle-orm"; +import { + companySecretBindings, + companySecrets, + connectionGrants, + toolConnections, + userSecretDeclarations, + type Db, +} from "@paperclipai/db"; +import { connectionSecretsUsedByOtherConsumers } from "./connection-credentials.js"; + +export type SecretConsumerScope = { + companyId: string; + connectionId: string; + secretIds: readonly string[]; + excludeGrantIds?: readonly string[]; + removingConnection: boolean; + liveOnly: boolean; +}; + +export async function findSecretConsumers(db: Db, scope: SecretConsumerScope): Promise> { + const wanted = [...new Set(scope.secretIds.filter((id) => typeof id === "string" && id.length > 0))]; + if (wanted.length === 0) return new Set(); + const wantedSet = new Set(wanted); + const held = await connectionSecretsUsedByOtherConsumers(db, wanted); + const excludedGrants = new Set(scope.excludeGrantIds ?? []); + + const grantFilters: SQL[] = [eq(connectionGrants.companyId, scope.companyId)]; + if (scope.liveOnly) grantFilters.push(ne(connectionGrants.status, "revoked")); + if (scope.removingConnection) grantFilters.push(ne(connectionGrants.connectionId, scope.connectionId)); + const grants = await db.select({ id: connectionGrants.id, refs: connectionGrants.credentialSecretRefs }) + .from(connectionGrants).where(and(...grantFilters)); + for (const row of grants) { + if (excludedGrants.has(row.id)) continue; + for (const ref of row.refs ?? []) if (wantedSet.has(ref.secretId)) held.add(ref.secretId); + } + + const connectionFilters: SQL[] = [eq(toolConnections.companyId, scope.companyId)]; + if (scope.liveOnly) connectionFilters.push(ne(toolConnections.status, "archived")); + if (scope.removingConnection) connectionFilters.push(ne(toolConnections.id, scope.connectionId)); + const connections = await db.select({ refs: toolConnections.credentialRefs, secretRefs: toolConnections.credentialSecretRefs }) + .from(toolConnections).where(and(...connectionFilters)); + for (const row of connections) { + for (const ref of [...(row.refs ?? []), ...(row.secretRefs ?? [])]) if (wantedSet.has(ref.secretId)) held.add(ref.secretId); + } + + const bindings = await db.select({ secretId: companySecretBindings.secretId }).from(companySecretBindings) + .where(and( + eq(companySecretBindings.companyId, scope.companyId), + inArray(companySecretBindings.secretId, wanted), + sql`not (${companySecretBindings.targetType} = 'tool_connection' and ${companySecretBindings.targetId} = ${scope.connectionId})`, + )); + for (const row of bindings) held.add(row.secretId); + + const definitions = await db.select({ id: companySecrets.id, definitionId: companySecrets.userSecretDefinitionId }) + .from(companySecrets) + .where(and(eq(companySecrets.companyId, scope.companyId), inArray(companySecrets.id, wanted))); + const definitionIds = [...new Set(definitions.flatMap((row) => row.definitionId ? [row.definitionId] : []))]; + if (definitionIds.length > 0) { + const declared = await db.select({ definitionId: userSecretDeclarations.userSecretDefinitionId }).from(userSecretDeclarations) + .where(and( + inArray(userSecretDeclarations.userSecretDefinitionId, definitionIds), + sql`not (${userSecretDeclarations.targetType} = 'tool_connection' and ${userSecretDeclarations.targetId} = ${scope.connectionId})`, + )); + const shared = new Set(declared.map((row) => row.definitionId)); + for (const row of definitions) if (row.definitionId && shared.has(row.definitionId)) held.add(row.id); + } + return held; +} 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 index 5225247469f..6abc14eba84 100644 --- a/server/src/services/tool-access/connections/google-access-removal.test.ts +++ b/server/src/services/tool-access/connections/google-access-removal.test.ts @@ -2,7 +2,7 @@ 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 })); +vi.mock("../../connection-credentials.js", () => ({ resolveConnectionGrantSecret, connectionSecretsUsedByOtherConsumers: async () => new Set() })); import { createManagedGoogleAccessRemoval, summarizeManagedGoogleAccess } from "./google-access-removal.js"; import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; diff --git a/server/src/services/tool-access/connections/google-access-removal.ts b/server/src/services/tool-access/connections/google-access-removal.ts index 4c00c9ff256..65d1560a4a3 100644 --- a/server/src/services/tool-access/connections/google-access-removal.ts +++ b/server/src/services/tool-access/connections/google-access-removal.ts @@ -1,9 +1,10 @@ import type { Db } from "@paperclipai/db"; import { companySecrets, connectionGrants, googlePendingRevocations, toolAccessAuditEvents, toolConnections } from "@paperclipai/db"; -import { and, eq, inArray, isNull, ne } from "drizzle-orm"; +import { and, eq, inArray, isNull } from "drizzle-orm"; import type { ManagedGoogleAccessRemoval, ManagedGoogleRevocationOutcome } from "@paperclipai/shared"; import { logger } from "../../../middleware/logger.js"; import { resolveConnectionGrantSecret } from "../../connection-credentials.js"; +import { findSecretConsumers } from "../../connection-secret-consumers.js"; import { isPaperclipCloudConnectorStrategy, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { managedConnectorConsentSubject, managedConnectorProfile } from "../oauth/client-settings.js"; import { oauthConfig } from "../oauth/metadata.js"; @@ -189,25 +190,10 @@ export function createManagedGoogleAccessRemoval(db: Db, deps: { 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; + return findSecretConsumers(db, { + companyId: connection.companyId, connectionId: connection.id, secretIds, + excludeGrantIds: grants.map((grant) => grant.id), removingConnection, liveOnly: true, + }); } async function deleteSentSecrets( diff --git a/server/src/services/tool-access/connections/grants.ts b/server/src/services/tool-access/connections/grants.ts index 990048188c6..f1e8cae4082 100644 --- a/server/src/services/tool-access/connections/grants.ts +++ b/server/src/services/tool-access/connections/grants.ts @@ -12,6 +12,7 @@ import { agents, connectionGrantMembers, connectionGrantDelegations, connectionG import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { createManagedGoogleAccessRemoval } from "./google-access-removal.js"; +import { createAntigravitySignInRemoval } from "../../antigravity-access-removal.js"; import { contentDeletionActor, deleteGoogleContentWhenAccessEnds } from "./google-content-retention.js"; import type { ConnectionGrantRevocationResult } from "@paperclipai/shared"; import { vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js"; @@ -30,6 +31,7 @@ type GrantDependencies = { export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets }: GrantDependencies) { const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector }); + const antigravitySignIn = createAntigravitySignInRemoval(db, { secrets }); return { listConnectionGrants: async (idOrUid: string, companyId?: string) => { const connection = await getConnectionRow(idOrUid, companyId); @@ -518,6 +520,7 @@ replaceConnectionGrantMembers: async ( removingConnection: false, removeSecret: (secretId, expectedVersion) => secrets.remove(secretId, { expectedVersion }), }); + const signInRemoval = await antigravitySignIn.prepare(connection, [currentGrant], { removingConnection: false }); if ( connection.credentialSource === "vercel_connect" && connection.externalCredential @@ -612,6 +615,7 @@ replaceConnectionGrantMembers: async ( }); if (!grant) throw notFound("Connection grant not found"); const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null; + const signIn = signInRemoval ? await signInRemoval.send() : null; await db.insert(toolAccessAuditEvents).values({ companyId: connection.companyId, connectionId: connection.id, @@ -623,7 +627,7 @@ replaceConnectionGrantMembers: async ( details: { grantId: grant.id, kind: grant.kind, providerRevocation }, }); releasedWaitPublications.forEach(publishActivity); - return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}) }; + return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}), ...(signIn ? { signInRemoval: signIn } : {}) }; } }; } diff --git a/server/src/services/tool-access/connections/removal.ts b/server/src/services/tool-access/connections/removal.ts index ae4602d3999..e770122ca5f 100644 --- a/server/src/services/tool-access/connections/removal.ts +++ b/server/src/services/tool-access/connections/removal.ts @@ -4,6 +4,9 @@ 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 { createAntigravitySignInRemoval } from "../../antigravity-access-removal.js"; +import { publishActivity } from "../../activity-log.js"; +import type { ActivityPublication } from "../../../types/activity-publication.js"; import { contentDeletionActor, deleteGoogleContentWhenAccessEnds } from "./google-content-retention.js"; import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { actorBinding, connectionActorUserId } from "../actor.js"; @@ -16,16 +19,16 @@ import { chatEndpoints } from "@paperclipai/db"; import { isBrowserUseConnection } from "../../browser-use-client.js"; import { browserUseService } from "../../browser-use.js"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; -import { and, eq, inArray, isNull, ne, sql } from "drizzle-orm"; +import { and, eq, inArray, isNull, ne, notInArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { connectionGrants, connectionTokenIssuances, companySecretBindings, companySecrets, userSecretDefinitions, userSecretDeclarations, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolOauthStates, toolGatewaySessions, toolMcpGateways, toolMcpGatewayTokens, toolProfileBindings, toolProfileEntries, toolProfiles, toolRuntimeSlots } from "@paperclipai/db"; +import { connectionGrants, connectionTokenIssuances, companySecretBindings, companySecrets, userSecretDefinitions, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolOauthStates, toolGatewaySessions, toolMcpGateways, toolMcpGatewayTokens, toolProfileBindings, toolProfileEntries, toolProfiles, toolRuntimeSlots } from "@paperclipai/db"; import type { ToolConnectionRemovalResult, ToolConnectionRemovalSummary } from "@paperclipai/shared"; import { notFound } from "../../../errors.js"; import { logger } from "../../../middleware/logger.js"; import { releaseProviderLimitWaits } from "../../heartbeat/provider-limit-wait.js"; import { forgetMcpHttpSessions } from "../../mcp-http.js"; import { secretService } from "../../secrets.js"; -import { connectionSecretsUsedByOtherConsumers } from "../../connection-credentials.js"; +import { findSecretConsumers } from "../../connection-secret-consumers.js"; import { createToolRuntimeSupervisor } from "../../tool-runtime-supervisor.js"; import { vercelConnectIntegrationStatus, vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js"; @@ -91,6 +94,7 @@ type RemovalDependencies = { export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow }: RemovalDependencies) { const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector }); + const antigravitySignIn = createAntigravitySignInRemoval(db, { secrets }); /** * Split the secrets a connection points at into the ones it owns outright and * the ones another consumer still depends on. @@ -139,63 +143,15 @@ async function classifyConnectionSecrets( ); const byId = new Map(secretRows.map((row) => [row.id, row])); - const referencedElsewhere = await connectionSecretsUsedByOtherConsumers(db, unique); - const foreignBindings = await db - .select({ secretId: companySecretBindings.secretId }) - .from(companySecretBindings) - .where( - and( - eq(companySecretBindings.companyId, connection.companyId), - inArray(companySecretBindings.secretId, unique), - sql`not (${companySecretBindings.targetType} = 'tool_connection' and ${companySecretBindings.targetId} = ${connection.id})`, - ), - ); - for (const row of foreignBindings) referencedElsewhere.add(row.secretId); - - // Bindings are the authority, but read the sibling refs too: a row written - // before `syncCredentialBindings` existed — or by hand — can reference a - // secret with no binding to prove it. - const siblingConnections = await db - .select({ - credentialRefs: toolConnections.credentialRefs, - credentialSecretRefs: toolConnections.credentialSecretRefs, - }) - .from(toolConnections) - .where( - and( - eq(toolConnections.companyId, connection.companyId), - ne(toolConnections.id, connection.id), - ), - ); - for (const row of siblingConnections) { - for (const ref of row.credentialRefs ?? []) - referencedElsewhere.add(ref.secretId); - for (const ref of row.credentialSecretRefs ?? []) - referencedElsewhere.add(ref.secretId); - } - const siblingGrants = await db - .select({ credentialSecretRefs: connectionGrants.credentialSecretRefs }) - .from(connectionGrants) - .where( - and( - eq(connectionGrants.companyId, connection.companyId), - ne(connectionGrants.connectionId, connection.id), - ), - ); - for (const row of siblingGrants) { - for (const ref of row.credentialSecretRefs ?? []) - referencedElsewhere.add(ref.secretId); - } + const referencedElsewhere = await findSecretConsumers(db, { + companyId: connection.companyId, connectionId: connection.id, secretIds: unique, + removingConnection: true, liveOnly: false, + }); const definitionIds = secretRows.flatMap((row) => row.userSecretDefinitionId ? [row.userSecretDefinitionId] : []); const definitions = definitionIds.length ? await db.select().from(userSecretDefinitions) .where(and(eq(userSecretDefinitions.companyId, connection.companyId), inArray(userSecretDefinitions.id, definitionIds))) : []; const dedicatedDefinitions = new Set(definitions.filter((row) => row.key.startsWith(CONNECTION_OWNED_SECRET_KEY_PREFIX) || row.key.startsWith(`tool_oauth.${connection.id}.`)).map((row) => row.id)); - const foreignDeclarations = definitionIds.length ? await db.select().from(userSecretDeclarations).where(and( - inArray(userSecretDeclarations.userSecretDefinitionId, definitionIds), - sql`not (${userSecretDeclarations.targetType} = 'tool_connection' and ${userSecretDeclarations.targetId} = ${connection.id})`, - )) : []; - const sharedDefinitions = new Set(foreignDeclarations.map((row) => row.userSecretDefinitionId)); const owned: string[] = []; const retained: string[] = []; for (const secretId of unique) { @@ -208,7 +164,7 @@ async function classifyConnectionSecrets( continue; } const dedicated = row.scope === "user" && row.userSecretDefinitionId - ? dedicatedDefinitions.has(row.userSecretDefinitionId) && !sharedDefinitions.has(row.userSecretDefinitionId) + ? dedicatedDefinitions.has(row.userSecretDefinitionId) : row.scope === "company" && row.userSecretDefinitionId === null && row.key.startsWith(CONNECTION_OWNED_SECRET_KEY_PREFIX); if (dedicated && !referencedElsewhere.has(secretId)) owned.push(secretId); @@ -294,8 +250,10 @@ async function removeConnection( if (await secrets.remove(secretId, { expectedVersion })) secretsRevoked += 1; }, }); - if (grantsToRevoke.length > 0) { - await db + const signInRemoval = await antigravitySignIn.prepare(connection, grantRows, { removingConnection: true }); + const releasedWaitPublications: ActivityPublication[] = []; + await db.transaction(async (tx) => { + if (grantsToRevoke.length > 0) await tx .update(connectionGrants) .set({ status: "revoked", @@ -313,16 +271,16 @@ async function removeConnection( grantsToRevoke.map((row) => row.id), ), ); - } - // Usage limits reported on a removed account no longer hold work. This - // runs before any provider call and covers grants an earlier attempt - // already revoked, so a failed release fails the removal and its retry - // releases them. - await releaseProviderLimitWaits(db, { - companyId: connection.companyId, reason: "ai_connection_revoked", - grantIds: grantRows.map((row) => row.id), - ...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}), + // Usage limits reported on a removed account no longer hold work. The + // release commits with the revocation, so waiting work never outlives it. + await releaseProviderLimitWaits(tx as unknown as Db, { + companyId: connection.companyId, reason: "ai_connection_revoked", + grantIds: grantRows.map((row) => row.id), + publications: releasedWaitPublications, + ...(binding.actorType && binding.actorId ? { actor: { actorType: binding.actorType, actorId: binding.actorId } } : {}), + }); }); + releasedWaitPublications.forEach(publishActivity); let externalCredentialCleanup: ToolConnectionRemovalSummary["externalCredentialCleanup"] = null; if ( @@ -624,6 +582,8 @@ async function removeConnection( } const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null; + const signIn = signInRemoval ? await signInRemoval.send() : null; + const retainedGrantIds = signInRemoval?.retainedGrantIds() ?? []; // Only now, with every access path closed, revoke the credentials. Each // `secrets.remove` marks the row deleted before it calls the provider, so a @@ -669,6 +629,8 @@ async function removeConnection( and( eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id), + eq(connectionGrants.status, "revoked"), + ...(retainedGrantIds.length > 0 ? [notInArray(connectionGrants.id, retainedGrantIds)] : []), ), ); } @@ -694,6 +656,7 @@ async function removeConnection( applicationArchived: archived.applicationArchived, externalCredentialCleanup, ...(providerAccess ? { providerAccess } : {}), + ...(signIn ? { signInRemoval: signIn } : {}), }, }; } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 562cdc0d041..f03d057fd7c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -278,7 +278,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": "87b4a095d07b2eace7cc8dfc44d6db9631012dd6", + "packages/shared/src/index.ts": "f0c8e72ac411fad0f9c090f68ea9590d15316d94", "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", @@ -438,7 +438,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": "60366f789182ba3a4fb6895f91454ec386988496", + "packages/shared/src/types/index.ts": "e566109a838995a8b14cb2a4d47394aea0b9a752", "packages/shared/src/types/instance.ts": "ddfef2455723757a5ecffaf3bab56ec47c287267", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5", @@ -462,7 +462,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": "f1f8dfb778e19835c79b808bfc9730663aa411ee", + "packages/shared/src/types/tool-access.ts": "e517c0282ce65664eb281eafa8534c642a5943a8", "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/components/ai-connections/ManagedAiConnectionDetails.tsx b/ui/src/components/ai-connections/ManagedAiConnectionDetails.tsx index fa8300e0cf1..50c90578237 100644 --- a/ui/src/components/ai-connections/ManagedAiConnectionDetails.tsx +++ b/ui/src/components/ai-connections/ManagedAiConnectionDetails.tsx @@ -1,4 +1,6 @@ import { heartbeatsApi } from "@/api/heartbeats"; +import { useToastActions } from "@/context/ToastContext"; +import { aiSignInRemovalNotice } from "@/features/connections/googleAccessRemoval"; import { Button } from "@/components/ui/button"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { aiConnectionsApi } from "@/api/ai-connections"; @@ -62,10 +64,15 @@ export function ManagedAiConnectionDetails({ const accountsView = useQueryView(accounts); const grantsView = useQueryView(grants); const refresh = () => client.invalidateQueries(); + const { pushToast } = useToastActions(); const revoke = useMutation({ mutationFn: (id: string) => toolsApi.revokeConnectionGrant(connection.id, id), - onSuccess: refresh, + onSuccess: (revoked) => { + const notice = aiSignInRemovalNotice(revoked.signInRemoval); + if (notice) pushToast({ title: "Account disconnected", body: notice.body, tone: notice.tone, ...(notice.action ? { action: notice.action } : {}) }); + return refresh(); + }, }); const stop = useMutation({ mutationFn: (id: string) => heartbeatsApi.cancel(id), diff --git a/ui/src/features/connections/googleAccessRemoval.test.ts b/ui/src/features/connections/googleAccessRemoval.test.ts index 61f5d27d19f..2fa83d88eb8 100644 --- a/ui/src/features/connections/googleAccessRemoval.test.ts +++ b/ui/src/features/connections/googleAccessRemoval.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { connectionRemovalToast, GOOGLE_THIRD_PARTY_ACCESS_URL, googleAccessRemovalNotice, googleAccessRetrySummary } from "./googleAccessRemoval"; +import { aiSignInRemovalNotice, connectionRemovalToast, GOOGLE_THIRD_PARTY_ACCESS_URL, googleAccessRemovalNotice, googleAccessRetrySummary } from "./googleAccessRemoval"; describe("googleAccessRemovalNotice", () => { afterEach(() => vi.unstubAllGlobals()); @@ -65,3 +65,37 @@ describe("googleAccessRemovalNotice", () => { expect(googleAccessRetrySummary("google_access_not_ended", { result: "gave_up" })).toBe("Paperclip stopped trying to end its access at Google without a confirmation"); }); }); + +describe("aiSignInRemovalNotice", () => { + it("says nothing when no saved Google sign-in was involved", () => { + expect(aiSignInRemovalNotice(undefined)).toBeNull(); + expect(aiSignInRemovalNotice(null)).toBeNull(); + }); + + it("says the saved sign-in was deleted and stays valid at Google", () => { + const notice = aiSignInRemovalNotice({ provider: "google", savedSignIn: "deleted", providerSignIn: "still_valid" }); + expect(notice?.tone).toBe("info"); + expect(notice?.body).toBe("Paperclip deleted its saved Google sign-in. The sign-in stays valid at Google until you remove it in your Google account's third-party connections. Removing it there also signs this Google account out of Antigravity everywhere."); + expect(notice?.action?.label).toBe("Open Google account connections"); + }); + + it("says a shared sign-in was kept", () => { + expect(aiSignInRemovalNotice({ provider: "google", savedSignIn: "kept_shared", providerSignIn: "still_valid" })?.body) + .toMatch(/^Another connection still uses this saved Google sign-in, so Paperclip kept it\./); + }); + + it("warns when the saved sign-in could not be deleted", () => { + expect(aiSignInRemovalNotice({ provider: "google", savedSignIn: "not_deleted", providerSignIn: "still_valid" })).toEqual({ + tone: "warn", + body: "Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry.", + }); + }); + + it("adds the notice to a connection removal toast", () => { + const toast = connectionRemovalToast({ + title: "Connection deleted", body: "Google is no longer available to agents.", providerAccess: null, + signInRemoval: { provider: "google", savedSignIn: "not_deleted", providerSignIn: "still_valid" }, + }); + expect(toast).toMatchObject({ tone: "warn", body: "Google is no longer available to agents. Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry." }); + }); +}); diff --git a/ui/src/features/connections/googleAccessRemoval.ts b/ui/src/features/connections/googleAccessRemoval.ts index a239cc96e4c..86d4cdfa6f4 100644 --- a/ui/src/features/connections/googleAccessRemoval.ts +++ b/ui/src/features/connections/googleAccessRemoval.ts @@ -1,4 +1,4 @@ -import type { ManagedGoogleAccessRemoval } from "@paperclipai/shared"; +import type { AiSignInRemoval, ManagedGoogleAccessRemoval } from "@paperclipai/shared"; import type { ToastAction, ToastInput, ToastTone } from "../../context/ToastContext"; export const GOOGLE_THIRD_PARTY_ACCESS_URL = "https://myaccount.google.com/connections"; @@ -51,12 +51,28 @@ export function googleAccessRemovalNotice( }; } +export function aiSignInRemovalNotice(removal: AiSignInRemoval | null | undefined): GoogleAccessRemovalNotice | null { + if (removal?.provider !== "google") return null; + if (removal.savedSignIn === "not_deleted") { + return { tone: "warn", body: "Paperclip couldn't delete its saved Google sign-in. Disconnect again to retry." }; + } + const kept = removal.savedSignIn === "kept_shared" + ? "Another connection still uses this saved Google sign-in, so Paperclip kept it." + : "Paperclip deleted its saved Google sign-in."; + return { + tone: "info", + body: `${kept} The sign-in stays valid at Google until you remove it in your Google account's third-party connections. Removing it there also signs this Google account out of Antigravity everywhere.`, + action: openGoogleAccountConnections, + }; +} + export function connectionRemovalToast(input: { title: string; body: string; providerAccess: ManagedGoogleAccessRemoval | null | undefined; + signInRemoval?: AiSignInRemoval | null; }): ToastInput { - const notice = googleAccessRemovalNotice(input.providerAccess); + const notice = googleAccessRemovalNotice(input.providerAccess) ?? aiSignInRemovalNotice(input.signInRemoval); return { title: input.title, body: notice ? `${input.body} ${notice.body}` : input.body, diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index a44dcdc63da..d53be347a4d 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -202,7 +202,7 @@ export function Connections() { 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 })); + pushToast(connectionRemovalToast({ title: "Connection deleted", body, providerAccess: removed?.removal?.providerAccess, signInRemoval: removed?.removal?.signInRemoval })); setConnectionToDelete(null); }, onError: (error) => diff --git a/ui/src/pages/audit/AuditFeed.tsx b/ui/src/pages/audit/AuditFeed.tsx index 83c3f7b1abd..70fa0717920 100644 --- a/ui/src/pages/audit/AuditFeed.tsx +++ b/ui/src/pages/audit/AuditFeed.tsx @@ -2,7 +2,7 @@ import { AgentAvatar } from "@/components/AgentAvatar"; import { useEffect, useMemo, useState } from "react"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Download, ScrollText, ShieldAlert } from "lucide-react"; -import type { Agent, CaseWorkflowTransition, ManagedGoogleAccessRemoval } from "@paperclipai/shared"; +import type { Agent, AiSignInRemoval, CaseWorkflowTransition, ManagedGoogleAccessRemoval } from "@paperclipai/shared"; import { Link, useCaseHref } from "@/lib/router"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; @@ -28,7 +28,7 @@ import { describeError } from "@/api/errors"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { useToastActions } from "@/context/ToastContext"; import { instanceSettingsApi } from "@/api/instanceSettings"; -import { googleAccessRemovalNotice } from "@/features/connections/googleAccessRemoval"; +import { aiSignInRemovalNotice, googleAccessRemovalNotice } from "@/features/connections/googleAccessRemoval"; const PAGE_SIZE = 50; const ALL = "__all"; @@ -211,10 +211,10 @@ function AuditEntityNode({ record }: { record: AuditActionRecord }) { function auditOutcome(record: AuditActionRecord): string | null { if (record.action === "tool_connection.archived" || record.action === "tool_connection.grant_revoked") { - return googleAccessRemovalNotice( + return (googleAccessRemovalNotice( record.details?.providerAccess as ManagedGoogleAccessRemoval | undefined, record.action === "tool_connection.grant_revoked" ? "credentials" : "connection", - )?.body ?? null; + ) ?? aiSignInRemovalNotice(record.details?.signInRemoval as AiSignInRemoval | undefined))?.body ?? null; } return formatActivityOutcome(record.action, record.details); }