Preserve newer Google Workspace draft choices during OAuth

Merge OAuth metadata and first-use client bindings against locked current rows. Retain request-local consent scopes and reject concurrent client identity changes.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-30 11:50:35 -05:00
1 parent 6c18e3aaf3
commit a0f9089fc1
4 files changed
+269 -60

No files matched your search

+5
View File
@@ -22,6 +22,11 @@ that choice, not the new-account write defaults. Historical drafts without a
matching saved intent require an explicit choice. Reconnecting an established
account without a new choice keeps its exact grant request.
Overlapping customer-owned starts preserve the latest saved draft choice through
client binding and authorization metadata updates. Each OAuth state and consent
URL keeps that attempt's own requested scopes. These updates preserve unrelated
current settings and other users' pending proposals in both configuration records.
An agent can hand setup to its responsible human without choosing services or
creating provider OAuth state. If the agent proposes services, the human can
review and change them in the picker. Saving the human's choice consumes only
@@ -84,6 +84,7 @@ import {
import { accessService } from "../services/access.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { createOAuthAuthorizationStart } from "../services/tool-access/oauth/authorization-start.js";
import { createOAuthClientRegistration } from "../services/tool-access/oauth/client-registration.js";
import { createPersonalConnectionIdentity } from "../services/tool-access/connections/personal-identity.js";
import { createConnectionSetupPolicy } from "../services/tool-access/connections/setup-policy.js";
import { toolAccessPolicyService } from "../services/tool-access-policy.js";
@@ -2680,6 +2681,167 @@ describeEmbeddedPostgres("tool access service", () => {
expect(coldState.requestedScopes).toEqual(["https://www.googleapis.com/auth/gmail.readonly"]);
});
it.each(["bound", "first-use"] as const)("preserves the latest Workspace draft choice across overlapping %s customer starts", async (bindingMode) => {
const company = await createCompany(db);
const userId = `workspace-overlap-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, [], "owner");
const actor = { actorType: "user" as const, actorId: userId };
const service = createTestToolAccessService(db);
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", connectionMethodKey: "customer-workspace-oauth", grantKind: "user",
oauthClient: { clientId: "fixture-client", clientSecret: "fixture-secret" },
}, actor);
const redirectUri = "https://paperclip.example.test/api/tools/oauth/callback";
const endpoints = {
provider: "google", authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token", registrationUrl: null,
scopes: googleWorkspaceSelectedScopes(GOOGLE_WORKSPACE_DEFAULT_SELECTION),
offlineAccessSupported: true, issuer: "https://accounts.google.com", resource: null,
};
const getConnectionRow = async () => {
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
return row;
};
const initial = await getConnectionRow();
if (bindingMode === "bound") {
const config = { ...initial.config, oauth: { ...(initial.config.oauth as Record<string, unknown>),
clientRedirectUri: redirectUri, clientIssuer: endpoints.issuer, clientResource: null, clientCompanyId: company.id,
} };
await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, initial.id));
} else {
expect((initial.config.oauth as Record<string, unknown>).clientRedirectUri).toBeUndefined();
}
const observedClientRows: typeof initial[] = [];
const ensureOAuthClient = createOAuthClientRegistration(db, {
now: () => new Date(), options: {}, getConnectionRow,
requestOAuthClientRegistration: vi.fn(),
store: {
createOrRotateOAuthSecret: vi.fn(), syncCredentialBindings: vi.fn(),
oauthClientForConnection: async (row) => {
observedClientRows.push(row);
return { clientId: "fixture-client", clientSecret: "fixture-secret", clientIdEnv: null, clientSecretEnv: null };
},
},
});
let releaseA!: () => void;
let reachedA!: () => void;
const pausedA = new Promise<void>(resolve => { reachedA = resolve; });
const resumeA = new Promise<void>(resolve => { releaseA = resolve; });
let discoveries = 0;
const makeStart = () => createOAuthAuthorizationStart(db, {
now: () => new Date(), getConnectionRow, ensureOAuthClient,
setupPolicy: createConnectionSetupPolicy(db), fixedPersonalIdentityForReconnect: createPersonalConnectionIdentity(db),
currentCloudConnector: () => null, vercelConnect: null,
oauthEndpointsForConnection: async () => {
if (++discoveries === 1) { reachedA(); await resumeA; }
return endpoints;
},
assertOAuthEndpointUrl: (_kind, url) => String(url),
});
const start = makeStart();
const first = start(company.id, initial.id, { redirectUri, actor, subjectUserId: userId, workspaceServices: { gmail: "write" } });
let startedA;
let startedB;
let afterB;
try {
await pausedA;
startedB = await start(company.id, initial.id, { redirectUri, actor, subjectUserId: userId, workspaceServices: { gmail: "read" } });
afterB = await getConnectionRow();
expect((afterB.config.oauth as Record<string, unknown>).clientRedirectUri).toBe(redirectUri);
const pending = { anotherUser: { requestedScopes: googleWorkspaceSelectedScopes({ calendar: "read" }), requestedAt: "2026-10-30T16:00:00Z" } };
await db.update(toolConnections).set({
config: { ...afterB.config, concurrentSetting: "config-b", oauth: { ...(afterB.config.oauth as Record<string, unknown>), pendingWorkspaceServiceRequests: pending } },
transportConfig: { ...afterB.transportConfig, transportOnlySetting: "transport-b", oauth: { ...(afterB.transportConfig.oauth as Record<string, unknown>), pendingWorkspaceServiceRequests: pending } },
}).where(eq(toolConnections.id, initial.id));
} finally {
releaseA();
startedA = await first;
}
const writeScopes = googleWorkspaceSelectedScopes({ gmail: "write" });
const readScopes = googleWorkspaceSelectedScopes({ gmail: "read" });
const expectedBinding = { version: 1, companyId: company.id, connectionId: initial.id, actorType: "user", actorId: userId,
grantKind: "user", subjectId: userId, requestedScopes: readScopes };
if (bindingMode === "first-use") {
expect(observedClientRows).toHaveLength(2);
expect((observedClientRows[1].config.oauth as Record<string, unknown>).clientRedirectUri).toBe(redirectUri);
expect(observedClientRows[1].config.workspaceSetup).toEqual(expectedBinding);
}
const latest = await getConnectionRow();
expect(afterB!.config.workspaceSetup).toEqual(expectedBinding);
expect(latest.config.workspaceSetup).toEqual(expectedBinding);
expect(latest.transportConfig.workspaceSetup).toEqual(expectedBinding);
expect(latest.config.concurrentSetting).toBe("config-b");
expect(latest.transportConfig.transportOnlySetting).toBe("transport-b");
for (const config of [latest.config, latest.transportConfig]) {
expect((config.oauth as Record<string, unknown>).pendingWorkspaceServiceRequests).toEqual({ anotherUser: {
requestedScopes: googleWorkspaceSelectedScopes({ calendar: "read" }), requestedAt: "2026-10-30T16:00:00Z",
} });
}
for (const [started, expected] of [[startedA!, writeScopes], [startedB!, readScopes]] as const) {
const url = new URL(started.authorizationUrl);
expect(url.searchParams.get("scope")?.split(" ")).toEqual(expected);
const [state] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, url.searchParams.get("state")!));
expect(state.requestedScopes).toEqual(expected);
}
const cold = await makeStart()(company.id, initial.id, { redirectUri, actor, subjectUserId: userId });
const coldUrl = new URL(cold.authorizationUrl);
expect(coldUrl.searchParams.get("scope")?.split(" ")).toEqual(readScopes);
const [coldState] = await db.select().from(toolOauthStates).where(eq(toolOauthStates.state, coldUrl.searchParams.get("state")!));
expect(coldState.requestedScopes).toEqual(readScopes);
});
it.each((["clientId", "clientSecretRef", "clientIssuer", "clientResource", "clientRedirectUri", "issuer", "resource"] as const)
.flatMap(field => (["discovery", "client-resolution"] as const).map(stage => [field, stage] as const)))(
"rejects a concurrent %s change during Workspace %s", async (field, stage) => {
const company = await createCompany(db);
const actor = { actorType: "user" as const, actorId: "board" };
const service = createTestToolAccessService(db);
const connected = await service.connectGalleryApp(company.id, {
galleryKey: "google-workspace", connectionMethodKey: "customer-workspace-oauth", grantKind: "organization",
oauthClient: { clientId: "fixture-client", clientSecret: "fixture-secret" },
}, actor);
const getConnectionRow = async () => {
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
return row;
};
const endpoints = { provider: "google", authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token", scopes: googleWorkspaceSelectedScopes({ gmail: "read" }),
issuer: "https://accounts.google.com", resource: null };
const ensureClient = createOAuthClientRegistration(db, {
now: () => new Date(), options: {}, getConnectionRow, requestOAuthClientRegistration: vi.fn(),
store: { createOrRotateOAuthSecret: vi.fn(), syncCredentialBindings: vi.fn(),
oauthClientForConnection: async () => ({ clientId: "fixture-client", clientSecret: "fixture-secret", clientIdEnv: null, clientSecretEnv: null }) },
});
let changed: Awaited<ReturnType<typeof getConnectionRow>>;
const mutateClient = async () => {
const row = await getConnectionRow();
const updates = field === "clientSecretRef"
? { credentialSecretRefs: row.credentialSecretRefs.map(ref => ref.configPath === "oauth.client_secret" ? { ...ref, versionSelector: 1 } : ref) }
: {
config: { ...row.config, oauth: { ...(row.config.oauth as Record<string, unknown>), [field]: `changed-${field}` } },
transportConfig: { ...row.transportConfig, oauth: { ...(row.transportConfig.oauth as Record<string, unknown>), [field]: `changed-${field}` } },
};
if (field === "clientSecretRef") expect(updates.credentialSecretRefs).not.toEqual(row.credentialSecretRefs);
[changed] = await db.update(toolConnections).set(updates).where(eq(toolConnections.id, row.id)).returning();
};
const start = createOAuthAuthorizationStart(db, {
now: () => new Date(), getConnectionRow,
setupPolicy: createConnectionSetupPolicy(db), fixedPersonalIdentityForReconnect: createPersonalConnectionIdentity(db),
currentCloudConnector: () => null, vercelConnect: null,
oauthEndpointsForConnection: async () => { if (stage === "discovery") await mutateClient(); return endpoints; },
ensureOAuthClient: async input => { const resolved = await ensureClient(input); if (stage === "client-resolution") await mutateClient(); return resolved; },
assertOAuthEndpointUrl: (_kind, url) => String(url),
});
await expect(start(company.id, connected.connectionId, {
redirectUri: "https://paperclip.example.test/api/tools/oauth/callback", actor, workspaceServices: { gmail: "read" },
})).rejects.toMatchObject({ status: 409 });
const retained = await getConnectionRow();
expect(retained.config).toEqual(changed!.config);
expect(retained.transportConfig).toEqual(changed!.transportConfig);
expect(retained.credentialSecretRefs).toEqual(changed!.credentialSecretRefs);
},
);
it.each(["user", "organization"] as const)("preserves the %s Workspace request when account-page reconnect omits a selection", async (kind) => {
const company = await createCompany(db);
const service = createTestToolAccessService(db);
@@ -1,7 +1,7 @@
import { notifyIssueReviewState } from "../../issue-review-state-notifications.js";
import { vercelConnectHttpError, vercelCredentialFor, vercelConnectResourcesFor } from "../vercel-credentials.js";
import { credentialScope, managedConnectorProfile } from "./client-settings.js";
import { createOAuthClientRegistration } from "./client-registration.js";
import { assertOAuthClientBindingUnchanged, createOAuthClientRegistration } from "./client-registration.js";
import type { ActorInfo } from "../types.js";
import { createOAuthEndpointPolicy } from "./endpoint-policy.js";
import { createOAuthDiscovery } from "./discovery.js";
@@ -672,10 +672,13 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
});
}
const nextConfig = {
...connection.config,
oauth: {
...oauthConfig(connection),
await db.transaction(async tx => {
const [saved] = await tx.select().from(toolConnections).where(and(
eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId),
)).for("no key update");
if (!saved) throw notFound("Tool connection not found");
assertOAuthClientBindingUnchanged(connection, saved, endpoints, input.redirectUri);
const oauth = {
provider: endpoints.provider,
authorizationUrl: endpoints.authorizationUrl,
tokenUrl: endpoints.tokenUrl,
@@ -698,27 +701,29 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
// Persist the issuer and resource this authorization run is bound to.
// `iss` on the callback is validated against `expectedIssuer`, and
// refresh/reconnect/revoke reuse the same pair rather than re-deriving it.
issuer: endpoints.issuer ?? oauthConfig(connection).issuer ?? null,
issuer: endpoints.issuer ?? oauthConfig(saved).issuer ?? null,
expectedIssuer: endpoints.issuer ?? null,
resource:
endpoints.resource ?? oauthConfig(connection).resource ?? null,
endpoints.resource ?? oauthConfig(saved).resource ?? null,
clientIdMetadataDocumentSupported:
endpoints.clientIdMetadataDocumentSupported === true,
},
};
await db
.update(toolConnections)
.set({
};
const nextConfig = { ...saved.config, oauth: { ...oauthConfig(saved), ...oauth } };
const nextTransportConfig = { ...saved.transportConfig, oauth: { ...asRecord(saved.transportConfig.oauth), ...oauth } };
await tx
.update(toolConnections)
.set({
// A generic URL connection starts life as `authKind: none`. Once it has
// completed OAuth discovery and client resolution it is an OAuth
// connection, and refresh, reconnect, revoke and diagnostics must all
// treat it as one.
authKind: "oauth",
config: nextConfig,
transportConfig: nextConfig,
updatedAt: new Date(),
})
.where(eq(toolConnections.id, connection.id));
authKind: "oauth",
config: nextConfig,
transportConfig: nextTransportConfig,
updatedAt: new Date(),
})
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId)));
});
return {
connectionId: connection.id,
@@ -1,6 +1,6 @@
import type { ActorInfo } from "../types.js";
import { createOAuthClientProtocol } from "./client.js";
import { oauthConfig, sameOAuthIssuer } from "./metadata.js";
import { asRecord, oauthConfig, sameOAuthIssuer } from "./metadata.js";
import { resolveOAuthClientIdMetadataDocumentUrl } from "./client-metadata.js";
import type { OAuthProviderEndpoints, OAuthClientRegistrationSource } from "./types.js";
import { connectionMethodForConnection } from "../connection-methods.js";
@@ -8,7 +8,7 @@ import { and, eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { toolConnections } from "@paperclipai/db";
import type { AppDefinition } from "@paperclipai/shared";
import { notFound, unprocessable } from "../../../errors.js";
import { conflict, notFound, unprocessable } from "../../../errors.js";
import { type RemoteHttpEndpointLookup } from "../../remote-http-endpoint-guard.js";
import type { OAuthCredentialStore } from "./credential-store.js";
@@ -24,6 +24,34 @@ type RegistrationDependencies = {
requestOAuthClientRegistration: ReturnType<typeof createOAuthClientProtocol>["requestOAuthClientRegistration"];
};
export function assertOAuthClientBindingUnchanged(
expected: typeof toolConnections.$inferSelect,
current: typeof toolConnections.$inferSelect,
endpoints: OAuthProviderEndpoints,
redirectUri: string,
) {
const changedSetup = expected.config.sourceTemplateKey === "google-workspace" && expected.status === "draft"
&& (current.status !== "draft" || (["credentialPolicy", "credentialSource", "authKind", "transport", "createdByUserId"] as const)
.some(key => current[key] !== expected[key])
|| ["sourceTemplateKey", "connectionMethodKey"].some(key => current.config[key] !== expected.config[key]
|| current.transportConfig[key] !== expected.transportConfig[key]));
const bindings: Record<string, unknown> = {
clientRedirectUri: redirectUri, clientIssuer: endpoints.issuer ?? null,
clientResource: endpoints.resource ?? null, clientCompanyId: expected.companyId,
issuer: endpoints.issuer ?? null, resource: endpoints.resource ?? null,
};
const changedClient = expected.ownership !== current.ownership
|| JSON.stringify(oauthSecretRef(expected, "oauth.client_secret")) !== JSON.stringify(oauthSecretRef(current, "oauth.client_secret"))
|| (["config", "transportConfig"] as const).some(target => {
const before = asRecord(expected[target].oauth);
const after = asRecord(current[target].oauth);
return ["clientId", "clientRegistrationSource", "clientTokenEndpointAuthMethod"].some(key => before[key] !== after[key])
|| Object.entries(bindings).some(([key, value]) => before[key] !== after[key]
&& !(before[key] == null && (after[key] == null || after[key] === value)));
});
if (changedSetup || changedClient) throw conflict("Connection sign-in settings changed. Reload before continuing");
}
export function createOAuthClientRegistration(db: Db, { now, options, store, getConnectionRow, requestOAuthClientRegistration }: RegistrationDependencies) {
const { createOrRotateOAuthSecret, oauthClientForConnection, syncCredentialBindings } = store;
async function registerOAuthClient(input: {
@@ -300,46 +328,55 @@ async function stampOAuthClientBinding(
endpoints: OAuthProviderEndpoints,
redirectUri: string,
): Promise<typeof toolConnections.$inferSelect> {
const originalOAuth = oauthConfig(connection);
const oauth = reviewedOAuthClientBinding(connection, endpoints);
const nextBinding = {
clientRedirectUri: redirectUri,
clientIssuer:
typeof oauth.clientIssuer === "string" && oauth.clientIssuer
? oauth.clientIssuer
: (endpoints.issuer ?? null),
clientResource:
typeof oauth.clientResource === "string" && oauth.clientResource
? oauth.clientResource
: (endpoints.resource ?? null),
clientCompanyId:
typeof oauth.clientCompanyId === "string" && oauth.clientCompanyId
? oauth.clientCompanyId
: connection.companyId,
};
const unchanged = Object.entries(nextBinding).every(
([key, value]) => originalOAuth[key] === value,
);
if (unchanged) return connection;
const nextConfig = {
...connection.config,
oauth: { ...oauth, ...nextBinding },
};
const [updated] = await db
.update(toolConnections)
.set({
config: nextConfig,
transportConfig: nextConfig,
updatedAt: now(),
})
.where(
and(
eq(toolConnections.id, connection.id),
eq(toolConnections.companyId, connection.companyId),
),
)
.returning();
return updated ?? connection;
return db.transaction(async tx => {
const [saved] = await tx.select().from(toolConnections).where(and(
eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId),
)).for("no key update");
if (!saved) throw notFound("Tool connection not found");
assertOAuthClientBindingUnchanged(connection, saved, endpoints, redirectUri);
const originalOAuth = oauthConfig(saved);
const oauth = reviewedOAuthClientBinding(saved, endpoints);
const nextBinding = {
clientRedirectUri: redirectUri,
clientIssuer:
typeof oauth.clientIssuer === "string" && oauth.clientIssuer
? oauth.clientIssuer
: (endpoints.issuer ?? null),
clientResource:
typeof oauth.clientResource === "string" && oauth.clientResource
? oauth.clientResource
: (endpoints.resource ?? null),
clientCompanyId:
typeof oauth.clientCompanyId === "string" && oauth.clientCompanyId
? oauth.clientCompanyId
: saved.companyId,
};
const unchanged = Object.entries(nextBinding).every(
([key, value]) => originalOAuth[key] === value,
);
if (unchanged) return saved;
const nextConfig = {
...saved.config,
oauth: { ...oauth, ...nextBinding },
};
const nextTransportConfig = { ...saved.transportConfig, oauth: { ...asRecord(saved.transportConfig.oauth), ...nextBinding } };
const [updated] = await tx
.update(toolConnections)
.set({
config: nextConfig,
transportConfig: nextTransportConfig,
updatedAt: now(),
})
.where(
and(
eq(toolConnections.id, connection.id),
eq(toolConnections.companyId, connection.companyId),
),
)
.returning();
if (!updated) throw notFound("Tool connection not found");
return updated;
});
}
/**