Files
PaperClipAI/server/src/services/tool-profile-binding-precedence.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

114 lines
4.4 KiB
TypeScript

import type { ToolProfileBindingTargetType } from "@paperclipai/shared";
type BindingLike = {
profileId: string;
targetType: ToolProfileBindingTargetType;
targetId: string;
priority: number;
createdAt: Date | string;
};
type ProfileLike = {
id: string;
profileKey: string;
metadata: unknown;
};
const TOOL_PROFILE_SCOPE_PRECEDENCE: Record<ToolProfileBindingTargetType, number> = {
// Named gateways bind one concrete MCP endpoint instance, so they should
// override broader run, agent, and company defaults when both match.
gateway: 0,
issue: 1,
routine: 2,
agent: 3,
project: 4,
company: 5,
};
function createdAtMillis(value: Date | string): number {
return value instanceof Date ? value.getTime() : new Date(value).getTime();
}
export function toolProfileBindingScopePrecedence(targetType: ToolProfileBindingTargetType): number {
return TOOL_PROFILE_SCOPE_PRECEDENCE[targetType];
}
export function narrowestScopeBindings<T extends BindingLike>(bindings: T[]): T[] {
if (bindings.length === 0) return [];
const winningScope = Math.min(...bindings.map((binding) => toolProfileBindingScopePrecedence(binding.targetType)));
return bindings
.filter((binding) => toolProfileBindingScopePrecedence(binding.targetType) === winningScope)
.sort((a, b) =>
a.priority - b.priority
|| createdAtMillis(a.createdAt) - createdAtMillis(b.createdAt)
|| a.profileId.localeCompare(b.profileId)
);
}
export function profileIdsInBindingOrder<T extends Pick<BindingLike, "profileId">>(bindings: T[]): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const binding of bindings) {
if (seen.has(binding.profileId)) continue;
seen.add(binding.profileId);
ordered.push(binding.profileId);
}
return ordered;
}
/**
* A profile that a connection's own access settings own: the app wizard's
* `app:<connectionId>` profile or an agent's `connection-intent` profile.
* With a connection id, only that connection's profiles match.
*/
export function isConnectionAccessProfile(profile: ProfileLike, connectionId?: string | null): boolean {
if (!profile.metadata || typeof profile.metadata !== "object" || Array.isArray(profile.metadata)) return false;
const metadata = profile.metadata as Record<string, unknown>;
if (metadata.source === "connection_intent" && typeof metadata.connectionId === "string" && typeof metadata.agentId === "string") {
return profile.profileKey === `connection-intent:${metadata.connectionId}:${metadata.agentId}`
&& (connectionId == null || metadata.connectionId === connectionId);
}
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;
}
/**
* App-wizard assignments are additive capabilities: choosing an app for all
* agents (or for one agent) must not disappear merely because that agent also
* has a narrower general-purpose profile. Ordinary profiles still use the
* narrowest-scope rule; only the profile managed by the app wizard is carried
* alongside that winning tier.
*/
export function effectiveToolProfileBindings<T extends BindingLike>(
bindings: T[],
profiles: ProfileLike[],
connectionId?: string | null,
options?: { includeAdditiveAppProfiles?: boolean },
): T[] {
if (options?.includeAdditiveAppProfiles === false) {
return narrowestScopeBindings(bindings);
}
const appProfileIds = new Set(
profiles.filter((profile) => isConnectionAccessProfile(profile, connectionId)).map((profile) => profile.id),
);
const accessProfileIds = new Set(profiles.filter(profile => {
const metadata = profile.metadata as Record<string, unknown> | null;
return metadata?.source === "connection_intent";
}).map(profile => profile.id));
const selected = [
...narrowestScopeBindings(bindings.filter(binding => !accessProfileIds.has(binding.profileId))),
...bindings.filter((binding) => appProfileIds.has(binding.profileId)),
];
const seen = new Set<string>();
return selected.filter((binding) => {
const key = `${binding.targetType}:${binding.targetId}:${binding.profileId}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}