diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index e601ab361cd..0f13b7fb742 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -2177,7 +2177,17 @@ registers a client on the fly and stores it on the connection: client. - Env-registered clients always win: when `PAPERCLIP_TOOL_OAUTH__CLIENT_ID/_SECRET` are configured, the - broker uses them (`customer` ownership) and skips registration. List both + broker uses them (`customer` ownership) and skips registration. The broker + sends an env client only to the method's `defaults.tokenEndpoint`, or, when + the method has none, to a token endpoint on the exact host of its fixed + `serverUrl`, `discoveryUrl`, `metadataUrl` or `authorizationEndpoint`. Set + `defaults.tokenEndpoint` when the vendor's token endpoint is on another host. + The method must list `customer` ownership. Box, Notion, PostHog, Sentry and + Xero rely on the same-host rule today: if their discovery returns a token + endpoint on another host, a deployment-wide client is refused until the + endpoint is pinned, and a client added to the connection always works. + `client-settings.test.ts` fails when a new customer method neither pins its + token endpoint nor joins that named list. List both `customer` and `dcr` in the method's `ownershipModes` when the vendor supports both. diff --git a/doc/connections/GENERIC-REMOTE-MCP.md b/doc/connections/GENERIC-REMOTE-MCP.md index 92fd6e805a4..05b1e226768 100644 --- a/doc/connections/GENERIC-REMOTE-MCP.md +++ b/doc/connections/GENERIC-REMOTE-MCP.md @@ -158,8 +158,10 @@ You never choose this; Paperclip resolves it and the wizard shows none of it. Recorded here for security review and diagnostics. In preference order: 1. **Deployment-preconfigured client.** `PAPERCLIP_TOOL_OAUTH__CLIENT_ID` - / `_SECRET`, or the unsuffixed `PAPERCLIP_TOOL_OAUTH_CLIENT_ID` / `_SECRET`. - Always wins when set. + / `_SECRET` and the unsuffixed `PAPERCLIP_TOOL_OAUTH_CLIENT_ID` / `_SECRET` + apply only to gallery apps, at the token endpoint their app definition + fixes. A pasted server never gets a deployment client. Add a client of your + own to the connection, or use CIMD or dynamic registration. 2. **Client ID Metadata Document (CIMD).** When the authorization server advertises `client_id_metadata_document_supported`, Paperclip presents the URL of its own published metadata document as the `client_id`. Nothing is diff --git a/packages/shared/src/app-definitions/asana.json b/packages/shared/src/app-definitions/asana.json index 4cc2859043a..42d051d84a5 100644 --- a/packages/shared/src/app-definitions/asana.json +++ b/packages/shared/src/app-definitions/asana.json @@ -55,6 +55,7 @@ "defaults": { "serverUrl": "https://mcp.asana.com/v2/mcp", "discoveryUrl": "https://mcp.asana.com/.well-known/oauth-protected-resource/v2", + "tokenEndpoint": "https://app.asana.com/-/oauth_token", "scopesHint": [ "default" ] diff --git a/packages/shared/src/app-definitions/railway.json b/packages/shared/src/app-definitions/railway.json index 96193b680a1..11cd0177e4a 100644 --- a/packages/shared/src/app-definitions/railway.json +++ b/packages/shared/src/app-definitions/railway.json @@ -33,7 +33,8 @@ ], "oauthAuthorizationParams": { "prompt": "consent" - } + }, + "tokenEndpoint": "https://backboard.railway.com/oauth/token" }, "guidanceMd": "Sign in to Railway and select the workspaces your agents may use. Paperclip adds direct service, deployment, and bounded log tools when Railway accepts the connection for API access. Container commands require the separate SSH setup on the connection. Project tokens are not supported by Railway's hosted connection.", "riskTier": "S4", diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index dd1cfc8b5e3..0827fd3cfc6 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1282,6 +1282,8 @@ export interface ConnectToolAppAuthChallenge { resource?: string | null; registrationSource?: ToolOAuthClientRegistrationSource | null; manualClientRequired?: boolean; + /** Plain-language reason shown with the client fields, when Paperclip has one. */ + manualClientReason?: string | null; } /** Public half of a key Paperclip holds for machine sign-in. Safe to show and share. */ diff --git a/scripts/ingest-app-definitions.mjs b/scripts/ingest-app-definitions.mjs index 05d997338f1..96af5ceb254 100644 --- a/scripts/ingest-app-definitions.mjs +++ b/scripts/ingest-app-definitions.mjs @@ -232,6 +232,7 @@ const apps = [ serverUrl: "https://mcp.railway.com", scopesHint: ["openid", "offline_access", "workspace:member"], oauthAuthorizationParams: { prompt: "consent" }, + tokenEndpoint: "https://backboard.railway.com/oauth/token", }, "S4", "Sign in to Railway and select the workspaces your agents may use. Paperclip adds direct service, deployment, and bounded log tools when Railway accepts the connection for API access. Container commands require the separate SSH setup on the connection. Project tokens are not supported by Railway's hosted connection.", @@ -1251,6 +1252,7 @@ const specialMethodsFor = (entry) => { defaults: { serverUrl: entry.serverUrl, discoveryUrl: "https://mcp.asana.com/.well-known/oauth-protected-resource/v2", + tokenEndpoint: "https://app.asana.com/-/oauth_token", scopesHint: ["default"], }, oauthClientSecretRequired: true, diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index 76c00292fc0..ae85753be94 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -2281,9 +2281,10 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { expect(fixture.requestsTo("/register")).toHaveLength(1); }); - it("prefers a deployment-preconfigured client over any registration", async () => { - const fixture = installMcpOAuthFixture({ auth: "oauth", cimd: true }); + it("never offers a deployment-wide client to a custom server", async () => { + installMcpOAuthFixture({ auth: "oauth", cimd: true }); vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); const company = await createCompany(db); const service = toolAccessService(db); @@ -2293,9 +2294,45 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { actor: { actorType: "user", actorId: "board-user" }, }); - expect(start.registrationSource).toBe("preconfigured"); - expect(new URL(start.authorizationUrl).searchParams.get("client_id")).toBe("preconfigured-client"); - expect(fixture.requestsTo("/register")).toHaveLength(0); + expect(start.registrationSource).not.toBe("preconfigured"); + expect(new URL(start.authorizationUrl).searchParams.get("client_id")).not.toBe("preconfigured-client"); + }); + + it("explains that a deployment-wide client cannot be used when a custom server has no other client", async () => { + installMcpOAuthFixture({ auth: "oauth", dcr: false }); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); + const company = await createCompany(db); + const service = toolAccessService(db); + + const connected = await service.connectGalleryApp(company.id, { link: MCP_URL, name: "Fixture refused deployment client" }); + await expect(service.startOAuth(company.id, connected.connectionId, { + redirectUri: REDIRECT_URI, + actor: { actorType: "user", actorId: "board-user" }, + })).rejects.toMatchObject({ details: { code: "oauth_manual_client_required", reason: expect.stringContaining("Add a client ID and secret") } }); + }); + + it("keeps the draft and asks for a client, with the reason, when a deployment-wide client cannot be used", async () => { + installMcpOAuthFixture({ auth: "oauth", dcr: false }); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "preconfigured-client"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "preconfigured-secret"); + const company = await createCompany(db); + const app = createRouteApp(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ link: MCP_URL, name: "Fixture refused deployment client" }) + .expect(201); + + expect(response.body.connectionId).toEqual(expect.any(String)); + expect(response.body.auth).toMatchObject({ + kind: "oauth", + startUrl: null, + manualClientRequired: true, + manualClientReason: expect.stringContaining("Add a client ID and secret"), + }); + await expect(db.select().from(toolConnections)).resolves.toHaveLength(1); }); it("asks for a preregistered client when the server offers neither CIMD nor DCR", async () => { diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 8aac435e157..dad5e4c1922 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -12017,14 +12017,6 @@ describeEmbeddedPostgres("tool access service", () => { // records discovery's universe as its scope set, a later refresh compares the provider's // response against the wider list and an asserted extra scope stops looking unrequested. it("keeps the narrowed request as the refresh baseline for a generic MCP connection", async () => { - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_NARROW_EXAMPLE_TEST_CLIENT_ID", - "narrow-client-id", - ); - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_NARROW_EXAMPLE_TEST_CLIENT_SECRET", - "narrow-client-secret", - ); const company = await createCompany(db); const userId = `narrow-scope-${randomUUID()}`; await grantBoardUser(db, company.id, userId, [], "owner"); @@ -12084,13 +12076,13 @@ describeEmbeddedPostgres("tool access service", () => { throw new Error(`unexpected fetch ${href}`); }); - const connection = await service.createConnection(company.id, connectionInput({ + const connected = await service.connectGalleryApp(company.id, { + link: "https://narrow.example.test/mcp", name: `Narrow generic ${randomUUID()}`, - transport: "mcp_remote", - config: { url: "https://narrow.example.test/mcp" }, - enabled: true, - status: "active", - })); + authMode: "oauth", + oauthClient: { clientId: "narrow-client-id", clientSecret: "narrow-client-secret" }, + }); + const connection = { id: connected.connectionId }; const started = await service.startOAuth(company.id, connection.id, { redirectUri: "https://paperclip.example/api/tools/oauth/callback", actor: { actorType: "user", actorId: userId }, @@ -15247,9 +15239,50 @@ describeEmbeddedPostgres("tool access service", () => { expect(fetchMock).not.toHaveBeenCalled(); }); - it("uses OAuth client credentials for shared machine-to-machine MCP connections", async () => { + it("sends a deployment OAuth client for a gallery app only to the token endpoint its definition pins", async () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "slack-deployment-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "slack-deployment-secret"); + const company = await createCompany(db); + const userId = `deployment-client-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, ["tools:use", "tools:manage_connections"]); + const service = createTestToolAccessService(db); + const connected = await service.connectGalleryApp(company.id, { galleryKey: "slack", name: "Deployment client" }, + { actorType: "user", actorId: userId }); + const started = await service.startOAuth(company.id, connected.connectionId, { + redirectUri: "https://paperclip.example/api/tools/oauth/callback", + actor: { actorType: "user", actorId: userId }, + }); + expect(new URL(started.authorizationUrl).searchParams.get("client_id")).toBe("slack-deployment-id"); + const tokenRequests: Array<{ url: string; clientId: string | null; clientSecret: string | null }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => { + const href = String(url); + if (href === "https://slack.com/api/oauth.v2.access") { + const body = new URLSearchParams(String(init?.body ?? "")); + tokenRequests.push({ url: href, clientId: body.get("client_id"), clientSecret: body.get("client_secret") }); + return { ok: true, status: 200, json: async () => ({ access_token: "deployment-access", refresh_token: "deployment-refresh", expires_in: 3600 }) } as Response; + } + if (href === "https://mcp.slack.com/mcp") { + const payload = JSON.parse(String(init?.body ?? "{}")) as { id?: string; method?: string }; + if (payload.method === "tools/list") return mcpHttpResponse({ jsonrpc: "2.0", id: payload.id, result: { tools: [] } }); + return mcpHttpResponse({ jsonrpc: "2.0", id: payload.id, result: { + protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "Slack test", version: "1.0.0" } } }); + } + throw new Error(`unexpected fetch ${href}`); + }); + await service.completeOAuthCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, + code: "deployment-authorization-code", + redirectUri: "https://paperclip.example/api/tools/oauth/callback", + actor: { actorType: "user", actorId: userId }, + }); + expect(tokenRequests).toEqual([{ url: "https://slack.com/api/oauth.v2.access", clientId: "slack-deployment-id", clientSecret: "slack-deployment-secret" }]); + }); + + it("never sends a deployment OAuth client to a machine-to-machine token endpoint of a custom server", async () => { vi.stubEnv("PAPERCLIP_TOOL_OAUTH_M2M_CLIENT_ID", "m2m-client-id"); vi.stubEnv("PAPERCLIP_TOOL_OAUTH_M2M_CLIENT_SECRET", "m2m-client-secret"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "generic-client-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "generic-client-secret"); const company = await createCompany(db); const service = createTestToolAccessService(db); const connection = await service.createConnection(company.id, connectionInput({ @@ -15267,63 +15300,22 @@ describeEmbeddedPostgres("tool access service", () => { enabled: true, status: "active", })); + const sentSecrets: string[] = []; const fetchMock = vi .spyOn(globalThis, "fetch") .mockImplementation(async (url, init) => { - const href = String(url); - if (href === "https://m2m.example.test/oauth/token") { - const body = init?.body as URLSearchParams; - expect(body.get("grant_type")).toBe("client_credentials"); - expect(body.get("client_id")).toBe("m2m-client-id"); - expect(body.get("client_secret")).toBe("m2m-client-secret"); - expect(body.get("scope")).toBe("tools.read"); - return { - ok: true, - json: async () => ({ - access_token: "m2m-access-token", - expires_in: 3600, - token_type: "Bearer", - }), - } as Response; - } - if (href === "https://m2m.example.test/mcp") { - expect(init?.headers).toEqual( - expect.objectContaining({ - Authorization: "Bearer m2m-access-token", - }), - ); - return mcpHttpResponse(catalogResponse([ - { name: "machine_read", annotations: { readOnlyHint: true } }, - ])); - } - throw new Error(`unexpected fetch ${href}`); + const body = init?.body instanceof URLSearchParams ? init.body : null; + if (body?.get("client_secret")) sentSecrets.push(body.get("client_secret")!); + throw new Error(`unexpected fetch ${String(url)}`); }); - const health = await service.checkHealth(connection.id, { + await service.checkHealth(connection.id, { actorType: "system", actorId: "health-check", - }); - expect(health.connection.healthStatus).toBe("ok"); - // Token request, the one-time MCP version probe, and the catalog listing. - expect(fetchMock).toHaveBeenCalledTimes(3); - const [updated] = await db - .select() - .from(toolConnections) - .where(eq(toolConnections.id, connection.id)); - expect(updated.credentialSecretRefs).toEqual([ - expect.objectContaining({ - configPath: "oauth.access_token", - label: "OAuth access token", - }), - ]); - expect(updated.credentialRefs).toEqual([ - expect.objectContaining({ - name: "oauth.access_token", - key: "Authorization", - prefix: "Bearer ", - }), - ]); - expect(JSON.stringify(updated.config)).not.toContain("m2m-access-token"); + }).catch(() => null); + + expect(fetchMock.mock.calls.map(([url]) => String(url))).not.toContain("https://m2m.example.test/oauth/token"); + expect(sentSecrets).toEqual([]); }); it.each(["catalog", "catalog/refresh", "health-check"])("returns reconnect instructions on %s for expired OAuth without a refresh token", async (path) => { @@ -17248,14 +17240,6 @@ describeEmbeddedPostgres("tool access service", () => { ); it("discovers OAuth for pasted MCP links and completes sign-in without a gallery entry", async () => { - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_GENERIC_EXAMPLE_TEST_CLIENT_ID", - "generic-client-id", - ); - vi.stubEnv( - "PAPERCLIP_TOOL_OAUTH_GENERIC_EXAMPLE_TEST_CLIENT_SECRET", - "generic-client-secret", - ); vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://paperclip.test"); const company = await createCompany(db); await grantBoardUser(db, company.id, "board-user", [ @@ -17318,6 +17302,8 @@ describeEmbeddedPostgres("tool access service", () => { .send({ link: "https://generic.example.test/mcp", name: "Generic OAuth MCP", + authMode: "oauth", + oauthClient: { clientId: "generic-client-id", clientSecret: "generic-client-secret" }, }); expect(connectRes.status).toBe(201); diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 4aed848a535..cc7058b729c 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -1063,9 +1063,14 @@ function connectorEnrollmentPrincipal(req: Request): string { // client they registered themselves. Report that instead of a 4xx so // the wizard can ask for it rather than losing the draft. const code = error instanceof HttpError ? String((error.details as { code?: unknown })?.code ?? "") : ""; - if (code !== "oauth_manual_client_required" && code !== "oauth_manual_client_rebinding_required") throw error; + if (code !== "oauth_manual_client_required" && code !== "oauth_manual_client_rebinding_required" + && code !== "oauth_instance_client_endpoint_mismatch") throw error; + const reason = (error as HttpError).details as { reason?: unknown } | undefined; result.auth.startUrl = null; result.auth.manualClientRequired = true; + result.auth.manualClientReason = typeof reason?.reason === "string" + ? reason.reason + : code === "oauth_instance_client_endpoint_mismatch" ? (error as HttpError).message : null; } } await logActivity(db, { diff --git a/server/src/services/tool-access/oauth/client-registration.ts b/server/src/services/tool-access/oauth/client-registration.ts index 92710807205..8850e04423c 100644 --- a/server/src/services/tool-access/oauth/client-registration.ts +++ b/server/src/services/tool-access/oauth/client-registration.ts @@ -13,7 +13,7 @@ import { type RemoteHttpEndpointLookup } from "../../remote-http-endpoint-guard. import type { OAuthCredentialStore } from "./credential-store.js"; import { singleFlight } from "../single-flight.js"; -import { configuredOAuthClientForConnection, oauthSecretRef } from "./client-settings.js"; +import { configuredOAuthClientForConnection, manualOAuthClientRequiredError, oauthSecretRef, refusedDeploymentClientError } from "./client-settings.js"; const oauthRegistrationFlights = new Map>(); type RegistrationDependencies = { @@ -421,6 +421,7 @@ function canRegisterOAuthClientDynamically( const configured = configuredOAuthClientForConnection( input.connection, input.endpoints.provider, + input.endpoints.tokenUrl, ); if (configured.clientId) { return { @@ -462,6 +463,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( bound, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: storedOAuthClientRegistrationSource(bound), @@ -488,6 +490,9 @@ function canRegisterOAuthClientDynamically( input.galleryEntry, ) ) { + if (refusedDeploymentClientError(input.endpoints.provider)) { + throw manualOAuthClientRequiredError(input.endpoints.provider, ""); + } throw unprocessable( `OAuth client id is not configured for ${input.endpoints.provider}`, { @@ -511,6 +516,7 @@ function canRegisterOAuthClientDynamically( const latestConfigured = configuredOAuthClientForConnection( latest, input.endpoints.provider, + input.endpoints.tokenUrl, ); if (latestConfigured.clientId) { return { @@ -537,6 +543,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( bound, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: storedOAuthClientRegistrationSource(bound), @@ -557,6 +564,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( adopted, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: "cimd" as const, @@ -564,9 +572,9 @@ function canRegisterOAuthClientDynamically( } // 4. Dynamic client registration. if (!input.endpoints.registrationUrl) { - throw unprocessable( + throw manualOAuthClientRequiredError( + input.endpoints.provider, "This server needs sign-in details you create yourself. Register Paperclip with the provider, then add the client ID and secret it gives you.", - { code: "oauth_manual_client_required" }, ); } const registered = await registerOAuthClient({ @@ -580,6 +588,7 @@ function canRegisterOAuthClientDynamically( client: await oauthClientForConnection( registered, input.endpoints.provider, + input.endpoints.tokenUrl, input.actor, ), source: "dcr" as const, diff --git a/server/src/services/tool-access/oauth/client-settings.test.ts b/server/src/services/tool-access/oauth/client-settings.test.ts new file mode 100644 index 00000000000..0998a32d556 --- /dev/null +++ b/server/src/services/tool-access/oauth/client-settings.test.ts @@ -0,0 +1,150 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { toolConnections } from "@paperclipai/db"; +import { APP_DEFINITIONS } from "@paperclipai/shared"; +import { configuredOAuthClientForConnection } from "./client-settings.js"; + +type Connection = typeof toolConnections.$inferSelect; + +function connection(config: Record): Connection { + return { + id: "connection-1", + companyId: "company-1", + transport: "mcp_remote", + config, + transportConfig: {}, + credentialSecretRefs: [], + } as unknown as Connection; +} + +const slack = (oauth: Record = {}) => + connection({ sourceTemplateKey: "slack", connectionMethodKey: "mcp-oauth", oauth }); +const generic = (oauth: Record = {}) => + connection({ url: "https://mcp.example.test/mcp", oauth }); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("instance OAuth clients", () => { + it("uses the instance client only at the token endpoint its app definition fixes", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + expect(configuredOAuthClientForConnection(slack(), "slack", "https://slack.com/api/oauth.v2.access")).toMatchObject({ + clientId: "instance-slack-id", + clientSecret: "instance-slack-secret", + }); + }); + + it.each([ + ["a different host", "https://attacker.example/token"], + ["a lookalike path on the vendor host", "https://slack.com/api/oauth.v2.access/../../collect"], + ["plain http on the vendor host", "http://slack.com/api/oauth.v2.access"], + ["a vendor subdomain", "https://evil.slack.com/api/oauth.v2.access"], + ["no token endpoint", null], + ])("never returns the instance secret for %s", (_label, tokenUrl) => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + const client = configuredOAuthClientForConnection(slack({ tokenUrl }), "slack", tokenUrl); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom connection the instance client of a provider it names", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + + const client = configuredOAuthClientForConnection( + generic({ provider: "slack", tokenUrl: "https://attacker.example/token" }), + "slack", + "https://attacker.example/token", + ); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom connection the unsuffixed instance client", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "instance-generic-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "instance-generic-secret"); + + const client = configuredOAuthClientForConnection(generic(), "mcp_example_test", "https://mcp.example.test/token"); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("never gives a custom server a host-named instance client, even at that host", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_MCP_EXAMPLE_TEST_CLIENT_ID", "instance-host-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_MCP_EXAMPLE_TEST_CLIENT_SECRET", "instance-host-secret"); + + expect(configuredOAuthClientForConnection(generic(), "mcp_example_test", "https://mcp.example.test/oauth/token").clientId).toBeNull(); + const lookalike = connection({ url: "https://mcp-example.test/mcp", oauth: {} }); + expect(configuredOAuthClientForConnection(lookalike, "mcp_example_test", "https://mcp-example.test/oauth/token").clientId).toBeNull(); + }); + + it.each(["", " ", " slack"])("never treats the gallery marker %j as an app definition", (marker) => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "instance-generic-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "instance-generic-secret"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret"); + const marked = connection({ sourceTemplateKey: marker, url: "https://attacker.example/mcp", oauth: {} }); + + for (const provider of [marker, "slack", "attacker_example"]) { + const client = configuredOAuthClientForConnection(marked, provider, "https://attacker.example/token"); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + } + expect(configuredOAuthClientForConnection(marked, "slack", "https://slack.com/api/oauth.v2.access").clientId).toBeNull(); + }); + + it("never uses one app's instance client for a connection that claims another provider", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_GMAIL_CLIENT_ID", "instance-gmail-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_GMAIL_CLIENT_SECRET", "instance-gmail-secret"); + + const client = configuredOAuthClientForConnection( + slack({ provider: "gmail" }), + "gmail", + "https://oauth2.googleapis.com/token", + ); + expect(client.clientId).toBeNull(); + expect(client.clientSecret).toBeNull(); + }); + + it("allows a discovered token endpoint only on a host the definition fixes when it fixes no token endpoint", () => { + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_NOTION_CLIENT_ID", "instance-notion-id"); + vi.stubEnv("PAPERCLIP_TOOL_OAUTH_NOTION_CLIENT_SECRET", "instance-notion-secret"); + const notion = connection({ sourceTemplateKey: "notion", connectionMethodKey: "mcp-oauth" }); + + expect(configuredOAuthClientForConnection(notion, "notion", "https://mcp.notion.com/token").clientId).toBe("instance-notion-id"); + for (const tokenUrl of [ + "https://api.notion.com/v1/oauth/token", + "https://evil.notion.com/token", + "https://mcp.notion.com:8443/token", + "https://attacker.example/token", + ]) { + expect(configuredOAuthClientForConnection(notion, "notion", tokenUrl).clientId).toBeNull(); + } + }); + + it.each([ + ["asana", "mcp-own-oauth", "https://app.asana.com/-/oauth_token"], + ["railway", "mcp-oauth", "https://backboard.railway.com/oauth/token"], + ])("allows the token endpoint that the %s definition pins", (slug, methodKey, tokenUrl) => { + vi.stubEnv(`PAPERCLIP_TOOL_OAUTH_${slug.toUpperCase()}_CLIENT_ID`, "instance-id"); + vi.stubEnv(`PAPERCLIP_TOOL_OAUTH_${slug.toUpperCase()}_CLIENT_SECRET`, "instance-secret"); + const pinned = connection({ sourceTemplateKey: slug, connectionMethodKey: methodKey }); + + expect(configuredOAuthClientForConnection(pinned, slug, tokenUrl).clientId).toBe("instance-id"); + expect(configuredOAuthClientForConnection(pinned, slug, "https://attacker.example/token").clientId).toBeNull(); + }); + + it("makes every customer OAuth method pin its token endpoint or name its same-host fallback", () => { + const sameHostFallback = new Set(["box:mcp-own-oauth", "notion:mcp-oauth", "posthog:mcp-oauth", "sentry:mcp-oauth", "xero:mcp-own-oauth"]); + const noFixedEndpoint = new Set(["oauth-generic:oauth"]); + const unpinned = APP_DEFINITIONS.flatMap((app) => app.methods + .filter((method) => method.auth === "oauth" && !method.oauthStrategy && method.ownershipModes.includes("customer") + && method.purpose !== "ai" && method.transport !== "runtime_auth" && !method.defaults?.tokenEndpoint) + .map((method) => `${app.slug}:${method.key}`)); + expect(unpinned.sort()).toEqual([...sameHostFallback, ...noFixedEndpoint].sort()); + }); +}); diff --git a/server/src/services/tool-access/oauth/client-settings.ts b/server/src/services/tool-access/oauth/client-settings.ts index b9f5f2aab69..3a7ed566909 100644 --- a/server/src/services/tool-access/oauth/client-settings.ts +++ b/server/src/services/tool-access/oauth/client-settings.ts @@ -37,9 +37,65 @@ export function oauthClientConfig(provider: string) { }; } +function httpsUrl(value: string | null | undefined): URL | null { + if (!value) return null; + try { + const url = new URL(value); + return url.protocol === "https:" && !url.username && !url.password ? url : null; + } catch { + return null; + } +} + +function instanceClientTokenUrlAllowed( + connection: typeof toolConnections.$inferSelect, + provider: string, + tokenUrl: string | null | undefined, +): boolean { + const target = httpsUrl(tokenUrl); + if (!target) return false; + const sourceTemplateKey = connection.config.sourceTemplateKey; + if (typeof sourceTemplateKey !== "string" || !sourceTemplateKey || provider !== sourceTemplateKey) return false; + const app = getConnectableAppDefinition(sourceTemplateKey); + if (!app) return false; + let method: ReturnType; + try { + method = connectionMethodForConnection(app, connection); + } catch { + return false; + } + if (method.auth !== "oauth" || !method.ownershipModes.includes("customer")) return false; + const defaults = method.defaults ?? {}; + if (defaults.tokenEndpoint) { + return httpsUrl(defaults.tokenEndpoint)?.href === target.href; + } + const fixedHosts = [defaults.serverUrl, defaults.discoveryUrl, defaults.metadataUrl, defaults.authorizationEndpoint] + .map((value) => httpsUrl(value)) + .filter((url): url is URL => url !== null) + .map((url) => url.host.toLowerCase()); + return fixedHosts.includes(target.host.toLowerCase()); +} + +const REFUSED_DEPLOYMENT_CLIENT_MESSAGE = + "The sign-in app set up for this Paperclip server can only be used with the app it was set up for. Add a client ID and secret for this server to the connection, then sign in again."; + +export function refusedDeploymentClientError(provider: string) { + if (!oauthClientConfig(provider).clientId) return null; + return unprocessable(REFUSED_DEPLOYMENT_CLIENT_MESSAGE, { code: "oauth_instance_client_endpoint_mismatch" }); +} + +export function manualOAuthClientRequiredError(provider: string, message: string) { + const refused = Boolean(oauthClientConfig(provider).clientId); + return unprocessable(refused ? REFUSED_DEPLOYMENT_CLIENT_MESSAGE : message, { + code: "oauth_manual_client_required", + ...(refused ? { reason: REFUSED_DEPLOYMENT_CLIENT_MESSAGE } : {}), + }); +} + export function configuredOAuthClientForConnection( connection: typeof toolConnections.$inferSelect, provider: string, + tokenUrl: string | null | undefined, ) { if (isSmokeLabOAuthFixture(connection) && provider === "smoke_lab") { return { @@ -49,7 +105,10 @@ export function configuredOAuthClientForConnection( clientSecret: null, }; } - return oauthClientConfig(provider); + const configured = oauthClientConfig(provider); + return instanceClientTokenUrlAllowed(connection, provider, tokenUrl) + ? configured + : { ...configured, clientId: null, clientSecret: null }; } export function credentialScope( diff --git a/server/src/services/tool-access/oauth/connection-refresh.ts b/server/src/services/tool-access/oauth/connection-refresh.ts index c67de010179..c646940da72 100644 --- a/server/src/services/tool-access/oauth/connection-refresh.ts +++ b/server/src/services/tool-access/oauth/connection-refresh.ts @@ -148,6 +148,7 @@ const oauthRefreshFlights = new Map>(); const client = machineSignIn ? null : await oauthClientForConnection( connection, oauth.provider, + oauth.tokenUrl, actor, ); if (client && !client.clientId) diff --git a/server/src/services/tool-access/oauth/credential-store.ts b/server/src/services/tool-access/oauth/credential-store.ts index 872abd2f364..d424230ecda 100644 --- a/server/src/services/tool-access/oauth/credential-store.ts +++ b/server/src/services/tool-access/oauth/credential-store.ts @@ -6,11 +6,11 @@ import { and, eq, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionGrants, toolConnections } from "@paperclipai/db"; import type { ToolConnection, ToolCredentialSecretRef } from "@paperclipai/shared"; -import { notFound } from "../../../errors.js"; +import { notFound, unprocessable } from "../../../errors.js"; import { secretService } from "../../secrets.js"; import { resolveConnectionGrantSecret, writeConnectionCredential } from "../../connection-credentials.js"; -import { configuredOAuthClientForConnection, oauthSecretRef } from "./client-settings.js"; +import { configuredOAuthClientForConnection, oauthSecretRef, refusedDeploymentClientError } from "./client-settings.js"; export function actorForSecret( actor?: ActorInfo, ): { userId?: string | null; agentId?: string | null } | undefined { @@ -58,16 +58,21 @@ async function syncCredentialBindings( async function oauthClientForConnection( connection: typeof toolConnections.$inferSelect, provider: string, + tokenUrl: string | null | undefined, actor?: ActorInfo, ) { - const configured = configuredOAuthClientForConnection(connection, provider); + const configured = configuredOAuthClientForConnection(connection, provider, tokenUrl); if (configured.clientId) return configured; const oauth = oauthConfig(connection); const clientId = typeof oauth.clientId === "string" && oauth.clientId.trim() ? oauth.clientId.trim() : null; - if (!clientId) return configured; + if (!clientId) { + const refused = refusedDeploymentClientError(provider); + if (refused) throw refused; + return configured; + } // CIMD clients and public DCR clients have no token-endpoint secret. A DCR // authorization server may instead issue a confidential client (for // example, `client_secret_basic`); in that case the registration secret is diff --git a/server/src/services/tool-access/oauth/direct-callback.ts b/server/src/services/tool-access/oauth/direct-callback.ts index 17404dc6002..728a4d10087 100644 --- a/server/src/services/tool-access/oauth/direct-callback.ts +++ b/server/src/services/tool-access/oauth/direct-callback.ts @@ -134,6 +134,7 @@ export function createDirectOAuthCallback(db: Db, dependencies: Dependencies) { const client = await oauthClientForConnection( connection, endpoints.provider, + endpoints.tokenUrl, input.actor, ); if (!client.clientId) diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index b811431f04c..3f3981411bc 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -306,6 +306,7 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo const client = await oauthClientForConnection( connection, oauthProvider, + oauthTokenUrl, credentialActor, ); if (!client.clientId) diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index b8997d084a3..f5711f2796e 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -85,7 +85,7 @@ "packages/shared/src/app-definitions/anthropic.json": "6c7cd96eefb4db6dca244fcddeb1c4a585a2af14", "packages/shared/src/app-definitions/api-key-generic.json": "09e6d4295513ac9f1002eaf37c34e7c2d00a3c05", "packages/shared/src/app-definitions/arcade.json": "c8379450055d4ea226d229b1cbf99c7ed2e52beb", - "packages/shared/src/app-definitions/asana.json": "4cc2859043a30037fd5cdc3ebd0909938b9344a8", + "packages/shared/src/app-definitions/asana.json": "42d051d84a576509d75a73fe49b23443d34759f8", "packages/shared/src/app-definitions/aws.json": "f6413552f37f06e3b003486324c7d892d8f3e5f3", "packages/shared/src/app-definitions/bedrock.json": "962d8a722ac6e2e4db00abc34f71947a3fdb733a", "packages/shared/src/app-definitions/beehiiv.json": "47aec8fdfbf5aed0919b6ac9bddb435de4988db3", @@ -162,7 +162,7 @@ "packages/shared/src/app-definitions/planetscale.json": "96d64734ee4b5b918461c6169ce97e9027bdfdc1", "packages/shared/src/app-definitions/posthog.json": "6042a291a24354e3eaba2ca283ec59c9cc7a258e", "packages/shared/src/app-definitions/postman.json": "bcee846eabd7d8592342324b2f6c0a825a912e3f", - "packages/shared/src/app-definitions/railway.json": "96193b680a11a41e1fa34fd5c96233b70c608ed8", + "packages/shared/src/app-definitions/railway.json": "11cd0177e4aac114875ebf8f70f48eb08596e9f5", "packages/shared/src/app-definitions/razorpay.json": "e2abe5d6f56864c2dae26b34c738c175307339d5", "packages/shared/src/app-definitions/resend.json": "38f7595265f9ff6afdc84b9bce18602cd2c6ebfa", "packages/shared/src/app-definitions/responses-api.json": "29ad92e4c41a0dc0e3a3b07f518200bdc8e2e6ff", @@ -456,7 +456,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "dd1cfc8b5e36f3ec572890022625402fe3fb637e", + "packages/shared/src/types/tool-access.ts": "0827fd3cfc63431077aef0cedc42bc7709957f57", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index c45cd32ec05..e4a81a937a1 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -1672,7 +1672,8 @@ function StandardConnectionSetupFlow({ if (result.auth.manualClientRequired) { oauthPopupRef.current?.close(); oauthPopupRef.current = null; - setLinkGuidance(genericConnectGuidance("oauth_manual_client_required", null)); + const guidance = genericConnectGuidance("oauth_manual_client_required", null); + setLinkGuidance(result.auth.manualClientReason ? { ...guidance, body: result.auth.manualClientReason } : guidance); setLinkAuthMode("oauth"); setLinkAdvancedOpen(true); setGenericOAuthPending(false); diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index ea1af85bb4b..b2c74ff24f9 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -5118,6 +5118,30 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => { expect(navigateTopLevelMock).not.toHaveBeenCalled(); }); + it("shows why a client is needed when the deployment's sign-in app cannot be used", async () => { + const reason = "The sign-in app set up for this Paperclip server can only be used with the app it was set up for. Add a client ID and secret for this server to the connection, then sign in again."; + connectAppMock.mockResolvedValue({ + connectionId: "conn-1", + application: { id: "app-1", name: "mcp.example.test" }, + actions: { readOnly: [], canMakeChanges: [] }, + catalog: [], + suggestedDefaults: {}, + auth: { kind: "oauth", startUrl: null, manualClientRequired: true, manualClientReason: reason }, + }); + await render(); + await gotoLinkFrame(container, "https://mcp.example.test/mcp"); + await act(async () => { + buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + await flushReact(); + await flushReact(); + + expect(container.textContent).toContain(reason); + expect(container.textContent).toContain("Client ID"); + expect(container.textContent).toContain("Client secret"); + expect(navigateTopLevelMock).not.toHaveBeenCalled(); + }); + it("submits custom headers as secret-backed credential values", async () => { await render(); await gotoLinkFrame(container, "https://mcp.example.test/mcp"); diff --git a/ui/src/pages/tools/PasteConfigTab.tsx b/ui/src/pages/tools/PasteConfigTab.tsx index 5085183ad19..037dcef9a13 100644 --- a/ui/src/pages/tools/PasteConfigTab.tsx +++ b/ui/src/pages/tools/PasteConfigTab.tsx @@ -205,7 +205,8 @@ export function PasteConfigTab({ companyId }: { companyId: string }) { authorization.cancel(); setOAuthPhase("error"); setOAuthError( - "This server requires OAuth client details from its provider settings. Continue in setup to add them.", + result.auth.manualClientReason + ?? "This server requires OAuth client details from its provider settings. Continue in setup to add them.", ); return; }