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:
Dotta authored and GitHub committed 2026-11-25 15:32:01 -06:00
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",
});
});
});