Files
PaperClipAI/server/src/__tests__/google-managed-connection-removal.test.ts
T
DottaandClaude Opus 5.5 23ce68a8dc feat(connections): end Google access when a Paperclip-managed Google connection is removed (#22065)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connectors let agents use Google Workspace through a Google sign-in
that Paperclip Cloud manages for the user
> - When a user removes a Paperclip-managed Google connection, Paperclip
deletes the tokens locally, but the grant stays live at Google
> - Google's OAuth review expects that a disconnect ends the app's
access, and users expect it too
> - Google's revoke ends the user's whole grant to the shared client, so
only the Paperclip Cloud broker can decide when it is safe to revoke
> - This pull request asks the broker to revoke each removed grant,
keeps local removal unconditional, and tells the user the outcome in
plain language
> - The benefit is that removal ends Google access when no other
Paperclip connection needs it, and the user knows what to do when it did
not

## Linked Issues or Issue Description

**Subsystem affected**
Connectors: Paperclip-managed Google Workspace and the legacy
per-service Google connections (server removal, shared contracts,
connection UI).

**Problem or motivation**
Removing a Paperclip-managed Google connection or grant was local only.
The refresh token was deleted in Paperclip, but Google still listed
Paperclip as having access to the account. The docs said so ("Removal is
local for managed grants").

**Proposed solution**
On removal, send each removed grant's refresh token to the broker's
signed `POST /v1/connector/revoke`. The broker revokes at Google only
when no other live binding could share the grant. Paperclip records the
broker's outcome code and shows one of three plain messages. Local
removal never waits on, or fails because of, that call.

**Alternatives considered**
Call Google's revoke endpoint from the app. This ends the user's whole
grant to the shared client and can break their other Google connections,
so the broker owns the decision.

**Additional context**
Older brokers answer 409 `REVOCATION_NOT_AVAILABLE`. The app treats
that, a timeout, and a network error as "could not end access at Google"
and still removes the connection.

## What Changed

- `paperclip-cloud-connector.ts`: `revoke()` takes an optional
`timeoutMs`, returns the broker's `outcome` from an allowlist, and keeps
`REVOCATION_NOT_AVAILABLE` as an allowed rejection reason.
- New `tool-access/connections/google-access-removal.ts`. For a managed
Google connection, `prepare()` reads each removed grant's refresh token
and returns a `send()` step. `send()` calls the broker for each distinct
token, one after another, under one 5-second deadline. Every result and
every error (including a Paperclip Cloud client that cannot be created)
becomes an outcome code. It never rejects and never logs a token. An
unexpected error is logged with the error name only and reported as
`unexpected_error`.
- Order for removing a whole connection: read the tokens, run the whole
local teardown (grants, installs, app profile, gateway tokens, runtime
slots, catalog, OAuth state, archive the connection), call the broker,
delete the sent refresh-token secrets whatever the outcome, then delete
the remaining secrets. A failure anywhere in the teardown makes no
broker call. Order for removing one grant: read the token, commit the
revocation, call the broker, delete the grant's refresh-token secret.
`send()` owns the call and the deletion through an injected
secret-removal function.
- Owed revocations: a revoked managed Google grant whose refresh-token
secret still exists (and that nothing live uses) is sent by every later
removal, then the secret is deleted. This covers a process stop after
the teardown and before the call, with no new column. Once the secret is
deleted, nothing is sent again.
- Shared tokens: the shared (organization) sign-in writes the same
secret refs to the organization grant and the connection. So revoking an
organization grant alone neither calls the broker nor deletes the
secret, because the connection still uses that token; removing the
connection does both. The same rule applies to any refresh token still
used by another live grant or connection.
- Audit history: once the broker call settles, a
`connection.google_access_removal` audit event records `reasonCode` =
result and `providerAccess` (plus `grantId` for a single grant). If that
write fails, the removal still succeeds and the failure is logged.
- Revoke signs with the subject that consented to the grant
(`providerTenant.externalId`, saved by the managed callback from the
claim). Grants saved without it fall back to the refresh rule. Refresh
is unchanged; see Risks.
- `removal.ts` and `grants.ts`: `providerAccess: { provider, result,
outcomes }` goes to the responses and to the `tool_connection.archived`
and `tool_connection.grant_revoked` activity entries. The tool access
audit field `providerRevocation` keeps its Vercel meaning only.
- `packages/shared`: `ManagedGoogleAccessRemoval`,
`ManagedGoogleRevocationOutcome`, `ConnectionGrantRevocationResult`.
- UI: one helper, `connectionRemovalToast`, builds the removal toast
(base sentence plus the Google notice, tone and action) for Connectors,
Connections and the app page. No codes are shown.
- API: `docs/api/tool-connections.md` documents both DELETE responses
and `providerAccess`. The OpenAPI registration describes the optional
field and its four results.
- Docs: `GOOGLE-WORKSPACE.md` (order, owed revocations, decision table),
`GMAIL.md`, the Google connector memory note, and the help page on
deleting connection data.

Decision table, judged over the distinct tokens sent in this removal:

| Outcomes | `result` | User message |
| --- | --- | --- |
| Every token `revoked` | `ended` | "Paperclip's access to this Google
account was also ended at Google." |
| Any failure-type code: `provider_revocation_failed`,
`binding_not_known` (the broker had no record, so Google was not
called), `provider_revocation_disabled`, `revocation_in_progress`,
`revocation_not_available`, `broker_unavailable`, `broker_error`,
`credential_unavailable`, `unexpected_error` | `not_ended` | "Paperclip
removed the connection but couldn't end its access at Google. You can
remove Paperclip from your Google account's third-party connections." +
"Open Google account connections" |
| Only `other_connections_remain` | `other_connections_remain` | "Other
Paperclip connections still use this Google account, so Google keeps
Paperclip's access until you remove those too." |
| At least one `revoked`, the rest `other_connections_remain` |
`ended_unconfirmed` | "Paperclip's access was ended at Google. If more
than one Google account was connected here, check your Google account's
third-party connections to be sure." + "Open Google account connections"
|

Grants record no Google account identity: the managed callback saves
`externalId` (the Paperclip subject), `name` (the provider name), and
OAuth timing and scopes, and none of the 14 scopes returns an account
identifier. So the last row is always `ended_unconfirmed`. This includes
two tokens of one user and several agent grants on one Google account.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/google-managed-connection-removal.test.ts
src/services/tool-access
src/services/paperclip-cloud-connector-revoke.test.ts
src/services/paperclip-cloud-connector.test.ts
src/__tests__/tool-connection-removal.test.ts
src/__tests__/tool-access-service.test.ts
src/__tests__/openapi-routes.test.ts` (714 passed)
- `pnpm --filter @paperclipai/ui exec vitest run
src/features/connections/googleAccessRemoval.test.ts src/pages/apps`
(passed)
- Server test typecheck (`node server/scripts/typecheck-layers.mjs`)
passes.
- Red then green: the server tests failed on `master` sources (21), then
each review round's new tests failed on the previous head and pass now.
They cover: the order on both paths, local failure before the grant
commit making no call and the retry sending, cleanup failure after the
call making no second call, a process stop between commit and call being
sent on retry with the secret deleted after, a Paperclip Cloud client
that cannot be created, the consenting subject for an organization
grant, sequential sends under one deadline, each row of the decision
table (per-agent and same-user cases give `ended_unconfirmed`, a mixed
failure gives `not_ended`), the unexpected-error log without a token, no
token in any log call, the delete-stored-data option, and a toast test
per surface.
- Added time, measured locally with a stubbed broker that answers at
once: median 22.1 ms against 20.3 ms without the broker step (12 runs
each), about 2 ms. With a real broker, one round trip per removed token,
capped at 5 seconds in total.
- `pnpm verify` exits 2 (a global CI input changed), so required CI
supplies the broad coverage.
- Not verified against a live broker or a real Google account.

## Risks

- A removal of a managed Google connection or grant can take up to 5
seconds longer when the broker is slow.
- Refresh subject is not changed in this PR. In the broker
(`recordProviderGrant`), a ledger row's subject is fixed when the row is
first written, and a refresh under another subject leaves that row
untouched. So moving refresh to a new subject could stop updating the
row's last-seen time. After 200 days the row would then count as not
live, and a later removal elsewhere could revoke at Google while this
connection still works. That risk cannot be ruled out from code for rows
written before this release, so both refresh paths keep their old rules.
The two refresh paths already use different subject orders today: the
gateway prefers `connectorSubjectAgentId` and then
`connectorSubjectUserId`, while background refresh prefers the grant's
own subject. That is pre-existing, and this PR leaves it unchanged.
Revoke uses the consenting subject, which matches the claim-time ledger
row. When the row was first written by a refresh under a different
subject, the broker answers `binding_not_known` and the user gets the
warning.
- Repeated removals can send an already-removed token again; the broker
returns its recorded outcome and changes nothing at Google.
- Against an older broker, users see the "could not end access at
Google" message, which is accurate.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## Checklist

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:52:20 -06:00

683 lines
37 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
authUsers,
companies,
companyMemberships,
companySecretBindings,
companySecrets,
companySecretVersions,
connectionGrants,
connectionTokenIssuances,
createDb,
secretAccessEvents,
toolAccessAuditEvents,
toolApplications,
toolCatalogEntries,
toolConnectionContentDeletions,
toolConnectionInstalls,
toolConnections,
toolOauthStates,
toolProfileBindings,
toolProfileEntries,
toolProfiles,
userSecretDeclarations,
userSecretDefinitions,
} from "@paperclipai/db";
import { and, eq, isNull, ne } from "drizzle-orm";
import { GOOGLE_WORKSPACE_CONNECTOR_PROFILES } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { toolAccessService } from "../services/tool-access.js";
import { toolAccessRoutes } from "../routes/tool-access.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { errorHandler } from "../middleware/index.js";
import { logger } from "../middleware/logger.js";
import { PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const REFRESH_TOKEN = "gmail-refresh-token-do-not-log";
function fakeConnector(companyId: string, userId: string) {
const credentials = {
v: 1 as const,
accessToken: "gmail-access-token",
refreshToken: REFRESH_TOKEN,
tokenType: "Bearer",
accessTokenExpiresAt: new Date(Date.now() + 3_600_000).toISOString(),
refreshTokenExpiresAt: null,
scopes: [...GOOGLE_WORKSPACE_CONNECTOR_PROFILES["gmail.draft"].scopes],
subject: userId,
companyId,
instanceId: "test-instance",
environment: "development" as const,
provider: "google" as const,
profile: "gmail.draft" as const,
};
return {
getCapabilities: vi.fn(async () => ["gmail.draft" as const]),
startAuthorization: vi.fn(async ({ returnState }: { returnState: string }) => ({
authorizationUrl: `https://accounts.google.com/o/oauth2/v2/auth?state=${encodeURIComponent(returnState)}`,
expiresAt: new Date(Date.now() + 600_000).toISOString(),
})),
claim: vi.fn(async ({ subject }: { subject: string }) => subject === userId
? credentials
: { ...credentials, subject, refreshToken: `${subject}-refresh-do-not-log`, accessToken: `${subject}-access` }),
refresh: vi.fn(async () => credentials),
revoke: vi.fn(async (_values: { subject: string; token: string }): Promise<{ outcome?: string }> => ({ outcome: "revoked" })),
};
}
function toolsListFetch() {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
const body = JSON.parse(String(init?.body));
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
return Response.json({ jsonrpc: "2.0", id: body.id,
result: body.method === "initialize" ? { protocolVersion: "2025-06-18" } : { tools: [] } });
});
}
describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-google-removal-");
db = createDb(tempDb.connectionString, { maxConnections: 4 });
await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: true });
}, 20_000);
afterEach(async () => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
await db.delete(toolConnectionContentDeletions);
await db.delete(toolOauthStates);
await db.delete(connectionTokenIssuances);
await db.delete(connectionGrants);
await db.delete(secretAccessEvents);
await db.delete(companySecretBindings);
await db.delete(userSecretDeclarations);
await db.delete(companySecretVersions);
await db.delete(companySecrets);
await db.delete(userSecretDefinitions);
await db.delete(activityLog);
await db.delete(toolAccessAuditEvents);
await db.delete(toolConnectionInstalls);
await db.delete(toolProfileBindings);
await db.delete(toolProfileEntries);
await db.delete(toolProfiles);
await db.delete(toolCatalogEntries);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
async function connectManagedGmail(grantKind: "user" | "organization" = "user") {
const [company] = await db.insert(companies).values({
name: `Google removal ${randomUUID()}`,
issuePrefix: `GR${randomUUID().slice(0, 6).toUpperCase()}`,
}).returning();
const userId = `google-removal-${randomUUID()}`;
await db.insert(companyMemberships).values({
companyId: company!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner",
});
const connector = fakeConnector(company!.id, userId);
const cloudConnector = connector as unknown as PaperclipCloudConnector;
const service = toolAccessService(db, {
paperclipCloudConnector: cloudConnector,
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
remoteHttpRequest: async (url, init) => fetch(url, init),
});
const actor = { actorType: "user" as const, actorId: userId };
toolsListFetch();
const connected = await service.connectGalleryApp(company!.id, {
galleryKey: "gmail", connectionMethodKey: "paperclip-draft", grantKind, name: "Gmail",
}, actor);
const started = await service.startOAuth(company!.id, connected.connectionId, {
redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor,
});
await service.completePaperclipCloudConnectorCallback({
state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "removal-claim", actor,
});
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "board", userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null,
isInstanceAdmin: false, source: "session", companyIds: [company!.id],
memberships: [{ companyId: company!.id, membershipRole: "owner", status: "active" }],
};
next();
});
app.use("/api", toolAccessRoutes(db, {
paperclipCloudConnector: cloudConnector,
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
remoteHttpRequest: async (url, init) => fetch(url, init),
}));
app.use(errorHandler);
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId));
return { company: company!, userId, connector, app, service, connectionId: connected.connectionId, grant: grant! };
}
async function googleAudit(connectionId: string) {
const rows = await db.select().from(toolAccessAuditEvents).where(and(
eq(toolAccessAuditEvents.connectionId, connectionId), eq(toolAccessAuditEvents.action, "connection.google_access_removal")));
return rows.map((row) => ({ reasonCode: row.reasonCode, providerAccess: (row.details as Record<string, unknown>).providerAccess }));
}
async function liveSecretCount(companyId: string) {
return (await db.select({ id: companySecrets.id }).from(companySecrets)
.where(and(eq(companySecrets.companyId, companyId), isNull(companySecrets.deletedAt)))).length;
}
it.each([
["revoked", "ended"],
["other_connections_remain", "other_connections_remain"],
["provider_revocation_failed", "not_ended"],
["binding_not_known", "not_ended"],
["provider_revocation_disabled", "not_ended"],
["revocation_in_progress", "not_ended"],
] as const)("asks Cloud to end Google access and reports %s as %s", async (outcome, result) => {
const fixture = await connectManagedGmail();
fixture.connector.revoke.mockResolvedValue({ outcome });
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(fixture.connector.revoke).toHaveBeenCalledWith({
subject: fixture.userId, companyId: fixture.company.id, profile: "gmail.draft", token: REFRESH_TOKEN, timeoutMs: expect.any(Number),
});
const [{ timeoutMs }] = fixture.connector.revoke.mock.calls[0] as unknown as [{ timeoutMs: number }];
expect(timeoutMs).toBeGreaterThan(4_000);
expect(timeoutMs).toBeLessThanOrEqual(5_000);
expect(response.body.removal.providerAccess).toEqual({ provider: "google", result, outcomes: [outcome] });
const [entry] = await db.select().from(activityLog).where(and(
eq(activityLog.companyId, fixture.company.id), eq(activityLog.action, "tool_connection.archived")));
expect(entry!.details).toMatchObject({ providerAccess: { provider: "google", result, outcomes: [outcome] } });
expect(JSON.stringify(entry!.details)).not.toContain(REFRESH_TOKEN);
expect(await liveSecretCount(fixture.company.id)).toBe(0);
expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: result, providerAccess: { provider: "google", result, outcomes: [outcome] } }]);
});
it.each([
["revoked", "ended"],
["other_connections_remain", "other_connections_remain"],
["binding_not_known", "not_ended"],
] as const)("records %s for a single grant in the audit history and keeps the existing audit field", async (outcome, result) => {
const fixture = await connectManagedGmail();
fixture.connector.revoke.mockResolvedValue({ outcome });
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: result, providerAccess: { provider: "google", result, outcomes: [outcome] } }]);
const [revoked] = await db.select().from(toolAccessAuditEvents).where(and(
eq(toolAccessAuditEvents.connectionId, fixture.connectionId), eq(toolAccessAuditEvents.action, "connection_grant.revoked")));
expect(revoked!.details).toMatchObject({ providerRevocation: "not_applicable" });
expect(revoked!.details).not.toHaveProperty("providerAccess");
});
it("still removes the connection when the audit record of the Google result cannot be written", async () => {
const fixture = await connectManagedGmail();
const insert = db.insert.bind(db);
vi.spyOn(db, "insert").mockImplementation(((table: unknown) => {
if (table === toolAccessAuditEvents) throw new Error("audit unavailable");
return insert(table as never);
}) as never);
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] });
});
it.each([
["an older broker", new PaperclipCloudConnectorError("rejected", "REAUTHORIZATION_REQUIRED", 409, undefined, "REVOCATION_NOT_AVAILABLE"), "revocation_not_available"],
["a broker timeout", new PaperclipCloudConnectorError("Paperclip Cloud connector is unavailable", "CONNECTOR_UNAVAILABLE"), "broker_unavailable"],
["a network error", new TypeError("fetch failed"), "broker_error"],
] as const)("still removes the connection locally after %s", async (_label, error, outcome) => {
const fixture = await connectManagedGmail();
fixture.connector.revoke.mockRejectedValue(error);
const logged: unknown[] = [];
for (const level of ["trace", "debug", "info", "warn", "error", "fatal"] as const) {
vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => { logged.push(args); }) as never);
}
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(response.body.status).toBe("archived");
expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "not_ended", outcomes: [outcome] });
expect(await liveSecretCount(fixture.company.id)).toBe(0);
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId));
expect(connection!.credentialSecretRefs).toEqual([]);
expect(JSON.stringify(logged)).not.toContain(REFRESH_TOKEN);
});
it("ends access at Google only after every local access path is closed", async () => {
const fixture = await connectManagedGmail();
const seen: Array<{ connection?: string; grant?: string; installs: number; refreshStored: boolean }> = [];
const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
fixture.connector.revoke.mockImplementation(async () => {
const [row] = await db.select({ status: toolConnections.status, enabled: toolConnections.enabled }).from(toolConnections).where(eq(toolConnections.id, fixture.connectionId));
const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, fixture.connectionId));
const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt)));
seen.push({ connection: row?.enabled ? row.status : `${row?.status}:disabled`, grant: grantRow?.status, installs: installs.length, refreshStored: Boolean(refresh) });
return { outcome: "revoked" };
});
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(seen).toEqual([{ connection: "archived:disabled", grant: "revoked", installs: 0, refreshStored: true }]);
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
it("revokes a single grant at Google only after the grant is marked revoked", async () => {
const fixture = await connectManagedGmail();
const seen: Array<string | undefined> = [];
fixture.connector.revoke.mockImplementation(async () => {
const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
seen.push(grantRow?.status);
return { outcome: "revoked" };
});
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
expect(seen).toEqual(["revoked"]);
});
it("makes no broker call when the local grant revocation fails", async () => {
const fixture = await connectManagedGmail();
vi.spyOn(db, "transaction").mockRejectedValue(new Error("local removal failed"));
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(500);
expect(fixture.connector.revoke).not.toHaveBeenCalled();
});
it("makes no broker call when the teardown fails, keeps the token, and the retry sends it once", async () => {
const fixture = await connectManagedGmail();
const transaction = vi.spyOn(db, "transaction").mockRejectedValue(new Error("teardown failed"));
const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(failed.status).toBe(500);
expect(fixture.connector.revoke).not.toHaveBeenCalled();
expect(await liveSecretCount(fixture.company.id)).toBeGreaterThan(0);
transaction.mockRestore();
const retried = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(retried.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(retried.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] });
expect(await liveSecretCount(fixture.company.id)).toBe(0);
const again = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(again.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
});
it("sends a revocation still owed when the process stopped after the teardown and before the call", async () => {
const fixture = await connectManagedGmail();
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id));
await db.update(toolConnections).set({ status: "archived", enabled: false }).where(eq(toolConnections.id, fixture.connectionId));
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
it("sends a revocation still owed when the process stopped after the grants were revoked", async () => {
const fixture = await connectManagedGmail();
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id));
const seen: number[] = [];
fixture.connector.revoke.mockImplementation(async () => {
seen.push(await liveSecretCount(fixture.company.id));
return { outcome: "revoked" };
});
const logged: unknown[] = [];
for (const level of ["trace", "debug", "info", "warn", "error", "fatal"] as const) {
vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => { logged.push(args); }) as never);
}
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: REFRESH_TOKEN }));
expect(seen[0]).toBeGreaterThan(0);
expect(await liveSecretCount(fixture.company.id)).toBe(0);
expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] });
expect(await googleAudit(fixture.connectionId)).toEqual([{ reasonCode: "ended", providerAccess: { provider: "google", result: "ended", outcomes: ["revoked"] } }]);
expect(JSON.stringify(logged)).not.toContain(REFRESH_TOKEN);
});
it("makes no broker call when removal fails before the grants are revoked, and the retry sends them", async () => {
const fixture = await connectManagedGmail();
const update = db.update.bind(db);
let failedOnce = false;
vi.spyOn(db, "update").mockImplementation(((table: unknown) => {
if (table === connectionGrants && !failedOnce) {
failedOnce = true;
throw new Error("grant revocation failed");
}
return update(table as never);
}) as never);
const failed = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(failed.status).toBe(500);
expect(fixture.connector.revoke).not.toHaveBeenCalled();
const retried = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(retried.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: REFRESH_TOKEN }));
expect(retried.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] });
});
it.each(["connection", "grant"] as const)("still completes the local %s removal when the Paperclip Cloud client cannot be created", async (path) => {
const fixture = await connectManagedGmail();
vi.stubEnv("PAPERCLIP_ID_CONNECTOR_INSTANCE_ID", "legacy-instance");
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "board", userId: fixture.userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null,
isInstanceAdmin: false, source: "session", companyIds: [fixture.company.id],
memberships: [{ companyId: fixture.company.id, membershipRole: "owner", status: "active" }],
};
next();
});
app.use("/api", toolAccessRoutes(db, {
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
remoteHttpRequest: async (url, init) => fetch(url, init),
}));
app.use(errorHandler);
const response = await request(app).delete(path === "connection"
? `/api/tool-connections/${fixture.connectionId}`
: `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
const providerAccess = path === "connection" ? response.body.removal.providerAccess : response.body.providerAccess;
expect(providerAccess).toEqual({ provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] });
const [grantRow] = await db.select({ status: connectionGrants.status }).from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
expect(grantRow!.status).toBe("revoked");
});
it("revokes an organization grant under the user who consented after the connection-wide subject changed", async () => {
const fixture = await connectManagedGmail("organization");
expect(fixture.grant.kind).toBe("organization");
const otherUserId = `google-removal-other-${randomUUID()}`;
await db.insert(companyMemberships).values({
companyId: fixture.company.id, principalType: "user", principalId: otherUserId, status: "active", membershipRole: "owner",
});
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId));
const config = { ...row!.config, oauth: { ...(row!.config.oauth as Record<string, unknown>), connectorSubjectUserId: otherUserId } };
await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, fixture.connectionId));
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
const sent = fixture.connector.revoke.mock.calls.map(([values]) => [values.subject, values.token]);
expect(sent).toEqual([[fixture.userId, REFRESH_TOKEN]]);
});
it("keeps the delete-stored-data option working alongside the Google outcome", async () => {
const fixture = await connectManagedGmail();
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}?deleteStoredContent=true`);
expect(response.status).toBe(200);
expect(response.body.contentDeletion).toBeTruthy();
expect(response.body.removal.providerAccess).toEqual({ provider: "google", result: "ended", outcomes: ["revoked"] });
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
it("revokes only the removed grant at Google and records the outcome", async () => {
const fixture = await connectManagedGmail();
fixture.connector.revoke.mockResolvedValue({ outcome: "other_connections_remain" });
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
expect(response.body.status).toBe("revoked");
expect(response.body.providerAccess).toEqual({ provider: "google", result: "other_connections_remain", outcomes: ["other_connections_remain"] });
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ subject: fixture.userId, token: REFRESH_TOKEN }));
const [entry] = await db.select().from(activityLog).where(and(
eq(activityLog.companyId, fixture.company.id), eq(activityLog.action, "tool_connection.grant_revoked")));
expect(entry!.details).toMatchObject({ providerAccess: { outcomes: ["other_connections_remain"] } });
expect(await googleAudit(fixture.connectionId)).toEqual([
{ reasonCode: "other_connections_remain", providerAccess: { provider: "google", result: "other_connections_remain", outcomes: ["other_connections_remain"] } },
]);
const repeated = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(repeated.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
const removal = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(removal.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(removal.body.removal.providerAccess).toBeUndefined();
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
async function signInAgain(fixture: Awaited<ReturnType<typeof connectManagedGmail>>, refreshToken: string | null) {
const actor = { actorType: "user" as const, actorId: fixture.userId };
const started = await fixture.service.startOAuth(fixture.company.id, fixture.connectionId, {
redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor,
});
const claimed = await fixture.connector.claim({ subject: fixture.userId });
fixture.connector.claim.mockResolvedValueOnce({ ...claimed, refreshToken } as typeof claimed);
return () => fixture.service.completePaperclipCloudConnectorCallback({
state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: `again-${randomUUID()}`, actor,
});
}
it.each(["connection", "grant"] as const)("deletes the sent token at the secret provider on %s removal", async (path) => {
const fixture = await connectManagedGmail();
const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
const [refresh] = await db.select({ key: companySecrets.key, provider: companySecrets.provider }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId));
expect(refresh!.provider).toBe("local_encrypted");
const providerDelete = vi.spyOn(localEncryptedProvider, "deleteOrArchive");
const response = await request(fixture.app).delete(path === "connection"
? `/api/tool-connections/${fixture.connectionId}`
: `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
const deletedKeys = providerDelete.mock.calls.map(([input]) => (input as { context: { secretKey: string } }).context.secretKey);
expect(deletedKeys.filter((key) => key.startsWith(refresh!.key))).toHaveLength(1);
const [row] = await db.select({ id: companySecrets.id }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId));
expect(row).toBeUndefined();
if (path === "connection") expect(response.body.removal.secretsRevoked).toBe(2);
});
it.each(["connection", "grant"] as const)("completes a %s removal on a database pool of one connection", async (path) => {
const fixture = await connectManagedGmail();
const single = createDb(tempDb!.connectionString, { maxConnections: 1 });
try {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "board", userId: fixture.userId, sessionId: `session-${randomUUID()}`, userName: "Owner", userEmail: null,
isInstanceAdmin: false, source: "session", companyIds: [fixture.company.id],
memberships: [{ companyId: fixture.company.id, membershipRole: "owner", status: "active" }],
};
next();
});
app.use("/api", toolAccessRoutes(single, {
paperclipCloudConnector: fixture.connector as unknown as PaperclipCloudConnector,
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
remoteHttpRequest: async (url, init) => fetch(url, init),
}));
app.use(errorHandler);
const url = path === "connection"
? `/api/tool-connections/${fixture.connectionId}`
: `/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`;
const outcome = await Promise.race([
request(app).delete(url).then((response) => response.status),
new Promise((resolve) => setTimeout(() => resolve("timed out"), 15_000)),
]);
expect(outcome).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt)));
expect(refresh).toBeUndefined();
} finally {
await single.$client.end({ timeout: 1 });
}
}, 30_000);
it("keeps the new token when the user signs in again while Paperclip Cloud answers a grant removal", async () => {
const fixture = await connectManagedGmail();
let finishSignIn: (() => Promise<unknown>) | null = null;
fixture.connector.revoke.mockImplementation(async () => {
await finishSignIn!();
return { outcome: "revoked" };
});
finishSignIn = await signInAgain(fixture, "fresh-refresh-token-do-not-log");
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
expect(grantRow!.status).toBe("active");
fixture.connector.refresh.mockClear();
await fixture.service.refreshOAuthGrantCredentials({
companyId: fixture.company.id, connectionId: fixture.connectionId, grantId: fixture.grant.id, forceRefresh: true,
actor: { actorType: "user", actorId: fixture.userId },
});
expect(fixture.connector.refresh).toHaveBeenCalledWith(expect.objectContaining({ refreshToken: "fresh-refresh-token-do-not-log" }));
});
async function liveRefsToMissingSecrets(companyId: string) {
const live = new Set((await db.select({ id: companySecrets.id }).from(companySecrets)
.where(and(eq(companySecrets.companyId, companyId), isNull(companySecrets.deletedAt)))).map((row) => row.id));
const grants = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), ne(connectionGrants.status, "revoked")));
const connections = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), ne(toolConnections.status, "archived")));
return [
...grants.flatMap((grant) => grant.credentialSecretRefs),
...connections.flatMap((connection) => [...connection.credentialSecretRefs, ...connection.credentialRefs]),
].filter((ref) => !live.has(ref.secretId));
}
it("refuses a managed Google sign-in that returns no refresh token and leaves the grant unchanged", async () => {
const fixture = await connectManagedGmail();
await expect((await signInAgain(fixture, null))()).rejects.toMatchObject({ details: { code: "oauth_refresh_missing" } });
const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
expect(grantRow!.status).toBe("active");
expect(grantRow!.credentialSecretRefs).toEqual(fixture.grant.credentialSecretRefs);
expect(await liveRefsToMissingSecrets(fixture.company.id)).toEqual([]);
});
it("still deletes the old refresh token when a sign-in without one is refused while Paperclip Cloud answers a grant removal", async () => {
const fixture = await connectManagedGmail();
const oldRefreshId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
const finishSignIn = await signInAgain(fixture, null);
let signIn: unknown = null;
fixture.connector.revoke.mockImplementation(async () => {
signIn = await finishSignIn().then(() => "completed", (error: { details?: { code?: string } }) => error.details?.code);
return { outcome: "revoked" };
});
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
expect(signIn).toBe("oauth_refresh_missing");
const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
expect(grantRow!.status).toBe("revoked");
const [oldRefresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(eq(companySecrets.id, oldRefreshId));
expect(oldRefresh).toBeUndefined();
expect(await liveRefsToMissingSecrets(fixture.company.id)).toEqual([]);
});
it("refuses a sign-in for a connection that was removed while Paperclip Cloud answered", async () => {
const fixture = await connectManagedGmail();
const finishSignIn = await signInAgain(fixture, "late-refresh-token-do-not-log");
let lateSignIn: unknown = null;
fixture.connector.revoke.mockImplementation(async () => {
lateSignIn = await finishSignIn().then(() => "completed", () => "refused");
return { outcome: "revoked" };
});
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(lateSignIn).toBe("refused");
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
it("sends the new token of a grant that was signed in again after an owed revocation", async () => {
const fixture = await connectManagedGmail();
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, fixture.grant.id));
await (await signInAgain(fixture, "renewed-refresh-token-do-not-log"))();
const [grantRow] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, fixture.grant.id));
expect(grantRow!.status).toBe("active");
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(response.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(fixture.connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ token: "renewed-refresh-token-do-not-log" }));
});
it("keeps the refresh token when its version changes while Paperclip Cloud answers", async () => {
const fixture = await connectManagedGmail();
const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
fixture.connector.revoke.mockImplementation(async () => {
const [row] = await db.select({ latestVersion: companySecrets.latestVersion }).from(companySecrets).where(eq(companySecrets.id, refreshSecretId));
await db.update(companySecrets).set({ latestVersion: row!.latestVersion + 1 }).where(eq(companySecrets.id, refreshSecretId));
return { outcome: "revoked" };
});
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt)));
expect(refresh).toBeTruthy();
});
it("neither ends access at Google nor deletes the token when revoking an organization grant the connection still uses", async () => {
const fixture = await connectManagedGmail("organization");
const refreshSecretId = fixture.grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.refresh_token")!.secretId;
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, fixture.connectionId));
const shared = [...row!.credentialSecretRefs, ...row!.credentialRefs].some((ref) => ref.secretId === refreshSecretId);
expect(shared).toBe(true);
const response = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}/grants/${fixture.grant.id}`);
expect(response.status).toBe(200);
expect(response.body.providerAccess).toBeUndefined();
expect(fixture.connector.revoke).not.toHaveBeenCalled();
const [refresh] = await db.select({ id: companySecrets.id }).from(companySecrets).where(and(eq(companySecrets.id, refreshSecretId), isNull(companySecrets.deletedAt)));
expect(refresh).toBeTruthy();
const removal = await request(fixture.app).delete(`/api/tool-connections/${fixture.connectionId}`);
expect(removal.status).toBe(200);
expect(fixture.connector.revoke).toHaveBeenCalledTimes(1);
expect(await liveSecretCount(fixture.company.id)).toBe(0);
});
});