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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-17 15:52:20 -06:00
1 parent 24728076d6
commit 23ce68a8dc
35 files changed
+1831 -75

No files matched your search

@@ -0,0 +1,682 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
authUsers,
companies,
companyMemberships,
companySecretBindings,
companySecrets,
companySecretVersions,
connectionGrants,
connectionTokenIssuances,
createDb,
secretAccessEvents,
toolAccessAuditEvents,
toolApplications,
toolCatalogEntries,
toolConnectionContentDeletions,
toolConnectionInstalls,
toolConnections,
toolOauthStates,
toolProfileBindings,
toolProfileEntries,
toolProfiles,
userSecretDeclarations,
userSecretDefinitions,
} from "@paperclipai/db";
import { and, eq, isNull, ne } from "drizzle-orm";
import { GOOGLE_WORKSPACE_CONNECTOR_PROFILES } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { toolAccessService } from "../services/tool-access.js";
import { toolAccessRoutes } from "../routes/tool-access.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { errorHandler } from "../middleware/index.js";
import { logger } from "../middleware/logger.js";
import { PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const REFRESH_TOKEN = "gmail-refresh-token-do-not-log";
function fakeConnector(companyId: string, userId: string) {
const credentials = {
v: 1 as const,
accessToken: "gmail-access-token",
refreshToken: REFRESH_TOKEN,
tokenType: "Bearer",
accessTokenExpiresAt: new Date(Date.now() + 3_600_000).toISOString(),
refreshTokenExpiresAt: null,
scopes: [...GOOGLE_WORKSPACE_CONNECTOR_PROFILES["gmail.draft"].scopes],
subject: userId,
companyId,
instanceId: "test-instance",
environment: "development" as const,
provider: "google" as const,
profile: "gmail.draft" as const,
};
return {
getCapabilities: vi.fn(async () => ["gmail.draft" as const]),
startAuthorization: vi.fn(async ({ returnState }: { returnState: string }) => ({
authorizationUrl: `https://accounts.google.com/o/oauth2/v2/auth?state=${encodeURIComponent(returnState)}`,
expiresAt: new Date(Date.now() + 600_000).toISOString(),
})),
claim: vi.fn(async ({ subject }: { subject: string }) => subject === userId
? credentials
: { ...credentials, subject, refreshToken: `${subject}-refresh-do-not-log`, accessToken: `${subject}-access` }),
refresh: vi.fn(async () => credentials),
revoke: vi.fn(async (_values: { subject: string; token: string }): Promise<{ outcome?: string }> => ({ outcome: "revoked" })),
};
}
function toolsListFetch() {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
const body = JSON.parse(String(init?.body));
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
return Response.json({ jsonrpc: "2.0", id: body.id,
result: body.method === "initialize" ? { protocolVersion: "2025-06-18" } : { tools: [] } });
});
}
describeEmbeddedPostgres("removing a Paperclip-managed Google connection", () => {
let db!: ReturnType<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);
});
});
@@ -194,7 +194,7 @@ function fakeGoogleWorkspaceConnector(
})),
claim: vi.fn(async () => credentials),
refresh: vi.fn(async () => credentials),
revoke: vi.fn(async () => undefined),
revoke: vi.fn(async () => ({})),
} satisfies Partial<PaperclipCloudConnector> as unknown as PaperclipCloudConnector;
}
@@ -233,7 +233,7 @@ function fakeGitHubConnector(
})),
claim: vi.fn(async () => credentials),
refresh: vi.fn(async () => credentials),
revoke: vi.fn(async () => undefined),
revoke: vi.fn(async () => ({})),
setWebhookBinding: vi.fn(async () => undefined),
leaseEvents: vi.fn(async () => null),
acknowledgeEvents: vi.fn(async () => 0),
@@ -8264,7 +8264,10 @@ describeEmbeddedPostgres("tool access service", () => {
await expect(
service.revokeConnectionGrant(connected.connectionId, grant!.id, actor),
).resolves.toMatchObject({ status: "revoked" });
expect(connector.revoke).not.toHaveBeenCalled();
expect(connector.revoke).toHaveBeenCalledTimes(1);
expect(connector.revoke).toHaveBeenCalledWith(expect.objectContaining({
subject: userId, profile: "gmail.draft", token: "gmail-refresh-token",
}));
} finally {
if (deadline) clearTimeout(deadline);
await callbackDb.$client.end({ timeout: 0 }).catch(() => undefined);
@@ -14399,7 +14402,7 @@ describeEmbeddedPostgres("tool access service", () => {
expiresAt: new Date(Date.now() + 600_000).toISOString(),
})),
claim: vi.fn(async () => credentials), refresh: vi.fn(async () => credentials),
revoke: vi.fn(async () => undefined),
revoke: vi.fn(async () => ({})),
} satisfies Partial<PaperclipCloudConnector> as unknown as PaperclipCloudConnector;
const service = createTestToolAccessService(db, { paperclipCloudConnector: connector });
const custom = await service.connectGalleryApp(company.id, {
+20
View File
@@ -12482,6 +12482,12 @@ registerCurrentRoute({
summary: "Revoke a personal tool connection grant delegation",
});
const managedGoogleAccessRemovalSchema = z.object({
provider: z.literal("google"),
result: z.enum(["ended", "ended_unconfirmed", "other_connections_remain", "not_ended"]),
outcomes: z.array(z.string()).describe("One diagnostic code per refresh token sent to Paperclip Cloud, in order."),
}).describe("Present only for a Google connection managed by Paperclip Cloud. A failure to end access at Google does not undo the local removal.");
registerCurrentRoute({
"x-paperclip-transport": "rest",
"x-paperclip-connection-management": "connections:configure",
@@ -12489,6 +12495,13 @@ registerCurrentRoute({
path: "/api/tool-connections/{connectionId}/grants/{grantId}",
tags: ["tool-access"],
summary: "Revoke a tool connection grant",
description: "Revokes the grant locally, then, for a Google connection managed by Paperclip Cloud, asks Paperclip Cloud to end the grant's access at Google and reports the result in providerAccess.",
responses: {
200: r.ok(z.object({ providerAccess: managedGoogleAccessRemovalSchema.optional() }).passthrough()),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registerCurrentRoute({
@@ -12574,7 +12587,14 @@ registerCurrentRoute({
path: "/api/tool-connections/{connectionId}",
tags: ["tool-access"],
summary: "Archive a tool connection",
description: "Removes the connection and its credentials. For a Google connection managed by Paperclip Cloud, removal.providerAccess reports whether access was ended at Google.",
query: z.object({ deleteStoredContent: z.enum(["true", "false"]).optional() }),
responses: {
200: r.ok(z.object({ removal: z.object({ providerAccess: managedGoogleAccessRemovalSchema.optional() }).passthrough() }).passthrough()),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registerCurrentRoute({
+1 -1
View File
@@ -2008,7 +2008,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
action: "tool_connection.grant_revoked",
entityType: "connection_grant",
entityId: grant.id,
details: { connectionId: connection.id, kind: grant.kind },
details: { connectionId: connection.id, kind: grant.kind, ...(grant.providerAccess ? { providerAccess: grant.providerAccess } : {}) },
});
res.json(grant);
});
@@ -68,6 +68,7 @@ export function developmentSlackManager(
async revoke(values) {
try { await api("auth.revoke", {}, values.token); }
catch { throw providerFailure("slack_manager_reauthorize"); }
return {};
},
};
}
@@ -0,0 +1,80 @@
import { createHash, generateKeyPairSync, type KeyObject } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import { createPaperclipCloudConnector, type PaperclipCloudConnectorConfig } from "./paperclip-cloud-connector.js";
const companyId = "company_test";
const subject = "user_test";
function rawPrivateKey(key: KeyObject): string {
const jwk = key.export({ format: "jwk" }) as { d?: string };
if (!jwk.d) throw new Error("missing private key bytes");
return jwk.d;
}
function config() {
return {
config: {
baseUrl: "https://my.example.test",
instanceId: "inst_test",
environment: "staging",
signPrivateKey: rawPrivateKey(generateKeyPairSync("ed25519").privateKey),
sealPrivateKey: rawPrivateKey(generateKeyPairSync("x25519").privateKey),
} satisfies PaperclipCloudConnectorConfig,
};
}
describe("Paperclip Cloud Google grant revocation", () => {
function decodeClaims(request: string) {
return JSON.parse(Buffer.from(request.split(".")[1]!, "base64url").toString("utf8"));
}
it("signs the Google profile, sends the refresh token only in the body, and returns the broker outcome", async () => {
const bodies: Array<{ request: string; token: string }> = [];
const request = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
bodies.push(JSON.parse(String(init?.body)));
return Response.json({ localBindingRemoved: true, revokedAtProvider: false, outcome: "other_connections_remain" });
});
const connector = createPaperclipCloudConnector({ config: config().config, request: request as typeof fetch });
await expect(connector.revoke({ subject, companyId, profile: "workspace.all", token: "refresh-secret" }))
.resolves.toEqual({ outcome: "other_connections_remain" });
expect(String(request.mock.calls[0]![0])).toBe("https://my.example.test/v1/connector/revoke");
const claims = decodeClaims(bodies[0]!.request);
expect(claims).toMatchObject({ op: "revoke", sub: subject, cid: companyId, prv: "google", prf: "workspace.all" });
expect(claims.sh).toBe(createHash("sha256").update("refresh-secret").digest("base64url"));
expect(bodies[0]!.token).toBe("refresh-secret");
expect(bodies[0]!.request).not.toContain("refresh-secret");
});
it.each(["revoked", "provider_revocation_failed", "binding_not_known", "provider_revocation_disabled", "revocation_in_progress"])(
"accepts the %s outcome",
async (outcome) => {
const connector = createPaperclipCloudConnector({ config: config().config,
request: vi.fn(async () => Response.json({ outcome })) as typeof fetch });
await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" })).resolves.toEqual({ outcome });
},
);
it("drops an unknown outcome", async () => {
const connector = createPaperclipCloudConnector({ config: config().config,
request: vi.fn(async () => Response.json({ outcome: "DO_NOT_REPORT" })) as typeof fetch });
await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" })).resolves.toEqual({});
});
it("reports an older broker's 409 as revocation not available", async () => {
const connector = createPaperclipCloudConnector({ config: config().config,
request: vi.fn(async () => Response.json({ error: "REVOCATION_NOT_AVAILABLE" }, { status: 409 })) as typeof fetch });
await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t" }))
.rejects.toMatchObject({ status: 409, brokerReason: "REVOCATION_NOT_AVAILABLE" });
});
it("aborts the broker call at the requested timeout", async () => {
const request = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(new Error("aborted")));
}));
const connector = createPaperclipCloudConnector({ config: config().config, request: request as unknown as typeof fetch });
const started = Date.now();
await expect(connector.revoke({ subject, companyId, profile: "gmail.read", token: "t", timeoutMs: 50 }))
.rejects.toMatchObject({ code: "CONNECTOR_UNAVAILABLE" });
expect(Date.now() - started).toBeLessThan(2_000);
});
});
@@ -160,7 +160,7 @@ const BROKER_REJECTION_REASONS = new Set([
"REQUEST_EXPIRED", "REQUEST_REPLAYED", "SIGNATURE_REJECTED",
"AUDIENCE_MISMATCH", "OPERATION_MISMATCH", "PAYLOAD_MISMATCH",
"MALFORMED_REQUEST", "UNSUPPORTED_ALGORITHM", "RATE_LIMITED",
"PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED",
"PROVIDER_OPERATION_FAILED", "PROVIDER_REAUTHORIZATION_REQUIRED", "REVOCATION_NOT_AVAILABLE",
"SLACK_ENROLLMENT_GENERATION_CHANGED", "SLACK_ENROLLMENT_IDENTITY_CHANGED",
"SLACK_ENROLLMENT_CHANGED", "SLACK_ENROLLMENT_UNSETTLED", "SLACK_ENROLLMENT_DISABLED",
"SLACK_COMPANY_MISMATCH", "SLACK_EVENTS_UNAVAILABLE",
@@ -169,6 +169,12 @@ const BROKER_REJECTION_REASONS = new Set([
]);
const UNKNOWN_BROKER_REASON = "UNKNOWN_BROKER_ERROR";
export const PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES = [
"revoked", "other_connections_remain", "provider_revocation_failed",
"binding_not_known", "provider_revocation_disabled", "revocation_in_progress",
] as const;
export type PaperclipCloudGrantRevocationOutcome = typeof PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES[number];
async function readBrokerRejectionReason(response: Response): Promise<string> {
if (response.bodyUsed || response.body?.locked) return UNKNOWN_BROKER_REASON;
const reader = response.body?.getReader();
@@ -301,6 +307,7 @@ export function createPaperclipCloudConnector(input: {
operation: PaperclipCloudConnectorOperation,
claims: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; scopes?: string[]; returnUri?: string; returnState?: string; claimId?: string; redemptionId?: string; eventWakeVersion?: 0 | 1 },
secret?: { field: "refreshToken" | "token" | "binding" | "acknowledgement" | "enrollment" | "operation"; value: string },
timeoutMs = 15_000,
): Promise<ConnectorResponse> {
const endpoint = new URL(ENDPOINTS[operation], `${config.baseUrl}/`).toString();
const issuedAt = Math.floor(now() / 1000);
@@ -344,7 +351,7 @@ export function createPaperclipCloudConnector(input: {
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: encodedBody,
signal: AbortSignal.timeout(15_000),
signal: AbortSignal.timeout(timeoutMs),
});
} catch {
throw new PaperclipCloudConnectorError("Paperclip Cloud connector is unavailable", "CONNECTOR_UNAVAILABLE");
@@ -588,8 +595,13 @@ export function createPaperclipCloudConnector(input: {
profile,
);
},
async revoke(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; token: string }) {
await call("revoke", { ...values, profile: values.profile ?? "gmail.draft" }, { field: "token", value: values.token });
async revoke(values: { subject: string; companyId: string; profile?: PaperclipCloudConnectorProfileId; token: string; timeoutMs?: number }): Promise<{ outcome?: PaperclipCloudGrantRevocationOutcome }> {
const { timeoutMs, ...claims } = values;
const response = await call("revoke", { ...claims, profile: claims.profile ?? "gmail.draft" }, { field: "token", value: claims.token }, timeoutMs);
const outcome = (response as ConnectorResponse & { outcome?: unknown }).outcome;
return typeof outcome === "string" && (PAPERCLIP_CLOUD_GRANT_REVOCATION_OUTCOMES as readonly string[]).includes(outcome)
? { outcome: outcome as PaperclipCloudGrantRevocationOutcome }
: {};
},
async setWebhookBinding(values: {
subject: string;
+23 -3
View File
@@ -985,6 +985,7 @@ function assertSelectableProviderConfig(config: {
export type RemoveSecretOptions = {
/** Runs after the secret is marked deleted and before its row is removed. */
beforeDelete?: (secret: typeof companySecrets.$inferSelect) => Promise<void>;
expectedVersion?: number;
};
export function secretService(db: Db | DbTransaction) {
@@ -3453,9 +3454,28 @@ export function secretService(db: Db | DbTransaction) {
async function removeSecretInternal(secretId: string, options: RemoveSecretOptions = {}) {
const preCheckSecret = await getById(secretId);
if (!preCheckSecret) return null;
return withAccountHomeSecretMutationLock(undefined, preCheckSecret.companyId, () =>
removeSecretUnlocked(secretId, options),
);
return withAccountHomeSecretMutationLock(undefined, preCheckSecret.companyId, async () => {
if (options.expectedVersion !== undefined) {
const now = new Date();
const claimed = await db
.update(companySecrets)
.set({
key: sql`${companySecrets.key} || '__deleted__' || ${companySecrets.id}`,
name: sql`${companySecrets.name} || '__deleted__' || ${companySecrets.id}`,
status: "deleted",
deletedAt: now,
updatedAt: now,
})
.where(and(
eq(companySecrets.id, secretId),
isNull(companySecrets.deletedAt),
eq(companySecrets.latestVersion, options.expectedVersion),
))
.returning({ id: companySecrets.id });
if (claimed.length === 0) return null;
}
return removeSecretUnlocked(secretId, options);
});
}
// The body of `removeSecretInternal` above, unchanged. Extracted to a named
+2 -2
View File
@@ -785,8 +785,8 @@ export function toolAccessService(
? createVercelConnectClient()
: options.vercelConnectClient;
const runtimeSupervisor = createToolRuntimeSupervisor(db, options);
const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect });
const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, getConnectionRow });
const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets });
const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow });
/**
* Connection setup resolves connector definitions synchronously. Refresh the
* plugin-provided part of the catalog from the plugins table first, so a
@@ -0,0 +1,260 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
const resolveConnectionGrantSecret = vi.hoisted(() => vi.fn());
vi.mock("../../connection-credentials.js", () => ({ resolveConnectionGrantSecret }));
import { createManagedGoogleAccessRemoval, summarizeManagedGoogleAccess } from "./google-access-removal.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { logger } from "../../../middleware/logger.js";
const companyId = "company-1";
function fakeDb(rows: { grants?: unknown[]; connections?: unknown[] } = {}) {
const answer = (columns: Record<string, unknown>) => ("secretRefs" in columns ? rows.connections ?? []
: "refs" in columns ? rows.grants ?? []
: "latestVersion" in columns ? [{ latestVersion: 1 }]
: "status" in columns ? [{ status: "revoked" }] : []);
const db: Record<string, unknown> = {
insert: vi.fn(() => ({ values: vi.fn(async () => undefined) })),
update: vi.fn(() => ({ set: () => ({ where: async () => undefined }) })),
select: vi.fn((columns: Record<string, unknown>) => ({
from: () => ({
where: () => {
const result = Promise.resolve(answer(columns));
return Object.assign(result, { for: () => result });
},
}),
})),
};
db.transaction = vi.fn(async (run: (tx: unknown) => Promise<unknown>) => run(db));
return db as unknown as Db;
}
const scope = () => ({ removingConnection: true, removeSecret: vi.fn(async () => true) });
function connection(oauth: Record<string, unknown>, authKind = "oauth") {
return { id: "connection-1", companyId, authKind, config: { oauth } } as never;
}
const managedGoogle = { strategy: "paperclip_cloud_connector", connectorProfile: "workspace.all", connectorSubjectUserId: "org-owner" };
function grant(
id: string,
kind: string,
subject: { subjectUserId?: string; subjectAgentId?: string; consentSubject?: string },
refreshSecretId = `${id}-refresh`,
) {
return {
id, companyId, connectionId: "connection-1", kind,
subjectUserId: subject.subjectUserId ?? null,
subjectAgentId: subject.subjectAgentId ?? null,
providerTenant: subject.consentSubject ? { externalId: subject.consentSubject } : null,
credentialSecretRefs: [
{ configPath: "oauth.access_token", secretId: `${id}-access` },
{ configPath: "oauth.refresh_token", secretId: refreshSecretId },
],
} as never;
}
type RevokeValues = Parameters<PaperclipCloudConnector["revoke"]>[0];
function connectorWith(revoke: (values: RevokeValues) => Promise<{ outcome?: string }>) {
return { revoke: vi.fn(revoke) } as unknown as PaperclipCloudConnector & { revoke: ReturnType<typeof vi.fn> };
}
async function run(
removal: ReturnType<typeof createManagedGoogleAccessRemoval>,
oauth: Record<string, unknown>,
grants: never[],
authKind?: string,
) {
const prepared = await removal.prepare(connection(oauth, authKind), grants, undefined, scope());
return prepared ? prepared.send() : null;
}
describe("managed Google access removal", () => {
beforeEach(() => {
vi.restoreAllMocks();
resolveConnectionGrantSecret.mockReset();
resolveConnectionGrantSecret.mockImplementation(async (_db, _connection, _grant, ref: { secretId: string }) => ({ value: `token-for-${ref.secretId}`, latestVersion: 1 }));
});
it("revokes per-user, per-agent and organization grants each under the subject that consented", async () => {
const connector = connectorWith(async () => ({ outcome: "revoked" }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, managedGoogle, [
grant("user-grant", "user", { subjectUserId: "user-1", consentSubject: "user-1" }),
grant("agent-grant", "agent", { subjectAgentId: "agent-1", consentSubject: "agent:agent-1" }),
grant("org-grant", "organization", { consentSubject: "first-consenter" }),
grant("old-org-grant", "organization", {}),
])).resolves.toEqual({ provider: "google", result: "ended", outcomes: ["revoked", "revoked", "revoked", "revoked"] });
expect(connector.revoke.mock.calls.map(([values]) => [values.subject, values.token, values.profile])).toEqual([
["user-1", "token-for-user-grant-refresh", "workspace.all"],
["agent:agent-1", "token-for-agent-grant-refresh", "workspace.all"],
["first-consenter", "token-for-org-grant-refresh", "workspace.all"],
["org-owner", "token-for-old-org-grant-refresh", "workspace.all"],
]);
});
it("sends a refresh token shared by two grants once", async () => {
const connector = connectorWith(async () => ({ outcome: "revoked" }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await run(removal, managedGoogle, [
grant("org-grant", "organization", {}, "shared-refresh"),
grant("user-grant", "user", { subjectUserId: "org-owner" }, "shared-refresh"),
]);
expect(connector.revoke).toHaveBeenCalledTimes(1);
});
it("sends two grants of one user one after the other and reports access ended but unconfirmed", async () => {
let inFlight = 0;
let maxInFlight = 0;
const outcomes = ["other_connections_remain", "revoked"];
const connector = connectorWith(async () => {
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
await new Promise((resolve) => setTimeout(resolve, 5));
inFlight -= 1;
return { outcome: outcomes.shift() };
});
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, managedGoogle, [
grant("org-grant", "organization", { consentSubject: "user-1" }),
grant("user-grant", "user", { subjectUserId: "user-1", consentSubject: "user-1" }),
])).resolves.toEqual({ provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] });
expect(maxInFlight).toBe(1);
expect(connector.revoke.mock.calls.map(([values]) => values.token)).toEqual([
"token-for-org-grant-refresh", "token-for-user-grant-refresh",
]);
});
it.each([
"binding_not_known", "provider_revocation_failed", "revocation_in_progress",
])("reports access not ended when one token was revoked and another reports %s", async (later) => {
const outcomes = ["revoked", later];
const connector = connectorWith(async () => ({ outcome: outcomes.shift() }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, managedGoogle, [
grant("a", "user", { consentSubject: "user-1" }),
grant("b", "organization", { consentSubject: "user-1" }),
])).resolves.toMatchObject({ result: "not_ended" });
});
it.each([
["a customer-owned Google client", { strategy: "authorization_code", provider: "google" }, "oauth"],
["a managed GitHub connection", { strategy: "paperclip_cloud_connector", connectorProfile: "github.code" }, "oauth"],
["a non-OAuth connection", managedGoogle, "api_key"],
])("makes no broker call for %s", async (_label, oauth, authKind) => {
const connector = connectorWith(async () => ({ outcome: "revoked" }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, oauth, [grant("user-grant", "user", { subjectUserId: "user-1" })], authKind)).resolves.toBeNull();
expect(connector.revoke).not.toHaveBeenCalled();
expect(resolveConnectionGrantSecret).not.toHaveBeenCalled();
});
it("reports access not ended when Paperclip Cloud is not configured or the token is unreadable", async () => {
resolveConnectionGrantSecret.mockRejectedValueOnce(new Error("missing"));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => null });
await expect(run(removal, managedGoogle, [
grant("user-grant", "user", { subjectUserId: "user-1" }),
grant("agent-grant", "agent", { subjectAgentId: "agent-1" }),
])).resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["credential_unavailable", "broker_unavailable"] });
});
it("reports access not ended when creating the Paperclip Cloud client throws", async () => {
const removal = createManagedGoogleAccessRemoval(fakeDb(), {
currentCloudConnector: () => { throw new Error("instance key is invalid"); },
});
await expect(run(removal, managedGoogle, [grant("user-grant", "user", { subjectUserId: "user-1" })]))
.resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["broker_unavailable"] });
});
it("logs an unexpected failure without the token and reports access not ended", async () => {
const warn = vi.spyOn(logger, "warn").mockImplementation((() => undefined) as never);
const broken = { ...(grant("user-grant", "user", { subjectUserId: "user-1" }) as object) };
Object.defineProperty(broken, "credentialSecretRefs", { get() { throw new TypeError("token-for-user-grant-refresh"); } });
const connector = connectorWith(async () => ({ outcome: "revoked" }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, managedGoogle, [broken as never]))
.resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["unexpected_error"] });
expect(warn).toHaveBeenCalledTimes(1);
expect(JSON.stringify(warn.mock.calls)).not.toContain("token-for-user-grant-refresh");
expect(connector.revoke).not.toHaveBeenCalled();
});
it("bounds all broker calls of one removal by a single deadline", async () => {
let clock = 0;
const connector = connectorWith(async (values) => {
clock += values.timeoutMs ?? 0;
return { outcome: "other_connections_remain" };
});
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector, timeoutMs: 5_000, now: () => clock });
await expect(run(removal, managedGoogle, [
grant("a", "user", { consentSubject: "user-1" }),
grant("b", "user", { consentSubject: "user-2" }),
])).resolves.toEqual({ provider: "google", result: "not_ended", outcomes: ["other_connections_remain", "broker_unavailable"] });
expect(connector.revoke).toHaveBeenCalledTimes(1);
expect(connector.revoke).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 5_000 }));
});
it("reports a per-agent connection whose last agent grant was revoked as ended but unconfirmed", async () => {
const outcomes = ["other_connections_remain", "revoked"];
const connector = connectorWith(async () => ({ outcome: outcomes.shift() }));
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
await expect(run(removal, managedGoogle, [
grant("agent-a", "agent", { subjectAgentId: "a", consentSubject: "agent:a" }),
grant("agent-b", "agent", { subjectAgentId: "b", consentSubject: "agent:b" }),
])).resolves.toMatchObject({ result: "ended_unconfirmed" });
});
it.each([
[["revoked", "revoked"], "ended"],
[["broker_unavailable", "revoked"], "not_ended"],
[["other_connections_remain", "binding_not_known"], "not_ended"],
[["revoked", "unexpected_error"], "not_ended"],
[["other_connections_remain", "other_connections_remain"], "other_connections_remain"],
[["other_connections_remain", "revoked"], "ended_unconfirmed"],
[["revoked", "other_connections_remain"], "ended_unconfirmed"],
] as const)("summarizes %j as %s", (outcomes, result) => {
expect(summarizeManagedGoogleAccess([...outcomes]).result).toBe(result);
});
it("records each result, including ended_unconfirmed, as its own audit event", async () => {
const values = vi.fn(async () => undefined);
const db = { ...fakeDb(), insert: vi.fn(() => ({ values })) } as unknown as Db;
const outcomes = ["other_connections_remain", "revoked"];
const connector = connectorWith(async () => ({ outcome: outcomes.shift() }));
const removal = createManagedGoogleAccessRemoval(db, { currentCloudConnector: () => connector });
const prepared = await removal.prepare(connection(managedGoogle), [
grant("agent-a", "agent", { subjectAgentId: "a", consentSubject: "agent:a" }),
grant("agent-b", "agent", { subjectAgentId: "b", consentSubject: "agent:b" }),
], undefined, { ...scope(), grantId: "agent-a" });
await prepared!.send();
expect(values).toHaveBeenCalledWith(expect.objectContaining({
action: "connection.google_access_removal",
reasonCode: "ended_unconfirmed",
details: { grantId: "agent-a", providerAccess: { provider: "google", result: "ended_unconfirmed", outcomes: ["other_connections_remain", "revoked"] } },
}));
expect(JSON.stringify(values.mock.calls)).not.toContain("token-for");
});
it("deletes each sent refresh token only after the broker answered, whatever the outcome", async () => {
const order: string[] = [];
const connector = connectorWith(async (values) => { order.push(`revoke:${values.token}`); return { outcome: "provider_revocation_failed" }; });
const removal = createManagedGoogleAccessRemoval(fakeDb(), { currentCloudConnector: () => connector });
const removeSecret = vi.fn(async (secretId: string) => { order.push(`delete:${secretId}`); });
const prepared = await removal.prepare(connection(managedGoogle), [grant("user-grant", "user", { consentSubject: "user-1" })], undefined, { removingConnection: true, removeSecret });
await prepared!.send();
expect(order).toEqual(["revoke:token-for-user-grant-refresh", "delete:user-grant-refresh"]);
});
it("neither sends nor deletes a refresh token that a live connection or grant still uses", async () => {
const connector = connectorWith(async () => ({ outcome: "revoked" }));
const db = fakeDb({ connections: [{ id: "connection-1", refs: [], secretRefs: [{ secretId: "org-grant-refresh" }] }] });
const removal = createManagedGoogleAccessRemoval(db, { currentCloudConnector: () => connector });
const removeSecret = vi.fn();
await expect(removal.prepare(connection(managedGoogle), [grant("org-grant", "organization", { consentSubject: "user-1" })], undefined, { removingConnection: false, removeSecret }))
.resolves.toBeNull();
expect(connector.revoke).not.toHaveBeenCalled();
expect(removeSecret).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,269 @@
import type { Db } from "@paperclipai/db";
import { companySecrets, connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db";
import { and, eq, inArray, isNull, ne } from "drizzle-orm";
import type { ManagedGoogleAccessRemoval, ManagedGoogleRevocationOutcome } from "@paperclipai/shared";
import { logger } from "../../../middleware/logger.js";
import { resolveConnectionGrantSecret } from "../../connection-credentials.js";
import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { managedConnectorConsentSubject, managedConnectorProfile } from "../oauth/client-settings.js";
import { oauthConfig } from "../oauth/metadata.js";
import type { ActorInfo } from "../types.js";
import { actorBinding } from "../actor.js";
export const MANAGED_GOOGLE_REVOKE_TIMEOUT_MS = 5_000;
type RemovedGrant = Pick<typeof connectionGrants.$inferSelect,
"id" | "companyId" | "connectionId" | "status" | "kind" | "subjectUserId" | "subjectAgentId" | "credentialSecretRefs" | "providerTenant">;
type PreparedRevocation =
| { kind: "call"; subject: string; token: string }
| { kind: "skip"; outcome: ManagedGoogleRevocationOutcome };
export type PreparedGoogleAccessRemoval = {
send(): Promise<ManagedGoogleAccessRemoval>;
};
export type GoogleAccessRemovalScope = {
grantId?: string;
removingConnection: boolean;
canRemoveSecret?(secretId: string): Promise<boolean>;
removeSecret(secretId: string, expectedVersion: number): Promise<unknown>;
};
function refreshSecretId(grant: RemovedGrant): string | null {
return (grant.credentialSecretRefs ?? []).find((ref) => ref.configPath === "oauth.refresh_token")?.secretId ?? null;
}
function outcomeForError(error: unknown): ManagedGoogleRevocationOutcome {
if (!(error instanceof PaperclipCloudConnectorError)) return "broker_error";
if (error.code === "CONNECTOR_UNAVAILABLE") return "broker_unavailable";
if (error.status === 409 && error.brokerReason === "REVOCATION_NOT_AVAILABLE") return "revocation_not_available";
return "broker_error";
}
export function summarizeManagedGoogleAccess(outcomes: ManagedGoogleRevocationOutcome[]): ManagedGoogleAccessRemoval {
const revoked = outcomes.filter((outcome) => outcome === "revoked").length;
const remaining = outcomes.filter((outcome) => outcome === "other_connections_remain").length;
const result: ManagedGoogleAccessRemoval["result"] = revoked + remaining < outcomes.length
? "not_ended"
: revoked === outcomes.length
? "ended"
: revoked === 0
? "other_connections_remain"
: "ended_unconfirmed";
return { provider: "google", result, outcomes };
}
export function createManagedGoogleAccessRemoval(db: Db, deps: {
currentCloudConnector: () => PaperclipCloudConnector | null;
timeoutMs?: number;
now?: () => number;
}) {
const timeoutMs = deps.timeoutMs ?? MANAGED_GOOGLE_REVOKE_TIMEOUT_MS;
const now = deps.now ?? Date.now;
async function send(
connection: typeof toolConnections.$inferSelect,
profile: string,
revocations: PreparedRevocation[],
): Promise<ManagedGoogleAccessRemoval> {
const outcomes: ManagedGoogleRevocationOutcome[] = [];
let connector: PaperclipCloudConnector | null = null;
let connectorUnavailable = false;
try {
connector = deps.currentCloudConnector();
} catch {
connectorUnavailable = true;
}
const deadline = now() + timeoutMs;
for (const revocation of revocations) {
if (revocation.kind === "skip") {
outcomes.push(revocation.outcome);
continue;
}
const remaining = deadline - now();
if (connectorUnavailable || !connector || remaining <= 0) {
outcomes.push("broker_unavailable");
continue;
}
try {
const { outcome } = await connector.revoke({
subject: revocation.subject,
companyId: connection.companyId,
profile: profile as Parameters<PaperclipCloudConnector["revoke"]>[0]["profile"],
token: revocation.token,
timeoutMs: remaining,
});
outcomes.push(outcome ?? "broker_error");
} catch (error) {
outcomes.push(outcomeForError(error));
}
}
const summary = summarizeManagedGoogleAccess(outcomes);
if (summary.result === "not_ended") {
logger.warn(
{ companyId: connection.companyId, connectionId: connection.id, outcomes: summary.outcomes },
"Paperclip Cloud did not end Google access for a removed connection",
);
}
return summary;
}
function unexpectedFailure(connection: typeof toolConnections.$inferSelect, error: unknown): PreparedGoogleAccessRemoval {
logger.warn(
{ companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error },
"Could not prepare ending Google access for a removed connection",
);
return { send: async () => summarizeManagedGoogleAccess(["unexpected_error"]) };
}
async function recordAudit(
connection: typeof toolConnections.$inferSelect,
actor: ActorInfo | undefined,
scope: GoogleAccessRemovalScope,
providerAccess: ManagedGoogleAccessRemoval,
) {
try {
const binding = actorBinding(actor);
await db.insert(toolAccessAuditEvents).values({
companyId: connection.companyId,
connectionId: connection.id,
actorType: binding.actorType ?? "system",
actorId: binding.actorId,
action: "connection.google_access_removal",
outcome: providerAccess.result === "not_ended" ? "failure" : "success",
reasonCode: providerAccess.result,
details: { ...(scope.grantId ? { grantId: scope.grantId } : {}), providerAccess },
});
} catch (error) {
logger.warn(
{ companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error },
"Could not record the Google access result for a removed connection",
);
}
}
async function secretsHeldElsewhere(
connection: typeof toolConnections.$inferSelect,
grants: RemovedGrant[],
secretIds: string[],
removingConnection: boolean,
): Promise<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;
}
async function deleteSentSecrets(
connection: typeof toolConnections.$inferSelect,
scope: GoogleAccessRemovalScope,
sent: Array<{ secretId: string; version: number }>,
) {
for (const { secretId, version } of sent) {
try {
if (scope.canRemoveSecret && !(await scope.canRemoveSecret(secretId))) continue;
await scope.removeSecret(secretId, version);
} catch (error) {
logger.warn(
{ companyId: connection.companyId, connectionId: connection.id, errorName: error instanceof Error ? error.name : typeof error },
"Could not delete a refresh token after ending Google access",
);
}
}
}
async function prepare(
connection: typeof toolConnections.$inferSelect,
grants: RemovedGrant[],
actor: ActorInfo | undefined,
scope: GoogleAccessRemovalScope,
): Promise<PreparedGoogleAccessRemoval | null> {
const oauth = oauthConfig(connection);
if (connection.authKind !== "oauth" || !isPaperclipCloudConnectorStrategy(oauth.strategy)) return null;
const profile = managedConnectorProfile(typeof oauth.connectorProfile === "string" ? oauth.connectorProfile : undefined);
if (profile?.provider !== "google") return null;
try {
const revokedSecretIds = grants.flatMap((grant) => {
const secretId = grant.status === "revoked" ? refreshSecretId(grant) : null;
return secretId ? [secretId] : [];
});
const stillStored = new Set(revokedSecretIds.length === 0 ? [] : (await db.select({ id: companySecrets.id }).from(companySecrets)
.where(and(eq(companySecrets.companyId, connection.companyId), inArray(companySecrets.id, revokedSecretIds), isNull(companySecrets.deletedAt))))
.map((row) => row.id));
const candidateSecretIds = grants.flatMap((grant) => {
const secretId = refreshSecretId(grant);
return secretId ? [secretId] : [];
});
const held = await secretsHeldElsewhere(connection, grants, candidateSecretIds, scope.removingConnection);
const seen = new Set<string>();
const revocations: PreparedRevocation[] = [];
const sentSecrets: Array<{ secretId: string; version: number }> = [];
for (const grant of grants) {
const secretId = refreshSecretId(grant);
const refreshRef = (grant.credentialSecretRefs ?? []).find((ref) => ref.configPath === "oauth.refresh_token");
if (!secretId || !refreshRef || seen.has(secretId)) continue;
if (grant.status === "revoked" && !stillStored.has(secretId)) continue;
if (held.has(secretId)) continue;
seen.add(secretId);
const subject = managedConnectorConsentSubject(grant, oauth);
if (!subject) {
revocations.push({ kind: "skip", outcome: "credential_unavailable" });
continue;
}
try {
const { value, latestVersion } = await resolveConnectionGrantSecret(db, connection, grant, refreshRef, {
consumerType: "tool_connection",
consumerId: connection.id,
actorType: actor?.actorType ?? "system",
actorId: actor?.actorId ?? null,
});
revocations.push({ kind: "call", subject, token: value });
sentSecrets.push({ secretId, version: latestVersion });
} catch {
revocations.push({ kind: "skip", outcome: "credential_unavailable" });
}
}
if (revocations.length === 0) return null;
return {
send: async () => {
let summary: ManagedGoogleAccessRemoval;
try {
summary = await send(connection, profile.id, revocations);
} catch (error) {
summary = await unexpectedFailure(connection, error).send();
}
await deleteSentSecrets(connection, scope, sentSecrets);
await recordAudit(connection, actor, scope, summary);
return summary;
},
};
} catch (error) {
const failed = unexpectedFailure(connection, error);
return {
send: async () => {
const summary = await failed.send();
await recordAudit(connection, actor, scope, summary);
return summary;
},
};
}
}
return { prepare };
}
@@ -1,16 +1,18 @@
import { notifyGitHubCredentialChange } from "../../github-connection-notifications.js";
import type { secretService } from "../../secrets.js";
import type { ConnectionManagementContext } from "../../connection-management.js";
import { connectionActorUserId } from "../actor.js";
import { toConnectionGrant } from "./projection.js";
import { actorBinding } from "../actor.js";
import { vercelConnectResourcesFor } from "../vercel-credentials.js";
import type { ActorInfo } from "../types.js";
import { oauthConfig } from "../oauth/metadata.js";
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, connectionGrantMembers, connectionGrantDelegations, connectionGrants, authUsers, companyMemberships, toolAccessAuditEvents, toolConnections } from "@paperclipai/db";
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js";
import { isPaperclipCloudConnectorStrategy } from "../../paperclip-cloud-connector.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { createManagedGoogleAccessRemoval } from "./google-access-removal.js";
import type { ConnectionGrantRevocationResult } from "@paperclipai/shared";
import { vercelTokenRequest, type VercelConnectClient } from "../../vercel-connect.js";
import type { createConnectionCredentialValidation } from "./credential-validation.js";
@@ -18,9 +20,12 @@ type GrantDependencies = {
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
assertSecretRefs: ReturnType<typeof createConnectionCredentialValidation>;
vercelConnect: VercelConnectClient | null;
currentCloudConnector: () => PaperclipCloudConnector | null;
secrets: Pick<ReturnType<typeof secretService>, "remove">;
};
export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect }: GrantDependencies) {
export function createConnectionGrants(db: Db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets }: GrantDependencies) {
const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector });
return {
listConnectionGrants: async (idOrUid: string, companyId?: string) => {
const connection = await getConnectionRow(idOrUid, companyId);
@@ -487,7 +492,7 @@ replaceConnectionGrantMembers: async (
idOrUid: string,
grantId: string,
actor?: ActorInfo,
) => {
): Promise<ConnectionGrantRevocationResult> => {
await actor?.managementContext?.reauthorize();
const connection = await getConnectionRow(idOrUid);
const binding = actorBinding(actor);
@@ -504,6 +509,11 @@ replaceConnectionGrantMembers: async (
.limit(1);
if (!currentGrant) throw notFound("Connection grant not found");
let providerRevocation = "not_applicable";
const providerAccessRemoval = await managedGoogleAccess.prepare(connection, [currentGrant], actor, {
grantId: currentGrant.id,
removingConnection: false,
removeSecret: (secretId, expectedVersion) => secrets.remove(secretId, { expectedVersion }),
});
if (
connection.credentialSource === "vercel_connect" &&
connection.externalCredential
@@ -527,15 +537,6 @@ replaceConnectionGrantMembers: async (
providerRevocation = "failed";
}
}
} else if (
isPaperclipCloudConnectorStrategy(oauthConfig(connection).strategy)
) {
// Google revocation is client-wide for a user. The managed Workspace
// profiles intentionally share one Paperclip-owned client, so revoking
// one token here could invalidate unrelated Gmail, Drive, and Calendar
// grants. A per-profile removal is therefore local-only. A future
// provider-level disconnect must warn that it removes every profile.
providerRevocation = "local_only_shared_client";
}
const grant = await db.transaction(async (tx) => {
await notifyGitHubCredentialChange(tx, connection);
@@ -597,6 +598,7 @@ replaceConnectionGrantMembers: async (
return updated;
});
if (!grant) throw notFound("Connection grant not found");
const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null;
await db.insert(toolAccessAuditEvents).values({
companyId: connection.companyId,
connectionId: connection.id,
@@ -607,7 +609,7 @@ replaceConnectionGrantMembers: async (
reasonCode: "grant_revoked",
details: { grantId: grant.id, kind: grant.kind, providerRevocation },
});
return toConnectionGrant(grant);
return { ...toConnectionGrant(grant), ...(providerAccess ? { providerAccess } : {}) };
}
};
}
@@ -3,6 +3,8 @@ import { notifyVoiceChange } from "../../voice/voice-recovery-notifications.js";
import { notifyChatEndpointWork } from "../../chat-work-notifications.js";
import { notifyToolConnectionHealth } from "../../tool-connection-health-notifications.js";
import { toConnection } from "./projection.js";
import { createManagedGoogleAccessRemoval } from "./google-access-removal.js";
import type { PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
import { actorBinding, connectionActorUserId } from "../actor.js";
import { stageSlackCloudEnrollmentIntent } from "../../chat-channels/slack/cloud-enrollment.js";
import { vercelConnectResourcesFor } from "../vercel-credentials.js";
@@ -81,10 +83,12 @@ type RemovalDependencies = {
secrets: ReturnType<typeof secretService>;
runtimeSupervisor: Pick<ReturnType<typeof createToolRuntimeSupervisor>, "stopSlot">;
vercelConnect: VercelConnectClient | null;
currentCloudConnector: () => PaperclipCloudConnector | null;
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
};
export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, getConnectionRow }: RemovalDependencies) {
export function createConnectionRemoval(db: Db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow }: RemovalDependencies) {
const managedGoogleAccess = createManagedGoogleAccessRemoval(db, { currentCloudConnector });
/**
* Split the secrets a connection points at into the ones it owns outright and
* the ones another consumer still depends on.
@@ -262,10 +266,14 @@ async function removeConnection(
const grantRows = await db
.select({
id: connectionGrants.id,
companyId: connectionGrants.companyId,
connectionId: connectionGrants.connectionId,
status: connectionGrants.status,
kind: connectionGrants.kind,
subjectUserId: connectionGrants.subjectUserId,
subjectAgentId: connectionGrants.subjectAgentId,
credentialSecretRefs: connectionGrants.credentialSecretRefs,
providerTenant: connectionGrants.providerTenant,
externalCredential: connectionGrants.externalCredential,
})
.from(connectionGrants)
@@ -276,6 +284,14 @@ async function removeConnection(
),
);
const grantsToRevoke = grantRows.filter((row) => row.status !== "revoked");
let secretsRevoked = 0;
const providerAccessRemoval = await managedGoogleAccess.prepare(connection, grantRows, actor, {
removingConnection: true,
canRemoveSecret: async (secretId) => (await classifyConnectionSecrets(connection, [secretId])).owned.includes(secretId),
removeSecret: async (secretId, expectedVersion) => {
if (await secrets.remove(secretId, { expectedVersion })) secretsRevoked += 1;
},
});
if (grantsToRevoke.length > 0) {
await db
.update(connectionGrants)
@@ -595,6 +611,8 @@ async function removeConnection(
await browserUseService(db, options.remoteHttpRequest).stopBeforeCredentialRemoval(connection.companyId, connection.id);
}
const providerAccess = providerAccessRemoval ? await providerAccessRemoval.send() : null;
// Only now, with every access path closed, revoke the credentials. Each
// `secrets.remove` marks the row deleted before it calls the provider, so a
// provider error leaves an unresolvable secret and a resumable removal
@@ -611,7 +629,6 @@ async function removeConnection(
connection,
candidateSecretIds,
);
let secretsRevoked = 0;
for (const secretId of owned) {
const removed = await secrets.remove(secretId);
if (removed) secretsRevoked += 1;
@@ -664,6 +681,7 @@ async function removeConnection(
gatewaySessionsRevoked,
applicationArchived: archived.applicationArchived,
externalCredentialCleanup,
...(providerAccess ? { providerAccess } : {}),
},
};
}
@@ -130,6 +130,23 @@ export async function oauthGalleryEntryForConnection(
export type ManagedConnectorProfileId =
GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId;
export function managedConnectorSubject(
grant: { kind: string; subjectUserId: string | null; subjectAgentId: string | null },
oauth: Record<string, unknown>,
): string | null {
if (grant.kind === "agent" && grant.subjectAgentId) return `agent:${grant.subjectAgentId}`;
if (grant.kind === "user" && grant.subjectUserId) return grant.subjectUserId;
return typeof oauth.connectorSubjectUserId === "string" ? oauth.connectorSubjectUserId : null;
}
export function managedConnectorConsentSubject(
grant: { kind: string; subjectUserId: string | null; subjectAgentId: string | null; providerTenant?: { externalId?: unknown } | null },
oauth: Record<string, unknown>,
): string | null {
const consentSubject = grant.providerTenant?.externalId;
return typeof consentSubject === "string" && consentSubject ? consentSubject : managedConnectorSubject(grant, oauth);
}
export function managedConnectorProfile(value: string | undefined): {
id: ManagedConnectorProfileId;
provider: "google" | "github" | "asana";
@@ -16,7 +16,7 @@ import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type P
import { actorForSecret, type OAuthCredentialStore } from "./credential-store.js";
import { withoutOAuthRefreshLease, type OAuthRefreshLeases } from "./refresh-leases.js";
import { managedConnectorProfile, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js";
import { managedConnectorProfile, managedConnectorSubject, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js";
import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js";
import { singleFlight } from "../single-flight.js";
import { usesClientCredentials } from "./client-credentials.js";
@@ -106,14 +106,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo
: undefined,
);
const cloudConnector = currentCloudConnector();
const connectorSubject =
grant.kind === "agent" && grant.subjectAgentId
? `agent:${grant.subjectAgentId}`
: grant.kind === "user" && grant.subjectUserId
? grant.subjectUserId
: typeof oauth.connectorSubjectUserId === "string"
? oauth.connectorSubjectUserId
: null;
const connectorSubject = managedConnectorSubject(grant, oauth);
const accessRef = grant.credentialSecretRefs.find(
(ref) => ref.configPath === "oauth.access_token",
);
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { managedConnectorConsentSubject, managedConnectorSubject } from "./client-settings.js";
const oauth = { connectorSubjectUserId: "latest-user" };
const organizationGrant = { kind: "organization", subjectUserId: null, subjectAgentId: null, providerTenant: { externalId: "consenting-user" } };
describe("managed connector subjects", () => {
it("keeps refresh on the subject rule it has always used", () => {
expect(managedConnectorSubject(organizationGrant, oauth)).toBe("latest-user");
expect(managedConnectorSubject({ kind: "agent", subjectUserId: null, subjectAgentId: "a1" }, oauth)).toBe("agent:a1");
expect(managedConnectorSubject({ kind: "user", subjectUserId: "u1", subjectAgentId: null }, oauth)).toBe("u1");
});
it("revokes under the subject that consented to the grant", () => {
expect(managedConnectorConsentSubject(organizationGrant, oauth)).toBe("consenting-user");
});
it("falls back to the refresh rule for grants saved without a consenting subject", () => {
expect(managedConnectorConsentSubject({ ...organizationGrant, providerTenant: null }, oauth)).toBe("latest-user");
});
});