fix(tool-gateway): let agents create gateway tokens without receiving the value (#20613)

## 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
> - Since delegated connection management (#17737), an agent can create
and revoke gateway client tokens for its responsible person
> - #20581 stopped agents from getting the one-time token value, but it
did this by making token creation person-only
> - The product decision is that agents keep their delegated authority
to create and revoke tokens
> - This pull request restores agent token creation, but the agent never
receives the token value: the person reveals the value once on the
gateway's Tokens page
> - The benefit is that an agent can do the rotation work for the
person, and the secret still never enters chat, run events, logs or tool
output

## Linked Issues or Issue Description

Refs #17737
Refs #20581

**What happened**
After #20581, `POST /api/tool-gateway/gateways/{gatewayId}/tokens`
returns 403 `gateway_token_requires_person` to every agent caller.
Agents lost the delegated authority to create gateway client tokens that
#17737 gave them. Before #20581, an agent that created a token received
the plaintext value in its tool result and could repeat it in chat.

**Expected behavior**
An agent with delegated connection management can create and revoke
gateway client tokens. The agent never receives a token value. The
responsible person gets the value once, on the gateway's Tokens page.
Person callers keep today's behavior.

**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 403 `gateway_token_requires_person`.

## What Changed

- Agent create: `POST /api/tool-gateway/gateways/:gatewayId/tokens` from
an agent with delegated authority returns 201 with token metadata only
(`id`, `tokenPrefix`, `expiresAt`, `pendingReveal: true`), plus
`tokensPath`, a `reveal_credential` `requiredUserAction` for the
responsible person, and a `nextStep` instruction. The saved row has no
usable value: its stored hash is of a value that is generated and then
discarded. Gateway authentication also rejects `pendingReveal` rows.
- Person reveal: new person-only `POST
/api/tool-gateway/gateway-tokens/:tokenId/reveal`. It generates the
value, stores its hash, clears `pendingReveal` and returns the value
once. A conditional update makes a second or concurrent reveal return
409. Only the token's responsible person can reveal it (403
`gateway_token_reveal_requires_responsible_person`). Agent callers get
403 `gateway_token_requires_person`. A token revoked before reveal
cannot be revealed.
- Why a reveal that generates the value: no stored plaintext existed to
reveal, and storing one (even encrypted) for later display adds a secret
at rest. Generating the value at reveal time keeps the existing one-time
display and stores only a hash.
- Schema: `tool_mcp_gateway_tokens.pending_reveal boolean not null
default false` (migration `0460_gateway_token_pending_reveal`). Shared
`ToolMcpGatewayToken.pendingReveal`, and `ConnectionRequiredUserAction`
gets `reveal_credential` / `gateway_token`.
- UI: the Tokens page shows a "Waiting for you to reveal" section for
pending tokens with a "Reveal token" button. The value appears in the
existing "New token — copy now" one-time block. Pending tokens show the
status "Not revealed".
- Agent gateway create: the 201 for agent callers also includes
`gatewayPath`, `tokensPath` and a `nextStep` that tells the agent to
link the saved gateway.
- The agent create-token `nextStep` and the catalog say not to revoke
the old token in the same turn: its client keeps working on it until the
person installs the new value.
- The reveal update and its `tool_gateway.token_revealed` activity entry
commit in one transaction. The Tokens page offers Reveal only for tokens
that act for the signed-in person.
- API reference: new `docs/api/tool-gateway-tokens.md` (create, reveal,
revoke) in the docs nav.
- Revoke stays allowed for agents with delegated authority (unchanged
route).
- API catalog: create-gateway, create-token, reveal and revoke
descriptions now say who acts, that agents never receive values, the
page paths, and that the old token is revoked only after the client
works with the new one.
- Agent access map: create-token policy note and a new reveal entry.
- Evals `gateways-profiles.create-gateway` and
`gateways-profiles.rotate-token`:
- Remove the keyword grader (`human|operator|admin|manage`) and the
handoff text checks. Grade saved state, rendered links and secret
absence. A plain reply or a question card is accepted.
- Remove the setup probes that called the create routes as the agent.
Under delegated authority, those probes created a real gateway
("Forbidden agent gateway"), which failed create-gateway before the
agent ran.
- create-gateway: exactly one gateway for the intended profile and
company, created by the agent (or by the person after a handoff); the
person opens it from a rendered link; attribution matches the creator;
any agent-created token is still pending reveal; no token value in chat,
cards or run events.
- rotate-token: after the agent's turn, both setup tokens still work and
any replacement the agent created is pending the person's reveal; the
person follows the rendered Tokens page link and reveals (or issues) the
value in a private browser; the new value works before the old token is
revoked; the unrelated client keeps access; no token value appears
anywhere, including a regex scan for any full `pcgw_<id>.<secret>`
value.
- The changed scenario context and outcomes are recorded in
`chat-full-catalog-testops-manifest.json` `changedFields` and pinned in
the manifest test. The inventory digest, descriptors (`oracleVersion`
v2, `sourceFiles`) and SDK public input pins are updated. The unused
`external-gateway-handoff.ts` module is removed.
- Fixture realism: the create-gateway profile now allows a real read
tool (an empty profile made the agent ask which apps to add instead of
finishing), and the rotation tokens get a neutral owner note instead of
"Disposable rotation fixture" (the agent read that note as an eval
hint).
- Shared private-browser helpers (`external-private-browser.ts`,
`external-private-browser-worker.ts`) get one optional `pendingTokenId`
input and one `revealedPending` receipt field.

## Verification

- Red: on `master` route code, the new integration tests `lets agents
create and revoke gateway client tokens without ever receiving a token
value` and `reveals an agent-created gateway token value only to its
responsible person` fail (403 `gateway_token_requires_person`).
- Green: `cd server && npx vitest run
src/__tests__/connection-management.integration.test.ts -t gateway` (25
passed). The test checks that the agent `call_api` result has no `token`
field and no token-shaped value, that the agent cannot reveal, that the
person reveals once (second reveal 409) and the value authenticates,
that agent revoke works and stops the value, that a token revoked before
reveal never gets a value, and that person create still returns the
value.
- `npx vitest run src/__tests__/tool-gateway.test.ts
src/__tests__/openapi-routes.test.ts
src/services/native-runtime/runner-api.test.ts` (2247 passed).
- `cd ui && npx vitest run
src/pages/apps/gateways/panels/TokensPanel.test.tsx
src/pages/apps/gateways/gateway-helpers.test.ts` (16 passed); `pnpm
check:token-gates` clean.
- Eval graders and catalog: `pnpm exec vitest run --config
tests/runner-e2e/vitest.config.ts` on the gateway oracle tests,
`external.test.ts`, catalog consistency/contract, TestOps
export/retained, phase/clock callers and SDK input/type tests (all
pass); `node --test` on the TestOps manifest, adapter, contract,
streaming and reconcile tests (all pass); `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(unchanged).
- `node scripts/check-maps.mjs` passes. `tsc --noEmit` for `server`,
`ui` and `tests/runner-e2e`: no errors in changed files.
- Paid end-to-end run of both eval cases, run
[42872921890](https://github.com/paperclipai/paperclip/actions/runs/42872921890)
on 39f38a7f6c (before the last three commits): both FAILED, for
agent-behavior reasons the later commits address. Not rerun yet.
- rotate-token: the agent created the replacement (pending reveal, no
value), then revoked the old token in the same turn, despite the create
response saying to wait. Its reasoning cited the eval-looking fixture
note. The grader rejected the premature revocation. The reply linked the
Tokens page correctly.
- create-gateway: the agent created the gateway and one pending token,
then asked a question card about which apps to add to the empty profile,
with no link to the gateway. The grader rejected the missing link.
- Token values: a scan of all evidence files of both cells found no full
`pcgw_<id>.<secret>` value and no `pcgw_<uuid>` form. Agent `call_api`
payloads in run events are redacted; the integration test proves the
agent tool result has no value.

## Risks

- Behavior change for agents: token create returns metadata and a Tokens
page path, not a value. Agents that expect `token` in the response must
send the person to the Tokens page.
- Migration adds one boolean column with a default. Existing tokens get
`false` and keep working.
- A pending token that is never revealed stays as an unusable row until
someone revokes it. It cannot authenticate.

## 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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-10 15:13:34 -06:00
1 parent 2150820bd8
commit 353945c86d
32 files changed
+1032 -352

No files matched your search

@@ -1546,27 +1546,92 @@ describe("connection management with production default agents", () => {
return { status: 201, body: { ...row, token } };
}
it("never returns gateway client token plaintext to agent callers", async () => {
it("lets agents create and revoke gateway client tokens without ever receiving a token value", 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,
} };
const call = (callId: string, operationId: string, pathParams: Record<string, string>, payload: unknown) =>
f.authority.execute({ tool: "call_api", callId, arguments: { operationId, pathParams, body: payload } }) as Promise<{ status: number; data: Record<string, unknown> }>;
const tokenValue = /pcgw_[0-9a-f-]{36}\.[A-Za-z0-9_-]+/;
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<string, unknown> };
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);
expect(gateway.body).toMatchObject({ tokensPath, gatewayPath: `/${company.issuePrefix}/apps/gateways/${gateway.body.id}/overview` });
const created = await call("gateway-client-create", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, body);
expect(created, JSON.stringify(created)).toMatchObject({ status: 201, data: { name: "Fixture client", pendingReveal: true, tokensPath,
tokenPrefix: expect.stringMatching(/^pcgw_[0-9a-f]{8}$/), createdByAgentId: f.agentId, responsibleUserId: f.userId,
requiredUserAction: { kind: "reveal_credential", userId: f.userId, setupPath: tokensPath, resource: { type: "gateway_token", id: created.data.id, companyId: f.companyId } } } });
expect(created.data).not.toHaveProperty("token");
expect(JSON.stringify(created)).not.toMatch(tokenValue);
const [pending] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, created.data.id as string));
expect(pending).toMatchObject({ pendingReveal: true, createdByAgentId: f.agentId, responsibleUserId: f.userId, subjectType: "gateway_client", revokedAt: null });
// Agents cannot reveal any value.
const agentReveal = await call("gateway-client-reveal", "POST /api/tool-gateway/gateway-tokens/{tokenId}/reveal", { tokenId: created.data.id as string }, { companyId: f.companyId });
expect(agentReveal, JSON.stringify(agentReveal)).toMatchObject({ status: 403, data: { reasonCode: "gateway_token_requires_person" } });
expect(JSON.stringify(agentReveal)).not.toMatch(tokenValue);
expect(await f.request("POST", `/tool-gateway/gateway-tokens/${created.data.id}/reveal`, { companyId: f.companyId })).toMatchObject({ status: 403 });
// The responsible person reveals the value exactly once, and it works.
const cookie = await server.humanSession(f.userId);
const reveal = () => fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${created.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
const revealed = await reveal();
expect(revealed.status).toBe(200);
const value = await revealed.json() as { token: string; pendingReveal: boolean; id: string };
expect(value).toMatchObject({ id: created.data.id, pendingReveal: false, token: expect.stringMatching(new RegExp(`^pcgw_${created.data.id}\\.`)) });
expect(await reveal()).toMatchObject({ status: 409 });
expect(await server.db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.action, "tool_gateway.token_revealed"))))
.toEqual([expect.objectContaining({ actorType: "user", actorId: f.userId, entityId: gateway.body.id, details: { tokenId: created.data.id } })]);
const use = () => f.request("POST", `/mcp/gateways/${gateway.body.gatewayPublicId}`, { jsonrpc: "2.0", id: 1, method: "tools/list" }, value.token);
expect(await use()).toMatchObject({ status: 200 });
// Agents keep delegated revoke.
const revoked = await call("gateway-client-revoke", "POST /api/tool-gateway/gateway-tokens/{tokenId}/revoke", { tokenId: created.data.id as string }, { companyId: f.companyId });
expect(revoked, JSON.stringify(revoked)).toMatchObject({ status: 200, data: { id: created.data.id, revokedAt: expect.any(String) } });
expect((await use()).status).toBeGreaterThanOrEqual(400);
// A token revoked before reveal never gets a value.
const unrevealed = await call("gateway-client-create-2", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, { ...body, name: "Never revealed" });
expect(unrevealed).toMatchObject({ status: 201 });
expect(await call("gateway-client-revoke-2", "POST /api/tool-gateway/gateway-tokens/{tokenId}/revoke", { tokenId: unrevealed.data.id as string }, { companyId: f.companyId })).toMatchObject({ status: 200 });
expect(await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${unrevealed.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) }))
.toMatchObject({ status: 409 });
// A token that expired before reveal never gets a value.
const expiring = await call("gateway-client-create-3", "POST /api/tool-gateway/gateways/{gatewayId}/tokens", { gatewayId: gateway.body.id }, { ...body, name: "Expired before reveal" });
expect(expiring).toMatchObject({ status: 201 });
await server.db.update(toolMcpGatewayTokens).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(toolMcpGatewayTokens.id, expiring.data.id as string));
const expiredReveal = await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${expiring.data.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
expect(expiredReveal.status).toBe(409);
expect(await expiredReveal.json()).toMatchObject({ reasonCode: "gateway_token_expired" });
const [stillPending] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, expiring.data.id as string));
expect(stillPending).toMatchObject({ pendingReveal: true });
// Person callers keep receiving the value from create.
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 });
expect(await personal.json()).toMatchObject({ token: expect.stringMatching(/^pcgw_/), createdByUserId: f.userId, createdByAgentId: null, pendingReveal: false });
});
it("reveals an agent-created gateway token value only to its responsible person", async () => {
const f = await fixture();
const profile = await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: "gateway-profile", name: "Gateway profile", entries: [] });
const gateway = await f.request("POST", `/companies/${f.companyId}/tools/gateways`, { name: "Delegated gateway", slug: "delegated", profileId: profile.body.id });
const created = await f.request("POST", `/tool-gateway/gateways/${gateway.body.id}/tokens`, { companyId: f.companyId, name: "Fixture client", clientLabel: "fixture" });
expect(created, JSON.stringify(created)).toMatchObject({ status: 201, body: { pendingReveal: true } });
const otherId = `other-admin-${randomUUID()}`;
await server.db.insert(authUsers).values({ id: otherId, name: "Other admin", email: `${otherId}@fixture.invalid`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() });
const access = accessService(server.db);
await access.ensureMembership(f.companyId, "user", otherId, "owner", "active");
await access.ensureRoleDefaultGrants(f.companyId, otherId, "owner", otherId);
const cookie = await server.humanSession(otherId);
const reveal = await fetch(`${server.apiUrl}/api/tool-gateway/gateway-tokens/${created.body.id}/reveal`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
expect(reveal.status).toBe(403);
expect(await reveal.json()).toMatchObject({ reasonCode: "gateway_token_reveal_requires_responsible_person" });
const [still] = await server.db.select().from(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, created.body.id));
expect(still).toMatchObject({ pendingReveal: true });
});
it("keeps durable agent-issued gateway client tokens bound to the issuer and responsible user", async () => {
+21 -1
View File
@@ -12915,6 +12915,7 @@ registerCurrentRoute({
path: "/api/companies/{companyId}/tools/gateways",
tags: ["tool-gateway"],
summary: "Create a named MCP gateway",
description: "Creates a gateway that exposes a tool access profile to external MCP clients. Agents with delegated connection management may create it; agent responses also include gatewayPath (/<prefix>/apps/gateways/<gatewayId>/overview) and tokensPath (/<prefix>/apps/gateways/<gatewayId>/tokens). Link the person to them as Markdown links. A client needs a gateway client token to connect; see POST /api/tool-gateway/gateways/{gatewayId}/tokens.",
body: createToolMcpGatewaySchema,
responses: {
201: r.ok(),
@@ -12950,7 +12951,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.",
description: "Creates a client token for an external MCP client. A person caller receives the token value once in the response. An agent with delegated connection management may create the token for its responsible person, but receives only metadata (id, tokenPrefix, expiresAt, pendingReveal: true) plus tokensPath, the gateway's Tokens page (/<prefix>/apps/gateways/<gatewayId>/tokens). The value does not exist until that person reveals it there; send the person to tokensPath as a Markdown link, and never ask for, accept, or repeat token values in chat. To rotate, create the replacement and leave the old token active in that turn: its client keeps working on it until the person installs the new value. Revoke the old token only after the person says the client works with the new one, or let them revoke it on the Tokens page.",
body: toolGatewayCompanyBodySchema,
responses: {
201: r.ok(),
@@ -12962,6 +12963,24 @@ registerCurrentRoute({
},
});
registerCurrentRoute({
"x-paperclip-transport": "rest",
method: "post",
path: "/api/tool-gateway/gateway-tokens/{tokenId}/reveal",
tags: ["tool-gateway"],
summary: "Reveal an agent-created MCP gateway token value",
description: "Person-only. Generates the value of an agent-created client token that is pending reveal and returns it once. Only the token's responsible person can reveal it; a second reveal, or a reveal after the token expired or was revoked, returns 409. Agent callers receive 403 gateway_token_requires_person.",
body: toolGatewayCompanyQuerySchema.required({ companyId: true }),
responses: {
200: r.ok(),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
409: r.conflict,
},
});
registerCurrentRoute({
"x-paperclip-transport": "rest",
"x-paperclip-connection-management": "connections:gateway",
@@ -12969,6 +12988,7 @@ registerCurrentRoute({
path: "/api/tool-gateway/gateway-tokens/{tokenId}/revoke",
tags: ["tool-gateway"],
summary: "Revoke a named MCP gateway token",
description: "Revokes a gateway client token immediately; clients using it stop working. Agents with delegated connection management may revoke. When rotating, revoke the old token only after the replacement works.",
body: toolGatewayCompanyQuerySchema.required({ companyId: true }),
responses: {
200: r.ok(),
+61 -17
View File
@@ -1,4 +1,4 @@
import { filterConnectionManagementRows, connectionManagementGuard, connectionRequestContext, connectionRequestUserId } from "./connection-management-authz.js";
import { filterConnectionManagementRows, connectionManagementGuard, connectionRequestContext, connectionRequestUserId, requiredConnectionUserAction } from "./connection-management-authz.js";
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";
@@ -362,6 +362,13 @@ export function toolGatewayRoutes(db: Db, toolGateway: ToolGatewayService) {
throw forbidden(`Missing permission: ${permissionKey}`);
}
/** The person-facing Tokens page of a gateway, where token values are revealed. */
async function gatewayTokensPath(companyId: string, gatewayId: string) {
const [company] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId)).limit(1);
if (!company) throw new ToolGatewayHttpError(404, "Company not found", "company_not_found");
return `/${company.issuePrefix}/apps/gateways/${gatewayId}/tokens`;
}
function assertBoardMutationAccess(req: import("express").Request, companyId: string) {
assertBoard(req);
assertCompanyAccess(req, companyId);
@@ -401,7 +408,15 @@ export function toolGatewayRoutes(db: Db, toolGateway: ToolGatewayService) {
actor: { agentId: actor.agentId, userId: req.actor.type === "board" ? req.actor.userId : null },
managementContext: connectionRequestContext(req),
});
res.status(201).json(gateway);
if (req.actor.type !== "agent") {
res.status(201).json(gateway);
return;
}
// Agents link the person to the saved gateway; clients need a token from its Tokens page.
const tokensPath = await gatewayTokensPath(req.params.companyId as string, gateway.id);
const gatewayPath = tokensPath.replace(/\/tokens$/, "/overview");
res.status(201).json({ ...gateway, gatewayPath, tokensPath,
nextStep: `Link the saved gateway as a Markdown link, such as [${gateway.name}](${gatewayPath}), in your reply or question. A client connects with a token from its Tokens page (${tokensPath}).` });
} catch (err) {
sendGatewayError(res, err);
}
@@ -437,32 +452,61 @@ 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 });
return;
}
const actor = getActorInfo(req);
res.status(201).json(await toolGateway.createNamedGatewayToken({
const input = {
companyId,
gatewayId: (req.params.gatewayId as string),
body: parsed.data,
actor: { agentId: actor.agentId, userId: req.actor.type === "board" ? req.actor.userId : null },
managementContext: connectionRequestContext(req),
}));
};
if (req.actor.type !== "agent") {
res.status(201).json(await toolGateway.createNamedGatewayToken(input));
return;
}
// A token value is shown once, to whoever receives the create response.
// An agent could repeat it in chat, so an agent-created client token has
// no value until its responsible person reveals one on the Tokens page.
// The validator admits only gateway_client subjects on this route.
const tokensPath = await gatewayTokensPath(companyId, input.gatewayId);
const created = await toolGateway.createPendingRevealGatewayToken(input);
res.status(201).json({
...created,
tokensPath,
...requiredConnectionUserAction(req, { type: "gateway_token", id: created.id, companyId }, tokensPath,
`Reveal and copy the value of "${created.name}" on the gateway's Tokens page, then give it to the client.`, "reveal_credential"),
nextStep: `Created "${created.name}" without a value. Its value is generated only when the person reveals it on the gateway's Tokens page (${tokensPath}); `
+ "link that page as a Markdown link. Never ask for, accept, or repeat token values in chat. "
+ "When this replaces an old token, do not revoke the old one in this turn: its client keeps working on it until the person reveals the new value "
+ "and installs it, and revoking now disconnects that client. Revoke the old token only after the person says the client works with the new one, "
+ "or tell them they can revoke it on the same Tokens page.",
});
} catch (err) {
sendGatewayError(res, err);
}
});
router.post("/tool-gateway/gateway-tokens/:tokenId/reveal", async (req, res) => {
try {
assertBoardOrAgent(req);
const companyId = typeof req.body?.companyId === "string" ? req.body.companyId : null;
if (!companyId) {
res.status(400).json({ error: "companyId is required" });
return;
}
if (req.actor.type !== "board" || !req.actor.userId) {
assertCompanyAccess(req, companyId);
throw new ToolGatewayHttpError(403,
"Final: only a person can reveal a gateway client token value, on the gateway's Tokens page. Do not ask for or repeat token values in chat.",
"gateway_token_requires_person");
}
await assertBoardPermission(req, companyId, "tools:admin");
res.json(await toolGateway.revealNamedGatewayToken({ companyId, tokenId: req.params.tokenId as string, userId: req.actor.userId }));
} catch (err) {
sendGatewayError(res, err);
}
+156 -81
View File
@@ -61,6 +61,7 @@ import {
asc,
desc,
eq,
gt,
inArray,
isNull,
lte,
@@ -137,7 +138,7 @@ import type {
AgentToolDescriptor,
PluginToolDispatcher,
} from "./plugin-tool-dispatcher.js";
import { logActivity, type LogActivityInput } from "./activity-log.js";
import { logActivity, publishActivity, type ActivityPublication, type LogActivityInput } from "./activity-log.js";
import { secretService } from "./secrets.js";
import { connectionGrantCredentialRef, resolveConnectionGrantSecret } from "./connection-credentials.js";
import { railwayCommandBudgetMs, createRailwayClient, isRailwayConnection, isRailwayEndpoint, isRailwayToolBlocked, normalizeRailwayToolName, RAILWAY_API_URL, RAILWAY_TOOL_PREFIX, RailwayError } from "./railway.js";
@@ -680,6 +681,14 @@ function generateGatewayToken(sessionId: string) {
return `pcgt_${sessionId}.${randomBytes(32).toString("base64url")}`;
}
interface NamedGatewayTokenInput {
companyId: string;
gatewayId: string;
body: CreateToolMcpGatewayToken;
actor?: { agentId?: string | null; userId?: string | null };
managementContext?: ConnectionManagementContext;
}
function generateNamedGatewayToken(tokenId: string) {
return `pcgw_${tokenId}.${randomBytes(32).toString("base64url")}`;
}
@@ -7000,6 +7009,85 @@ export function createToolGatewayService(
};
}
async function insertNamedGatewayToken(input: NamedGatewayTokenInput, pendingReveal: boolean) {
await input.managementContext?.reauthorize();
const [gateway] = await db
.select()
.from(toolMcpGateways)
.where(
and(
eq(toolMcpGateways.companyId, input.companyId),
eq(toolMcpGateways.id, input.gatewayId),
),
)
.limit(1);
if (!gateway)
throw new ToolGatewayHttpError(
404,
"MCP gateway not found",
"gateway_not_found",
);
if (input.actor?.agentId && !input.managementContext && input.body.subjectType !== "heartbeat_run") {
throw new ToolGatewayHttpError(403, "Agent client tokens require delegated authority", "gateway_token_run_context_invalid");
}
if (input.managementContext?.actor.type === "agent" && input.body.subjectType === "heartbeat_run" &&
(!input.managementContext.actor.runId || input.body.subjectId !== input.managementContext.actor.runId)) {
throw new ToolGatewayHttpError(403, "Heartbeat tokens must bind the authenticated run", "gateway_token_run_context_invalid");
}
const tokenId = randomUUID();
const token = generateNamedGatewayToken(tokenId);
const tokenPrefix = `pcgw_${tokenId.slice(0, 8)}`;
const now = new Date();
const [row] = await db.transaction(async tx => {
if (input.body.expiresAt) await notifyDeliveryWork(tx, DELIVERY_QUEUES.gatewayCredentialExpiry);
return tx
.insert(toolMcpGatewayTokens)
.values({
id: tokenId,
companyId: input.companyId,
gatewayId: input.gatewayId,
name: input.body.name,
// A pending token's stored hash is of a value nobody receives.
tokenHash: hashGatewayToken(token),
tokenPrefix,
pendingReveal,
subjectType: input.body.subjectType ?? "gateway_client",
subjectId: input.body.subjectId ?? null,
clientLabel: input.body.clientLabel,
ownerNote: input.body.ownerNote,
allowedActions: input.body.allowedActions ?? [
"tools/list",
"tools/call",
"resources/list",
"resources/read",
"prompts/list",
"prompts/get",
],
expiresAt: input.body.expiresAt ?? null,
expiryOverrideReason: input.body.expiryOverrideReason ?? null,
expiryOverrideByAgentId:
input.actor?.agentId && input.body.expiryOverrideReason
? input.actor.agentId
: null,
expiryOverrideByUserId:
input.actor?.userId && input.body.expiryOverrideReason
? input.actor.userId
: null,
expiryOverrideAt: input.body.expiryOverrideReason ? now : null,
responsibleUserId: input.managementContext?.actor.type === "agent" ? input.managementContext.responsibleUserId : null,
createdByAgentId: input.actor?.agentId ?? null,
createdByUserId: input.actor?.userId ?? null,
createdAt: now,
updatedAt: now,
})
.returning();
});
if (input.managementContext) await logActivity(db, { companyId: input.companyId, ...input.managementContext.audit,
action: "tool_gateway.token_created", entityType: "tool_mcp_gateway", entityId: input.gatewayId,
details: { tokenId: row.id, subjectType: row.subjectType, allowedActions: row.allowedActions, ...(pendingReveal ? { pendingReveal } : {}) } });
return { row, token };
}
function toGatewayToken(
row: typeof toolMcpGatewayTokens.$inferSelect,
): ToolMcpGatewayToken {
@@ -7024,6 +7112,7 @@ export function createToolGatewayService(
createdByAgentId: row.createdByAgentId,
createdByUserId: row.createdByUserId,
responsibleUserId: row.responsibleUserId,
pendingReveal: row.pendingReveal,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
@@ -7446,6 +7535,15 @@ export function createToolGatewayService(
clientMetadata,
});
}
if (row.token.pendingReveal) {
await recordNamedGatewayAuthFailure({
gatewayId: input.gatewayId,
gatewayPublicId: input.gatewayPublicId,
bearerToken,
reasonCode: "gateway_token_invalid",
clientMetadata,
});
}
if (row.token.expiresAt && row.token.expiresAt.getTime() <= Date.now()) {
await recordNamedGatewayAuthFailure({
gatewayId: input.gatewayId,
@@ -9341,89 +9439,66 @@ export function createToolGatewayService(
return getGatewayWithTokens(input.companyId, updated.id);
},
async createNamedGatewayToken(input: {
companyId: string;
gatewayId: string;
body: CreateToolMcpGatewayToken;
actor?: { agentId?: string | null; userId?: string | null };
managementContext?: ConnectionManagementContext;
}): Promise<ToolMcpGatewayTokenCreated> {
await input.managementContext?.reauthorize();
const [gateway] = await db
.select()
.from(toolMcpGateways)
.where(
and(
eq(toolMcpGateways.companyId, input.companyId),
eq(toolMcpGateways.id, input.gatewayId),
),
)
.limit(1);
if (!gateway)
throw new ToolGatewayHttpError(
404,
"MCP gateway not found",
"gateway_not_found",
);
if (input.actor?.agentId && !input.managementContext && input.body.subjectType !== "heartbeat_run") {
throw new ToolGatewayHttpError(403, "Agent client tokens require delegated authority", "gateway_token_run_context_invalid");
}
if (input.managementContext?.actor.type === "agent" && input.body.subjectType === "heartbeat_run" &&
(!input.managementContext.actor.runId || input.body.subjectId !== input.managementContext.actor.runId)) {
throw new ToolGatewayHttpError(403, "Heartbeat tokens must bind the authenticated run", "gateway_token_run_context_invalid");
}
const tokenId = randomUUID();
const token = generateNamedGatewayToken(tokenId);
const tokenPrefix = `pcgw_${tokenId.slice(0, 8)}`;
const now = new Date();
const [row] = await db.transaction(async tx => {
if (input.body.expiresAt) await notifyDeliveryWork(tx, DELIVERY_QUEUES.gatewayCredentialExpiry);
return tx
.insert(toolMcpGatewayTokens)
.values({
id: tokenId,
companyId: input.companyId,
gatewayId: input.gatewayId,
name: input.body.name,
tokenHash: hashGatewayToken(token),
tokenPrefix,
subjectType: input.body.subjectType ?? "gateway_client",
subjectId: input.body.subjectId ?? null,
clientLabel: input.body.clientLabel,
ownerNote: input.body.ownerNote,
allowedActions: input.body.allowedActions ?? [
"tools/list",
"tools/call",
"resources/list",
"resources/read",
"prompts/list",
"prompts/get",
],
expiresAt: input.body.expiresAt ?? null,
expiryOverrideReason: input.body.expiryOverrideReason ?? null,
expiryOverrideByAgentId:
input.actor?.agentId && input.body.expiryOverrideReason
? input.actor.agentId
: null,
expiryOverrideByUserId:
input.actor?.userId && input.body.expiryOverrideReason
? input.actor.userId
: null,
expiryOverrideAt: input.body.expiryOverrideReason ? now : null,
responsibleUserId: input.managementContext?.actor.type === "agent" ? input.managementContext.responsibleUserId : null,
createdByAgentId: input.actor?.agentId ?? null,
createdByUserId: input.actor?.userId ?? null,
createdAt: now,
updatedAt: now,
})
.returning();
});
if (input.managementContext) await logActivity(db, { companyId: input.companyId, ...input.managementContext.audit,
action: "tool_gateway.token_created", entityType: "tool_mcp_gateway", entityId: input.gatewayId,
details: { tokenId: row.id, subjectType: row.subjectType, allowedActions: row.allowedActions } });
async createNamedGatewayToken(input: NamedGatewayTokenInput): Promise<ToolMcpGatewayTokenCreated> {
const { row, token } = await insertNamedGatewayToken(input, false);
return { ...toGatewayToken(row), token };
},
/**
* Saves an agent-created client token without a usable value. The value is
* generated only when the responsible person reveals it, so the creating
* agent never receives it in a tool result.
*/
async createPendingRevealGatewayToken(input: NamedGatewayTokenInput): Promise<ToolMcpGatewayToken> {
return toGatewayToken((await insertNamedGatewayToken(input, true)).row);
},
async revealNamedGatewayToken(input: {
companyId: string;
tokenId: string;
userId: string;
}): Promise<ToolMcpGatewayTokenCreated> {
const [existing] = await db.select().from(toolMcpGatewayTokens).where(and(
eq(toolMcpGatewayTokens.companyId, input.companyId),
eq(toolMcpGatewayTokens.id, input.tokenId),
)).limit(1);
if (!existing) throw new ToolGatewayHttpError(404, "MCP gateway token not found", "gateway_token_not_found");
if (!existing.pendingReveal) throw new ToolGatewayHttpError(409, "This token's value was already shown once. Issue a new token to get a new value.", "gateway_token_already_revealed");
if (existing.revokedAt) throw new ToolGatewayHttpError(409, "This token was revoked before its value was revealed.", "gateway_token_revoked");
if (existing.expiresAt && existing.expiresAt.getTime() <= Date.now()) {
throw new ToolGatewayHttpError(409, "This token expired before its value was revealed. Create a new token instead.", "gateway_token_expired");
}
if (existing.responsibleUserId && existing.responsibleUserId !== input.userId) {
throw new ToolGatewayHttpError(403, "Only the person this agent-created token acts for can reveal its value.", "gateway_token_reveal_requires_responsible_person");
}
const token = generateNamedGatewayToken(existing.id);
const now = new Date();
// Conditional on pendingReveal so concurrent reveals produce one value.
// The value exists only in this response, so the reveal and its audit
// entry commit together: a failed audit write leaves the token pending.
const publications: ActivityPublication[] = [];
const row = await db.transaction(async tx => {
const [updated] = await tx.update(toolMcpGatewayTokens)
.set({ tokenHash: hashGatewayToken(token), pendingReveal: false, updatedAt: now })
.where(and(
eq(toolMcpGatewayTokens.companyId, input.companyId),
eq(toolMcpGatewayTokens.id, input.tokenId),
eq(toolMcpGatewayTokens.pendingReveal, true),
isNull(toolMcpGatewayTokens.revokedAt),
or(isNull(toolMcpGatewayTokens.expiresAt), gt(toolMcpGatewayTokens.expiresAt, now)),
))
.returning();
if (!updated) throw new ToolGatewayHttpError(409, "This token's value was already shown once. Issue a new token to get a new value.", "gateway_token_already_revealed");
await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "user", actorId: input.userId,
action: "tool_gateway.token_revealed", entityType: "tool_mcp_gateway", entityId: updated.gatewayId,
details: { tokenId: updated.id } }, publications);
return updated;
});
for (const publication of publications) publishActivity(publication);
return { ...toGatewayToken(row), token };
},
async revokeNamedGatewayToken(input: {
companyId: string;
tokenId: string;