From 1fdd1126828015c68e03533513ffcb25b35069e7 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:09:19 -0600 Subject: [PATCH] fix(connections): keep resumed setup drafts unbound until finish (#23553) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A connection starts as a draft. The operator saves its actions and agent access at the finish step. > - A saved draft can resume through the same connection path as a removed connection. > - That path restored default access for every saved connection, including a new draft. > - This created a company binding before the operator selected an audience. Finish then checked every agent in the company. > - This pull request keeps a resumed draft unbound until finish. Previously configured connections keep their restore behavior. > - A small audience now has a small authorization cost, even in a large company. ## Linked Issues or Issue Description **What happened?** A saved MCP draft gained a company-wide profile when setup resumed. Saving access for one agent then caused 16,610 SQL queries in a local fixture with 1,100 agents. The request took about 8 seconds with a local database. A remote setup request can exceed the client's deadline while its write still completes later. **Expected behavior** A new draft must have no profile or access binding until the operator saves access. Saving one selected agent must not check the full company roster. **Steps to reproduce** 1. Create a disabled MCP URL draft in a company with 1,100 agents. 2. Resume it with `reconnectConnectionId` and complete catalog discovery. 3. Finish with one selected agent and one Ask first action. 4. Before this fix, the draft has a company binding and finish runs thousands of queries. **Paperclip version or commit** Reproduced on `master` at `3d0e0b6dd989baeb469f99380b496c273b0b290a`. **Deployment mode** Any server with saved connection drafts. The local proof uses embedded PostgreSQL and the real service and HTTP route. Related work: [#22080](https://github.com/paperclipai/paperclip/pull/22080) resumes saved sign-in drafts. This change fixes the default access restored during a draft resume. ## What Changed - `connectGalleryApp` does not request default restoration when the retained connection is still a draft. - Active and archived connections keep the existing restoration path. - Two database regressions cover URL drafts and gallery API-key drafts. The URL test uses 1,100 agents, the real finish route, an owner session, and a bound of fewer than 200 SQL queries. It also checks that only the selected agent is installed and the Ask first policy is saved. - Tests stay in the existing service suite. Its shared PostgreSQL fixture already owns setup, finish, and restore coverage. No new production module or schema is needed. ## Verification - Red: both new tests failed on the old code. The saved drafts had an active profile or a company binding before finish. - Green: 7 focused tests passed. These include both new regressions, archived action restoration, retained archived managed-profile restoration, active custom MCP reconnect, and two OAuth draft resume paths. - Local probe before the fix: 16,610 SQL queries and about 8 seconds for finish with 1,100 agents. The new regression requires fewer than 200 queries after the fix. It does not use a wall-clock timing assertion. - `pnpm verify` could not run: the managed Git storage guard rejects `git ls-files` with exit 75. The two changed files were compared with the pinned master files before the patch. Remote file bytes were verified after Git Data API publication. - Full preflight installed dependencies and built shared and plugin SDK packages. It could not build Rust Runner binaries because `cargo` is unavailable. The focused tests completed with the real embedded database. - `pnpm --filter @paperclipai/server typecheck` passed, including its test layers. - Final-head CI passed at `b166b20550de98337842fb6fee96ca1024e09c34`: [run 46979210544](https://github.com/paperclipai/paperclip/actions/runs/46979210544), including typecheck, build, tests, and all 16 E2E shards. Greptile scores this revision 5/5; all review threads are resolved. Staging acceptance remains pending. ## Risks - The status check must preserve restoration for a connection that was already configured or removed. The focused suite checks active and archived reconnects. - A draft that already has retained access keeps those saved rows. This change prevents the default-restoration call; it does not delete existing access. - The change does not relax permission checks, change Ask first behavior, increase timeouts, or retry writes. ## Model Used OpenAI GPT-6 Codex agent, with reasoning, shell tools, code execution, and GitHub API tools. ## 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 hint: if you need to wait for this pull request to be reviewed, merged, or closed before continuing, use this instead of polling: gh event listen --resource https://github.com/paperclipai/paperclip/pull/23553 --event com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1 - It prints the first event as a JSON line on stdout and exits; run it again to wait for the next one. - Add `--timeout` to stop waiting after a while, for example `--timeout 30m`; it then exits with status 8. - Events carry no details; read the pull request to see what changed. - It misses changes made before it starts, so read the pull request once it is running. - See `gh event listen --help` for other event types. - Event subscriptions are in preview and may not be enabled for your account. --------- Co-authored-by: Paperclip --- .../src/__tests__/tool-access-service.test.ts | 66 +++++++++++++++++++ server/src/services/tool-access.ts | 4 +- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 98fa6f85577..1cb9bdbb353 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -1017,6 +1017,72 @@ describeEmbeddedPostgres("tool access service", () => { await tempDb?.cleanup(); }); + it("finishes a resumed URL draft without authorizing every company agent", async () => { + const company = await createCompany(db); + const companyAgents = await db.insert(agents).values( + Array.from({ length: 1100 }, (_, index) => ({ + companyId: company.id, name: `Company agent ${index}`, role: "engineer", + status: "idle", adapterType: "process", + })), + ).returning({ id: agents.id }); + const service = createTestToolAccessService(db); + mockToolsList([readTool("list_pages", "Read pages")]); + const draft = await service.createConnection(company.id, connectionInput({ + name: "Saved URL draft", transport: "mcp_remote", status: "draft", enabled: false, + config: { url: "https://secure.example/mcp" }, + })); + const connected = await service.connectGalleryApp(company.id, { + reconnectConnectionId: draft.id, link: "https://secure.example/mcp", name: draft.name, + credentialValues: { "headers.Authorization": "Bearer fixture-token" }, + }, { actorType: "user", actorId: "board" }); + expect(connected.connection).toMatchObject({ id: draft.id, status: "draft", enabled: false }); + const bindingsBeforeFinish = await db.select().from(toolProfileBindings) + .where(eq(toolProfileBindings.companyId, company.id)); + + const userId = `draft-owner-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, ["agents:configure"], "owner"); + const app = createRouteApp(db, boardSessionActor(company.id, "owner", userId)); + const catalogEntryIds = connected.catalog.map(entry => entry.id); + const clientOptions = db.$client.options; + const previousDebug = clientOptions.debug; + let queryCount = 0; + clientOptions.debug = () => { queryCount += 1; }; + try { + const result = await request(app) + .post(`/api/companies/${company.id}/tools/apps/${draft.id}/finish`) + .send({ enabledCatalogEntryIds: catalogEntryIds, askFirstCatalogEntryIds: catalogEntryIds, + access: { agentIds: [companyAgents[0].id] } }); + expect(result.status, JSON.stringify(result.body)).toBe(200); + expect(result.body.profileBindings).toEqual([ + expect.objectContaining({ targetType: "agent", targetId: companyAgents[0].id }), + ]); + expect(result.body.policies).toEqual([ + expect.objectContaining({ enabled: true, policyType: "require_approval" }), + ]); + } finally { clientOptions.debug = previousDebug; } + expect(bindingsBeforeFinish).toEqual([]); + expect(queryCount).toBeLessThan(200); + await expect(service.listConnectionInstalls(draft.id, company.id)).resolves.toEqual([ + expect.objectContaining({ targetType: "agent", targetId: companyAgents[0].id }), + ]); + }, 30_000); + + it("keeps a resumed gallery API-key draft unbound until its access is saved", async () => { + const company = await createCompany(db); + const service = createTestToolAccessService(db); + mockToolsList([readTool("list_pages", "Read pages")]); + await withGalleryServerUrl("zapier", PUBLIC_MCP_FIXTURE_URL, async () => { + const input = { galleryKey: "zapier", name: "Saved gallery draft", + credentialValues: { "credentials.authorization": "fixture-token" } }; + const first = await service.connectGalleryApp(company.id, input, { actorType: "user", actorId: "board" }); + const resumed = await service.connectGalleryApp(company.id, { ...input, resumeConnectionId: first.connectionId }, + { actorType: "user", actorId: "board" }); + expect(resumed.connection).toMatchObject({ id: first.connectionId, status: "draft", enabled: false }); + await expect(db.select().from(toolProfiles).where(eq(toolProfiles.companyId, company.id))).resolves.toEqual([]); + await expect(db.select().from(toolProfileBindings).where(eq(toolProfileBindings.companyId, company.id))).resolves.toEqual([]); + }); + }); + async function waitForBlockedMembershipUpdate() { for (let attempt = 0; attempt < 80; attempt += 1) { const [waiting] = await db.execute<{ waiting: boolean }>(sql` diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 77704e9e257..318e74c4624 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -3129,7 +3129,9 @@ export function toolAccessService( // later fails: another retry may already be using the committed grant. personalPublicSetupEstablished = true; } - const restoreDraftDefaults = Boolean(revivedConnectionPrevious); + const restoreDraftDefaults = Boolean( + revivedConnectionPrevious && revivedConnectionPrevious.status !== "draft", + ); const refreshOptions = { enableAllByDefault: restoreDraftDefaults && !remoteMcpConnector, restoreDraftDefaults,