fix(connections): avoid timeouts when saving agent access (#23790)

## Thinking Path

> - Paperclip manages agents and the connections they can use.
> - A connection's Permissions page saves its actions and agent audience
together.
> - The save checks the saved profile, its agent targets, and related
accounts.
> - Those checks repeat database reads for each target and action. They
also expand the same profile for each related account.
> - On a large company, the request can time out before it reaches the
save transaction.
> - This change bounds that work and keeps the existing permission
decisions and reauthorization boundaries.

## Linked Issues or Issue Description

**What happened?**

Adding an agent to an existing connection leaves the page at “Saving…”
until the request fails. Refreshing shows the old audience. The browser
reproduction ended with HTTP 502 at the five-minute request deadline.

**Expected behavior**

Save an authorized agent-audience change and return the saved
permissions without repeated checks across the full company and catalog.

**Steps to reproduce**

Use a company with many agents, several accounts under one application,
and an existing connection profile with many catalog entries. Add an
agent on the connection's Permissions page. The new regression covers 40
additional agents, three accounts, and 50 actions through the assembled
server and real PostgreSQL.

GitHub searches found no duplicate fix.

## What Changed

- Share membership and grant reads inside one authorization check.
Retain the existing two-second age limit. Close the scope before the
handler runs and start a fresh scope for each reauthorization.
- Resolve catalog references and canonical agent target IDs in batches.
Keep the ordinary target lookup outside the check scope and for other
UUID spellings. Continue to decide permissions for every target.
- Keep the already checked profile in each related account's permission
scope without expanding that profile again. Continue to check changed
profiles, gateway bindings, and the referenced accounts.
- Add a save regression with SQL-count bounds and a subsequent
grant-revocation refusal. Cover nested, completed, and failed
authorization-check scopes.

## Verification

- `cd server && pnpm run typecheck` — passed, including the test-tree
layers. Repeated successfully after rebasing onto current `master`.
- `cd server && pnpm exec vitest run
src/__tests__/connection-management.integration.test.ts
src/__tests__/connection-management-delegated-policy.integration.test.ts
src/__tests__/connection-management-gateway-rules.integration.test.ts
src/__tests__/connection-management-delegated-tests.integration.test.ts
src/__tests__/connection-management-providers.integration.test.ts
src/__tests__/connection-management-gateways.integration.test.ts
src/__tests__/authorization-request-reads.test.ts` — 7 files and 110
tests passed.
- After rebase, repeated both
`connection-management.integration.test.ts` and
`authorization-request-reads.test.ts` on head `fc8b3ecf16cc`: 2 files
and 31 tests passed. The 110-test run above preceded the rebase.
- Red/green: the new HTTP regression first failed on 2,218 membership
reads. It now saves the requested audience, retains all 50 actions,
meets the query bounds, and refuses the next request after its grant
scope is restricted.
- Read-only replay of the affected authorization path completed with the
fix. No tenant database rows were changed by the replay.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/connection-management.integration.test.ts
server/src/__tests__/authorization-request-reads.test.ts` — passed.
- `git diff --check` and Gitleaks scan of the diff — passed. The diff
was also checked for private identifiers and personal data.
- `pnpm verify` selected 2,008 test files through the shared
authorization dependencies. That broad local run was stopped; it is not
a pass. The focused suites and server typecheck above passed. Required
CI must supply the broad checks on this revision.
- Final head `fc8b3ecf16cc`: [CI
run](https://github.com/paperclipai/paperclip/actions/runs/47445309988)
passed, including typecheck, build, all general and serialized server
shards, native Runner checks, and all end-to-end shards. [Greptile
review](https://github.com/paperclipai/paperclip/pull/23790#issuecomment-7426956976)
scored 5/5 with no actionable issues or unresolved threads. GitHub
reports the branch mergeable with a clean merge state.
- The fix has not been deployed. A live browser save and refresh on the
new release remain to be verified after deployment.

## Risks

No schema, API, or deployment-policy change. Shared authorization code
is affected. Reuse is limited to one check with the existing age limit;
each pre-write reauthorization reads fresh facts. The related-account
checks still include profile IDs in their permission scopes. Existing
delegated, scoped-grant, company-isolation, and gateway tests pass.
Revert this commit to roll back.

## Model Used

OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with xhigh
reasoning and tool use.

## 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 (the
public contract is unchanged; the internal boundaries and validation are
recorded above)
- [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

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-12-04 15:35:22 -08:00
1 parent ab79cb9cdd
commit 1bbf734ce6
6 files changed
+136 -12

No files matched your search

@@ -7,7 +7,7 @@ import { authUsers, companyMemberships, instanceUserRoles, issues, projects } fr
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { issueRoutes } from "../routes/issues.js";
import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js";
import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerAuthorizationCheck, readOncePerRequest, withFreshAuthorizationReads } from "../services/authorization-read-scope.js";
import { readInstanceAdmin } from "../services/authorization.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
@@ -178,6 +178,21 @@ describeEmbeddedPostgres("authorization reads per request", () => {
describe("authorization read scope boundaries", () => {
afterEach(() => { vi.useRealTimers(); });
it("shares facts only within one authorization check and refreshes before its continuation", async () => {
let reads = 0;
const read = () => readOncePerAuthorizationCheck("grant:company:user:reader:tools:manage_connections", async () => ++reads);
await withFreshAuthorizationReads(async () => {
expect(await read()).toBe(1);
expect(await read()).toBe(1);
await withFreshAuthorizationReads(async () => { expect(await read()).toBe(2); });
expect(await read()).toBe(1);
});
expect(await read()).toBe(3);
await withFreshAuthorizationReads(async () => { expect(await read()).toBe(4); });
await expect(withFreshAuthorizationReads(async () => { await read(); throw new Error("denied"); })).rejects.toThrow("denied");
expect(await read()).toBe(6);
});
function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) {
let reads = 0;
const gates: Array<() => void> = [];
@@ -1,4 +1,5 @@
import { createToolGatewayService } from "../services/tool-gateway.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { commitToolActionReview } from "../services/tool-action-review.js";
import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared";
import { createHash, randomBytes, randomUUID, generateKeyPairSync } from "node:crypto";
@@ -299,6 +300,66 @@ describe("connection management with production default agents", () => {
expect(profile, JSON.stringify(profile)).toMatchObject({ status: 201 });
});
it("saves a large connection's agent access without repeating authorization reads for every target and action", async () => {
const f = await server.fixture({ connectionScenario: "fresh" });
const userId = f.responsibleUserId!;
const cookie = await server.humanSession(userId);
await server.db.insert(principalPermissionGrants).values(["tools:manage_connections", "agents:configure"].map(permissionKey => ({
companyId: f.companyId, principalType: "user" as const, principalId: userId, permissionKey,
}))).onConflictDoNothing();
const peers = await server.db.insert(agents).values(Array.from({ length: 40 }, (_, index) => ({
companyId: f.companyId, name: `Access target ${index}`, adapterType: "process",
}))).returning();
const [application] = await server.db.insert(toolApplications).values({ companyId: f.companyId, name: "Shared catalog", type: "mcp_http" }).returning();
const connections = await server.db.insert(toolConnections).values(Array.from({ length: 3 }, (_, index) => ({
companyId: f.companyId, applicationId: application.id, uid: randomUUID(), name: `Shared account ${index}`,
transport: "mcp_remote" as const, authKind: "none" as const, status: "active" as const,
}))).returning();
const connection = connections[0];
await server.db.insert(toolConnectionInstalls).values(connections.map(row => ({
companyId: f.companyId, connectionId: row.id, targetType: "company" as const, targetId: f.companyId,
})));
const catalog = await server.db.insert(toolCatalogEntries).values(Array.from({ length: 50 }, (_, index) => ({
companyId: f.companyId, applicationId: application.id, connectionId: connection.id,
name: `action_${index}`, toolName: `action_${index}`, versionHash: `action_${index}`,
}))).returning();
const [profile] = await server.db.insert(toolProfiles).values({
companyId: f.companyId, profileKey: `app:${connection.id}`, name: connection.name,
}).returning();
await server.db.insert(toolProfileEntries).values(catalog.map(entry => ({
companyId: f.companyId, profileId: profile.id, selectorType: "catalog_entry" as const,
applicationId: application.id, connectionId: connection.id, catalogEntryId: entry.id,
})));
const finish = () => fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/apps/${connection.id}/finish`, {
method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
body: JSON.stringify({ enabledCatalogEntryIds: catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [f.agentId, peers[0].id] } }),
});
const meter = meterDatabaseStatements(server.db, server.databaseUrl);
try {
meter.startLog();
const response = await finish();
const body = await response.json();
const statements = meter.stopLog();
expect(response.status, JSON.stringify(body)).toBe(200);
expect(body.profileBindings.map((row: { targetId: string }) => row.targetId).sort()).toEqual([f.agentId, peers[0].id].sort());
expect(body.profileEntries).toHaveLength(50);
for (const table of ["company_memberships", "principal_permission_grants", "tool_catalog_entries"]) {
expect(statements.filter(entry => entry.sql.includes(`from "${table}"`)).length, table).toBeLessThan(30);
}
// Company-wide install expansion still reads the company roster. It must
// not add one agent lookup per target in each referenced account.
expect(statements.filter(entry => entry.sql.includes('from "agents"')).length).toBeLessThan(80);
// A fresh request must still check all referenced accounts with current grants.
await server.db.update(principalPermissionGrants).set({ scope: { connectionIds: [connection.id] } }).where(and(
eq(principalPermissionGrants.companyId, f.companyId), eq(principalPermissionGrants.principalId, userId),
eq(principalPermissionGrants.permissionKey, "tools:manage_connections"),
));
const denied = await finish();
expect(denied.status).toBe(403);
expect(await server.db.select().from(toolProfileBindings).where(eq(toolProfileBindings.profileId, profile.id))).toHaveLength(2);
} finally { meter.uninstall(); }
});
it("checks effective-profile connection access once for hundreds of tools on the same account", async () => {
const f = await fixture();
const connection = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Large catalog", transport: "mcp_remote", authKind: "none", config: { url: "https://1.1.1.1/mcp" } });
@@ -1,12 +1,13 @@
import { isUuidLike, type ConnectionRequiredUserAction } from "@paperclipai/shared";
import type { Request, RequestHandler } from "express";
import { and, eq, or, sql } from "drizzle-orm";
import { and, eq, inArray, or, sql } from "drizzle-orm";
import { type Db, toolConnections, toolApplications, toolProfiles, toolProfileEntries, toolProfileBindings,
toolMcpGateways, toolMcpGatewayTokens, chatEndpoints, chatConversations, connectionGrants, connectionGrantDelegations, agents, issues,
toolConnectionInstalls, heartbeatRuns, toolPolicies, toolRuntimeSlots, toolCatalogEntries, chatSlackManagerGrants, adapterAuthSessions, companySecrets, companies, companyMemberships } from "@paperclipai/db";
import { badRequest, forbidden, notFound, HttpError } from "../errors.js";
import { assertAuthenticated, assertCompanyAccess, hasCompanyAccess, getActorInfo } from "./authz.js";
import { connectionManagementService, responsibleConnectionUser, type ConnectionManagementContext } from "../services/connection-management.js";
import { withFreshAuthorizationReads } from "../services/authorization-read-scope.js";
import type { ConnectionManagementAction, ConnectionManagementResource } from "../services/connection-management-policy.js";
const contexts = new WeakMap<Request, ConnectionManagementContext>();
@@ -78,7 +79,7 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai
const management = connectionManagementService(db);
return (action: ConnectionManagementAction, operation: string, options: { personal?: boolean; slackManagerGrant?: boolean } = {}): RequestHandler => async (req, _res, next) => {
const rawBody = req.body ?? {};
const authorizeRequest = async (afterHumanAction?: boolean): Promise<ConnectionManagementContext> => {
const authorizeRequest = async (afterHumanAction?: boolean): Promise<ConnectionManagementContext> => withFreshAuthorizationReads(async () => {
const authorize: typeof management.authorize = (actor, requestedAction, resolved, checkOptions) =>
management.authorize(actor, requestedAction, resolved, { ...checkOptions, afterHumanAction });
assertAuthenticated(req);
@@ -316,6 +317,22 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai
const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, companyId));
companyAgents.forEach(agent => targets.add(agent.id));
}
// Saved profiles often repeat one account across many catalog entries.
// Resolve their references together; bindCompany below still checks each row.
const catalogIds = [...new Set(selectors.flatMap(selected => [
...(selected.catalogEntryId ? [uuid(selected.catalogEntryId)] : []),
...(Array.isArray(selected.catalogEntryIds) ? selected.catalogEntryIds.map(uuid) : []),
]))];
if (catalogIds.length) {
const entries = await db.select({ id: toolCatalogEntries.id, companyId: toolCatalogEntries.companyId,
connectionId: toolCatalogEntries.connectionId, applicationId: toolCatalogEntries.applicationId,
}).from(toolCatalogEntries).where(inArray(toolCatalogEntries.id, catalogIds));
const byId = new Map(entries.map(entry => [entry.id, entry]));
for (const id of catalogIds) {
const entry = byId.get(id.toLowerCase());
lookupCache.set(`catalog:${id}`, Promise.resolve(entry ? [entry] : []));
}
}
for (let index = 0; index < selectors.length; index++) {
const selected = selectors[index];
const profileOperation = operation.includes("profile");
@@ -394,7 +411,12 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai
const authorizeReferenced = async (afterHumanAction?: boolean) => {
for (const referenced of uniqueResources.values()) {
const resolved = { ...referenced, companyId: resource.companyId };
const checkOptions = { targetAgentIds: [...targets], mutation: req.method !== "GET", afterHumanAction };
const checkOptions = { targetAgentIds: [...targets], mutation: req.method !== "GET", afterHumanAction,
// The root authorization already expanded this profile, including
// its linked gateways and sibling accounts. Keep the profile in
// the permission scope without expanding it again for each account.
expandedProfile: Boolean(resource.profileId) && resolved.profileId === resource.profileId && resolved.gatewayId === resource.gatewayId,
};
await authorize(req.actor, action, resolved, checkOptions);
if (changesGatewayBindings || changesAudience) await authorize(req.actor, "connections:profiles", resolved, checkOptions);
if (action === "connections:profiles" && resolved.connectionId && req.method !== "GET" && (req.actor.type === "agent" || !resolved.selfServiceAgentInstalls)) {
@@ -413,7 +435,7 @@ export function connectionManagementGuard(db: Db, purpose: "tool" | "chat" | "ai
contexts.set(req, current);
};
return context;
};
});
try {
contexts.set(req, await authorizeRequest());
next();
@@ -3,10 +3,28 @@ import type { RequestHandler, Response } from "express";
export const AUTHORIZATION_READ_MAX_AGE_MS = 2_000;
type ReadScope = { open: boolean; entries: Map<string, { value: Promise<unknown>; readAt: number }> };
type ReadScope = { open: boolean; check?: boolean; entries: Map<string, { value: Promise<unknown>; readAt: number }> };
const reads = new AsyncLocalStorage<ReadScope>();
/** One authorization pass, never the mutation or a later reauthorization. */
export function withFreshAuthorizationReads<T>(check: () => Promise<T>): Promise<T> {
const scope: ReadScope = { open: true, check: true, entries: new Map() };
return reads.run(scope, async () => {
try { return await check(); }
finally { scope.open = false; scope.entries.clear(); }
});
}
export function readOncePerAuthorizationCheck<T>(key: string, read: () => Promise<T>): Promise<T> {
return authorizationCheckScopeActive() ? readOncePerRequest(key, read) : read();
}
export function authorizationCheckScopeActive(): boolean {
const scope = reads.getStore();
return scope?.check === true && scope.open;
}
function closeWhenResponseStarts(res: Response, close: () => void) {
const { write, flushHeaders, writeHead } = res;
res.write = function (this: Response, ...args: Parameters<Response["write"]>) {
+3 -3
View File
@@ -1,5 +1,5 @@
import { dashboardConversationCondition, dashboardConversationReadable } from "./responsibility-privacy.js";
import { readOncePerRequest } from "./authorization-read-scope.js";
import { readOncePerAuthorizationCheck, readOncePerRequest } from "./authorization-read-scope.js";
import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agentInteractionDenial, type AgentInteractionDenial, type AgentInteractionOperation } from "./agent-interaction-policy.js";
@@ -1061,7 +1061,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
principalId: string,
permissionKey: PermissionKey,
) {
return db
return readOncePerAuthorizationCheck(`grant:${companyId}:${principalType}:${principalId}:${permissionKey}`, () => db
.select()
.from(principalPermissionGrants)
.where(
@@ -1072,7 +1072,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
eq(principalPermissionGrants.permissionKey, permissionKey),
),
)
.then((rows) => rows[0] ?? null);
.then((rows) => rows[0] ?? null));
}
async function decidePrincipalGrant(input: {
+11 -3
View File
@@ -1,4 +1,5 @@
import { assertAgentInteraction } from "./agent-interaction-policy.js";
import { authorizationCheckScopeActive } from "./authorization-read-scope.js";
import { and, eq, inArray, or } from "drizzle-orm";
import { isUuidLike } from "@paperclipai/shared";
import { agents, agentApiKeys, heartbeatRuns, runIdentityContexts, issues, projects, toolApplications, toolCatalogEntries, toolConnections, toolConnectionInstalls, toolProfiles, toolProfileEntries, toolProfileBindings, toolMcpGateways, aiConnectionPools, connectionGrants, routines, type Db } from "@paperclipai/db";
@@ -269,7 +270,7 @@ export function connectionManagementService(db: Db) {
expandedTargets, referencedConnections, currentGatewayResource, savedConnection };
}
async function evaluateTarget(prepared: PreparedAuthorization, targetAgentId: string | undefined): Promise<AuthorizationDecision> {
async function evaluateTarget(prepared: PreparedAuthorization, targetAgentId: string | undefined, companyTargets?: ReadonlySet<string>): Promise<AuthorizationDecision> {
const { actor, action, resource, responsibleUserId } = prepared;
const resolved = { ...resource, ...(targetAgentId ? { targetAgentId } : {}) };
const decision = await authorization.decide({ actor, action, resource: resolved, scope: { ...resolved } });
@@ -284,7 +285,8 @@ export function connectionManagementService(db: Db) {
if (!resourceTrust.allowed) throw forbidden(resourceTrust.explanation);
}
if (targetAgentId) {
const [target] = await db.select({ id: agents.id }).from(agents).where(and(eq(agents.id, targetAgentId), eq(agents.companyId, resource.companyId)));
const target = companyTargets ? companyTargets.has(targetAgentId)
: (await db.select({ id: agents.id }).from(agents).where(and(eq(agents.id, targetAgentId), eq(agents.companyId, resource.companyId))))[0];
if (!target) throw forbidden("Target agent is outside this company");
if (targetAgentId === resource.targetAgentId && (prepared.options.mutation ?? action !== "connections:read")) {
await assertAgentToolAssignmentInteractions(db, actor.type === "agent" ? actor.agentId : null, resource.companyId, [targetAgentId]);
@@ -306,9 +308,15 @@ export function connectionManagementService(db: Db) {
const { actor, action, resource, options, responsibleUserId, workContext, capturedRun,
expandedTargets, referencedConnections, currentGatewayResource } = prepared;
const targets = [...new Set([...expandedTargets, ...(resource.targetAgentId ? [resource.targetAgentId] : [])])];
// Preserve the ordinary lookup for noncanonical UUID spellings. Decisions
// remain per target, including scoped grants and agent interaction checks.
const companyTargets = authorizationCheckScopeActive() && targets.length && targets.every(id => isUuidLike(id) && id === id.toLowerCase())
? new Set((await db.select({ id: agents.id }).from(agents)
.where(and(eq(agents.companyId, resource.companyId), inArray(agents.id, targets)))).map(row => row.id))
: undefined;
let decision: AuthorizationDecision | undefined;
for (const targetAgentId of targets.length ? targets : [undefined]) {
decision = await evaluateTarget(prepared, targetAgentId);
decision = await evaluateTarget(prepared, targetAgentId, companyTargets);
}
if (action === "connections:profiles" && resource.requestedInstallCompanyIds && !resource.selfServiceAgentInstalls) {
await authorize(actor, "connections:configure", resource, options);