diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index c819e2699a8..79f784e7b32 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -1352,11 +1352,11 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { expect(await summary()).toEqual([["create_insight", "allowed"], ["list_insights", "allowed"]]); }); - it("keeps the unscoped tools:use grant for agents the connection's profile does not cover", async () => { + it("denies agents without an install on a connection installed for another agent, even with the default unscoped tools:use grant", async () => { const { company, summary } = await setUpGovernedTwoActionConnection({ enabled: "read" }); const [other] = await db.insert(agents).values({ companyId: company.id, name: "Riley", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); await db.insert(principalPermissionGrants).values({ companyId: company.id, principalType: "agent", principalId: other!.id, permissionKey: "tools:use", scope: null }); - expect(await summary(other!.id)).toEqual([["create_insight", "allowed"], ["list_insights", "allowed"]]); + expect(await summary(other!.id)).toEqual([["create_insight", "off"], ["list_insights", "off"]]); }); it("does not let the unscoped tools:use grant override a profile entry that excludes the application", async () => { @@ -3391,7 +3391,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { await expect(policy.decide(decisionInput(writeEntry.id, "create_insight"))) .resolves.toMatchObject({ allowed: false, reasonCode: "deny_default" }); await expect(policy.decide(decisionInput(readEntry.id, "list_insights", outsideAgent!.id))) - .resolves.toMatchObject({ allowed: false, reasonCode: "deny_default" }); + .resolves.toMatchObject({ allowed: false, reasonCode: "deny_connection_not_installed" }); // Simulate a profile written by the legacy install path. Saving installs // must self-heal this over-broad entry as well as avoiding it for new apps. diff --git a/server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts b/server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts index ab83a4c72f2..96c5948033c 100644 --- a/server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts +++ b/server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts @@ -582,6 +582,9 @@ describeEmbeddedPostgres("heartbeat runtime MCP servers", () => { await db.insert(toolProfileBindings).values({ companyId: company!.id, profileId: gateway!.profileId!, targetType: "agent", targetId: gatewayReader!.id, }); + await db.insert(toolConnectionInstalls).values({ + companyId: company!.id, connectionId: connection!.id, targetType: "agent", targetId: gatewayReader!.id, + }); const effective = await toolAccessService(db).getEffectiveProfilesForAgent(company!.id, gatewayReader!.id); expect(effective.allowedTools.map((tool) => tool.id).sort()).toEqual(allowed.map((tool) => tool.id).sort()); expect(effective.allowedToolNames).not.toContain("excluded"); diff --git a/server/src/__tests__/tool-access-policy-index.test.ts b/server/src/__tests__/tool-access-policy-index.test.ts index 97cc4ac4ee4..8ce592d03f1 100644 --- a/server/src/__tests__/tool-access-policy-index.test.ts +++ b/server/src/__tests__/tool-access-policy-index.test.ts @@ -169,6 +169,7 @@ function randomContext(random: ReturnType): ToolAccessContext { catalogSchemaHash: null, providerType: pick(["mcp_remote_http", "paperclip_self", null]), connectionTransport: null, + agentAccessConfigured: false, applicationKey: pick(["github", "linear", null]), upstreamToolName: pick(upstreamNames), toolName: pick([...toolNames, ""]), diff --git a/server/src/__tests__/tool-access-policy-service.test.ts b/server/src/__tests__/tool-access-policy-service.test.ts index c7e468e0dfd..050287eae96 100644 --- a/server/src/__tests__/tool-access-policy-service.test.ts +++ b/server/src/__tests__/tool-access-policy-service.test.ts @@ -1,11 +1,15 @@ import { createHash, randomUUID } from "node:crypto"; -import { eq, sql } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; +import express from "express"; +import request from "supertest"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { activityLog, agents, companies, + companyMemberships, companySecrets, + connectionGrants, createDb, heartbeatRuns, issues, @@ -16,6 +20,7 @@ import { toolApplications, toolCatalogEntries, toolCallEvents, + toolConnectionInstalls, toolConnections, toolInvocations, toolMcpGateways, @@ -33,6 +38,9 @@ import { toolAccessPolicyService } from "../services/tool-access-policy.js"; import { toolAccessService } from "../services/tool-access.js"; import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js"; import { canonicalToolArguments, signToolArguments } from "../services/tool-content-guards.js"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { errorHandler } from "../middleware/index.js"; +import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../lib/agent-permissions.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_POLICY_TEST_DATABASE_URL"); @@ -236,10 +244,13 @@ describeEmbeddedPostgres("tool access policy service", () => { await db.delete(toolMcpGateways); await db.delete(toolProfiles); await db.delete(toolCatalogEntries); + await db.delete(toolConnectionInstalls); + await db.delete(connectionGrants); await db.delete(toolConnections); await db.delete(toolApplications); await db.delete(companySecrets); await db.delete(principalPermissionGrants); + await db.delete(companyMemberships); await db.delete(issues); await db.delete(projects); await db.delete(activityLog); @@ -1892,4 +1903,565 @@ describeEmbeddedPostgres("tool access policy service", () => { }], })).rejects.toThrow(/same company/); }); + + async function grantStandardAgentDefaults(companyId: string, agentId: string) { + await db.insert(principalPermissionGrants).values( + NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({ + companyId, + principalType: "agent" as const, + principalId: agentId, + permissionKey, + scope: newStandardAgentGrantScope(permissionKey, agentId), + })), + ); + } + + it.each([ + { label: "remote MCP", transport: "mcp_remote" as const, appType: "mcp_http" as const }, + { label: "OAuth REST API", transport: "rest_api" as const, appType: "rest_api" as const }, + { label: "local stdio", transport: "local_stdio" as const, appType: "mcp_stdio" as const }, + ])("denies uninstalled agents with default tools:use on an agent-scoped $label connection while allowing the installed agent", async ({ transport, appType }) => { + const company = await createCompany(db); + const agentA = await createAgent(db, company.id); + const agentB = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentA.id); + await grantStandardAgentDefaults(company.id, agentB.id); + + const [application] = await db.insert(toolApplications).values({ + companyId: company.id, + applicationKey: `isolated-${randomUUID()}`, + name: `Isolated ${transport}`, + type: appType, + status: "active", + }).returning(); + const [connection] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: application!.id, + name: `Agent A ${transport}`, + uid: `test/${randomUUID()}`, + transport, + status: "active", + enabled: true, + healthStatus: "ok", + config: transport === "local_stdio" ? { templateId: "fixture" } : { url: "https://8.8.8.8/mcp" }, + }).returning(); + const [catalogEntry] = await db.insert(toolCatalogEntries).values({ + companyId: company.id, + applicationId: application!.id, + connectionId: connection!.id, + name: "read_mailbox", + toolName: "read_mailbox", + riskLevel: "read", + versionHash: randomUUID(), + schemaHash: randomUUID(), + }).returning(); + + const accessSvc = toolAccessService(db); + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: { agentIds: [agentA.id] }, + }); + + const policySvc = toolAccessPolicyService(db); + const decideFor = (agentId: string) => policySvc.decide({ + companyId: company.id, + actor: { actorType: "agent", actorId: agentId, agentId }, + request: { connectionId: connection!.id, catalogEntryId: catalogEntry!.id, toolName: "read_mailbox" }, + }); + + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_profile", + }); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // An agent created after the connection was installed for Agent A must also be denied. + const agentC = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentC.id); + expect(await decideFor(agentC.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // Simulate a pre-marker connection whose wizard-authored app_gallery_finish + // binding exists without config markers, then remove the final install + // through putConnectionInstalls. The installs writer must persist the + // explicit marker and immediately deny the removed agent in policy and + // Effective Access. + const [beforeStrip] = await db + .select({ config: toolConnections.config }) + .from(toolConnections) + .where(eq(toolConnections.id, connection!.id)); + const strippedConfig = { ...((beforeStrip?.config as Record | null) ?? {}) }; + delete strippedConfig.agentAccessConfigured; + delete strippedConfig.mcpAgentAccessConfigured; + await db + .update(toolConnections) + .set({ config: strippedConfig }) + .where(eq(toolConnections.id, connection!.id)); + + await accessSvc.putConnectionInstalls(connection!.id, { installs: [] }); + const [afterUninstall] = await db + .select({ config: toolConnections.config }) + .from(toolConnections) + .where(eq(toolConnections.id, connection!.id)); + expect((afterUninstall?.config as Record | null)?.agentAccessConfigured).toBe(true); + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + const effectiveAfterUninstall = await accessSvc.getEffectiveProfilesForAgent(company.id, agentA.id); + expect(effectiveAfterUninstall.allowedTools).toEqual([]); + expect(effectiveAfterUninstall.profiles.every((profile) => profile.summary.allowedToolCount === 0)).toBe(true); + + // Re-installing for Agent A restores access, and clearing via finish denies everyone. + await accessSvc.putConnectionInstalls(connection!.id, { installs: [{ targetType: "agent", targetId: agentA.id }] }); + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_profile", + }); + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: { agentIds: [] }, + }); + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // Company-wide install allows existing and newly created agents. + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: "all_agents", + }); + for (const agent of [agentA, agentB, agentC]) { + expect(await decideFor(agent.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_profile", + }); + } + }); + + it("aligns policy/test route, live gateway execution, and Effective Access for agent-installed connections and newly created agents", async () => { + const company = await createCompany(db); + await db.insert(companyMemberships).values({ + companyId: company.id, + principalType: "user", + principalId: "board-user", + status: "active", + membershipRole: "admin", + }); + const agentA = await createAgent(db, company.id); + const agentB = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentA.id); + await grantStandardAgentDefaults(company.id, agentB.id); + + // Give Agent B a general allow-by-default profile to ensure Effective Access + // still respects connection installation boundaries and agrees with policy/test. + const [generalProfile] = await db.insert(toolProfiles).values({ + companyId: company.id, + profileKey: `general-allow-${randomUUID()}`, + name: "General Allow", + status: "active", + defaultAction: "allow", + }).returning(); + await db.insert(toolProfileBindings).values({ + companyId: company.id, + profileId: generalProfile!.id, + targetType: "agent", + targetId: agentB.id, + priority: 100, + }); + + const [application] = await db.insert(toolApplications).values({ + companyId: company.id, + applicationKey: `mailbox-${randomUUID()}`, + name: "Mailbox MCP", + type: "mcp_http", + status: "active", + }).returning(); + const [connection] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: application!.id, + name: "Agent A Mailbox", + uid: `test/${randomUUID()}`, + transport: "mcp_remote", + status: "active", + enabled: true, + healthStatus: "ok", + credentialPolicy: "shared", + config: { url: "https://8.8.8.8/mcp" }, + }).returning(); + await db.insert(connectionGrants).values({ + companyId: company.id, + connectionId: connection!.id, + kind: "organization", + status: "active", + isDefault: true, + }); + const [catalogEntry] = await db.insert(toolCatalogEntries).values({ + companyId: company.id, + applicationId: application!.id, + connectionId: connection!.id, + name: "list_messages", + toolName: "list_messages", + riskLevel: "read", + status: "active", + versionHash: randomUUID(), + schemaHash: randomUUID(), + }).returning(); + + const accessSvc = toolAccessService(db); + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: { agentIds: [agentA.id] }, + }); + + const remoteCalls: string[] = []; + const gateway = createToolGatewayService(db, { + toolActionSigningSecret: "conn-install-e2e-secret", + remoteHttpRequest: async (_url, init) => { + const body = JSON.parse(String(init.body)); + if (body.method === "tools/call") remoteCalls.push(body.params.name); + return new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + result: body.method === "initialize" + ? { protocolVersion: "2025-03-26", capabilities: {}, serverInfo: { name: "mailbox", version: "1" } } + : { content: [{ type: "text", text: "secret-mail" }] }, + }), + { headers: { "content-type": "application/json" } }, + ); + }, + }); + + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { + type: "board", + userId: "board-user", + userName: "Board User", + userEmail: null, + isInstanceAdmin: true, + source: "local_implicit", + }; + next(); + }); + app.use("/api", toolAccessRoutes(db, { toolGateway: gateway })); + app.use(errorHandler); + + const agentC = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentC.id); + + const policyTest = (agentId: string) => + request(app) + .post(`/api/companies/${company.id}/tools/policy/test`) + .send({ + companyId: company.id, + actor: { actorType: "agent", actorId: agentId, agentId }, + request: { connectionId: connection!.id, catalogEntryId: catalogEntry!.id, toolName: "list_messages", arguments: {} }, + }); + const effectiveAccess = (agentId: string) => + request(app).get(`/api/companies/${company.id}/tools/profiles/effective/agents/${agentId}`); + + // 1. POST /companies/:companyId/tools/policy/test + const testA = await policyTest(agentA.id).expect(200); + expect(testA.body.decision).toMatchObject({ allowed: true, decision: "allow", reasonCode: "allow_profile" }); + const testB = await policyTest(agentB.id).expect(200); + expect(testB.body.decision).toMatchObject({ allowed: false, decision: "deny", reasonCode: "deny_connection_not_installed" }); + const testC = await policyTest(agentC.id).expect(200); + expect(testC.body.decision).toMatchObject({ allowed: false, decision: "deny", reasonCode: "deny_connection_not_installed" }); + + // 2. Effective Access view agrees with policy/test for all three agents + const effA = await effectiveAccess(agentA.id).expect(200); + expect(effA.body.allowedTools.map((t: { id: string }) => t.id)).toContain(catalogEntry!.id); + const effB = await effectiveAccess(agentB.id).expect(200); + expect(effB.body.allowedTools.map((t: { id: string }) => t.id)).not.toContain(catalogEntry!.id); + expect(effB.body.profiles[0].summary.allowedToolCount).toBe(0); + const effC = await effectiveAccess(agentC.id).expect(200); + expect(effC.body.allowedTools.map((t: { id: string }) => t.id)).not.toContain(catalogEntry!.id); + + // 3. Live gateway listing + tool execution + const runA = await createRun(db, company.id, agentA.id); + const runB = await createRun(db, company.id, agentB.id); + const runC = await createRun(db, company.id, agentC.id); + const sessionA = await gateway.createSession({ companyId: company.id, agentId: agentA.id, runId: runA.id }); + const sessionB = await gateway.createSession({ companyId: company.id, agentId: agentB.id, runId: runB.id }); + const sessionC = await gateway.createSession({ companyId: company.id, agentId: agentC.id, runId: runC.id }); + + const toolA = (await gateway.listToolsForSession(sessionA.token)).find((t) => t.connectionId === connection!.id); + expect(toolA).toBeDefined(); + expect((await gateway.listToolsForSession(sessionB.token)).filter((t) => t.connectionId === connection!.id)).toEqual([]); + expect((await gateway.listToolsForSession(sessionC.token)).filter((t) => t.connectionId === connection!.id)).toEqual([]); + + const execA = await gateway.executeTool({ sessionToken: sessionA.token, tool: toolA!.name, parameters: {} }); + expect(execA.status).toBe("completed"); + expect(remoteCalls).toEqual(["list_messages"]); + + await expect(gateway.executeTool({ sessionToken: sessionB.token, tool: toolA!.name, parameters: {} })) + .rejects.toMatchObject({ reasonCode: "deny_connection_not_installed" }); + await expect(gateway.executeTool({ sessionToken: sessionC.token, tool: toolA!.name, parameters: {} })) + .rejects.toMatchObject({ reasonCode: "deny_connection_not_installed" }); + expect(remoteCalls).toEqual(["list_messages"]); + }); + + it("does not widen agent-scoped connection installs when catalog default access rebuilds the app profile on reconnect", async () => { + const company = await createCompany(db); + const agentA = await createAgent(db, company.id); + const agentB = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentA.id); + await grantStandardAgentDefaults(company.id, agentB.id); + + const [application] = await db.insert(toolApplications).values({ + companyId: company.id, + applicationKey: `reconnect-${randomUUID()}`, + name: "Reconnect MCP", + type: "mcp_http", + status: "active", + }).returning(); + const [connection] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: application!.id, + name: "Reconnect Connection", + uid: `test/${randomUUID()}`, + transport: "mcp_remote", + status: "active", + enabled: true, + healthStatus: "ok", + config: { url: "https://8.8.8.8/mcp" }, + }).returning(); + const [catalogEntry] = await db.insert(toolCatalogEntries).values({ + companyId: company.id, + applicationId: application!.id, + connectionId: connection!.id, + name: "read_record", + toolName: "read_record", + riskLevel: "read", + status: "active", + versionHash: randomUUID(), + schemaHash: randomUUID(), + }).returning(); + + const accessSvc = toolAccessService(db, { + remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }], + remoteHttpRequest: async (_url, init) => { + const body = JSON.parse(String(init.body)); + if (body.method === "notifications/initialized") return new Response(null, { status: 202 }); + return Response.json({ + jsonrpc: "2.0", + id: body.id, + result: body.method === "initialize" + ? { protocolVersion: "2025-03-26", capabilities: {}, serverInfo: { name: "reconnect", version: "1" } } + : { tools: [{ name: "read_record", description: "Read", inputSchema: { type: "object" } }] }, + }); + }, + }); + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: { agentIds: [agentA.id] }, + }); + + // Archive the app profile to simulate a retained/revived profile rebuild during reconnect refresh. + await db + .update(toolProfiles) + .set({ status: "archived" }) + .where(eq(toolProfiles.profileKey, `app:${connection!.id}`)); + + await accessSvc.refreshCatalog(connection!.id, undefined, { enableAllByDefault: true, restoreDraftDefaults: true }); + + const [rebuiltProfile] = await db + .select() + .from(toolProfiles) + .where(eq(toolProfiles.profileKey, `app:${connection!.id}`)); + const rebuiltBindings = await db + .select() + .from(toolProfileBindings) + .where(eq(toolProfileBindings.profileId, rebuiltProfile!.id)); + expect(rebuiltBindings.map((b) => ({ targetType: b.targetType, targetId: b.targetId }))).toEqual([ + { targetType: "agent", targetId: agentA.id }, + ]); + + const policySvc = toolAccessPolicyService(db); + expect(await policySvc.decide({ + companyId: company.id, + actor: { actorType: "agent", actorId: agentA.id, agentId: agentA.id }, + request: { connectionId: connection!.id, catalogEntryId: catalogEntry!.id, toolName: "read_record" }, + })).toMatchObject({ allowed: true, decision: "allow" }); + expect(await policySvc.decide({ + companyId: company.id, + actor: { actorType: "agent", actorId: agentB.id, agentId: agentB.id }, + request: { connectionId: connection!.id, catalogEntryId: catalogEntry!.id, toolName: "read_record" }, + })).toMatchObject({ allowed: false, decision: "deny", reasonCode: "deny_connection_not_installed" }); + }); + + it("denies generic require_approval for uninstalled or removed agents while preserving explicit allow policies and tool-targeted grants", async () => { + const company = await createCompany(db); + const agentA = await createAgent(db, company.id); + const agentB = await createAgent(db, company.id); + await grantStandardAgentDefaults(company.id, agentA.id); + await grantStandardAgentDefaults(company.id, agentB.id); + + const [application] = await db.insert(toolApplications).values({ + companyId: company.id, + applicationKey: `approval-precedence-${randomUUID().slice(0, 8)}`, + name: "Approval Precedence App", + type: "mcp_http", + status: "active", + }).returning(); + const [connection] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: application!.id, + name: "Approval Precedence Connection", + uid: `test/${randomUUID()}`, + transport: "mcp_remote", + status: "active", + enabled: true, + healthStatus: "ok", + config: { url: "https://8.8.8.8/mcp" }, + }).returning(); + const [catalogEntry] = await db.insert(toolCatalogEntries).values({ + companyId: company.id, + applicationId: application!.id, + connectionId: connection!.id, + name: "read_record", + toolName: "read_record", + riskLevel: "read", + status: "active", + versionHash: randomUUID(), + schemaHash: randomUUID(), + }).returning(); + + const accessSvc = toolAccessService(db); + await accessSvc.finishGalleryAppConnection(company.id, connection!.id, { + enabledCatalogEntryIds: [catalogEntry!.id], + askFirstCatalogEntryIds: [], + access: { agentIds: [agentA.id] }, + }); + + const [approvalPolicy] = await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Require approval on reads", + policyType: "require_approval", + priority: 10, + selectors: { connectionId: connection!.id }, + config: {}, + enabled: true, + }).returning(); + + const policySvc = toolAccessPolicyService(db); + const decideFor = (agentId: string) => policySvc.decide({ + companyId: company.id, + actor: { actorType: "agent", actorId: agentId, agentId }, + request: { connectionId: connection!.id, catalogEntryId: catalogEntry!.id, toolName: "read_record" }, + }); + + // Installed Agent A hits require_approval; uninstalled Agent B is denied outright. + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: false, + decision: "require_approval", + reasonCode: "requires_approval_policy", + }); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // Removing Agent A's final install immediately denies instead of returning + // require_approval, so a previously pending approval cannot execute. + await accessSvc.putConnectionInstalls(connection!.id, { installs: [] }); + expect(await decideFor(agentA.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // A lower-priority allow policy must not bypass a higher-priority require_approval + // on an uninstalled agent. + await accessSvc.putConnectionInstalls(connection!.id, { installs: [{ targetType: "agent", targetId: agentA.id }] }); + const [allowPolicy] = await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Explicit allow for Agent B", + policyType: "allow", + priority: 20, + selectors: { connectionId: connection!.id, agentId: agentB.id }, + config: {}, + enabled: true, + }).returning(); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + + // Without the higher-priority require_approval policy, an explicit operator + // allow policy or tool-targeted tools:use grant authorizes Agent B. + await db.delete(toolPolicies).where(eq(toolPolicies.id, approvalPolicy!.id)); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_policy", + }); + + await db.delete(toolPolicies).where(eq(toolPolicies.id, allowPolicy!.id)); + await db + .update(principalPermissionGrants) + .set({ scope: { connectionId: connection!.id } }) + .where(and( + eq(principalPermissionGrants.companyId, company.id), + eq(principalPermissionGrants.principalId, agentB.id), + eq(principalPermissionGrants.permissionKey, "tools:use"), + )); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_explicit_grant", + }); + + await db + .update(principalPermissionGrants) + .set({ scope: { allow: ["tool:read_record"] } }) + .where(and( + eq(principalPermissionGrants.companyId, company.id), + eq(principalPermissionGrants.principalId, agentB.id), + eq(principalPermissionGrants.permissionKey, "tools:use"), + )); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: true, + decision: "allow", + reasonCode: "allow_explicit_grant", + }); + + // Reverting Agent B to default unscoped tools:use restores denial. + await db + .update(principalPermissionGrants) + .set({ scope: null }) + .where(and( + eq(principalPermissionGrants.companyId, company.id), + eq(principalPermissionGrants.principalId, agentB.id), + eq(principalPermissionGrants.permissionKey, "tools:use"), + )); + expect(await decideFor(agentB.id)).toMatchObject({ + allowed: false, + decision: "deny", + reasonCode: "deny_connection_not_installed", + }); + }); }); diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 6b0944c38ad..18a0a34fb96 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -17,7 +17,6 @@ import { toolCatalogEntries, toolConnections, toolCallEvents, - toolConnectionInstalls, toolInvocations, toolMcpGateways, toolMcpGatewayTokens, @@ -62,6 +61,11 @@ import { type CompiledPolicySelector, type PolicySelectorIndex, } from "./tool-access/policy-selector-index.js"; +import { + agentAccessConfiguredSql, + readConnectionAccessBoundaries, + type ConnectionAccessBoundary, +} from "./tool-access/connection-access-boundary.js"; class RejectedInvocationAdmission extends Error { constructor(readonly decision: ToolAccessDecision) { @@ -87,6 +91,7 @@ export type ToolAccessContext = { catalogSchemaHash: string | null; providerType: string | null; connectionTransport: string | null; + agentAccessConfigured: boolean; applicationKey: string | null; upstreamToolName: string | null; toolName: string; @@ -1167,6 +1172,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 connectionAccessBoundary( + ctx: ToolAccessContext, + cache?: ToolAccessDecisionCache, + ): Promise { + if (ctx.actorType !== "agent" || !ctx.connectionId) return null; + const connectionId = ctx.connectionId; + return cachedRead(cache, `connection-access-boundary:${ctx.companyId}:${ctx.agentId ?? "none"}:${connectionId}`, async () => { + const boundaries = await readConnectionAccessBoundaries(db, { + companyId: ctx.companyId, + agentId: ctx.agentId, + connectionIds: [connectionId], + knownConnections: new Map([[connectionId, { + transport: ctx.connectionTransport, + agentAccessConfigured: ctx.agentAccessConfigured, + }]]), + }); + return boundaries.get(connectionId) ?? null; + }); } async function explicitGrant(ctx: ToolAccessContext, cache?: ToolAccessDecisionCache, options: { toolTargetedOnly?: boolean } = {}): Promise { @@ -1618,14 +1637,18 @@ export function toolAccessPolicyService(db: Pick profile.id); - const permittedByProfile = profileState.profiles.some((profile) => { + const permittedByProfile = !blockedByConnectionInstall && profileState.profiles.some((profile) => { const matchingEntries = profileState.entries.filter((entry) => entry.profileId === profile.id && profileEntryMatches(entry, ctx)); return !matchingEntries.some((entry) => entry.effect === "exclude") && (profile.defaultAction === "allow" || matchingEntries.some((entry) => entry.effect === "include")); @@ -1704,6 +1727,7 @@ export function toolAccessPolicyService(db: Pick isConnectionAccessProfile(profile, ctx.connectionId)) + Boolean(connectionBoundary?.requiresInstall || connectionBoundary?.hasManagedProfile) + || profileState.profiles.some((profile) => isConnectionAccessProfile(profile, ctx.connectionId)) || profileState.entries.some((entry) => entry.connectionId === ctx.connectionId || profileEntryMatches(entry, ctx)) ); if (await explicitGrant(ctx, cache, { toolTargetedOnly: governedByConnectionProfile })) { return decision("allow", "allow_explicit_grant", "Tool access allowed by explicit grant.", effectiveProfileIds, [], { redactionPlan: redaction.redactionPlan }); } + if (blockedByConnectionInstall) { + return decision("deny", "deny_connection_not_installed", + "This connection is not installed for this agent.", effectiveProfileIds, [], { redactionPlan: redaction.redactionPlan }); + } const entriesByProfile = new Map>(); for (const entry of profileState.entries) { @@ -2052,6 +2088,7 @@ export function toolAccessPolicyService(db: Pick = galleryEntry ? { ...baseConfig, + ...preservedAccessMarkers, ...(awsRoleIssuer ? { [AWS_MCP_ISSUER_CONFIG_KEY]: awsRoleIssuer } : {}), sourceTemplateKey: galleryEntry.slug, connectionMethodKey: method?.key, @@ -2315,6 +2324,7 @@ export function toolAccessService( } : { ...baseConfig, + ...preservedAccessMarkers, quarantineNewEntries: false, unverifiedServer: true, // Peer tool prefix, fixed when the identity is created. A retained @@ -3786,10 +3796,15 @@ export function toolAccessService( .update(toolConnections) .set({ status: "active", enabled: true, - ...(connection.connectionPurpose === "tool" && connection.transport === "mcp_remote" ? { - config: sql`${toolConnections.config} || '{"mcpAgentAccessConfigured":true}'::jsonb`, - transportConfig: sql`${toolConnections.transportConfig} || '{"mcpAgentAccessConfigured":true}'::jsonb`, - } : {}), + ...(connection.connectionPurpose === "tool" ? (() => { + const accessMarker = connection.transport === "mcp_remote" + ? '{"agentAccessConfigured":true,"mcpAgentAccessConfigured":true}' + : '{"agentAccessConfigured":true}'; + return { + config: sql`${toolConnections.config} || ${accessMarker}::jsonb`, + transportConfig: sql`${toolConnections.transportConfig} || ${accessMarker}::jsonb`, + }; + })() : {}), ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), updatedAt: new Date(), }) diff --git a/server/src/services/tool-access/catalog/default-access.ts b/server/src/services/tool-access/catalog/default-access.ts index 7f77a9560dc..caad8f5cf78 100644 --- a/server/src/services/tool-access/catalog/default-access.ts +++ b/server/src/services/tool-access/catalog/default-access.ts @@ -6,6 +6,7 @@ import { and, eq, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { toolCatalogEntries, toolConnections, toolPolicies, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; import type { ToolPolicy } from "@paperclipai/shared"; +import { defaultConnectionProfileBindingTargets } from "../connection-access-boundary.js"; function asRecord(value: unknown): Record { if (value && typeof value === "object" && !Array.isArray(value)) @@ -72,6 +73,8 @@ export function createCatalogDefaultAccess(db: Db) { const createdProfile = !profile; const resetToRecommendedDefaults = !profile || profile.status !== "active"; if (resetToRecommendedDefaults) await lockToolAssignmentAgents(dbClient, input.connection.companyId, [{ targetType: "company", targetId: input.connection.companyId }]); + const defaultBindingTargets = () => defaultConnectionProfileBindingTargets(dbClient, input.connection); + if (!profile) { const [sameName] = await dbClient .select({ id: toolProfiles.id }) @@ -101,25 +104,30 @@ export function createCatalogDefaultAccess(db: Db) { }, }) .returning(); - await dbClient.insert(toolProfileBindings).values({ - companyId: input.connection.companyId, - profileId: profile.id, - targetType: "company", - targetId: input.connection.companyId, - priority: 100, - metadata: { source: "app_gallery_finish" }, - createdByAgentId: - input.actor?.actorType === "agent" - ? (input.actor.actorId ?? null) - : null, - createdByUserId: - connectionActorUserId(input.actor), - }); + const targets = await defaultBindingTargets(); + if (targets.length > 0) { + await dbClient.insert(toolProfileBindings).values( + targets.map((target) => ({ + companyId: input.connection.companyId, + profileId: profile.id, + targetType: target.targetType, + targetId: target.targetId, + priority: 100, + metadata: { source: "app_gallery_finish" }, + createdByAgentId: + input.actor?.actorType === "agent" + ? (input.actor.actorId ?? null) + : null, + createdByUserId: + connectionActorUserId(input.actor), + })), + ); + } } else if (resetToRecommendedDefaults) { // Removing an app may retain its profile row when another record still // references it (for example, an MCP gateway). Reconnecting revives the - // same connection id, so restore that retained profile as a fresh - // all-agents assignment instead of leaving every read action Off. + // same connection id, so restore that retained profile without widening + // any saved install boundaries. [profile] = await dbClient .update(toolProfiles) .set({ @@ -151,20 +159,25 @@ export function createCatalogDefaultAccess(db: Db) { eq(toolProfileEntries.profileId, profile.id), ), ); - await dbClient.insert(toolProfileBindings).values({ - companyId: input.connection.companyId, - profileId: profile.id, - targetType: "company", - targetId: input.connection.companyId, - priority: 100, - metadata: { source: "app_gallery_finish" }, - createdByAgentId: - input.actor?.actorType === "agent" - ? (input.actor.actorId ?? null) - : null, - createdByUserId: - connectionActorUserId(input.actor), - }); + const targets = await defaultBindingTargets(); + if (targets.length > 0) { + await dbClient.insert(toolProfileBindings).values( + targets.map((target) => ({ + companyId: input.connection.companyId, + profileId: profile.id, + targetType: target.targetType, + targetId: target.targetId, + priority: 100, + metadata: { source: "app_gallery_finish" }, + createdByAgentId: + input.actor?.actorType === "agent" + ? (input.actor.actorId ?? null) + : null, + createdByUserId: + connectionActorUserId(input.actor), + })), + ); + } } if (resetToRecommendedDefaults) { diff --git a/server/src/services/tool-access/connection-access-boundary.ts b/server/src/services/tool-access/connection-access-boundary.ts new file mode 100644 index 00000000000..405a93ad260 --- /dev/null +++ b/server/src/services/tool-access/connection-access-boundary.ts @@ -0,0 +1,212 @@ +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + toolConnectionInstalls, + toolConnections, + toolProfileBindings, + toolProfiles, +} from "@paperclipai/db"; +import { isConnectionAccessProfile } from "../tool-profile-binding-precedence.js"; + +type ReadDb = Pick; + +export type ConnectionAccessBoundary = { + installedForAgent: boolean; + hasAnyInstalls: boolean; + agentAccessConfigured: boolean; + hasManagedProfile: boolean; + hasUnboundManagedProfile: boolean; + requiresInstall: boolean; +}; + +export type KnownConnectionAccessMeta = { + transport: string | null; + agentAccessConfigured: boolean; +}; + +export function hasAgentAccessConfiguredMarker(config: unknown): boolean { + if (!config || typeof config !== "object" || Array.isArray(config)) return false; + const record = config as Record; + return record.agentAccessConfigured === true || record.mcpAgentAccessConfigured === true; +} + +export function agentAccessConfiguredSql() { + return sql`coalesce((${toolConnections.config} ->> 'agentAccessConfigured') = 'true' or (${toolConnections.config} ->> 'mcpAgentAccessConfigured') = 'true', false)`.as("agent_access_configured"); +} + +export function connectionRequiresInstall(state: { + transport: string | null; + hasAnyInstalls: boolean; + agentAccessConfigured: boolean; + hasUnboundManagedProfile: boolean; +}): boolean { + return state.transport === "plugin" + || state.hasAnyInstalls + || state.agentAccessConfigured + || state.hasUnboundManagedProfile; +} + +export async function readConnectionAccessBoundaries( + db: ReadDb, + input: { + companyId: string; + agentId: string | null; + connectionIds: readonly string[]; + knownConnections?: ReadonlyMap; + }, +): Promise> { + const uniqueIds = [...new Set(input.connectionIds)]; + const result = new Map(); + if (uniqueIds.length === 0) return result; + + const missingConnectionIds = uniqueIds.filter((id) => !input.knownConnections?.has(id)); + const [connectionRows, installRows, managedProfileRows] = await Promise.all([ + missingConnectionIds.length > 0 + ? db + .select({ + id: toolConnections.id, + transport: toolConnections.transport, + agentAccessConfigured: agentAccessConfiguredSql(), + }) + .from(toolConnections) + .where(and( + eq(toolConnections.companyId, input.companyId), + inArray(toolConnections.id, missingConnectionIds), + )) + : Promise.resolve([]), + db + .select({ + connectionId: toolConnectionInstalls.connectionId, + targetType: toolConnectionInstalls.targetType, + targetId: toolConnectionInstalls.targetId, + }) + .from(toolConnectionInstalls) + .where(and( + eq(toolConnectionInstalls.companyId, input.companyId), + inArray(toolConnectionInstalls.connectionId, uniqueIds), + )), + db + .select({ + id: toolProfiles.id, + profileKey: toolProfiles.profileKey, + metadata: toolProfiles.metadata, + }) + .from(toolProfiles) + .where(and( + eq(toolProfiles.companyId, input.companyId), + eq(toolProfiles.status, "active"), + or( + inArray(toolProfiles.profileKey, uniqueIds.map((id) => `app:${id}`)), + sql`${toolProfiles.metadata}->>'source' = 'connection_intent' and (${toolProfiles.metadata}->>'connectionId') = any(${sql.param(uniqueIds)}::text[])`, + ), + )), + ]); + + const metaByConnectionId = new Map(); + if (input.knownConnections) { + for (const [id, meta] of input.knownConnections.entries()) { + metaByConnectionId.set(id, meta); + } + } + for (const row of connectionRows) { + metaByConnectionId.set(row.id, { + transport: row.transport, + agentAccessConfigured: Boolean(row.agentAccessConfigured), + }); + } + + const installsByConnectionId = new Map>(); + for (const row of installRows) { + const list = installsByConnectionId.get(row.connectionId) ?? []; + list.push({ targetType: row.targetType, targetId: row.targetId }); + installsByConnectionId.set(row.connectionId, list); + } + + const managedCandidates = managedProfileRows.flatMap((row) => { + const metadata = row.metadata && typeof row.metadata === "object" && !Array.isArray(row.metadata) + ? row.metadata as Record + : null; + const connectionId = typeof metadata?.connectionId === "string" ? metadata.connectionId : null; + return connectionId && isConnectionAccessProfile(row, connectionId) + ? [{ id: row.id, connectionId }] + : []; + }); + + const boundManagedProfileIds = managedCandidates.length > 0 + ? new Set( + (await db + .select({ profileId: toolProfileBindings.profileId }) + .from(toolProfileBindings) + .where(and( + eq(toolProfileBindings.companyId, input.companyId), + inArray(toolProfileBindings.profileId, managedCandidates.map((profile) => profile.id)), + )) + .groupBy(toolProfileBindings.profileId) + ).map((row) => row.profileId), + ) + : new Set(); + + const managedByConnectionId = new Map>(); + for (const profile of managedCandidates) { + const list = managedByConnectionId.get(profile.connectionId) ?? []; + list.push({ hasBinding: boundManagedProfileIds.has(profile.id) }); + managedByConnectionId.set(profile.connectionId, list); + } + + for (const connectionId of uniqueIds) { + const meta = metaByConnectionId.get(connectionId); + const installs = installsByConnectionId.get(connectionId) ?? []; + const hasAnyInstalls = installs.length > 0; + const installedForAgent = Boolean( + input.agentId && installs.some((install) => + (install.targetType === "company" && install.targetId === input.companyId) + || (install.targetType === "agent" && install.targetId === input.agentId), + ), + ); + const agentAccessConfigured = Boolean(meta?.agentAccessConfigured); + const managed = managedByConnectionId.get(connectionId) ?? []; + const hasManagedProfile = managed.length > 0; + const hasUnboundManagedProfile = hasManagedProfile && managed.every((profile) => !profile.hasBinding); + const requiresInstall = connectionRequiresInstall({ + transport: meta?.transport ?? null, + hasAnyInstalls, + agentAccessConfigured, + hasUnboundManagedProfile, + }); + result.set(connectionId, { + installedForAgent, + hasAnyInstalls, + agentAccessConfigured, + hasManagedProfile, + hasUnboundManagedProfile, + requiresInstall, + }); + } + + return result; +} + +export async function defaultConnectionProfileBindingTargets( + db: ReadDb, + connection: Pick, +): Promise> { + const existingInstalls = await db + .select({ targetType: toolConnectionInstalls.targetType, targetId: toolConnectionInstalls.targetId }) + .from(toolConnectionInstalls) + .where(and( + eq(toolConnectionInstalls.companyId, connection.companyId), + eq(toolConnectionInstalls.connectionId, connection.id), + )); + if (existingInstalls.length > 0) { + if (existingInstalls.some((install) => install.targetType === "company" && install.targetId === connection.companyId)) { + return [{ targetType: "company", targetId: connection.companyId }]; + } + return existingInstalls + .filter((install) => install.targetType === "agent") + .map((install) => ({ targetType: "agent", targetId: install.targetId })); + } + if (hasAgentAccessConfiguredMarker(connection.config)) { + return []; + } + return [{ targetType: "company", targetId: connection.companyId }]; +} diff --git a/server/src/services/tool-access/connections/installs.ts b/server/src/services/tool-access/connections/installs.ts index 87884cba51e..07c7ec9a827 100644 --- a/server/src/services/tool-access/connections/installs.ts +++ b/server/src/services/tool-access/connections/installs.ts @@ -171,8 +171,15 @@ export function createConnectionInstalls(db: Db, { now, getConnectionRow, assert ); } } + const markAgentAccessConfigured = connection.connectionPurpose !== "ai" + && connection.config.agentAccessConfigured !== true; const markMcpAccessConfigured = connection.transport === "mcp_remote" && connection.config.mcpAgentAccessConfigured !== true; + const accessMarkerPatch = { + ...(markAgentAccessConfigured ? { agentAccessConfigured: true } : {}), + ...(markMcpAccessConfigured ? { mcpAgentAccessConfigured: true } : {}), + }; + const markAccessConfigured = Object.keys(accessMarkerPatch).length > 0; const accessExtensions: Array<{ targetType: "company" | "agent"; targetId: string; @@ -180,12 +187,13 @@ export function createConnectionInstalls(db: Db, { now, getConnectionRow, assert }> = []; await db.transaction(async (tx) => { await lockToolConnectionRuntimeInputs(tx, connection.companyId, connection.id); - if (markMcpAccessConfigured) { - // Preserve an explicit zero-agent selection through OAuth. Merge the - // marker in SQL so concurrent credential/config changes are retained. + if (markAccessConfigured) { + // Preserve explicit install selections (including zero agents) across + // OAuth and uninstalls. Merge in SQL so concurrent changes stay intact. + const patchJson = JSON.stringify(accessMarkerPatch); await tx.update(toolConnections).set({ - config: sql`${toolConnections.config} || '{"mcpAgentAccessConfigured":true}'::jsonb`, - transportConfig: sql`${toolConnections.transportConfig} || '{"mcpAgentAccessConfigured":true}'::jsonb`, + config: sql`${toolConnections.config} || ${patchJson}::jsonb`, + transportConfig: sql`${toolConnections.transportConfig} || ${patchJson}::jsonb`, updatedAt: now(), }).where(and( eq(toolConnections.companyId, connection.companyId), @@ -310,7 +318,7 @@ export function createConnectionInstalls(db: Db, { now, getConnectionRow, assert }); } } - if (markMcpAccessConfigured || removeIds.length > 0 || additions.length > 0) { + if (markAccessConfigured || removeIds.length > 0 || additions.length > 0) { const binding = actorBinding(actor); await tx.insert(toolAccessAuditEvents).values({ companyId: connection.companyId, @@ -321,6 +329,7 @@ export function createConnectionInstalls(db: Db, { now, getConnectionRow, assert outcome: "success", reasonCode: "installs_changed", details: { + ...(markAgentAccessConfigured ? { agentAccessConfigured: true } : {}), ...(markMcpAccessConfigured ? { mcpAgentAccessConfigured: true } : {}), added: additions.map((install) => ({ targetType: install.targetType, diff --git a/server/src/services/tool-access/oauth/catalog-completion.ts b/server/src/services/tool-access/oauth/catalog-completion.ts index 5e090ec3462..adf87bdd7db 100644 --- a/server/src/services/tool-access/oauth/catalog-completion.ts +++ b/server/src/services/tool-access/oauth/catalog-completion.ts @@ -3,10 +3,11 @@ import type { ActorInfo } from "../types.js"; import { isPluginAppSlug, isRemoteMcpConnectorMethod } from "@paperclipai/shared"; import { and, eq } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { issueThreadInteractions, toolConnectionInstalls, toolConnections } from "@paperclipai/db"; +import { issueThreadInteractions, toolConnectionInstalls, toolConnections, toolProfiles } from "@paperclipai/db"; import type { ConnectToolAppResult, FinishToolApp, ToolCatalogEntry } from "@paperclipai/shared"; import type { FinishConnectionSetup } from "../catalog/contracts.js"; +import { hasAgentAccessConfiguredMarker } from "../connection-access-boundary.js"; function asRecord(value: unknown): Record { if (value && typeof value === "object" && !Array.isArray(value)) return value as Record; @@ -66,18 +67,30 @@ export function createOAuthCatalogCompletion(db: Db, finishGalleryAppConnection: : suggestedAgentIds.length > 0 ? { agentIds: suggestedAgentIds } : "all_agents"; + const [existingAppProfile] = installs.length === 0 + ? await db + .select({ id: toolProfiles.id }) + .from(toolProfiles) + .where(and( + eq(toolProfiles.companyId, input.connection.companyId), + eq(toolProfiles.profileKey, `app:${input.connection.id}`), + eq(toolProfiles.status, "active"), + )) + .limit(1) + : []; // Workspace setup saves the operator's install selection before OAuth too. // An empty selection means no agents, not permission to apply all-agent // defaults after the user returns from Google. // A plugin connector never gets agent access from signing in: an agent or // company install is always an explicit operator choice. - const preserveEmptyInstalls = isPluginAppSlug(input.connection.config.sourceTemplateKey) + const preserveEmptyInstalls = Boolean(existingAppProfile) + || isPluginAppSlug(input.connection.config.sourceTemplateKey) || input.connection.config.sourceTemplateKey === "google-workspace" || isRemoteMcpConnectorMethod( - input.connection.config.sourceTemplateKey, - input.connection.config.connectionMethodKey, - ) || (input.connection.transport === "mcp_remote" - && input.connection.config.mcpAgentAccessConfigured === true); + input.connection.config.sourceTemplateKey, + input.connection.config.connectionMethodKey, + ) + || hasAgentAccessConfiguredMarker(input.connection.config); const access: FinishToolApp["access"] = deferTaskAccess ? { agentIds: [] } : installs.length === 0 diff --git a/server/src/services/tool-access/oauth/vercel-callback.ts b/server/src/services/tool-access/oauth/vercel-callback.ts index 65e2b406768..8dc82a7b263 100644 --- a/server/src/services/tool-access/oauth/vercel-callback.ts +++ b/server/src/services/tool-access/oauth/vercel-callback.ts @@ -230,9 +230,10 @@ export function createVercelOAuthCallback(db: Db, dependencies: Dependencies) { "Vercel Connect connection is missing its reviewed app definition", ); const method = connectionMethodForConnection(galleryEntry, connection); + const shouldFinalizeDefaults = preActivationLifecycle.status === "draft"; const refresh = await refreshCatalog(connection.id, input.actor, { - enableAllByDefault: true, - skipDefaultProfileSync: true, + enableAllByDefault: shouldFinalizeDefaults, + skipDefaultProfileSync: shouldFinalizeDefaults, credentialHeaders: { ...projectedConnectionHeaders(connection), [credential.headerName]: `${credential.headerPrefix ?? ""}${token.token}`, @@ -242,13 +243,15 @@ export function createVercelOAuthCallback(db: Db, dependencies: Dependencies) { galleryEntry, method.key, ); - const finished = await finishOAuthCatalogWithRecommendedDefaults({ - interactionId: stateRow.interactionId, - connection, - catalog: refresh.catalog, - suggestedDefaults, - actor: input.actor, - }); + const finished = shouldFinalizeDefaults + ? await finishOAuthCatalogWithRecommendedDefaults({ + interactionId: stateRow.interactionId, + connection, + catalog: refresh.catalog, + suggestedDefaults, + actor: input.actor, + }) + : null; const [application] = await db .select() .from(toolApplications) @@ -256,7 +259,7 @@ export function createVercelOAuthCallback(db: Db, dependencies: Dependencies) { return { connectionId: connection.id, application: toApplication(application), - connection: finished.connection, + connection: finished?.connection ?? refresh.connection, catalog: refresh.catalog, actions: groupedActions(refresh.catalog), suggestedDefaults, diff --git a/server/src/services/tool-access/profiles/resolution.ts b/server/src/services/tool-access/profiles/resolution.ts index b06683b8203..3e919322293 100644 --- a/server/src/services/tool-access/profiles/resolution.ts +++ b/server/src/services/tool-access/profiles/resolution.ts @@ -3,6 +3,7 @@ import type { Db } from "@paperclipai/db"; import { agents, toolCatalogEntries, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; import type { ToolCatalogEntry, ToolConnection, ToolProfileEffectiveSummary, ToolProfileWithDetails } from "@paperclipai/shared"; import { effectiveToolProfileBindings, profileIdsInBindingOrder } from "../../tool-profile-binding-precedence.js"; +import { readConnectionAccessBoundaries } from "../connection-access-boundary.js"; import { buildProfileDetails, profileCatalogColumns, profileCatalogMatcher, toProfileBinding, toProfileEntry, type ProfileCatalogEntry, type ProfileEntryMatch, type ProfileCatalogMatch } from "./projection.js"; type ProfileAssignmentDependencies = { assertOptionalAgent(companyId: string, agentId: string | null | undefined, label: string): Promise; @@ -108,6 +109,35 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve return { bindings, activeProfiles }; } + async function filterCatalogByConnectionInstalls( + companyId: string, + agentId: string, + catalog: T[], + installedConnections: ToolConnection[], + ): Promise { + if (catalog.length === 0) return catalog; + const installedIds = new Set(installedConnections.map((connection) => connection.id)); + const uninstalledConnectionIds = [...new Set( + catalog + .map((entry) => entry.connectionId) + .filter((connectionId) => !installedIds.has(connectionId)), + )]; + if (uninstalledConnectionIds.length === 0) return catalog; + const boundaries = await readConnectionAccessBoundaries(db, { + companyId, + agentId, + connectionIds: uninstalledConnectionIds, + }); + const blockedConnectionIds = new Set(); + for (const [connectionId, boundary] of boundaries.entries()) { + if (boundary.requiresInstall && !boundary.installedForAgent) { + blockedConnectionIds.add(connectionId); + } + } + if (blockedConnectionIds.size === 0) return catalog; + return catalog.filter((entry) => !blockedConnectionIds.has(entry.connectionId)); + } + async function resolveEffectiveProfiles( companyId: string, agentId: string, @@ -130,7 +160,7 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve }; } const activeProfileIds = activeProfiles.map((profile) => profile.id); - const [entries, catalog, companyAgents] = await Promise.all([ + const [entries, catalog, companyAgents, installedConnections] = await Promise.all([ db .select() .from(toolProfileEntries) @@ -146,6 +176,10 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve .select({ id: agents.id }) .from(agents) .where(eq(agents.companyId, companyId)), + resolveInstalledConnectionsForAgent( + companyId, + agentId, + ), ]); const entriesByProfile = new Map< string, @@ -156,7 +190,8 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve list.push(entry); entriesByProfile.set(entry.profileId, list); } - const { allowedCatalogIds, allowedToolNames } = resolveCatalogAccess(activeProfiles, entries, catalog); + const eligibleCatalog = await filterCatalogByConnectionInstalls(companyId, agentId, catalog, installedConnections); + const { allowedCatalogIds, allowedToolNames } = resolveCatalogAccess(activeProfiles, entries, eligibleCatalog); const agentIds = companyAgents.map((agent) => agent.id); const details: ToolProfileWithDetails[] = activeProfiles.map((profile) => buildProfileDetails({ @@ -165,11 +200,11 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve bindings: bindings.filter( (binding) => binding.profileId === profile.id, ), - catalog, + catalog: eligibleCatalog, agentIds, }), ); - const allowedTools = catalog + const allowedTools = eligibleCatalog .filter((entry) => allowedCatalogIds.has(entry.id)) .map(toAllowedTool); return { @@ -181,10 +216,7 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve allowedToolNames: [...allowedToolNames].sort((a, b) => a.localeCompare(b), ), - installedConnections: await resolveInstalledConnectionsForAgent( - companyId, - agentId, - ), + installedConnections, }; } async function getConnectionAssignmentsForAgent(companyId: string, agentId: string, connectionIds: string[]) { @@ -192,15 +224,18 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve if (activeProfiles.length === 0 || connectionIds.length === 0) { return { allowedConnectionIds: [], installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId) }; } - const catalog = await db.select({ - id: toolCatalogEntries.id, - applicationId: toolCatalogEntries.applicationId, - connectionId: toolCatalogEntries.connectionId, - toolName: toolCatalogEntries.toolName, - riskLevel: toolCatalogEntries.riskLevel, - }).from(toolCatalogEntries).where(and( - eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds), - )); + const [catalog, installedConnections] = await Promise.all([ + db.select({ + id: toolCatalogEntries.id, + applicationId: toolCatalogEntries.applicationId, + connectionId: toolCatalogEntries.connectionId, + toolName: toolCatalogEntries.toolName, + riskLevel: toolCatalogEntries.riskLevel, + }).from(toolCatalogEntries).where(and( + eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds), + )), + resolveInstalledConnectionsForAgent(companyId, agentId), + ]); const entries = catalog.length === 0 ? [] : await db.select({ profileId: toolProfileEntries.profileId, effect: toolProfileEntries.effect, @@ -220,10 +255,11 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve and(eq(toolProfileEntries.selectorType, "risk_level"), catalogValuesContain(toolProfileEntries.riskLevel, catalog.map(entry => entry.riskLevel))), ), )); - const { allowedCatalogIds } = resolveCatalogAccess(activeProfiles, entries, catalog); + const eligibleCatalog = await filterCatalogByConnectionInstalls(companyId, agentId, catalog, installedConnections); + const { allowedCatalogIds } = resolveCatalogAccess(activeProfiles, entries, eligibleCatalog); return { - allowedConnectionIds: [...new Set(catalog.filter(entry => allowedCatalogIds.has(entry.id)).map(entry => entry.connectionId))], - installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId), + allowedConnectionIds: [...new Set(eligibleCatalog.filter(entry => allowedCatalogIds.has(entry.id)).map(entry => entry.connectionId))], + installedConnections, }; } diff --git a/server/src/services/tool-profile-binding-precedence.ts b/server/src/services/tool-profile-binding-precedence.ts index c43711c80a0..0e48c7d8890 100644 --- a/server/src/services/tool-profile-binding-precedence.ts +++ b/server/src/services/tool-profile-binding-precedence.ts @@ -68,7 +68,10 @@ export function isConnectionAccessProfile(profile: ProfileLike, connectionId?: s return profile.profileKey === `connection-intent:${metadata.connectionId}:${metadata.agentId}` && (connectionId == null || metadata.connectionId === connectionId); } - if (metadata.source !== "app_gallery_finish" || typeof metadata.connectionId !== "string") return false; + if ( + (metadata.source !== "app_gallery_finish" && metadata.source !== "tool_connection_install") + || typeof metadata.connectionId !== "string" + ) return false; if (profile.profileKey !== `app:${metadata.connectionId}`) return false; return connectionId === undefined || connectionId === null || metadata.connectionId === connectionId; }