mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(tool-access): enforce connection installs across non-plugin transports (#22967)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents call external tools (remote MCP, OAuth REST apps, local stdio, plugins) through Paperclip's tool-access policy, Effective Access view, and tool gateway > - Non-plugin connections installed only for Agent A could still be called by Agent B because `tool-access-policy.ts` only checked `tool_connection_installs` for `plugin` connections, `governedByConnectionProfile` only checked the calling agent's own bound profiles (allowing Agent B's default unscoped `tools:use` grant to match), Effective Access did not filter by connection installs, and reconnect/uninstall paths could drop agent scoping > - This is a cross-agent security boundary bypass where an agent can access another agent's private connection or mailbox > - This pull request extracts one shared `connection-access-boundary` helper and enforces connection install boundaries consistently across policy decisions, Effective Access (`allowedTools` and profile summary counts), install removal (`putConnectionInstalls`), generic approval policies, and gallery reconnect/catalog sync while preserving legacy shared connections and explicit policy/targeted-grant overrides > - The benefit is airtight per-agent connection isolation across all transports with policy/test, Effective Access, and the live tool gateway in full agreement ## Linked Issues or Issue Description - Fixes: #17166 ## What Changed - **`server/src/services/tool-access/connection-access-boundary.ts`**: Extracted a single shared batched helper (`readConnectionAccessBoundaries`, `connectionRequiresInstall`, `hasAgentAccessConfiguredMarker`, `agentAccessConfiguredSql`, `defaultConnectionProfileBindingTargets`) so policy evaluation, Effective Access projection, and default binding helpers share one query and predicate. - **`server/src/services/tool-access-policy.ts`**: - Keeps the pre-policy install gate for `plugin` connections unchanged. - Enforces the shared connection install boundary for non-plugin governed connections (any connection with `tool_connection_installs` rows, `agentAccessConfigured` / `mcpAgentAccessConfigured` marker, or unbound managed profiles): denies uninstalled agents with `deny_connection_not_installed` before profile/trust allows and blocks generic `require_approval` policies when `blockedByConnectionInstall` is true (so pending approvals cannot execute after uninstall and cannot fall through to lower-priority allow policies), while preserving explicit `block`/`allow` policies and tool-targeted `tools:use` grants (`scope: { connectionId }`, `{ allow: [...] }`, etc.) required by delegated policy contracts. - Rejects default unscoped `tools:use` (`scope: null`) whenever the connection is governed by installs or managed connection profiles, and suppresses `app_gallery_finish` / `connection_intent` approval and trust rules for uninstalled agents. - Preserves legacy company-wide / unscoped connections that have no install rows, no `agentAccessConfigured` marker, and no unbound managed profiles. - **`server/src/services/tool-access/profiles/resolution.ts`**: Uses `readConnectionAccessBoundaries` to filter Effective Access `allowedTools` and passes `eligibleCatalog` to `buildProfileDetails` so `profile.summary.allowedToolCount` agrees with `allowedTools` and `POST /companies/:companyId/tools/policy/test`. - **`server/src/services/tool-access/connections/installs.ts` & `server/src/services/tool-access.ts`**: - Persists `agentAccessConfigured: true` on all governed tool connections when installs are saved via `putConnectionInstalls` or `finishGalleryAppConnection` (alongside `mcpAgentAccessConfigured: true` for `mcp_remote`), so removing the final install via `putConnectionInstalls({ installs: [] })` closes access across `mcp_remote`, `rest_api`, and `local_stdio`. - Preserves `agentAccessConfigured` / `mcpAgentAccessConfigured` on `connectGalleryApp` reconnect when the retained connection is not `archived` (while allowing revival of an archived connection to restore fresh defaults). - **`server/src/services/tool-access/catalog/default-access.ts` & `server/src/services/tool-access/oauth/catalog-completion.ts`**: Uses `defaultConnectionProfileBindingTargets` and `hasAgentAccessConfiguredMarker` so reconnecting or syncing catalog tools preserves existing agent-scoped installs and zero-agent restrictions without widening access to the whole company. - **Tests (`server/src/__tests__/tool-access-policy-service.test.ts`, `heartbeat-runtime-mcp-servers.test.ts`, `tool-access-policy-index.test.ts`)**: Added RED-before-fix regression tests and embedded-Postgres route/gateway E2E coverage across `mcp_remote`, `rest_api`, and `local_stdio`, newly created Agent C, stripped-marker zero-agent removal via `putConnectionInstalls({ installs: [] })`, generic `require_approval` + explicit allow/targeted-grant precedence, reconnect preservation, Effective Access profile summary counts, and legacy shared connections. ## Verification - Verified RED-before-fix on base `2d06567795`: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/tool-access-policy-service.test.ts -t "denies uninstalled agents|aligns policy/test route"` failed 4/4 with uninstalled agents receiving `allow_explicit_grant`. - Verified GREEN-after-fix on `484ecb416a`: - `pnpm --filter @paperclipai/server typecheck` (PASS, all 7 layers) - `node scripts/check-test-budget.mjs --files server/src/__tests__/tool-access-policy-service.test.ts` (PASS) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/tool-access-policy-service.test.ts src/__tests__/connection-management-delegated-policy.integration.test.ts src/__tests__/plugin-connector-install-gate.test.ts` (3 files, 100/100 tests PASS) - Full Paperclip CI (`66/66` executed checks PASS) + Greptile **5/5** (`0` unresolved review threads) ## Risks - Low risk: legacy unscoped/company-wide connections with no `tool_connection_installs` rows, no `agentAccessConfigured` / `mcpAgentAccessConfigured` marker, and no unbound managed connection profiles continue to evaluate unchanged. - Explicit `block`/`allow` policies and tool-targeted `tools:use` grants continue to take precedence over the non-plugin install gate (matching `connection-management-delegated-policy.integration.test.ts`), while default unscoped `tools:use` (`scope: null`), generic `require_approval`, and profile/trust allows can no longer bypass connection install boundaries. ## Model Used - Google Gemini (Antigravity agentic workflow with tool use, code execution, and embedded-Postgres verification) ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
0774cb90cd
commit
263c6f6c04
13 files changed
+1010
-93
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -169,6 +169,7 @@ function randomContext(random: ReturnType<typeof seeded>): 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, ""]),
|
||||
|
||||
@@ -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<string, unknown> | 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<string, unknown> | 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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<Db, "select" | "insert" | "upda
|
||||
let upstreamToolName = typeof input.request.upstreamToolName === "string" ? input.request.upstreamToolName : null;
|
||||
let riskLevel = asToolRiskLevel(input.request.riskLevel);
|
||||
let connectionTransport: string | null = null;
|
||||
let agentAccessConfigured = false;
|
||||
let applicationType: string | null = null;
|
||||
|
||||
if (catalogEntryId) {
|
||||
@@ -1209,6 +1215,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
enabled: toolConnections.enabled,
|
||||
status: toolConnections.status,
|
||||
transport: toolConnections.transport,
|
||||
agentAccessConfigured: agentAccessConfiguredSql(),
|
||||
})
|
||||
.from(toolConnections)
|
||||
.where(eq(toolConnections.id, contextConnectionId)));
|
||||
@@ -1220,6 +1227,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
}
|
||||
applicationId = connection.applicationId;
|
||||
connectionTransport = connection.transport;
|
||||
agentAccessConfigured = Boolean(connection.agentAccessConfigured);
|
||||
}
|
||||
if (applicationId) {
|
||||
const contextApplicationId = applicationId;
|
||||
@@ -1273,6 +1281,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
catalogSchemaHash,
|
||||
providerType,
|
||||
connectionTransport,
|
||||
agentAccessConfigured,
|
||||
applicationKey,
|
||||
upstreamToolName,
|
||||
toolName: input.request.toolName,
|
||||
@@ -1329,14 +1338,24 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
return { profiles: activeProfiles, entries };
|
||||
}
|
||||
|
||||
async function connectionInstalledForAgent(ctx: ToolAccessContext, cache?: ToolAccessDecisionCache): Promise<boolean> {
|
||||
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<ConnectionAccessBoundary | null> {
|
||||
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<boolean> {
|
||||
@@ -1618,14 +1637,18 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
return decision("deny", "deny_policy_block", "Tool invocation no longer matches this admission.", [], []);
|
||||
}
|
||||
if (input.consumeRateLimit === true) consumedRateAdmissions.push(...(admittedRates ?? []));
|
||||
const connectionBoundary = await connectionAccessBoundary(ctx, cache);
|
||||
if (ctx.actorType === "agent" && ctx.connectionId && ctx.connectionTransport === "plugin"
|
||||
&& !(await connectionInstalledForAgent(ctx, cache))) {
|
||||
&& !connectionBoundary?.installedForAgent) {
|
||||
return decision("deny", "deny_connection_not_installed",
|
||||
"This connection is not installed for this agent.", [], [], { redactionPlan: redaction.redactionPlan });
|
||||
}
|
||||
const blockedByConnectionInstall = Boolean(
|
||||
connectionBoundary && connectionBoundary.requiresInstall && !connectionBoundary.installedForAgent,
|
||||
);
|
||||
const profileState = await effectiveProfiles(ctx, cache);
|
||||
const effectiveProfileIds = profileState.profiles.map((profile) => 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<Db, "select" | "insert" | "upda
|
||||
continue;
|
||||
}
|
||||
if (policy.policyType === "trust_rule") {
|
||||
if (blockedByConnectionInstall) continue;
|
||||
const rule = trustRuleConfig(policy);
|
||||
if (!rule || !trustRuleIsActive(policy)) continue;
|
||||
if (!argumentFiltersMatch(rule.argumentFilters, ctx)) continue;
|
||||
@@ -1730,6 +1754,13 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
// The connection's Ask first control restricts an existing action grant;
|
||||
// it must never grant access to agents outside that connection's profile.
|
||||
if (["app_gallery_finish", "connection_intent"].includes(String(policy.config?.source)) && !permittedByProfile) continue;
|
||||
if (blockedByConnectionInstall) {
|
||||
if (explicitBlock) {
|
||||
return decision("deny", "deny_policy_block", explicitBlock.policy.description ?? "Tool access is blocked by policy.", effectiveProfileIds, [explicitBlock.policy.id], { redactionPlan: redaction.redactionPlan });
|
||||
}
|
||||
return decision("deny", "deny_connection_not_installed",
|
||||
"This connection is not installed for this agent.", effectiveProfileIds, [], { redactionPlan: redaction.redactionPlan });
|
||||
}
|
||||
if (policy.config?.source === "connection_intent" && explicitBlock) {
|
||||
return decision("deny", "deny_policy_block", explicitBlock.policy.description ?? "Tool access is blocked by policy.", effectiveProfileIds, [explicitBlock.policy.id], { redactionPlan: redaction.redactionPlan });
|
||||
}
|
||||
@@ -1748,12 +1779,17 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
// application. A grant that names the action, connection or application
|
||||
// still applies. Board users keep their operator grants.
|
||||
const governedByConnectionProfile = ctx.actorType === "agent" && !!ctx.connectionId && (
|
||||
profileState.profiles.some((profile) => 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<string, Array<typeof toolProfileEntries.$inferSelect>>();
|
||||
for (const entry of profileState.entries) {
|
||||
@@ -2052,6 +2088,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
|
||||
routineId: null,
|
||||
gatewayId: null,
|
||||
connectionTransport: null,
|
||||
agentAccessConfigured: false,
|
||||
applicationId: invocation.applicationId,
|
||||
connectionId: invocation.connectionId,
|
||||
catalogEntryId: invocation.catalogEntryId,
|
||||
|
||||
@@ -2271,9 +2271,18 @@ export function toolAccessService(
|
||||
const awsRoleIssuer = !awsMcpMethodUsesIssuer(galleryEntry?.slug, method?.key) ? null
|
||||
: typeof recordedAwsIssuer === "string" ? recordedAwsIssuer
|
||||
: awsIssuerOrigin.available ? workloadIdentityIssuer(awsIssuerOrigin.origin, companyId) : null;
|
||||
const preservedAccessMarkers = retainedConnection && retainedConnection.status !== "archived"
|
||||
? {
|
||||
...(asRecord(retainedConnection.config).agentAccessConfigured === true ? { agentAccessConfigured: true } : {}),
|
||||
...(transport === "mcp_remote" && asRecord(retainedConnection.config).mcpAgentAccessConfigured === true
|
||||
? { mcpAgentAccessConfigured: true }
|
||||
: {}),
|
||||
}
|
||||
: {};
|
||||
let config: Record<string, unknown> = 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(),
|
||||
})
|
||||
|
||||
@@ -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<string, unknown> {
|
||||
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) {
|
||||
|
||||
@@ -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<Db, "select">;
|
||||
|
||||
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<string, unknown>;
|
||||
return record.agentAccessConfigured === true || record.mcpAgentAccessConfigured === true;
|
||||
}
|
||||
|
||||
export function agentAccessConfiguredSql() {
|
||||
return sql<boolean>`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<string, KnownConnectionAccessMeta>;
|
||||
},
|
||||
): Promise<Map<string, ConnectionAccessBoundary>> {
|
||||
const uniqueIds = [...new Set(input.connectionIds)];
|
||||
const result = new Map<string, ConnectionAccessBoundary>();
|
||||
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<string, KnownConnectionAccessMeta>();
|
||||
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<string, Array<{ targetType: string; targetId: string }>>();
|
||||
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<string, unknown>
|
||||
: 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<string>();
|
||||
|
||||
const managedByConnectionId = new Map<string, Array<{ hasBinding: boolean }>>();
|
||||
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<typeof toolConnections.$inferSelect, "id" | "companyId" | "config">,
|
||||
): Promise<Array<{ targetType: "company" | "agent"; targetId: string }>> {
|
||||
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 }];
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, unknown> {
|
||||
if (value && typeof value === "object" && !Array.isArray(value))
|
||||
return value as Record<string, unknown>;
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<void>;
|
||||
@@ -108,6 +109,35 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve
|
||||
return { bindings, activeProfiles };
|
||||
}
|
||||
|
||||
async function filterCatalogByConnectionInstalls<T extends { connectionId: string }>(
|
||||
companyId: string,
|
||||
agentId: string,
|
||||
catalog: T[],
|
||||
installedConnections: ToolConnection[],
|
||||
): Promise<T[]> {
|
||||
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<string>();
|
||||
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<TEntry extends ProfileCatalogEntry, TAllowedTool>(
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user