From 45c3f4caa22cae943b3cf33872620e06ea81dd06 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:34:09 -0600 Subject: [PATCH] fix(connectors): require an install before an agent reaches a plugin connector (#22237) 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 > - Plugins can add connectors that serve their own tools (`transport: "plugin"`, #22004, #22019, #22201) > - The activation rule is that an agent gets a connector's tools only through an install of an active connection for that agent > - An agent with no install could still list and call a plugin connector's tools, and the plugin worker ran them with that agent's run context > - This pull request makes the tool access policy require the install for plugin-served connections > - The benefit is that a plugin connector reaches only the agents it is installed for ## Linked Issues or Issue Description Refs #22004 Refs #22019 Refs #22201 **Subsystem affected** Tool access policy and tool gateway (plugin-served connectors). **Problem or motivation** A plugin connection was installed for agent A only. Agent B, a standard agent with no install, called one of its tools. The plugin worker got a run context with B's agent id. **Root cause** An install gives access only through the connection's app profile binding. The policy does not check installs. For an agent outside that profile, the policy goes on to its other allow routes. The common route is the unscoped `tools:use` grant that every new standard agent receives (`NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS`). `governedByConnectionProfile` is false for B, because B is not bound to the connection's profile. So `explicitGrant` allowed the tool for discovery and invocation. Organization-grant connections ran the worker. Per-agent connections listed the tools and reached grant resolution. **Expected behavior** An agent without an install for the connection (or a company install) sees no tools and cannot call them. An installed agent is not affected. ## What Changed - `server/src/services/tool-access-policy.ts`: for an agent caller on a connection whose stored transport is `plugin`, deny with the new reason `deny_connection_not_installed` unless an install exists for that agent or the company. The check runs before profiles, grants, trust rules and allow policies, so none of them can replace the install. It reads the transport from the stored connection, not from the caller. The install read uses the decision cache, so a listing batch reads it once per connection. - `packages/shared/src/types/tool-access.ts`: add `deny_connection_not_installed` to `ToolAccessReasonCode`. - `doc/connections/CONNECTOR-PLAYBOOK.md`: document the rule. - Legacy plugin tools (`paperclip_plugin`) keep their own implicit-install gate and are not changed. ## Verification - New `server/src/__tests__/plugin-connector-install-gate.test.ts` (embedded Postgres, real routes). Both agents get the default standard-agent grants, including the unscoped `tools:use`. For an organization-grant connection and a per-agent connection installed for A only: - A lists the tool through its gateway session and its Paperclip Runner assigned-tool gateway, and a call reaches the worker. - B (with its own install of an unrelated connection) lists none of them in either path. - B's direct call by name through its gateway session, its runner gateway, and the runner's `paperclip_call_assigned_tool` is refused. The worker is never called. - Before the fix, both cases failed: B listed the tool. - Regression suites pass: `tool-access-policy-service`, `tool-access-policy-index`, `tool-gateway`, `tool-gateway-service`, `tool-gateway-*`, `prompt-injection-gateway`, `plugin-connectors-plugin-transport` (legacy plugin tools), `plugin-connectors-circleback-parity`, `plugin-connector-agent-grant`, `heartbeat-runtime-mcp-servers`, `run-preparation`, `tool-access-service`, `generic-mcp-connection`, `remote-mcp-connectors`, `railway-connection`, `aws-mcp-connector`, `mcp-protocol-versions`, `google-workspace-*`. - `tsc --noEmit` passes for `server`, `packages/shared` and `ui` source. ## Risks - Behavior change: an uninstalled agent loses access to plugin-served connection tools it reached before through a general grant, a trust rule or an allow policy. That access broke the activation rule. Installed agents and company installs are not affected. - The board's per-agent access check now shows `deny_connection_not_installed` for agents without an install. - Built-in (non-plugin) connections are not changed by this pull request. They have the same policy path. Whether to require installs for them is a separate decision, because existing setups may depend on it. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## 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 --- doc/connections/CONNECTOR-PLAYBOOK.md | 4 + packages/shared/src/types/tool-access.ts | 1 + .../plugin-connector-install-gate.test.ts | 182 ++++++++++++++++++ .../tool-access-policy-index.test.ts | 1 + server/src/services/tool-access-policy.ts | 19 ++ .../runner-e2e/source-sdk-public-inputs.json | 2 +- 6 files changed, 208 insertions(+), 1 deletion(-) create mode 100644 server/src/__tests__/plugin-connector-install-gate.test.ts diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index 853a75c89fe..8305fafe8eb 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -192,6 +192,10 @@ create the agent grant in the callback. Methods without sign-in (`none` or that grant; one connection serves exactly one agent, so connecting it for a second agent is a conflict. Finish never creates agent grants: the grant still gives no tools until finish or the installs API adds that agent's install. +For a plugin-served connection (`transport: "plugin"`) the tool access policy +denies an agent with no install for it (or for the company) with +`deny_connection_not_installed`, before any profile, grant, trust rule or allow +policy. A general `tools:use` grant does not replace the install. A later successful catalog refresh clears an earlier connection-health error without new consent. An agent caller denied for lacking its own grant must not change shared health diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 978cac1aca7..2cc8b33a474 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1538,6 +1538,7 @@ export type ToolAccessReasonCode = | "deny_default" | "deny_company_boundary" | "deny_disabled_connection" + | "deny_connection_not_installed" | "deny_disabled_application" | "deny_archived_application" | "deny_missing_tool" diff --git a/server/src/__tests__/plugin-connector-install-gate.test.ts b/server/src/__tests__/plugin-connector-install-gate.test.ts new file mode 100644 index 00000000000..48851ec5671 --- /dev/null +++ b/server/src/__tests__/plugin-connector-install-gate.test.ts @@ -0,0 +1,182 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { eq } from "drizzle-orm"; +import express from "express"; +import request from "supertest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, companies, companyMemberships, createDb, heartbeatRuns, issues, plugins, principalPermissionGrants, toolConnectionInstalls, +} from "@paperclipai/db"; +import { pluginAppSlug, pluginManifestV1Schema, type PaperclipPluginManifestV1 } from "@paperclipai/shared"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { errorHandler } from "../middleware/index.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { buildPaperclipRuntimeMcpServers } from "../services/heartbeat.js"; +import { createAssignedMcpTools } from "../services/native-runtime/assigned-mcp-tools.js"; +import { resolveNativeRuntimeMcpSnapshot } from "../services/native-runtime/runtime-context.js"; +import { setPluginConnectorWorkers } from "../services/plugin-connector-runtime.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../lib/agent-permissions.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const PLUGIN_KEY = "example.install-gate"; +const SHARED = pluginAppSlug(PLUGIN_KEY, "shared"); +const PER_AGENT = pluginAppSlug(PLUGIN_KEY, "dedicated"); +const OTHER = pluginAppSlug(PLUGIN_KEY, "other"); +const tools = (prefix: string) => ({ + kind: "static" as const, + list: [{ name: `${prefix}_lookup`, description: "Look up a record.", risk: "read" as const, parametersSchema: { type: "object" } }], +}); +const app = (slug: string, method: Record) => ({ + schemaVersion: 1, slug, name: `Gate ${slug}`, description: `${slug} records`, categories: ["developer"], + branding: { logoUrl: "/brands/apps/api-key-generic.svg" }, urlPatterns: [], + methods: [{ key: "none", transport: "plugin", auth: "none", ownershipModes: ["customer"], whenToUse: "Use it.", + guidanceMd: "Connect it.", riskTier: "S1", ...method }], +}); +const manifest = pluginManifestV1Schema.parse({ + id: PLUGIN_KEY, apiVersion: 1, version: "1.0.0", displayName: "Install gate", description: "Install gate connectors", + author: "Tests", categories: ["connector"], capabilities: ["connectors.provide"], entrypoints: { worker: "worker.js" }, + apps: [ + app("shared", { tools: tools("shared") }), + app("dedicated", { grantKinds: ["agent"], tools: tools("dedicated") }), + app("other", { tools: tools("other") }), + ], +}) as PaperclipPluginManifestV1; + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("plugin connector tools need an install", () => { + let db: ReturnType; + let temp: Awaited>; + let keyDir: string; + const workerCalls: Array<{ method: string; params: any }> = []; + + beforeAll(async () => { + keyDir = await mkdtemp(join(tmpdir(), "plugin-install-gate-secrets-")); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key")); + vi.stubEnv("PAPERCLIP_API_URL", "http://127.0.0.1:3100"); + temp = await startEmbeddedPostgresTestDatabase("paperclip-plugin-install-gate-"); + db = createDb(temp.connectionString); + await db.insert(plugins).values({ pluginKey: PLUGIN_KEY, packageName: `@test/${PLUGIN_KEY}`, version: "1.0.0", manifestJson: manifest, status: "ready" }); + setPluginConnectorWorkers({ + isRunning: () => true, + getWorker: () => ({ status: "running" }), + call: vi.fn(async (_id: string, method: string, params: any) => { + workerCalls.push({ method, params: structuredClone(params) }); + if (method === "executeTool") return { content: `ran ${params.toolName}` }; + throw new Error(`unexpected ${method}`); + }), + } as unknown as PluginWorkerManager); + }, 60_000); + afterAll(async () => { + setPluginConnectorWorkers(null); + await temp?.cleanup(); + vi.unstubAllEnvs(); + if (keyDir) await rm(keyDir, { recursive: true, force: true }); + }); + + async function setup() { + const [company] = await db.insert(companies).values({ name: "Install gate", issuePrefix: `IG${randomUUID().slice(0, 6).toUpperCase()}` }).returning(); + await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: "board-user", status: "active", membershipRole: "admin" }); + const [agentA, agentB] = await db.insert(agents).values([ + { companyId: company!.id, name: "Installed", role: "engineer", adapterType: "process" }, + { companyId: company!.id, name: "Not installed", role: "engineer", adapterType: "process" }, + ]).returning(); + for (const agent of [agentA!, agentB!]) { + await db.insert(principalPermissionGrants).values(NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({ + companyId: company!.id, principalType: "agent", principalId: agent.id, permissionKey, + scope: newStandardAgentGrantScope(permissionKey, agent.id), + }))); + } + const routes = express(); + routes.use(express.json()); + routes.use((req, _res, next) => { + req.actor = { type: "board", userId: "board-user", userName: "Board User", userEmail: null, isInstanceAdmin: true, source: "local_implicit" }; + next(); + }); + routes.use("/api", toolAccessRoutes(db, {})); + routes.use(errorHandler); + const gateway = createToolGatewayService(db, { toolActionSigningSecret: "plugin-install-gate-signing" }); + const runs = new Map(); + const sessions = new Map(); + for (const agent of [agentA!, agentB!]) { + const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Work", assigneeAgentId: agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent.id, issueId: issue!.id, scopeKind: "issue", + invocationSource: "on_demand", status: "running", responsibleUserId: "board-user", contextSnapshot: { issueId: issue!.id } }).returning(); + runs.set(agent.id, run!.id); + sessions.set(agent.id, (await gateway.createSession({ companyId: company!.id, agentId: agent.id, runId: run!.id, issueId: issue!.id })).token); + } + const connect = async (body: Record, agentIds: string[]) => { + const connected = await request(routes).post(`/api/companies/${company!.id}/tools/apps/connect`).send(body); + expect(connected.status, JSON.stringify(connected.body)).toBe(201); + const finished = await request(routes).post(`/api/companies/${company!.id}/tools/apps/${connected.body.connectionId}/finish`) + .send({ enabledCatalogEntryIds: connected.body.catalog.map((entry: { id: string }) => entry.id), askFirstCatalogEntryIds: [], access: { agentIds } }); + expect(finished.status, JSON.stringify(finished.body)).toBe(200); + return connected.body.connectionId as string; + }; + const gatewayTools = async (agentId: string) => + (await gateway.listToolsForSession(sessions.get(agentId)!)).filter((tool) => tool.providerType === "paperclip_plugin_connection"); + const runner = async (agentId: string) => { + const agent = agentId === agentA!.id ? agentA! : agentB!; + const runId = runs.get(agentId)!; + const snapshot = await resolveNativeRuntimeMcpSnapshot({ db, agent, runId }); + const [server] = await buildPaperclipRuntimeMcpServers({ db, agent, runId, expectedAssignmentDigest: snapshot.digest }); + if (!server) return null; + const gatewayPublicId = server.url.split("/").at(-1)!; + const listed = await gateway.listToolsForNamedGateway({ gatewayPublicId, bearerToken: server.token }); + const assigned = await createAssignedMcpTools({ gateway, companyId: company!.id, gatewayPublicId, bearerToken: server.token }); + return { listed, assigned, gatewayPublicId, bearerToken: server.token }; + }; + return { company: company!, agentA: agentA!, agentB: agentB!, routes, gateway, sessions, connect, gatewayTools, runner }; + } + + const executeCalls = () => workerCalls.filter((call) => call.method === "executeTool").length; + + it.each([ + { label: "organization grant", body: { galleryKey: SHARED, connectionMethodKey: "none" }, perAgent: false }, + { label: "per-agent grant", body: { galleryKey: PER_AGENT, connectionMethodKey: "none", grantKind: "agent" }, perAgent: true }, + ])("gives the tools of a $label connection only to the installed agent", async ({ body, perAgent }) => { + const f = await setup(); + const connectionId = await f.connect({ ...body, ...(perAgent ? { subjectAgentId: f.agentA.id } : {}) }, [f.agentA.id]); + await f.connect({ galleryKey: OTHER, connectionMethodKey: "none" }, [f.agentB.id]); + const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connectionId)); + expect(installs.map((install) => install.targetId)).toEqual([f.agentA.id]); + + const toolA = (await f.gatewayTools(f.agentA.id)).find((tool) => tool.connectionId === connectionId)!; + expect(toolA).toBeDefined(); + const runnerA = await f.runner(f.agentA.id); + expect(runnerA!.listed.some((tool) => tool.connectionId === connectionId)).toBe(true); + const before = executeCalls(); + await f.gateway.executeTool({ gatewayPublicId: runnerA!.gatewayPublicId, sessionToken: runnerA!.bearerToken, tool: toolA.name, + parameters: {}, idempotencyKey: randomUUID() }); + expect(executeCalls()).toBe(before + 1); + + expect((await f.gatewayTools(f.agentB.id)).filter((tool) => tool.connectionId === connectionId)).toEqual([]); + const runnerB = await f.runner(f.agentB.id); + expect(runnerB!.listed.filter((tool) => tool.connectionId === connectionId)).toEqual([]); + expect(runnerB!.listed.some((tool) => tool.upstreamToolName === "other_lookup")).toBe(true); + const callsBefore = executeCalls(); + await expect(f.gateway.executeTool({ sessionToken: f.sessions.get(f.agentB.id)!, tool: toolA.name, parameters: {}, idempotencyKey: randomUUID() })) + .rejects.toMatchObject({ reasonCode: "deny_connection_not_installed" }); + await expect(f.gateway.executeTool({ gatewayPublicId: runnerB!.gatewayPublicId, sessionToken: runnerB!.bearerToken, tool: toolA.name, + parameters: {}, idempotencyKey: randomUUID() })).rejects.toMatchObject({ status: expect.any(Number) }); + await expect(runnerB!.assigned.execute({ tool: "paperclip_call_assigned_tool", arguments: { name: toolA.name, arguments: {} } })) + .rejects.toThrow(); + expect(executeCalls()).toBe(callsBefore); + }); + + it("gives the tools of a company-installed connection to every agent", async () => { + const f = await setup(); + const connectionId = await f.connect({ galleryKey: SHARED, connectionMethodKey: "none" }, []); + await request(f.routes).put(`/api/tool-connections/${connectionId}/installs`) + .send({ installs: [{ targetType: "company", targetId: f.company.id }] }).expect(200); + for (const agentId of [f.agentA.id, f.agentB.id]) { + const tool = (await f.gatewayTools(agentId)).find((candidate) => candidate.connectionId === connectionId)!; + expect(tool).toBeDefined(); + const before = executeCalls(); + await f.gateway.executeTool({ sessionToken: f.sessions.get(agentId)!, tool: tool.name, parameters: {}, idempotencyKey: randomUUID() }); + expect(executeCalls()).toBe(before + 1); + } + }); +}); diff --git a/server/src/__tests__/tool-access-policy-index.test.ts b/server/src/__tests__/tool-access-policy-index.test.ts index 1eb798ddd78..97cc4ac4ee4 100644 --- a/server/src/__tests__/tool-access-policy-index.test.ts +++ b/server/src/__tests__/tool-access-policy-index.test.ts @@ -168,6 +168,7 @@ function randomContext(random: ReturnType): ToolAccessContext { catalogVersionHash: null, catalogSchemaHash: null, providerType: pick(["mcp_remote_http", "paperclip_self", null]), + connectionTransport: null, applicationKey: pick(["github", "linear", null]), upstreamToolName: pick(upstreamNames), toolName: pick([...toolNames, ""]), diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 3ee19aa3fd4..c1c10e4a610 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -17,6 +17,7 @@ import { toolCatalogEntries, toolConnections, toolCallEvents, + toolConnectionInstalls, toolInvocations, toolMcpGateways, toolMcpGatewayTokens, @@ -85,6 +86,7 @@ export type ToolAccessContext = { catalogVersionHash: string | null; catalogSchemaHash: string | null; providerType: string | null; + connectionTransport: string | null; applicationKey: string | null; upstreamToolName: string | null; toolName: string; @@ -1264,6 +1266,7 @@ export function toolAccessPolicyService(db: Pick { + if (!ctx.agentId || !ctx.connectionId) return false; + const installs = await cachedRead(cache, `connection-installs:${ctx.companyId}:${ctx.connectionId}`, async () => + db.select({ targetType: toolConnectionInstalls.targetType, targetId: toolConnectionInstalls.targetId }) + .from(toolConnectionInstalls) + .where(and(eq(toolConnectionInstalls.companyId, ctx.companyId), eq(toolConnectionInstalls.connectionId, ctx.connectionId!)))); + return installs.some((install) => (install.targetType === "company" && install.targetId === ctx.companyId) + || (install.targetType === "agent" && install.targetId === ctx.agentId)); + } + async function explicitGrant(ctx: ToolAccessContext, cache?: ToolAccessDecisionCache, options: { toolTargetedOnly?: boolean } = {}): Promise { const principalType = ctx.actorType === "agent" ? "agent" : ctx.actorType === "user" ? "user" : null; const principalId = ctx.actorType === "agent" ? ctx.agentId : ctx.actorId; @@ -1599,6 +1612,11 @@ export function toolAccessPolicyService(db: Pick profile.id); const permittedByProfile = profileState.profiles.some((profile) => { @@ -2004,6 +2022,7 @@ export function toolAccessPolicyService(db: Pick