From 491dfa1c6d5fa26952cc8a09ef3a2f9927720d2b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:31:43 -0600 Subject: [PATCH] fix(tool-gateway): make gateway client token creation person-only (#20581) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Tool gateways let external MCP clients use a company's tools with a gateway client token > - A gateway client token is shown only once, to the caller that creates it > - Since delegated connection management (#17737), an agent can create a gateway client token for its responsible person > - In that case the agent receives the one-time token value, and it can repeat the value in chat > - This pull request makes gateway client token creation person-only > - The benefit is that the one-time token value goes only to the person who creates it in the gateway UI ## Linked Issues or Issue Description Refs #17737 **What happened** A person asked the CEO agent in chat to replace the token of a gateway client. The agent called `POST /api/tool-gateway/gateways/{gatewayId}/tokens` under delegated authority. The response gave the agent the new token value, and the agent put the value in its chat reply. **Expected behavior** An agent does not receive a gateway client token value. A person creates the token on the gateway's Tokens page and gives it to the client. The agent tells the person where to do this. **Steps to reproduce** 1. Give an agent delegated connection management for a responsible person with `tools:admin`. 2. As the agent, call `POST /api/tool-gateway/gateways/{gatewayId}/tokens` (for example through `call_api`). 3. See a 201 response that contains the new token value. ## What Changed - `POST /api/tool-gateway/gateways/:gatewayId/tokens` returns 403 `gateway_token_requires_person` to agent callers before it creates a token. The message is final. It gives the Tokens page path (`//apps/gateways//tokens`) and tells the agent not to ask for or repeat token values. The response also has `tokensPath`. - Board (person) callers are not changed. - The API catalog entry for the route now says that it is person-only. - Existing agent-issued tokens are not changed. Runtime issuer and responsible-user checks still apply to them. The integration tests now seed such tokens directly to keep that coverage. ## Verification - Red: the new integration test `never returns gateway client token plaintext to agent callers` fails on `master` (the agent `call_api` result is 201 with the token value). - Green: `cd server && npx vitest run src/__tests__/connection-management.integration.test.ts -t gateway` (24 passed). The test also checks that no token row is created for the agent, and that a person session still gets a 201 with the token. - `npx vitest run src/__tests__/tool-gateway.test.ts src/__tests__/openapi-routes.test.ts` (152 passed). - `npx vitest run src/services/native-runtime/runner-api.test.ts` (2090 passed). - `tsc --noEmit -p server`: no errors in the changed files. ## Risks - Behavior change: agents can no longer create gateway client tokens. A workflow that relied on that now gets a 403 that sends the person to the Tokens page. Agents can still revoke tokens and manage gateways under delegated authority. - Low migration risk: no schema change, and existing tokens keep working. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code execution in Claude Code. ## 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 --- .../connection-management.integration.test.ts | 50 +++++++++++++------ server/src/routes/openapi.ts | 1 + server/src/routes/tool-gateway.ts | 15 +++++- 3 files changed, 50 insertions(+), 16 deletions(-) diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index aadbab09c64..54467c59edf 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -1,7 +1,7 @@ import { createToolGatewayService } from "../services/tool-gateway.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared"; -import { randomUUID, generateKeyPairSync } from "node:crypto"; +import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto"; import { join } from "node:path"; import { createServer } from "node:http"; import { and, eq, sql } from "drizzle-orm"; @@ -1536,26 +1536,46 @@ describe("connection management with production default agents", () => { } }); - it("keeps durable gateway client tokens bound to the issuer and responsible user", async () => { + // Tokens issued by agents before client-token minting became person-only + // remain valid until revoked, so runtime enforcement still covers them. + async function legacyAgentIssuedGatewayToken(f: Awaited>, gatewayId: string, name: string) { + const id = randomUUID(), token = `pcgw_${id}.${randomBytes(32).toString("base64url")}`; + const [row] = await server.db.insert(toolMcpGatewayTokens).values({ id, companyId: f.companyId, gatewayId, name, tokenHash: createHash("sha256").update(token).digest("hex"), + tokenPrefix: `pcgw_${id.slice(0, 8)}`, subjectType: "gateway_client", clientLabel: "fixture", allowedActions: ["tools/list", "tools/call", "resources/list", "resources/read", "prompts/list", "prompts/get"], + responsibleUserId: f.userId, createdByAgentId: f.agentId }).returning(); + return { status: 201, body: { ...row, token } }; + } + + it("never returns gateway client token plaintext to agent callers", async () => { const f = await fixture(); const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] }); expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 }); const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id }); expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 }); + const body = { companyId: f.companyId, name: "Fixture client", clientLabel: "fixture", expiresAt: new Date(Date.now() + 3600000).toISOString() }; const call = { tool: "call_api", callId: "gateway-client-secret", arguments: { - operationId: "POST /api/tool-gateway/gateways/{gatewayId}/tokens", pathParams: { gatewayId: gateway.body.id }, - body: { companyId: f.companyId, name: "Fixture client", clientLabel: "fixture", expiresAt: new Date(Date.now() + 3600000).toISOString() }, + operationId: "POST /api/tool-gateway/gateways/{gatewayId}/tokens", pathParams: { gatewayId: gateway.body.id }, body, } }; - const issued = await f.authority.execute(call) as { status: number; data: { id: string; token: string } }; - expect(issued, JSON.stringify(issued)).toMatchObject({ status: 201, data: { token: expect.any(String), responsibleUserId: f.userId } }); - expect(await f.authority.execute(call)).toEqual(issued); - const token = { status: issued.status, body: issued.data }; - const [receiptRun] = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); - expect(JSON.stringify(receiptRun.resultJson)).not.toContain(token.body.token); - const receipts = (receiptRun.resultJson as { apiToolReceipts: Record }).apiToolReceipts; - expect(Object.values(receipts).find(receipt => receipt.operationId === call.arguments.operationId)).toHaveProperty("encryptedResult"); - expect(JSON.stringify(redactRunnerApiPayloads(issued))).not.toContain(token.body.token); - expect(await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.gatewayId, gateway.body.id))).toHaveLength(1); + const [company] = await server.db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, f.companyId)); + const tokensPath = `/${company.issuePrefix}/apps/gateways/${gateway.body.id}/tokens`; + const denied = await f.authority.execute(call) as { status: number; data: Record }; + expect(denied, JSON.stringify(denied)).toMatchObject({ status: 403, data: { reasonCode: "gateway_token_requires_person", tokensPath } }); + expect(JSON.stringify(denied)).not.toMatch(/pcgw_/); + expect(await f.request("POST", `/tool-gateway/gateways/${gateway.body.id}/tokens`, body)).toMatchObject({ status: 403, body: { reasonCode: "gateway_token_requires_person" } }); + expect(await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.gatewayId, gateway.body.id))).toHaveLength(0); + const cookie = await server.humanSession(f.userId); + const personal = await fetch(`${server.apiUrl}/api/tool-gateway/gateways/${gateway.body.id}/tokens`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify(body) }); + expect(personal.status).toBe(201); + expect(await personal.json()).toMatchObject({ token: expect.stringMatching(/^pcgw_/), createdByUserId: f.userId, createdByAgentId: null }); + }); + + it("keeps durable agent-issued gateway client tokens bound to the issuer and responsible user", async () => { + const f = await fixture(); + const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] }); + expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 }); + const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id }); + expect(gateway, JSON.stringify(gateway)).toMatchObject({ status: 201 }); + const token = await legacyAgentIssuedGatewayToken(f, gateway.body.id, "Fixture client"); const [saved] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id)); expect(saved).toMatchObject({ createdByAgentId: f.agentId, responsibleUserId: f.userId, subjectType: "gateway_client" }); const use = () => f.request("POST", `/mcp/gateways/${gateway.body.gatewayPublicId}`, { jsonrpc: "2.0", id: 1, method: "tools/list" }, token.body.token); @@ -1617,7 +1637,7 @@ describe("connection management with production default agents", () => { const token = mode === "ask-board" ? await (async () => { const response = await fetch(`${server.apiUrl}/api/tool-gateway/gateways/${gateway.body.id}/tokens`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify(tokenBody) }); return { status: response.status, body: await response.json() }; - })() : await f.request("POST", `/tool-gateway/gateways/${gateway.body.id}/tokens`, tokenBody); + })() : await legacyAgentIssuedGatewayToken(f, gateway.body.id, tokenBody.name); expect(token, JSON.stringify(token)).toMatchObject({ status: 201 }); const path = `/mcp/gateways/${gateway.body.gatewayPublicId}`; const rpc = (method: string, params?: unknown) => f.request("POST", path, { jsonrpc: "2.0", id: randomUUID(), method, ...(params ? { params } : {}) }, token.body.token); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 796d49c7e3f..2e4689bfe53 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -12886,6 +12886,7 @@ registerCurrentRoute({ path: "/api/tool-gateway/gateways/{gatewayId}/tokens", tags: ["tool-gateway"], summary: "Create a named MCP gateway token", + description: "Person-only. Returns the new token's plaintext exactly once to the creator. Agent callers receive 403 gateway_token_requires_person with the gateway's Tokens page path, where a person creates the token and hands it to the client.", body: toolGatewayCompanyBodySchema, responses: { 201: r.ok(), diff --git a/server/src/routes/tool-gateway.ts b/server/src/routes/tool-gateway.ts index 45d647e2245..9e392880de1 100644 --- a/server/src/routes/tool-gateway.ts +++ b/server/src/routes/tool-gateway.ts @@ -2,7 +2,7 @@ import { filterConnectionManagementRows, connectionManagementGuard, connectionRe import { Router, type Request, type Response } from "express"; import { and, desc, eq, gte, ilike, inArray, lt, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { agents, toolApplications, toolCallEvents, toolConnections, toolInvocations, toolRuntimeSlots } from "@paperclipai/db"; +import { agents, companies, toolApplications, toolCallEvents, toolConnections, toolInvocations, toolRuntimeSlots } from "@paperclipai/db"; import { humanizeConnectionDisplayName, type PermissionKey, @@ -437,6 +437,19 @@ export function toolGatewayRoutes(db: Db, toolGateway: ToolGatewayService) { return; } await assertBoardPermission(req, companyId, "tools:admin"); + if (req.actor.type === "agent") { + // The plaintext is shown exactly once. An agent caller would receive it + // in its tool result and could repeat it in chat, so only a person + // creates client tokens, from the gateway's Tokens page. + const [company] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId)).limit(1); + const tokensPath = company ? `/${company.issuePrefix}/apps/gateways/${req.params.gatewayId as string}/tokens` : null; + throw new ToolGatewayHttpError(403, + "Final: agents cannot create gateway client tokens, because the token is shown only once to whoever creates it. " + + `A person with gateway access must create the replacement on the gateway's Tokens page${tokensPath ? ` (${tokensPath})` : ""}, give it to the client, and revoke the old token after the client works. ` + + "Do not ask for or repeat token values in chat.", + "gateway_token_requires_person", + tokensPath ? { tokensPath } : {}); + } const parsed = createToolMcpGatewayTokenSchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(422).json({ error: "Invalid gateway token payload", issues: parsed.error.issues });