Files
PaperClipAI/server/src/services/tool-access/oauth/client-settings.test.ts
T
DottaandClaude Opus 5.5 ba1b0585bc 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>
2026-11-23 18:41:15 +00:00

151 lines
7.4 KiB
TypeScript

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<string, unknown>): Connection {
return {
id: "connection-1",
companyId: "company-1",
transport: "mcp_remote",
config,
transportConfig: {},
credentialSecretRefs: [],
} as unknown as Connection;
}
const slack = (oauth: Record<string, unknown> = {}) =>
connection({ sourceTemplateKey: "slack", connectionMethodKey: "mcp-oauth", oauth });
const generic = (oauth: Record<string, unknown> = {}) =>
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());
});
});