mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 06:50:43 +01:00
## 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
271 lines
9.6 KiB
TypeScript
271 lines
9.6 KiB
TypeScript
import { writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js";
|
|
import { connectionActorUserId } from "../actor.js";
|
|
import { vercelConnectHttpError, vercelCredentialFor, vercelConnectResourcesFor } from "../vercel-credentials.js";
|
|
import type { ActorInfo } from "../types.js";
|
|
import { connectionMethodForConnection, projectedConnectionHeaders } from "../connection-methods.js";
|
|
import { emitConnectionUpdated } from "../../connector-telemetry.js";
|
|
import { and, eq, ne } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { connectionGrants, companyMemberships, toolApplications, toolConnections } from "@paperclipai/db";
|
|
import type { ConnectionGrantKind, ConnectToolAppResult } from "@paperclipai/shared";
|
|
import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared";
|
|
import { badRequest, forbidden, HttpError } from "../../../errors.js";
|
|
import { lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
|
import { deriveVercelConnectSubject, vercelGrantReference, vercelTokenRequest, VercelConnectClientError, type VercelConnectClient } from "../../vercel-connect.js";
|
|
|
|
import type { OAuthStateStore } from "./state.js";
|
|
|
|
import type { OAuthCatalogCompletion } from "./catalog-completion.js";
|
|
import type { RefreshConnectionCatalog } from "../catalog/contracts.js";
|
|
|
|
import { toApplication } from "../applications/projection.js";
|
|
import { groupedActions } from "../catalog/action-summary.js";
|
|
|
|
type Dependencies = {
|
|
now: () => Date;
|
|
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
|
|
state: OAuthStateStore;
|
|
refreshCatalog: RefreshConnectionCatalog;
|
|
finishOAuthCatalogWithRecommendedDefaults: OAuthCatalogCompletion;
|
|
vercelConnect: VercelConnectClient | null;
|
|
};
|
|
|
|
export function createVercelOAuthCallback(db: Db, dependencies: Dependencies) {
|
|
const { now, getConnectionRow, state, refreshCatalog, finishOAuthCatalogWithRecommendedDefaults, vercelConnect } = dependencies;
|
|
const { consumeOAuthState, rejectPendingOAuthInteraction } = state;
|
|
async function completeVercelConnectCallback(input: {
|
|
state: string;
|
|
error?: string | null;
|
|
actor?: ActorInfo;
|
|
}): Promise<ConnectToolAppResult> {
|
|
const stateRow = await consumeOAuthState(input.state, input.actor);
|
|
if (stateRow.codeVerifier !== "vercel-connect") {
|
|
throw badRequest("OAuth state does not belong to a Vercel Connect flow");
|
|
}
|
|
if (input.error) {
|
|
await rejectPendingOAuthInteraction(stateRow, input.actor);
|
|
throw new HttpError(
|
|
400,
|
|
"Vercel Connect authorization did not complete. Start a new authorization to try again.",
|
|
{
|
|
code:
|
|
input.error === "access_denied"
|
|
? "oauth_authorization_denied"
|
|
: "vercel_connect_authorization_required",
|
|
},
|
|
);
|
|
}
|
|
if (!vercelConnect)
|
|
throw vercelConnectHttpError(
|
|
new VercelConnectClientError("vercel_connect_unavailable", 503),
|
|
);
|
|
let connection = await getConnectionRow(
|
|
stateRow.connectionId,
|
|
stateRow.companyId,
|
|
);
|
|
const credential = vercelCredentialFor(connection);
|
|
if (
|
|
credential.principalMode !== "user" ||
|
|
connection.authKind !== "oauth"
|
|
) {
|
|
throw badRequest(
|
|
"Vercel Connect callback does not match this connection",
|
|
);
|
|
}
|
|
const grantKind: ConnectionGrantKind = stateRow.subjectUserId
|
|
? "user"
|
|
: "organization";
|
|
if (stateRow.subjectUserId) {
|
|
const [membership] = await db
|
|
.select({ id: companyMemberships.id })
|
|
.from(companyMemberships)
|
|
.where(
|
|
and(
|
|
eq(companyMemberships.companyId, connection.companyId),
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, stateRow.subjectUserId),
|
|
eq(companyMemberships.status, "active"),
|
|
ne(companyMemberships.membershipRole, "viewer"),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (!membership) {
|
|
throw forbidden(
|
|
"Your company membership no longer permits connection changes. Restore non-viewer access before authorizing this connection.",
|
|
);
|
|
}
|
|
}
|
|
const [existingGrant] = await db
|
|
.select()
|
|
.from(connectionGrants)
|
|
.where(
|
|
and(
|
|
eq(connectionGrants.companyId, connection.companyId),
|
|
eq(connectionGrants.connectionId, connection.id),
|
|
eq(connectionGrants.kind, grantKind),
|
|
grantKind === "user"
|
|
? eq(connectionGrants.subjectUserId, stateRow.subjectUserId!)
|
|
: eq(connectionGrants.isDefault, true),
|
|
),
|
|
)
|
|
.limit(1);
|
|
const derived = deriveVercelConnectSubject({
|
|
credential,
|
|
connectionId: connection.id,
|
|
companyId: connection.companyId,
|
|
grantKind,
|
|
subjectUserId: stateRow.subjectUserId,
|
|
});
|
|
const request = vercelTokenRequest({
|
|
credential,
|
|
connectionId: connection.id,
|
|
companyId: connection.companyId,
|
|
resources: vercelConnectResourcesFor(connection),
|
|
grant: {
|
|
kind: grantKind,
|
|
subjectUserId: stateRow.subjectUserId,
|
|
externalCredential: existingGrant?.externalCredential,
|
|
},
|
|
});
|
|
let token;
|
|
try {
|
|
token = await vercelConnect.getToken(request, { forceRefresh: true });
|
|
} catch (error) {
|
|
throw vercelConnectHttpError(error);
|
|
}
|
|
if (
|
|
token.connector.id !== credential.connectorId &&
|
|
token.connector.uid !== credential.connectorUid
|
|
) {
|
|
throw new HttpError(
|
|
502,
|
|
"Vercel Connect returned a token for a different connector.",
|
|
{
|
|
code: "vercel_connect_connector_mismatch",
|
|
},
|
|
);
|
|
}
|
|
const externalGrant = vercelGrantReference({
|
|
credential,
|
|
token,
|
|
subjectId: derived.subjectId,
|
|
verifiedAt: now(),
|
|
});
|
|
const grantValues = {
|
|
providerTenant: token.tenantId
|
|
? { name: credential.service, externalId: token.tenantId }
|
|
: { name: credential.service },
|
|
credentialSecretRefs: [],
|
|
externalCredential: externalGrant,
|
|
status: "active" as const,
|
|
isDefault: grantKind === "organization",
|
|
revokedAt: null,
|
|
revokedByAgentId: null,
|
|
revokedByUserId: null,
|
|
updatedAt: now(),
|
|
};
|
|
const preActivationLifecycle = {
|
|
status: connection.status,
|
|
enabled: connection.enabled,
|
|
};
|
|
const activating = connection;
|
|
[connection] = await writeToolConnectionHealthChange(db, connection, async tx => {
|
|
if (existingGrant) {
|
|
await tx.select({ id: connectionGrants.id }).from(connectionGrants)
|
|
.where(eq(connectionGrants.id, existingGrant.id))
|
|
.for("update");
|
|
}
|
|
await lockConnectionForSignIn(tx, activating);
|
|
if (existingGrant) {
|
|
await tx
|
|
.update(connectionGrants)
|
|
.set(grantValues)
|
|
.where(eq(connectionGrants.id, existingGrant.id));
|
|
} else {
|
|
await tx.insert(connectionGrants).values({
|
|
companyId: activating.companyId,
|
|
connectionId: activating.id,
|
|
kind: grantKind,
|
|
subjectUserId: stateRow.subjectUserId,
|
|
...grantValues,
|
|
createdByUserId:
|
|
connectionActorUserId(input.actor),
|
|
});
|
|
}
|
|
return tx
|
|
.update(toolConnections)
|
|
.set({
|
|
status: "active",
|
|
enabled: true,
|
|
credentialRefs: [],
|
|
credentialSecretRefs: [],
|
|
updatedAt: now(),
|
|
})
|
|
.where(
|
|
and(
|
|
eq(toolConnections.id, activating.id),
|
|
eq(toolConnections.companyId, activating.companyId),
|
|
),
|
|
)
|
|
.returning();
|
|
});
|
|
emitConnectionUpdated(
|
|
connection,
|
|
preActivationLifecycle,
|
|
"oauth_callback",
|
|
);
|
|
await db
|
|
.update(toolApplications)
|
|
.set({ status: "active", updatedAt: now() })
|
|
.where(eq(toolApplications.id, connection.applicationId));
|
|
const sourceTemplateKey =
|
|
typeof connection.config.sourceTemplateKey === "string"
|
|
? connection.config.sourceTemplateKey
|
|
: null;
|
|
const galleryEntry = sourceTemplateKey
|
|
? getConnectableAppDefinition(sourceTemplateKey)
|
|
: null;
|
|
if (!galleryEntry)
|
|
throw badRequest(
|
|
"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: shouldFinalizeDefaults,
|
|
skipDefaultProfileSync: shouldFinalizeDefaults,
|
|
credentialHeaders: {
|
|
...projectedConnectionHeaders(connection),
|
|
[credential.headerName]: `${credential.headerPrefix ?? ""}${token.token}`,
|
|
},
|
|
});
|
|
const suggestedDefaults = recommendedDefaultsForApp(
|
|
galleryEntry,
|
|
method.key,
|
|
);
|
|
const finished = shouldFinalizeDefaults
|
|
? await finishOAuthCatalogWithRecommendedDefaults({
|
|
interactionId: stateRow.interactionId,
|
|
connection,
|
|
catalog: refresh.catalog,
|
|
suggestedDefaults,
|
|
actor: input.actor,
|
|
})
|
|
: null;
|
|
const [application] = await db
|
|
.select()
|
|
.from(toolApplications)
|
|
.where(eq(toolApplications.id, connection.applicationId));
|
|
return {
|
|
connectionId: connection.id,
|
|
application: toApplication(application),
|
|
connection: finished?.connection ?? refresh.connection,
|
|
catalog: refresh.catalog,
|
|
actions: groupedActions(refresh.catalog),
|
|
suggestedDefaults,
|
|
auth: null,
|
|
};
|
|
}
|
|
return completeVercelConnectCallback;
|
|
}
|