fix(ai-connections): delete the saved Google Antigravity sign-in on disconnect (#22931)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - AI connections let a company sign in to a model provider, and Google
Antigravity uses a Google account sign-in with a long-lived refresh
token
> - When a user disconnected that account, or removed its connection,
Paperclip marked the grant revoked but kept the saved sign-in in its
database
> - The obvious fix, revoking the token at Google, is unsafe here: the
sign-in uses the OAuth client of Google's own Antigravity runtime, and
Google revocation removes the grant for that whole client
> - A revoke would sign the person out of their own Antigravity app or
CLI and out of every other Paperclip connection for that Google account
> - This pull request deletes Paperclip's saved sign-in on disconnect
and removal, does not call Google, and says plainly that the sign-in
stays valid at Google until the person removes it there
> - The benefit is that "disconnect" does what the person expects in
Paperclip, never breaks their other tools, and never leaves a usable
token behind in Paperclip

## Linked Issues or Issue Description

No issue exists. This follows the feature request template.

**Subsystem affected**

AI connections: Google Antigravity subscription sign-in, its disconnect
and connection removal paths, the connection removal transaction, and
the disconnect messages in the UI and activity log.

**Problem or motivation**

Disconnecting a Google Antigravity subscription account marked the
connection grant revoked in Paperclip only. The saved sign-in (an
encrypted company secret that holds the refresh token) was not deleted.
Connection removal kept it too, because removal only deletes secrets in
the app-owned key namespace. Separately, connection removal revoked the
grants and then released usage-limit holds in two separate writes, so a
failure between them left the grants revoked while held work kept
waiting.

**Proposed solution**

On disconnect or removal, delete Paperclip's saved sign-in and record
the result in plain words. Do not call Google's token revocation. Keep a
saved sign-in that another grant or target still uses. If the delete
fails, keep the reference and let the next disconnect retry. Never
delete a sign-in that a reconnect saved in the meantime. Commit the
grant revocation and the hold release in one transaction, as the
single-grant revoke already does.

**Alternatives considered**

Revoking the refresh token at `https://oauth2.googleapis.com/revoke`
(the first revision of this pull request). The saved credential always
uses client
`1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com`
(`sanitizeAntigravityCredential` rejects any other), which belongs to
Google's own Antigravity runtime that Paperclip runs for sign-in.
Google's OAuth guide for installed apps ("Token revocation") says
revocation "removes all OAuth 2.0 scopes previously granted to a
project" and invalidates tokens for all clients registered under that
project. So a revoke would sign the person out of every Antigravity
sign-in for that account, not only Paperclip's. Paperclip has no client
of its own for this sign-in, so it cannot revoke only its own access.

**Roadmap alignment**

This is work item 5 of the merged plan
`doc/plans/2026-11-25-antigravity-cloud-rollout.md` (gap G10). This pull
request updates G10, item 5 and the security table there to record the
decision.

## What Changed

- `server/src/services/antigravity-access-removal.ts`: for a Google
Antigravity subscription connection, deletes the grant's own saved
sign-in (the private `ai-<grant>` or `ai_<grant>` slot only). It keeps a
sign-in that a live grant or connection elsewhere, a secret binding or
user-secret declaration on another target, or another consumer (agent
profile, routine trigger, secret proposal) still uses. On connection
removal, other grants of the same connection do not count. The delete
passes the saved version, and the grant must still be revoked, so a
reconnect that saved a new version is never deleted. A failed delete
keeps the grant's reference so the next disconnect retries, and the
retry finds a sign-in that is already marked deleted and finishes the
purge. It also clears the quota-recovery file for that grant.
- New `server/src/services/connection-secret-consumers.ts`: one
`findSecretConsumers` check for "is this secret used elsewhere?".
Connection removal (`classifyConnectionSecrets`), managed Google removal
(`secretsHeldElsewhere`) and this change use it. Removal keeps its rule
that any grant or connection counts; the two Google paths count only
live ones. Managed Google removal now also respects bindings,
declarations and other consumers, which only keeps more secrets.
- `packages/shared`: new `AiSignInRemoval` result (`savedSignIn: deleted
| kept_shared | not_deleted`, `providerSignIn: still_valid`) on the
grant revocation result and the connection removal summary.
- `grants.ts`, `removal.ts`, `routes/tool-access.ts`: return and log the
result. Removal does not clear a grant reference whose delete failed,
and its final reference clear only touches revoked grants, so a
reconnect that lands during removal keeps its sign-in.
- `removal.ts`: the grant revocation and the usage-limit hold release
now commit in one transaction.
- `ai-connections.ts`: a personal reconnect reuses the grant's existing
secret definition only if the owner created it, it is live, and it is a
Paperclip-managed local definition. Otherwise the reconnect is refused
in plain words and no token is written.
- UI: the AI account disconnect shows a toast, and connection removal
and the audit feed show the result in plain words, for example
"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." A failed delete says "Paperclip couldn't delete
its saved Google sign-in. Disconnect again to retry."
- Docs: `doc/connections/AI-CONNECTIONS.md` and the rollout plan.
- The first revision's direct Google call and its retry branch in the
Google revocation queue are removed. `google-pending-revocation.ts` is
unchanged from `master`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for
the changed shared export.

## Verification

- `npx vitest run src/__tests__/antigravity-disconnect-sign-in.test.ts`
(server, embedded Postgres, network calls fail the test): 17 cases.
Disconnect through the route deletes the sign-in, makes no network call,
logs the result with no token, and the owner can reconnect. Connection
removal deletes it, also when a second grant of the same connection
references it. It is kept when a grant on another live connection, a
binding on another target, a declaration on another target, or a routine
trigger uses it. A failed delete (forced by a database trigger) is
reported, keeps the reference, and the next disconnect deletes it, for
disconnect and removal, and also when the failure comes after the
sign-in was marked deleted. A reconnect during the delete, or during
connection removal, keeps its sign-in. A personal reconnect is refused
when the slot was created by someone else, deleted, or moved to another
provider, and no token is written. A hold-release failure during removal
leaves every grant active and the sign-in saved.
- Red/green: with `master`'s `grants.ts`, `removal.ts`,
`ai-connections.ts` and `routes/tool-access.ts`, the disconnect and
removal cases fail. Each guard was also removed on its own, and its case
failed: the saved-version check, the revoked-only final clear, the
half-deleted retry, the same-connection exclusion, and the definition
ownership check.
- `ui`: `npx vitest run
src/features/connections/googleAccessRemoval.test.ts` (13 pass, 5 new).
- Connection removal and managed Google tests pass:
`tool-connection-removal`, `tool-access-service`,
`google-managed-connection-removal`, `google-pending-revocation`,
`ai-connections`, and the browser-use, client-credentials, generic MCP,
Braintrust, 1Password and remote MCP connection suites.
- Server typecheck passes. UI `tsc` shows no errors in changed files.
`pnpm verify` selects about 1,900 test files for this change (removal is
widely imported), so required CI supplies that broad coverage.

## Risks

- The Google sign-in stays valid at Google after a disconnect. The UI
and activity log say so and link to the Google account page. This is
deliberate; see Alternatives considered.
- A reconnect still keeps older versions of a rotated shared secret, as
before this change.
- Company deletion does not change here.
- No schema change and no migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs, web reading of
Google's OAuth documentation).

## Checklist

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 08:52:03 -06:00
1 parent 917fe1ba29
commit 1bea1eeaed
21 files changed
+810 -117

No files matched your search

@@ -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<typeof import("../services/heartbeat/provider-limit-wait.js")>();
return {
...actual,
releaseProviderLimitWaits: async (...args: Parameters<typeof actual.releaseProviderLimitWaits>) => {
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<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | 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<typeof vault.remove>) => {
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);
});
});
@@ -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<unknown>, ...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);
+1 -1
View File
@@ -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);
});
+8 -2
View File
@@ -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("-", "_")}`,
@@ -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<typeof connectionGrants.$inferSelect, "id" | "kind" | "credentialSecretRefs">;
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<AiSignInRemoval | null>;
retainedGrantIds(): string[];
};
export function isAntigravitySubscriptionConnection(connection: Pick<Connection, "connectionPurpose" | "config">): 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<ReturnType<typeof secretService>, "remove">;
}) {
async function privateSlot(connection: Connection, grant: RemovedGrant, secretId: string): Promise<Target | null> {
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<boolean> {
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<CredentialResult> {
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<PreparedAiSignInRemoval | null> {
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 };
}
@@ -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<Set<string>> {
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;
}
@@ -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<string>() }));
import { createManagedGoogleAccessRemoval, summarizeManagedGoogleAccess } from "./google-access-removal.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
@@ -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<Set<string>> {
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<string>();
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(
@@ -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 } : {}) };
}
};
}
@@ -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 } : {}),
},
};
}