fix(server): send deployment OAuth client secrets only to the token endpoint they are configured for (#22649)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - App connections sign in with OAuth, and an operator can set a
deployment-wide OAuth client with `PAPERCLIP_TOOL_OAUTH_*` variables
> - The server picked that client by a provider name, and a connection's
own settings could set both the provider name and the token URL
> - So a deployment client secret could go to a token URL that the
deployment did not choose
> - A deployment secret must go only to the endpoint of the app it was
set up for
> - This pull request pins each deployment client to the token endpoint
that its app definition fixes, and fails closed for any other endpoint
> - The benefit is that member-entered or custom endpoints get only a
member-entered client

## Linked Issues or Issue Description

Refs #22635

**What happened?**
`configuredOAuthClientForConnection` returned the deployment client for
any connection whose provider name matched, or the unsuffixed client for
any connection. The token exchange then sent that client secret to the
connection's token URL.

**What did you expect to happen?**
A deployment client goes only to the token endpoint that its app
definition fixes. A custom endpoint needs a client that the member adds.

**Steps to reproduce**
Set a provider-specific deployment client. Create a custom connection
that names that provider and a different token URL, and start sign-in.
The new unit tests cover this case.

**Impact**
Secret-handling hardening for deployment OAuth clients.

## What Changed

- `configuredOAuthClientForConnection` now takes the token URL that the
caller will post to. It returns a deployment client only when the
connection comes from a real app definition, the provider is that app,
the method lists `customer` ownership, and the token URL equals the
method's `defaults.tokenEndpoint` (or, when the method fixes no token
endpoint, is on the exact host of its fixed server, discovery, metadata
or authorization URL).
- A pasted (custom) server never gets a deployment client, including the
unsuffixed one. It needs a client of its own, or CIMD or dynamic
registration.
- The token URL is required at every call site: start, callback,
connection refresh and grant refresh.
- When a deployment client exists but the endpoint does not match, and
the connection has no client of its own, sign-in fails with
`oauth_instance_client_endpoint_mismatch` and a clear message.
- Pin `defaults.tokenEndpoint` in the Asana and Railway definitions,
whose token endpoints are on another host than their MCP servers.
- Update `doc/connections/GENERIC-REMOTE-MCP.md` and
`doc/connections/CONNECTOR-PLAYBOOK.md`.

## Verification

- New `server/src/services/tool-access/oauth/client-settings.test.ts`
(16 tests): other hosts, a path that resolves elsewhere, plain HTTP,
vendor subdomains, another port, a missing URL, empty or padded gallery
markers, colliding host names, a custom connection that names a
provider, the unsuffixed client on a custom connection, and a connection
that names another app's provider all get no deployment client. Slack's
fixed endpoint, Notion's server host and the pinned Asana and Railway
endpoints still get it. These cases failed before the fix and pass now.
- `server/src/__tests__/generic-mcp-connection.test.ts` and the
machine-to-machine test in `tool-access-service.test.ts` now check that
a pasted server never receives the deployment client or secret. Both
failed before the fix. Two other pasted-server tests now use a client of
their own.
- A positive test sends the Slack deployment client to Slack's pinned
token endpoint, with its secret, and nowhere else.
- The connect route keeps the draft and returns `manualClientRequired`
with a plain reason when a deployment client cannot be used (route and
UI tests).
- `npx vitest run` on the OAuth service and connection tests: 686 tests
pass. Shared app-definition tests pass. `tsc --noEmit` for `server`
passes.
- `pnpm verify` exits 2 because a global CI input (a doc) changed.
Required CI gives the broad coverage.

## Risks

- A self-hosted deployment that used `PAPERCLIP_TOOL_OAUTH_*` for a
pasted server must add a client to that connection. Sign-in shows a
clear error instead of sending the secret.
- A gallery app with `customer` ownership whose token endpoint is on
another host than its fixed URLs needs `defaults.tokenEndpoint` to keep
using a deployment client. Asana and Railway are pinned here. Box,
Notion, PostHog, Sentry and Xero rely on the same-host rule: 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. A test lists these apps by name, so a new
app must choose. Gallery apps with a fixed token endpoint (Slack,
Linear, Google) do not change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, 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-23 18:41:15 +00:00
1 parent 7b4f4c81e0
commit ba1b0585bc
20 files changed
+394 -96

No files matched your search

@@ -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 () => {
@@ -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);