Files
PaperClipAI/server/src/services/tool-access/connection-access-boundary.ts
T
Dotta 263c6f6c04 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
2026-11-25 15:32:01 -06:00

213 lines
7.8 KiB
TypeScript

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 }];
}