From 725a9e36b6818a2f728f12857e85ea6f064b0a7f Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Tue, 1 Dec 2026 22:40:42 -0800 Subject: [PATCH] fix(connections): let a dedicated account serve every agent picked for its connection (#23431) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A GitHub connection can use "A dedicated account for an agent", for example a bot account that an agent uses instead of the person who gives instructions > - The account lives on the grant of the agent that signed in. Core gives one connection to one signed-in agent > - A team often wants several agents to use the same bot account, or to move a bot account to a new agent. Today each agent needs its own GitHub sign-in as the bot > - The permissions page also lets an owner pick more agents for the connection, which looks like sharing but gives those agents nothing > - Sharing a credential must stay under the owner's control: an install of a connection needs only `agents:configure`, which agents and operators have, so installs cannot be the share signal > - This pull request adds an explicit share list for a dedicated account. Only the person who connected the account, a company owner or admin, or an instance admin can change it > - The benefit is that a bot account can serve several agents without a new sign-in, and no one else can attach the account to their agents ## Linked Issues or Issue Description No public issue exists. **What happened?** A GitHub connection with a dedicated account was signed in for agent A. The owner then picked agent B for the same connection on the permissions page. The page showed "Used only by A" and also "2 agents selected" with A and B. Agent B made no GitHub tool calls through the connection, and its git work used the responsible person's GitHub account. There was no way to let agent B use the bot account without a second GitHub sign-in as the bot. **Expected behavior** The owner of a dedicated account can share it with chosen agents, and those agents use it for managed git and the connection's tools. No one else can share it. **Steps to reproduce** 1. Add a GitHub connection with "A dedicated account for an agent" and pick agent A. 2. On the connection's permissions page, pick agent B too. 3. Start a run for agent B that pushes with git. See that it uses the responsible person's account, and that the page offers no way to share the bot account. **Paperclip version or commit** `master` at fcb8fc5deb7. **Deployment mode** Any deployment with a GitHub connection that uses a dedicated agent account. ## What Changed - `agent-grant.ts`: - `agentGrantScope`: a dedicated grant serves its signed-in agent, or an agent with a share row (a `connection_grant_delegations` row on the agent grant). Installs and app profile bindings do not count. - `replaceSharedAgents`: replaces the share list in one transaction, and checks share permission again on the locked grant row, so a share request cannot land after another person's reconnect. It accepts only active agents of the company, skips the signed-in agent, refuses an inactive grant, and records a `connection_grant.shared_agents_replaced` audit event. - `sharedAgentGrantIds` and `dedicatedIdentityAgentIds` read the share list. - New route `PUT /tool-connections/:connectionId/grants/:grantId/shared-agents` with `replaceDedicatedAccountAgentsSchema` (at most `DEDICATED_ACCOUNT_SHARE_LIMIT`, 1000 agents, the same as a grant's member audience; the picker does not send a larger selection and says why). Only a board user can call it, and only when the user connected the account, is a company owner or admin, or is an instance admin. Agents and other operators get 403. - The credential access, tool gateway and token broker lookups for a per-agent connection use `agentGrantScope`. - `git-credentials.ts`: managed git identity uses the share list. An agent that has its own dedicated account uses its own account first. Live shared grants come before revoked ones, and a run still asks for a reconnect when no live grant remains. - The grants endpoint returns `dedicatedAgentIds` (the signed-in agent and the shared agents) and `canShareDedicatedIdentity` for the viewer. - Existing delegation lookups match only personal grants, so a share never acts as a personal delegation. - Every path that replaces a dedicated grant's credential (the connect upsert, the cloud connector callback and the credential reconnect) calls `reauthorizeAgentGrant`. It locks and rereads the grant, records the new authorizer as the grant's `createdByUserId`, and clears the share list when the authorizer or the provider account changes. So only the person behind the current credential, or an admin, can share it. - `revokeConnectionGrant` keeps the share rows of a dedicated agent grant, so a revoked account asks shared agents to reconnect instead of switching them to a person's account. A reconnect reactivates the same grant with its shares. - Permissions page: the GitHub identity card lists each agent that uses the account and, for a person who can share it, shows "Share this account with other agents". The sharing state lives in the new `useDedicatedAccountSharing` hook. - Agent Tools tab: uses `dedicatedAgentIds`, so a shared agent shows the shared account. - `doc/execution-github-identity.md`: describes the share list and who can change it. ## Verification - `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter @paperclipai/ui typecheck` pass. - `server/src/__tests__/agent-grant-scope.test.ts` (7 tests, including a reconnect that clears shares and a share request whose permission is checked against the locked, already-reconnected grant): the signed-in and shared agents get the grant; installed, bound and unpicked agents do not; a former agent keeps only its own revoked grant; the share list accepts only active company agents, skips the signed-in agent, refuses an inactive grant and records an audit event. - `server/src/__tests__/dedicated-account-sharing-routes.test.ts` (3 tests): an operator with `tools:manage_connections` and a member get 403; after another person reconnects the account, the shares are cleared and only that person (or an admin) can share; the person who connected the account and an admin can replace the list; the grants endpoint reports the agents and the viewer's permission. - `github-operation-credentials.test.ts`: a shared agent uses the dedicated account; installed and bound agents use the person's account; an agent's own dedicated account comes first; a revoked grant for another account does not make the identity ambiguous. 27 tests pass. - `agent-grant-scope.test.ts` also checks that a revoke keeps the share list (fails without the change), and `github-operation-credentials.test.ts` checks that a shared agent gets a reconnect error, not the person's account, after a revoke. - UI: `DedicatedIdentity.test.tsx` (4 tests, including the sharing picker with 800 agents and 20 unchanged rerenders under a fixed read budget), `dedicated-github-identity.test.ts` (3 tests) and `useDedicatedIdentityAgents.test.ts` (2 tests, 800 agents behind a read counter). - I ran the 92 server test files that mention per-agent connections, agent grants, dedicated accounts or delegations: 81 files and 6852 tests pass, including `openapi-routes.test.ts` with the new route in the spec. The other 11 files are integration tests that skip without their test database. I also ran 34 UI test files for the apps pages, the Tools tab and replay masking: 457 tests pass. - `tests/runner-e2e/source-sdk-public-inputs.json` is regenerated with `source-sdk-public-inputs.mjs --write`, because the change touches pinned `packages/shared` files. ## Risks - No schema change: the share list reuses `connection_grant_delegations`. - Agents keep their current identity after this change. An agent uses a shared account only after an owner or admin shares it. - A connection manager who is not an admin can still remove a share through the existing delegation delete route. That only reduces access. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, read-only database queries on a hosted instance for the diagnosis). ## 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 - [ ] All Paperclip CI gates are green - [ ] 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 --- doc/execution-github-identity.md | 4 +- packages/shared/src/index.ts | 3 + packages/shared/src/types/tool-access.ts | 2 + packages/shared/src/validators/index.ts | 3 + packages/shared/src/validators/tool-access.ts | 5 + .../src/__tests__/agent-grant-scope.test.ts | 179 ++++++++++++++++++ .../dedicated-account-sharing-routes.test.ts | 146 ++++++++++++++ .../github-operation-credentials.test.ts | 47 +++++ server/src/routes/openapi.ts | 20 ++ server/src/routes/tool-access.ts | 45 +++++ server/src/services/git-credentials.ts | 28 ++- server/src/services/tool-access.ts | 5 +- .../tool-access/connections/agent-grant.ts | 159 +++++++++++++++- .../tool-access/connections/grants.ts | 4 +- .../services/tool-access/credential-access.ts | 3 +- .../tool-access/oauth/cloud-callback.ts | 4 +- .../tool-access/token-broker/service.ts | 4 +- server/src/services/tool-gateway.ts | 4 +- .../runner-e2e/source-sdk-public-inputs.json | 8 +- ui/src/api/tools.ts | 5 + .../hooks/useDedicatedIdentityAgents.test.ts | 57 ++++++ ui/src/hooks/useDedicatedIdentityAgents.ts | 46 +++++ ui/src/lib/dedicated-github-identity.test.ts | 33 ++++ ui/src/lib/dedicated-github-identity.ts | 14 ++ ui/src/pages/AgentToolsTab.tsx | 17 +- ui/src/pages/apps/AppDetail.tsx | 6 + .../app-detail/DedicatedIdentity.test.tsx | 119 ++++++++++++ .../apps/app-detail/IdentitiesSection.tsx | 75 +++++++- 28 files changed, 1004 insertions(+), 41 deletions(-) create mode 100644 server/src/__tests__/agent-grant-scope.test.ts create mode 100644 server/src/__tests__/dedicated-account-sharing-routes.test.ts create mode 100644 ui/src/hooks/useDedicatedIdentityAgents.test.ts create mode 100644 ui/src/hooks/useDedicatedIdentityAgents.ts create mode 100644 ui/src/lib/dedicated-github-identity.test.ts create mode 100644 ui/src/lib/dedicated-github-identity.ts create mode 100644 ui/src/pages/apps/app-detail/DedicatedIdentity.test.tsx diff --git a/doc/execution-github-identity.md b/doc/execution-github-identity.md index 10786facda0..8f093f80eb6 100644 --- a/doc/execution-github-identity.md +++ b/doc/execution-github-identity.md @@ -192,7 +192,9 @@ a reconnect requirement. An explicit dedicated-agent grant overrides personal selection. Revoked, disabled, unavailable, or ambiguous dedicated grants do not fall back to a person's account. Removing the dedicated configuration restores personal selection. -Connection setup and permissions display: “This agent uses this GitHub account for everyone's work, instead of the person giving instructions.” +A dedicated account signs in one agent. The person who connected the account, a company owner or admin, or an instance admin can share it with other agents of the company on the connection's permissions page. Each share is an audited delegation on the dedicated grant. An agent uses a shared account for managed git and for the connection's tools only through that share list: an install of the connection or an app profile binding never gives an agent the account. An agent that has its own dedicated account uses its own account first. + +Connection setup and permissions display: “This agent uses this GitHub account for everyone's work, instead of the person giving instructions.” The permissions page lists each agent that uses the account. A person who can share it sees “Share this account with other agents”. The GitHub permissions page shows repositories across all connected accounts in one scrollable list. It has no account filter or repository search. Repository icons, private-repository indicators, refresh, and GitHub configuration links remain available. The “Add More Repos on GitHub” button opens GitHub’s app installation and repository-access setup. diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index dab61eb6382..076c2aba16f 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2459,6 +2459,8 @@ export { connectionTokenSubjectSchema, startConnectionAuthorizationSchema, createConnectionGrantDelegationSchema, + replaceDedicatedAccountAgentsSchema, + DEDICATED_ACCOUNT_SHARE_LIMIT, replaceConnectionGrantMembersSchema, toolConnectionTestCallSchema, toolPolicyTestRequestSchema, @@ -2551,6 +2553,7 @@ export { type UpdateToolMcpGateway, type ConnectionTokenRequestInput, type CreateConnectionGrantDelegation, + type ReplaceDedicatedAccountAgents, type ReplaceConnectionGrantMembersInput, type ImportMcpJson, type ToolPolicyTestRequestInput, diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 203dc803d73..65f9f89a79b 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -340,6 +340,8 @@ export interface ConnectionGrantsResponse { capabilities: ToolConnectionCapabilities; currentUserId: string | null; members: ConnectionAudienceMember[]; + dedicatedAgentIds?: string[]; + canShareDedicatedIdentity?: boolean; } /** A company member that can appear in an organization grant's audience. */ diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index c96d9929e41..0739d0fdc6a 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -947,6 +947,8 @@ export { connectionTokenSubjectSchema, startConnectionAuthorizationSchema, createConnectionGrantDelegationSchema, + replaceDedicatedAccountAgentsSchema, + DEDICATED_ACCOUNT_SHARE_LIMIT, replaceConnectionGrantMembersSchema, createToolTrustRuleFromActionRequestSchema, revokeToolTrustRuleSchema, @@ -1039,6 +1041,7 @@ export { type UpsertToolCatalogEntry, type ConnectionTokenRequestInput, type CreateConnectionGrantDelegation, + type ReplaceDedicatedAccountAgents, type ReplaceConnectionGrantMembersInput, type ToolPolicyTestRequestInput, type CreateToolTrustRuleFromActionRequest, diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts index f7ed5d9b279..29a4a25c495 100644 --- a/packages/shared/src/validators/tool-access.ts +++ b/packages/shared/src/validators/tool-access.ts @@ -75,6 +75,11 @@ export const createConnectionGrantDelegationSchema = z.object({ agentId: z.string().guid(), }); export type CreateConnectionGrantDelegation = z.infer; +export const DEDICATED_ACCOUNT_SHARE_LIMIT = 1000; +export const replaceDedicatedAccountAgentsSchema = z.object({ + agentIds: z.array(z.string().guid()).max(DEDICATED_ACCOUNT_SHARE_LIMIT), +}).strict(); +export type ReplaceDedicatedAccountAgents = z.infer; export const toolConnectionCredentialPolicySchema = z.enum(["shared", "per_user", "per_user_with_fallback", "per_agent"]); export const toolConnectionStatusSchema = z.enum(["draft", "active", "disabled", "archived"]); export const toolConnectionInstallTargetTypeSchema = z.enum(["company", "agent"]); diff --git a/server/src/__tests__/agent-grant-scope.test.ts b/server/src/__tests__/agent-grant-scope.test.ts new file mode 100644 index 00000000000..7cbcb28bb02 --- /dev/null +++ b/server/src/__tests__/agent-grant-scope.test.ts @@ -0,0 +1,179 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + agents, + companies, + connectionGrantDelegations, + connectionGrants, + createDb, + toolAccessAuditEvents, + toolApplications, + toolConnectionInstalls, + toolConnections, + toolProfileBindings, + toolProfiles, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { + agentGrantPreference, + agentGrantScope, + createAgentGrantStore, + dedicatedIdentityAgentIds, + reauthorizeAgentGrant, +} from "../services/tool-access/connections/agent-grant.js"; +import { toolAccessService } from "../services/tool-access.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +(support.supported ? describe : describe.skip)("dedicated agent grant sharing", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-agent-grant-scope-"); + db = createDb(database.connectionString); + }, 30_000); + + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + }, 60_000); + + async function seed() { + const companyId = randomUUID(); + const [owner, shared, installed, bound, unpicked, former, retired] = Array.from({ length: 7 }, () => randomUUID()); + const applicationId = randomUUID(); + const connectionId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: companyId, issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values([owner, shared, installed, bound, unpicked, former, retired].map((id) => ({ + id, companyId, name: id, role: "engineer", adapterType: "codex_local", status: id === retired ? "terminated" : "idle", + }))); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "mcp_http" }); + await db.insert(toolConnections).values({ + id: connectionId, companyId, applicationId, name: connectionId, uid: connectionId, + transport: "mcp_remote", status: "active", enabled: true, credentialPolicy: "per_agent", + config: { sourceTemplateKey: "github" }, + }); + const [revoked] = await db.insert(connectionGrants).values({ + companyId, connectionId, kind: "agent", subjectAgentId: former, status: "revoked", credentialSecretRefs: [], + }).returning(); + const [active] = await db.insert(connectionGrants).values({ + companyId, connectionId, kind: "agent", subjectAgentId: owner, status: "active", credentialSecretRefs: [], + createdByUserId: "user-owner", + }).returning(); + await db.insert(toolConnectionInstalls).values([owner, installed].map((targetId) => ({ + companyId, connectionId, targetType: "agent" as const, targetId, + }))); + const [profile] = await db.insert(toolProfiles).values({ + companyId, profileKey: `app:${connectionId}`, name: `app ${connectionId}`, + }).returning(); + await db.insert(toolProfileBindings).values({ companyId, profileId: profile!.id, targetType: "agent", targetId: bound }); + await db.insert(connectionGrantDelegations).values({ companyId, grantId: active!.id, agentId: shared, createdByUserId: "user-owner" }); + return { companyId, connectionId, owner, shared, installed, bound, unpicked, former, retired, active: active!, revoked: revoked! }; + } + + async function grantFor(input: Awaited>, agentId: string, activeOnly = true) { + const rows = await db.select().from(connectionGrants).where(and( + eq(connectionGrants.companyId, input.companyId), + eq(connectionGrants.connectionId, input.connectionId), + eq(connectionGrants.kind, "agent"), + activeOnly ? eq(connectionGrants.status, "active") : undefined, + agentGrantScope(db, agentId), + )).orderBy(...agentGrantPreference(agentId)).limit(1); + return rows[0]?.id ?? null; + } + + it("serves the signed-in agent and agents it is shared with, never an agent picked only by install or access", async () => { + const input = await seed(); + expect(await grantFor(input, input.owner)).toBe(input.active.id); + expect(await grantFor(input, input.shared)).toBe(input.active.id); + expect(await grantFor(input, input.installed)).toBeNull(); + expect(await grantFor(input, input.bound)).toBeNull(); + expect(await grantFor(input, input.unpicked)).toBeNull(); + }); + + it("keeps a former agent on its own revoked grant and off the live one", async () => { + const input = await seed(); + expect(await grantFor(input, input.former, false)).toBe(input.revoked.id); + expect(await grantFor(input, input.former)).toBeNull(); + }); + + it("lists the signed-in agent and the shared agents of the live dedicated grant", () => { + const grants = [ + { kind: "agent" as const, status: "active" as const, subjectAgentId: "owner", delegations: [{ agentId: "shared" }] }, + { kind: "agent" as const, status: "revoked" as const, subjectAgentId: "former", delegations: [{ agentId: "old-share" }] }, + ]; + expect(dedicatedIdentityAgentIds({ credentialPolicy: "per_agent" }, grants)).toEqual(["owner", "shared"]); + expect(dedicatedIdentityAgentIds({ credentialPolicy: "per_user" }, grants)).toEqual([]); + }); + + it("keeps the share list when the dedicated account is revoked, so shared agents ask to reconnect", async () => { + const input = await seed(); + await toolAccessService(db).revokeConnectionGrant(input.connectionId, input.active.id, { actorType: "user", actorId: "user-owner" }); + const shares = await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id)); + expect(shares.map((row) => row.agentId)).toEqual([input.shared]); + expect(await grantFor(input, input.shared)).toBeNull(); + expect(await grantFor(input, input.shared, false)).toBe(input.active.id); + }); + + it("clears the share list when a reconnect brings a different account or a different authorizer", async () => { + const input = await seed(); + const shares = () => db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id)); + await db.update(connectionGrants).set({ providerTenant: { externalId: "github-1" } }).where(eq(connectionGrants.id, input.active.id)); + const grant = input.active; + expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-owner", externalId: "github-1" })) + .toEqual({ createdByUserId: "user-owner" }); + expect(await shares()).toHaveLength(1); + expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-owner", externalId: "github-2" })) + .toEqual({ createdByUserId: "user-owner" }); + expect(await shares()).toHaveLength(0); + await db.insert(connectionGrantDelegations).values({ companyId: input.companyId, grantId: input.active.id, agentId: input.shared, createdByUserId: "user-owner" }); + expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-other" })).toEqual({ createdByUserId: "user-other" }); + expect(await shares()).toHaveLength(0); + expect(await reauthorizeAgentGrant(db, { ...grant, kind: "user" }, { authorizingUserId: "user-other" })).toEqual({}); + }); + + it("checks share permission against the locked grant, so a share made before a reconnect cannot land after it", async () => { + const input = await seed(); + await db.update(connectionGrants).set({ createdByUserId: "user-new" }).where(eq(connectionGrants.id, input.active.id)); + const seen: Array = []; + await expect(createAgentGrantStore(db).replaceSharedAgents({ + companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds: [input.installed], + actorUserId: "user-owner", + mayShare: (grant) => { seen.push(grant.createdByUserId); return grant.createdByUserId === "user-owner"; }, + })).rejects.toMatchObject({ status: 403 }); + expect(seen).toEqual(["user-new"]); + const shares = await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id)); + expect(shares.map((row) => row.agentId)).toEqual([input.shared]); + }); + + it("replaces the share list with active agents of the company and records an audit event", async () => { + const input = await seed(); + const store = createAgentGrantStore(db); + const replaced = await store.replaceSharedAgents({ + companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, + agentIds: [input.installed, input.owner, input.installed], actorUserId: "user-admin", mayShare: () => true, + }); + expect(replaced.map((row) => row.agentId)).toEqual([input.installed]); + expect(await grantFor(input, input.installed)).toBe(input.active.id); + expect(await grantFor(input, input.shared)).toBeNull(); + const [audit] = await db.select().from(toolAccessAuditEvents).where(and( + eq(toolAccessAuditEvents.connectionId, input.connectionId), + eq(toolAccessAuditEvents.action, "connection_grant.shared_agents_replaced"), + )); + expect(audit?.details).toMatchObject({ addedAgentIds: [input.installed], removedAgentIds: [input.shared] }); + + for (const agentIds of [[input.retired], [randomUUID()]]) { + await expect(store.replaceSharedAgents({ + companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds, actorUserId: "user-admin", mayShare: () => true, + })).rejects.toMatchObject({ status: 422 }); + } + await expect(store.replaceSharedAgents({ + companyId: input.companyId, connectionId: input.connectionId, grantId: input.revoked.id, agentIds: [], actorUserId: "user-admin", mayShare: () => true, + })).rejects.toMatchObject({ status: 409 }); + expect((await store.replaceSharedAgents({ + companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds: [], actorUserId: "user-admin", mayShare: () => true, + }))).toEqual([]); + }); +}); diff --git a/server/src/__tests__/dedicated-account-sharing-routes.test.ts b/server/src/__tests__/dedicated-account-sharing-routes.test.ts new file mode 100644 index 00000000000..848cfa92d7d --- /dev/null +++ b/server/src/__tests__/dedicated-account-sharing-routes.test.ts @@ -0,0 +1,146 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + agents, + companies, + companyMemberships, + connectionGrantDelegations, + connectionGrants, + createDb, + principalPermissionGrants, + toolApplications, + toolConnections, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { DEDICATED_ACCOUNT_SHARE_LIMIT, replaceDedicatedAccountAgentsSchema } from "@paperclipai/shared"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { createAgentGrantStore } from "../services/tool-access/connections/agent-grant.js"; +import { errorHandler } from "../middleware/index.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +(support.supported ? describe : describe.skip)("sharing a dedicated account with other agents", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-dedicated-account-sharing-"); + db = createDb(database.connectionString, { maxConnections: 4 }); + }, 30_000); + + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + }, 60_000); + + const roles = { connector: "operator", admin: "admin", operator: "operator", member: "member" } as const; + + async function seed() { + const companyId = randomUUID(); + const [subject, shared] = [randomUUID(), randomUUID()]; + const applicationId = randomUUID(); + const connectionId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: companyId, issuePrefix: companyId.slice(0, 8) }); + await db.insert(companyMemberships).values(Object.entries(roles).map(([userId, membershipRole]) => ({ + companyId, principalType: "user", principalId: `${companyId}-${userId}`, status: "active", membershipRole, + }))); + await db.insert(principalPermissionGrants).values({ + companyId, principalType: "user", principalId: `${companyId}-operator`, permissionKey: "tools:manage_connections", + scope: null, grantedByUserId: `${companyId}-admin`, + }); + await db.insert(agents).values([subject, shared].map((id) => ({ + id, companyId, name: id, role: "engineer", adapterType: "codex_local", + }))); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "mcp_http" }); + await db.insert(toolConnections).values({ + id: connectionId, companyId, applicationId, name: connectionId, uid: connectionId, + transport: "mcp_remote", status: "active", enabled: true, credentialPolicy: "per_agent", + config: { sourceTemplateKey: "github" }, createdByUserId: `${companyId}-connector`, + }); + const [grant] = await db.insert(connectionGrants).values({ + companyId, connectionId, kind: "agent", subjectAgentId: subject, status: "active", credentialSecretRefs: [], + createdByUserId: `${companyId}-connector`, + }).returning(); + return { companyId, connectionId, grantId: grant!.id, subject, shared }; + } + + function app(companyId: string, user: keyof typeof roles) { + const server = express(); + server.use(express.json()); + server.use((req, _res, next) => { + req.actor = { + type: "board", userId: `${companyId}-${user}`, sessionId: `session-${randomUUID()}`, userName: user, userEmail: null, + isInstanceAdmin: false, source: "session", companyIds: [companyId], + memberships: [{ companyId, membershipRole: roles[user], status: "active" }], + }; + next(); + }); + server.use("/api", toolAccessRoutes(db, {})); + server.use(errorHandler); + return server; + } + + const share = (input: Awaited>, user: keyof typeof roles, agentIds: string[]) => + request(app(input.companyId, user)) + .put(`/api/tool-connections/${input.connectionId}/grants/${input.grantId}/shared-agents`) + .send({ agentIds }); + + const sharedWith = async (grantId: string) => + (await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, grantId))).map((row) => row.agentId); + + it("lets only the person who connected the account or a company admin share it", async () => { + const input = await seed(); + for (const user of ["operator", "member"] as const) { + const refused = await share(input, user, [input.shared]); + expect(refused.status).toBe(403); + } + expect((await share(input, "operator", [input.shared])).body.error) + .toBe("Only the person who connected this account or a company admin can share it with other agents"); + expect(await sharedWith(input.grantId)).toEqual([]); + + const byConnector = await share(input, "connector", [input.shared]); + expect(byConnector.status).toBe(200); + expect(byConnector.body).toEqual({ grantId: input.grantId, agentIds: [input.shared] }); + expect(await sharedWith(input.grantId)).toEqual([input.shared]); + + expect(replaceDedicatedAccountAgentsSchema.safeParse({ agentIds: Array.from({ length: DEDICATED_ACCOUNT_SHARE_LIMIT }, () => randomUUID()) }).success).toBe(true); + expect(replaceDedicatedAccountAgentsSchema.safeParse({ agentIds: Array.from({ length: DEDICATED_ACCOUNT_SHARE_LIMIT + 1 }, () => randomUUID()) }).success).toBe(false); + const byAdmin = await share(input, "admin", []); + expect(byAdmin.status).toBe(200); + expect(await sharedWith(input.grantId)).toEqual([]); + }); + + it("tells the page who uses the account and whether this person can share it", async () => { + const input = await seed(); + await share(input, "connector", [input.shared]); + const forConnector = await request(app(input.companyId, "connector")).get(`/api/tool-connections/${input.connectionId}/grants`); + expect(forConnector.status).toBe(200); + expect(new Set(forConnector.body.dedicatedAgentIds)).toEqual(new Set([input.subject, input.shared])); + expect(forConnector.body.canShareDedicatedIdentity).toBe(true); + const forOperator = await request(app(input.companyId, "operator")).get(`/api/tool-connections/${input.connectionId}/grants`); + expect(forOperator.body.canShareDedicatedIdentity).toBe(false); + }); + + it("moves share authority to the person who reconnects the account and clears the old shares", async () => { + const input = await seed(); + await share(input, "connector", [input.shared]); + const store = createAgentGrantStore(db); + await store.upsertConnectAgentGrant({ + companyId: input.companyId, connectionId: input.connectionId, subjectAgentId: input.subject, + credentialSecretRefs: [], actor: { actorType: "user", actorId: `${input.companyId}-connector` }, + }); + expect(await sharedWith(input.grantId)).toEqual([input.shared]); + + await store.upsertConnectAgentGrant({ + companyId: input.companyId, connectionId: input.connectionId, subjectAgentId: input.subject, + credentialSecretRefs: [], actor: { actorType: "user", actorId: `${input.companyId}-operator` }, + }); + expect(await sharedWith(input.grantId)).toEqual([]); + expect((await share(input, "connector", [input.shared])).status).toBe(403); + expect((await share(input, "operator", [input.shared])).status).toBe(200); + expect(await sharedWith(input.grantId)).toEqual([input.shared]); + }); +}); diff --git a/server/src/__tests__/github-operation-credentials.test.ts b/server/src/__tests__/github-operation-credentials.test.ts index 75eeeacfcb5..786679645d1 100644 --- a/server/src/__tests__/github-operation-credentials.test.ts +++ b/server/src/__tests__/github-operation-credentials.test.ts @@ -15,6 +15,7 @@ import { companies, companyMemberships, companySecrets, + connectionGrantDelegations, connectionGrants, createDb, heartbeatRuns, @@ -25,6 +26,8 @@ import { toolApplications, toolConnectionInstalls, toolConnections, + toolProfileBindings, + toolProfiles, userSecretDefinitions, } from "@paperclipai/db"; import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared"; @@ -560,6 +563,50 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu env: {}, }); }); + it("lends a dedicated account only to the agents it is shared with, never to an agent picked by install or access", async () => { + const input = await seed(); + const personal = await grant(input, "A"); + const robot = await grant(input, "robot", true); + const [shared, installed, bound, former] = [randomUUID(), randomUUID(), randomUUID(), randomUUID()]; + await db.insert(agents).values([shared, installed, bound, former].map((id) => ({ + id, companyId: input.companyId, name: id, role: "engineer", adapterType: "codex_local", + }))); + await db.insert(toolConnectionInstalls).values([shared, installed, bound].map((targetId) => ({ + companyId: input.companyId, connectionId: personal.connectionId, targetType: "agent" as const, targetId, + }))); + await db.insert(toolConnectionInstalls).values({ + companyId: input.companyId, connectionId: robot.connectionId, targetType: "agent", targetId: installed, + }); + const [profile] = await db.insert(toolProfiles).values({ + companyId: input.companyId, profileKey: `app:${robot.connectionId}`, name: `app ${robot.connectionId}`, + }).returning(); + await db.insert(toolProfileBindings).values({ + companyId: input.companyId, profileId: profile!.id, targetType: "agent", targetId: bound, + }); + const [robotGrant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, robot.id)); + const [formerGrant] = await db.insert(connectionGrants).values({ + companyId: input.companyId, connectionId: robot.connectionId, kind: "agent", subjectAgentId: former, + status: "revoked", credentialSecretRefs: robotGrant!.credentialSecretRefs, + providerTenant: { ...robotGrant!.providerTenant, github: { ...robotGrant!.providerTenant!.github!, userId: "former-robot", login: "former-robot" } }, + }).returning(); + await db.insert(connectionGrantDelegations).values([robot.id, formerGrant!.id].map((grantId) => ({ + companyId: input.companyId, grantId, agentId: shared, createdByUserId: "A", + }))); + expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" })) + .toMatchObject({ configured: true, identitySource: "dedicated", grant: { id: robot.id } }); + for (const agentId of [installed, bound]) { + expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId, responsibleUserId: "A" })) + .toMatchObject({ configured: true, identitySource: "personal", grant: { id: personal.id } }); + } + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, robot.id)); + const revoked = await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" }); + expect(revoked).toMatchObject({ configured: true, identitySource: "dedicated" }); + expect(revoked.grant).toBeUndefined(); + await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, robot.id)); + const own = await grant({ ...input, agentId: shared }, "shared-robot", true); + expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" })) + .toMatchObject({ identitySource: "dedicated", grant: { id: own.id } }); + }); it("does not resolve the company default person's GitHub", async () => { const input = await seed(); await grant(input, "A"); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index ed5dfab97f2..3d135aac28d 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -315,6 +315,7 @@ import { testMachineSignInSchema, rotateMachineSignInSchema, configureRailwaySshSchema, + replaceDedicatedAccountAgentsSchema, createToolApplicationSchema, updateToolApplicationSchema, createToolConnectionSchema, @@ -12936,6 +12937,25 @@ registerCurrentRoute({ summary: "Replace the member audience of a tool connection grant", }); +registerCurrentRoute({ + "x-paperclip-transport": "rest", + "x-paperclip-connection-management": "connections:configure", + method: "put", + path: "/api/tool-connections/{connectionId}/grants/{grantId}/shared-agents", + tags: ["tool-access"], + summary: "Replace the agents that share a dedicated account", + body: replaceDedicatedAccountAgentsSchema, + responses: { + 200: r.ok(), + 400: r.badRequest, + 401: r.unauthorized, + 403: r.forbidden, + 404: r.notFound, + 409: r.conflict, + 422: r.unprocessable, + }, +}); + registerCurrentRoute({ "x-paperclip-transport": "rest", "x-paperclip-connection-management": "connections:configure", diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 34406aceea3..b0dba41b372 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -31,6 +31,7 @@ import { type MachineSignInStatus, configureRailwaySshSchema, createConnectionGrantDelegationSchema, + replaceDedicatedAccountAgentsSchema, createToolStdioCommandTemplateSchema, createToolApplicationSchema, createToolConnectionSchema, @@ -108,6 +109,7 @@ import { trustedBoardMutationOrigin } from "../middleware/board-mutation-guard.j import { connectionIntentService } from "../services/connection-intents.js"; import { redactRemoteUrlCredential } from "../services/remote-url-credentials.js"; import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js"; +import { createAgentGrantStore, dedicatedIdentityAgentIds } from "../services/tool-access/connections/agent-grant.js"; import type { heartbeatService } from "../services/heartbeat.js"; const COMPANY_INSTALL_DENIAL_REASON = @@ -654,6 +656,16 @@ function connectorEnrollmentPrincipal(req: Request): string { return membership; } + function canShareDedicatedAccount(req: Request, companyId: string, grant: { createdByUserId?: string | null }) { + if (req.actor.type !== "board") return false; + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; + const membership = req.actor.memberships?.find((item) => item.companyId === companyId); + if (membership?.status !== "active") return false; + const userId = connectionRequestUserId(req); + return Boolean(userId && grant.createdByUserId === userId) + || ["owner", "admin"].includes(String(membership.membershipRole)); + } + async function isToolConnectionManager(req: Request, companyId: string) { assertBoardOrAgent(req); assertCompanyAccess(req, companyId); @@ -2067,6 +2079,9 @@ function connectorEnrollmentPrincipal(req: Request): string { members: capabilities.canConfigure ? await svc.listConnectionAudienceMembers(connection.companyId) : [], + dedicatedAgentIds: dedicatedIdentityAgentIds(connection, listed.grants), + canShareDedicatedIdentity: listed.grants.some((grant) => grant.kind === "agent" && grant.status === "active" + && canShareDedicatedAccount(req, connection.companyId, grant)), }); }); @@ -2179,6 +2194,36 @@ function connectorEnrollmentPrincipal(req: Request): string { res.status(201).json(delegation); }); + router.put("/tool-connections/:connectionId/grants/:grantId/shared-agents", managementGuard("connections:configure", "PUT /tool-connections/:connectionId/grants/:grantId/shared-agents"), validate(replaceDedicatedAccountAgentsSchema), async (req, res) => { + assertBoard(req); + const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found"); + if (!connection) return; + const { grants } = await svc.listConnectionGrants(connection.id, connection.companyId); + const grant = grants.find((candidate) => candidate.id === req.params.grantId && candidate.kind === "agent"); + if (!grant) throw notFound("Dedicated account not found"); + if (!canShareDedicatedAccount(req, connection.companyId, grant)) { + throw forbidden("Only the person who connected this account or a company admin can share it with other agents"); + } + const delegations = await createAgentGrantStore(db).replaceSharedAgents({ + companyId: connection.companyId, + connectionId: connection.id, + grantId: grant.id, + agentIds: req.body.agentIds, + actorUserId: connectionRequestUserId(req)!, + actor: connectionRequestActor(req), + mayShare: (locked) => canShareDedicatedAccount(req, connection.companyId, locked), + }); + await logActivity(db, { + companyId: connection.companyId, + ...connectionRequestActor(req), + action: "tool_connection.dedicated_account_shared", + entityType: "connection_grant", + entityId: grant.id, + details: { connectionId: connection.id, agentIds: delegations.map((row) => row.agentId) }, + }); + res.json({ grantId: grant.id, agentIds: delegations.map((row) => row.agentId) }); + }); + router.delete("/tool-connections/:connectionId/grants/:grantId/delegations/:delegationId", managementGuard("connections:profiles", "DELETE /tool-connections/:connectionId/grants/:grantId/delegations/:delegationId", { personal: true }), async (req, res) => { assertBoardOrAgent(req); const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found"); diff --git a/server/src/services/git-credentials.ts b/server/src/services/git-credentials.ts index fed5e00d6fa..b17d8ff2c8f 100644 --- a/server/src/services/git-credentials.ts +++ b/server/src/services/git-credentials.ts @@ -14,6 +14,7 @@ import { and, eq, inArray, or, sql } from "drizzle-orm"; import { isGitHubDotCom } from "./github-fetch.js"; import { secretService } from "./secrets.js"; import { toolAccessService } from "./tool-access.js"; +import { sharedAgentGrantIds } from "./tool-access/connections/agent-grant.js"; /** * Server-side git credentials for managed project checkouts and execution-workspace base @@ -392,12 +393,18 @@ export async function resolveManagedGitHubIdentitySelection( eq(toolConnectionInstalls.companyId, companyId), inArray(toolConnectionInstalls.connectionId, connectionIds), )); - const eligibleConnectionIds = new Set(githubConnections.filter((connection) => installs.some((install) => - install.connectionId === connection.id && ( - (install.targetType === "company" && install.targetId === companyId) - || (install.targetType === "agent" && install.targetId === context.agentId) - ) - )).map((connection) => connection.id)); + const sharedGrants = context.agentId + ? await sharedAgentGrantIds(db, companyId, context.agentId, githubConnections + .filter((connection) => connection.credentialPolicy === "per_agent").map((connection) => connection.id)) + : new Map(); + const sharedConnectionIds = new Set(sharedGrants.values()); + const eligibleConnectionIds = new Set(githubConnections.filter((connection) => sharedConnectionIds.has(connection.id) + || installs.some((install) => + install.connectionId === connection.id && ( + (install.targetType === "company" && install.targetId === companyId) + || (install.targetType === "agent" && install.targetId === context.agentId) + ) + )).map((connection) => connection.id)); // A GitHub connection installed only for another agent is not configured for // this run. Treating the company-wide connection as configured here would // make unrelated agents fail before their adapter starts and would also @@ -409,9 +416,16 @@ export async function resolveManagedGitHubIdentitySelection( context.explicitGrantId ? eq(connectionGrants.id, context.explicitGrantId) : undefined, or(eq(connectionGrants.kind, "agent"), eq(connectionGrants.kind, "user")), )); - const dedicated = context.agentId + const ownDedicated = context.agentId ? grants.filter((grant) => grant.kind === "agent" && grant.subjectAgentId === context.agentId) : []; + const sharedDedicated = ownDedicated.length > 0 || !context.agentId + ? [] + : grants.filter((grant) => grant.kind === "agent" && sharedGrants.has(grant.id)); + const liveSharedDedicated = sharedDedicated.filter((grant) => grant.status === "active"); + const dedicated = ownDedicated.length > 0 + ? ownDedicated + : liveSharedDedicated.length > 0 ? liveSharedDedicated : sharedDedicated; // Connections are already restricted above to the owner-selected install // targets. Within that consent boundary the server-resolved responsible user // is authoritative; standing delegation is only an ownerless-run fallback. diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 5cd52c6656b..77704e9e257 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -33,7 +33,7 @@ import { toApplication } from "./tool-access/applications/projection.js"; import { groupedActions } from "./tool-access/catalog/action-summary.js"; import { createConnectionSetupPolicy, assertSupportedConnection } from "./tool-access/connections/setup-policy.js"; import { createOrganizationGrantStore } from "./tool-access/connections/organization-grant.js"; -import { createAgentGrantStore } from "./tool-access/connections/agent-grant.js"; +import { createAgentGrantStore, reauthorizeAgentGrant } from "./tool-access/connections/agent-grant.js"; import { createPersonalConnectionIdentity } from "./tool-access/connections/personal-identity.js"; import { createOAuthStateStore } from "./tool-access/oauth/state.js"; import { createOAuthCatalogCompletion } from "./tool-access/oauth/catalog-completion.js"; @@ -4039,9 +4039,10 @@ export function toolAccessService( } } if (agentGrant) { + const authorizer = await reauthorizeAgentGrant(tx, agentGrant, { authorizingUserId: connectionActorUserId(actor) }); await tx .update(connectionGrants) - .set({ credentialSecretRefs, updatedAt }) + .set({ credentialSecretRefs, updatedAt, ...authorizer }) .where(eq(connectionGrants.id, agentGrant.id)); } const [nextConnection] = await tx diff --git a/server/src/services/tool-access/connections/agent-grant.ts b/server/src/services/tool-access/connections/agent-grant.ts index 67e6262a824..7fb16fd67e3 100644 --- a/server/src/services/tool-access/connections/agent-grant.ts +++ b/server/src/services/tool-access/connections/agent-grant.ts @@ -1,15 +1,84 @@ -import { and, eq } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, ne, or, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db"; +import { agents, connectionGrantDelegations, connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db"; import type { CreateToolConnection } from "@paperclipai/shared"; -import { conflict } from "../../../errors.js"; +import { conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; import { connectionActorUserId } from "../actor.js"; import type { ActorInfo } from "../types.js"; type ConnectionGrant = typeof connectionGrants.$inferSelect; +export function agentGrantScope(db: Pick, agentId: string): SQL { + return or( + eq(connectionGrants.subjectAgentId, agentId), + exists(db.select({ id: connectionGrantDelegations.id }).from(connectionGrantDelegations).where(and( + eq(connectionGrantDelegations.companyId, connectionGrants.companyId), + eq(connectionGrantDelegations.grantId, connectionGrants.id), + eq(connectionGrantDelegations.agentId, agentId), + ))), + )!; +} + +export function agentGrantPreference(agentId: string): SQL[] { + return [desc(eq(connectionGrants.status, "active")), desc(eq(connectionGrants.subjectAgentId, agentId))]; +} + +export async function sharedAgentGrantIds( + db: Pick, + companyId: string, + agentId: string, + connectionIds: string[], +): Promise> { + if (connectionIds.length === 0) return new Map(); + const rows = await db.select({ grantId: connectionGrantDelegations.grantId, connectionId: connectionGrants.connectionId }) + .from(connectionGrantDelegations) + .innerJoin(connectionGrants, and( + eq(connectionGrants.companyId, connectionGrantDelegations.companyId), + eq(connectionGrants.id, connectionGrantDelegations.grantId), + )) + .where(and( + eq(connectionGrantDelegations.companyId, companyId), + eq(connectionGrantDelegations.agentId, agentId), + eq(connectionGrants.kind, "agent"), + inArray(connectionGrants.connectionId, connectionIds), + )); + return new Map(rows.map((row) => [row.grantId, row.connectionId])); +} + +export async function reauthorizeAgentGrant( + tx: Pick, + grant: Pick, + next: { authorizingUserId: string | null; externalId?: string | null }, +): Promise<{ createdByUserId?: string }> { + if (grant.kind !== "agent") return {}; + const [current] = await tx.select({ createdByUserId: connectionGrants.createdByUserId, providerTenant: connectionGrants.providerTenant }) + .from(connectionGrants) + .where(and(eq(connectionGrants.companyId, grant.companyId), eq(connectionGrants.id, grant.id))) + .for("update"); + if (!current) return {}; + const previousExternalId = current.providerTenant?.externalId ?? null; + const accountChanged = Boolean(next.externalId && previousExternalId && next.externalId !== previousExternalId); + const authorizerChanged = Boolean(next.authorizingUserId && next.authorizingUserId !== current.createdByUserId); + if (accountChanged || authorizerChanged) { + await tx.delete(connectionGrantDelegations).where(and( + eq(connectionGrantDelegations.companyId, grant.companyId), + eq(connectionGrantDelegations.grantId, grant.id), + )); + } + return next.authorizingUserId ? { createdByUserId: next.authorizingUserId } : {}; +} + +export function dedicatedIdentityAgentIds( + connection: { credentialPolicy: string }, + grants: Array & { delegations?: Array<{ agentId: string }> }>, +): string[] { + if (connection.credentialPolicy !== "per_agent") return []; + const active = grants.filter((grant) => grant.kind === "agent" && grant.status === "active" && grant.subjectAgentId); + return [...new Set(active.flatMap((grant) => [grant.subjectAgentId!, ...(grant.delegations ?? []).map((row) => row.agentId)]))]; +} + /** - * Dedicated-agent identities. A per-agent connection serves exactly one + * Dedicated-agent identities. A per-agent connection signs in exactly one * agent: its credential lives on that agent's grant, never on the connection. * OAuth methods write the grant in their callback; methods without sign-in * write it here when connect names the agent. @@ -47,10 +116,14 @@ export function createAgentGrantStore(db: Db) { ); } const previous = grants.find((grant) => grant.subjectAgentId === input.subjectAgentId) ?? null; + const authorizer = previous + ? await reauthorizeAgentGrant(tx, previous, { authorizingUserId: connectionActorUserId(input.actor) }) + : {}; const [current] = previous ? await tx .update(connectionGrants) .set({ + ...authorizer, credentialSecretRefs: input.credentialSecretRefs, status: "active", revokedAt: null, @@ -108,5 +181,81 @@ export function createAgentGrantStore(db: Db) { return grants.length === 1 ? grants[0]! : null; } - return { upsertConnectAgentGrant, activeAgentGrant }; + async function replaceSharedAgents(input: { + companyId: string; + connectionId: string; + grantId: string; + agentIds: string[]; + actorUserId: string; + actor?: ActorInfo; + mayShare: (grant: ConnectionGrant) => boolean; + }): Promise> { + return db.transaction(async (tx) => { + const [grant] = await tx.select().from(connectionGrants).where(and( + eq(connectionGrants.companyId, input.companyId), + eq(connectionGrants.connectionId, input.connectionId), + eq(connectionGrants.id, input.grantId), + eq(connectionGrants.kind, "agent"), + )).for("update"); + if (!grant?.subjectAgentId) throw notFound("Dedicated account not found"); + if (!input.mayShare(grant)) { + throw forbidden("Only the person who connected this account or a company admin can share it with other agents"); + } + if (grant.status !== "active") { + throw conflict("Reconnect this dedicated account before you share it", { code: "dedicated_account_inactive" }); + } + const requested = [...new Set(input.agentIds)].filter((agentId) => agentId !== grant.subjectAgentId); + const found = requested.length === 0 ? [] : await tx.select({ id: agents.id }).from(agents).where(and( + eq(agents.companyId, input.companyId), + inArray(agents.id, requested), + ne(agents.status, "terminated"), + )).for("no key update"); + if (found.length !== requested.length) { + throw unprocessable("Share a dedicated account only with active agents in this company", { code: "dedicated_account_agent_invalid" }); + } + const existing = await tx.select().from(connectionGrantDelegations).where(and( + eq(connectionGrantDelegations.companyId, input.companyId), + eq(connectionGrantDelegations.grantId, grant.id), + )); + const removed = existing.filter((row) => !requested.includes(row.agentId)).map((row) => row.id); + const added = requested.filter((agentId) => !existing.some((row) => row.agentId === agentId)); + if (removed.length > 0) { + await tx.delete(connectionGrantDelegations).where(and( + eq(connectionGrantDelegations.companyId, input.companyId), + inArray(connectionGrantDelegations.id, removed), + )); + } + if (added.length > 0) { + await tx.insert(connectionGrantDelegations).values(added.map((agentId) => ({ + companyId: input.companyId, + grantId: grant.id, + agentId, + createdByUserId: input.actorUserId, + }))); + } + if (added.length > 0 || removed.length > 0) { + await tx.insert(toolAccessAuditEvents).values({ + companyId: input.companyId, + connectionId: input.connectionId, + actorType: input.actor?.actorType ?? "user", + actorId: input.actor?.actorId ?? input.actorUserId, + action: "connection_grant.shared_agents_replaced", + outcome: "success", + reasonCode: "dedicated_account_shared", + details: { + grantId: grant.id, + subjectAgentId: grant.subjectAgentId, + addedAgentIds: added, + removedAgentIds: existing.filter((row) => removed.includes(row.id)).map((row) => row.agentId), + }, + }); + } + return tx.select().from(connectionGrantDelegations).where(and( + eq(connectionGrantDelegations.companyId, input.companyId), + eq(connectionGrantDelegations.grantId, grant.id), + )); + }); + } + + return { upsertConnectAgentGrant, activeAgentGrant, replaceSharedAgents }; } diff --git a/server/src/services/tool-access/connections/grants.ts b/server/src/services/tool-access/connections/grants.ts index f1e8cae4082..5b4049a5b67 100644 --- a/server/src/services/tool-access/connections/grants.ts +++ b/server/src/services/tool-access/connections/grants.ts @@ -548,14 +548,14 @@ replaceConnectionGrantMembers: async ( const releasedWaitPublications: ActivityPublication[] = []; const grant = await db.transaction(async (tx) => { await notifyGitHubCredentialChange(tx, connection); - const [lockedGrant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants) + const [lockedGrant] = await tx.select({ id: connectionGrants.id, kind: connectionGrants.kind }).from(connectionGrants) .where(and(eq(connectionGrants.id, grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id))) .for("update"); if (!lockedGrant) throw notFound("Connection grant not found"); await tx.select({ id: agents.id }).from(agents) .where(and(eq(agents.companyId, connection.companyId), notInArray(agents.status, ["pending_approval", "terminated"]))) .orderBy(agents.id).for("no key update"); - const removedDelegations = await tx + const removedDelegations = lockedGrant.kind === "agent" ? [] : await tx .delete(connectionGrantDelegations) .where( and( diff --git a/server/src/services/tool-access/credential-access.ts b/server/src/services/tool-access/credential-access.ts index eb9c6709c11..1c82c03e30d 100644 --- a/server/src/services/tool-access/credential-access.ts +++ b/server/src/services/tool-access/credential-access.ts @@ -12,6 +12,7 @@ import { parseRemoteHttpEndpoint } from "../remote-http-endpoint-guard.js"; import { REMOTE_URL_SECRET_CONFIG_PATH, remoteUrlCredentialMatchesPublicUrl } from "../remote-url-credentials.js"; import { secretService } from "../secrets.js"; import { connectionCredentialConfigPath as credentialRefConfigPath, connectionGrantCredentialRef } from "../connection-credentials.js"; +import { agentGrantScope } from "./connections/agent-grant.js"; import type { ToolAccessAudit } from "./audit.js"; import type { VercelCredentialService } from "./vercel-credentials.js"; @@ -60,7 +61,7 @@ export function createConnectionCredentialAccess(db: Db, { secrets, audit, verce eq(connectionGrants.connectionId, connection.id), eq(connectionGrants.kind, "agent"), eq(connectionGrants.status, "active"), - ...(agentId ? [eq(connectionGrants.subjectAgentId, agentId)] : []), + ...(agentId ? [agentGrantScope(db, agentId)] : []), )).limit(2); if (grants.length !== 1) { throw unprocessable(grants.length > 1 diff --git a/server/src/services/tool-access/oauth/cloud-callback.ts b/server/src/services/tool-access/oauth/cloud-callback.ts index f58e5ec6d59..4a853998b63 100644 --- a/server/src/services/tool-access/oauth/cloud-callback.ts +++ b/server/src/services/tool-access/oauth/cloud-callback.ts @@ -12,6 +12,7 @@ import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoo import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, gte, ne } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; +import { reauthorizeAgentGrant } from "../connections/agent-grant.js"; import { connectionGrants, companyMemberships, principalPermissionGrants, issueThreadInteractions, toolApplications, toolConnections, toolOauthStates } from "@paperclipai/db"; import type { ConnectionGrantKind, ConnectToolAppResult } from "@paperclipai/shared"; import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared"; @@ -339,9 +340,10 @@ export function createCloudOAuthCallback(db: Db, dependencies: Dependencies) { updatedAt: now(), }; if (existingCredentialGrant) { + const authorizer = await reauthorizeAgentGrant(tx, existingCredentialGrant, { authorizingUserId, externalId: credentials.subject }); await tx .update(connectionGrants) - .set(grantValues) + .set({ ...grantValues, ...authorizer }) .where(eq(connectionGrants.id, existingCredentialGrant.id)); } else { await tx.insert(connectionGrants).values({ diff --git a/server/src/services/tool-access/token-broker/service.ts b/server/src/services/tool-access/token-broker/service.ts index 92eb69df346..3fde021779d 100644 --- a/server/src/services/tool-access/token-broker/service.ts +++ b/server/src/services/tool-access/token-broker/service.ts @@ -13,6 +13,7 @@ import { toolAccessPolicyService } from "../../tool-access-policy.js"; import type { ToolAccessAudit } from "../audit.js"; import { createTokenBrokerAdmission, lockAuthorizedBrokerResponsibleMembership } from "./admission.js"; import { createTokenIssuanceRecorder } from "./issuance.js"; +import { agentGrantPreference, agentGrantScope } from "../connections/agent-grant.js"; import { createConnectionTokenExchange } from "./exchange.js"; import { CONNECTION_TOKEN_MINT_TOOL_NAME, assertScopeSubset, bearerTokenHash, connectionTokenBrokerEnabled, defaultScopesForConnection, inferConnectionTokenPath, normalizeConnectionTokenScopes, parentScopesForConnection, requestedTtlSeconds } from "./configuration.js"; type TokenBrokerDependencies = { @@ -228,9 +229,10 @@ export function createConnectionTokenBroker(db: Db, { now, secrets, policySvc, a eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id), eq(connectionGrants.kind, "agent"), - eq(connectionGrants.subjectAgentId, input.agentId), + agentGrantScope(db, input.agentId), ), ) + .orderBy(...agentGrantPreference(input.agentId)) .limit(1); if (!grant) { await fail( diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index dd929277a72..9184d9392ae 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -314,6 +314,7 @@ import { verifyToolArgumentsSignature, } from "./tool-content-guards.js"; import { extendApprovedExecutionWaitDeadline } from "./approved-execution-wait.js"; +import { agentGrantPreference, agentGrantScope } from "./tool-access/connections/agent-grant.js"; const DEFAULT_SESSION_TTL_MS = 15 * 60 * 1000; const MAX_SESSION_TTL_MS = 60 * 60 * 1000; @@ -5592,10 +5593,11 @@ export function createToolGatewayService( eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id), eq(connectionGrants.kind, "agent"), - eq(connectionGrants.subjectAgentId, session.agentId), + agentGrantScope(db, session.agentId), eq(connectionGrants.status, "active"), ), ) + .orderBy(...agentGrantPreference(session.agentId)) .limit(1); if (!agentGrant) { throw new ToolGatewayHttpError( diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 786d5203237..4c910b47324 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -290,7 +290,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "dab61eb638290a2e8bdcb0f4598bf5eeaa697396", + "packages/shared/src/index.ts": "076c2aba16fcb05907198379862d8bbe47825778", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -484,7 +484,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "203dc803d733c0fda990cbd8d5fc0dabb457730b", + "packages/shared/src/types/tool-access.ts": "65f9f89a79bb7cceff634499b858a4689fb2f553", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", @@ -540,7 +540,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "c96d9929e410dc95a8b2e0325b37e6c303711ebe", + "packages/shared/src/validators/index.ts": "0739d0fdc6aa48a681def520bb28b22b91f7aca3", "packages/shared/src/validators/instance.test.ts": "a8eac3e9a6eed97d6aa4f54e14e77c44720600af", "packages/shared/src/validators/instance.ts": "9cfe716ebf4dc1e24324e162ca096cdacbe97c4a", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", @@ -577,7 +577,7 @@ "packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa", "packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8", "packages/shared/src/validators/tool-access.test.ts": "ed01e972998730e91c97b5086badf7131bd0264e", - "packages/shared/src/validators/tool-access.ts": "f7ed5d9b27910aca23789f2e111df4a3429ff627", + "packages/shared/src/validators/tool-access.ts": "29a4a25c4954402f83c9da77e24706175f90e718", "packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e", "packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b", "packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index 2bd2edec831..b78f63c3307 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -432,6 +432,11 @@ export const toolsApi = { `/tool-connections/${connectionId}/grants/${grantId}/members`, { memberUserIds }, ), + replaceDedicatedAccountAgents: (connectionId: string, grantId: string, agentIds: string[]) => + api.put<{ grantId: string; agentIds: string[] }>( + `/tool-connections/${connectionId}/grants/${grantId}/shared-agents`, + { agentIds }, + ), /** * Start the signed-in user's own personal authorization. `subjectUserId` must * be the caller: the server refuses any other subject, so there is no way to diff --git a/ui/src/hooks/useDedicatedIdentityAgents.test.ts b/ui/src/hooks/useDedicatedIdentityAgents.test.ts new file mode 100644 index 00000000000..13503c999d0 --- /dev/null +++ b/ui/src/hooks/useDedicatedIdentityAgents.test.ts @@ -0,0 +1,57 @@ +// @vitest-environment jsdom +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it } from "vitest"; +import { dedicatedIdentityAgents, useDedicatedIdentityAgents } from "./useDedicatedIdentityAgents"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const AGENT_COUNT = 800; +const SERVED_COUNT = 300; +const READS_PER_AGENT = 2; + +let unmount: (() => void) | null = null; +afterEach(() => { unmount?.(); unmount = null; }); + +function countedAgents() { + let reads = 0; + const agents = Array.from({ length: AGENT_COUNT }, (_, index) => new Proxy( + { id: `agent-${index}`, name: `Agent ${index}`, status: index % 50 === 0 ? "terminated" : "idle" }, + { + get(target, property, receiver) { + if (++reads > AGENT_COUNT * READS_PER_AGENT) throw new Error("Dedicated identity agents exceeded their collection work limit"); + return Reflect.get(target, property, receiver); + }, + }, + )); + const served = Array.from({ length: SERVED_COUNT }, (_, index) => `agent-${index * 2}`); + return { agents, served, reads: () => reads }; +} + +describe("dedicated identity agents", () => { + it("reads each agent a bounded number of times with hundreds of agents", () => { + const { agents, served, reads } = countedAgents(); + const result = dedicatedIdentityAgents(agents, served); + expect(result).toHaveLength(SERVED_COUNT - Math.ceil(SERVED_COUNT * 2 / 50)); + expect(reads()).toBeLessThanOrEqual(AGENT_COUNT * READS_PER_AGENT); + expect(dedicatedIdentityAgents(agents, [])).toEqual([]); + }); + + it("does no collection work on rerenders with unchanged data", () => { + const { agents, served, reads } = countedAgents(); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const results: unknown[] = []; + function Harness() { + results.push(useDedicatedIdentityAgents(agents, served)); + return null; + } + unmount = () => { act(() => root.unmount()); host.remove(); }; + act(() => root.render(createElement(Harness))); + const firstReads = reads(); + for (let index = 0; index < 20; index += 1) act(() => root.render(createElement(Harness))); + expect(reads()).toBe(firstReads); + expect(new Set(results).size).toBe(1); + }); +}); diff --git a/ui/src/hooks/useDedicatedIdentityAgents.ts b/ui/src/hooks/useDedicatedIdentityAgents.ts new file mode 100644 index 00000000000..3dacbd3584f --- /dev/null +++ b/ui/src/hooks/useDedicatedIdentityAgents.ts @@ -0,0 +1,46 @@ +import { useMemo } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { toolsApi } from "@/api/tools"; +import { queryKeys } from "@/lib/queryKeys"; + +export function dedicatedIdentityAgents( + agents: readonly T[], + dedicatedAgentIds: readonly string[] | undefined, +): T[] { + if (!dedicatedAgentIds?.length) return []; + const served = new Set(dedicatedAgentIds); + return agents.filter((agent) => served.has(agent.id) && agent.status !== "terminated"); +} + +export function useDedicatedIdentityAgents( + agents: readonly T[] | undefined, + dedicatedAgentIds: readonly string[] | undefined, +): T[] { + return useMemo(() => dedicatedIdentityAgents(agents ?? [], dedicatedAgentIds), [agents, dedicatedAgentIds]); +} + +export function useDedicatedAccountSharing( + connectionId: string, + agents: readonly T[] | undefined, + dedicatedAgentIds: readonly string[] | undefined, + onError: (error: Error) => void, +) { + const queryClient = useQueryClient(); + const identityAgents = useDedicatedIdentityAgents(agents, dedicatedAgentIds); + const shareableAgents = useMemo(() => (agents ?? []).filter((agent) => agent.status !== "terminated"), [agents]); + const mutation = useMutation({ + mutationFn: ({ grantId, agentIds }: { grantId: string; agentIds: string[] }) => + toolsApi.replaceDedicatedAccountAgents(connectionId, grantId, agentIds), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connectionGrants(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); + }, + onError, + }); + return { + identityAgents, + shareableAgents, + pending: mutation.isPending, + share: (grantId: string, agentIds: string[]) => mutation.mutate({ grantId, agentIds }), + }; +} diff --git a/ui/src/lib/dedicated-github-identity.test.ts b/ui/src/lib/dedicated-github-identity.test.ts new file mode 100644 index 00000000000..645e94862bd --- /dev/null +++ b/ui/src/lib/dedicated-github-identity.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import type { ConnectionGrant, ToolConnection } from "@paperclipai/shared"; +import { dedicatedGitHubIdentityFor } from "./dedicated-github-identity"; + +const connection = { id: "conn-1", name: "robot", credentialPolicy: "per_agent" } as ToolConnection; +const grant = (overrides: Partial) => + ({ id: "grant-1", kind: "agent", subjectAgentId: "agent-a", status: "active", ...overrides }) as ConnectionGrant; + +describe("dedicatedGitHubIdentityFor", () => { + it("finds a shared account for an agent that the server says it serves, with or without an install", () => { + const rows = [{ connection, grant: grant({}), dedicatedAgentIds: ["agent-a", "agent-b"] }]; + expect(dedicatedGitHubIdentityFor(rows, "agent-b")).toEqual({ row: rows[0], shared: true }); + expect(dedicatedGitHubIdentityFor(rows, "agent-c")).toEqual({ row: null, shared: false }); + }); + + it("marks the signed-in agent's account as shared when another agent uses it", () => { + const shared = [{ connection, grant: grant({}), dedicatedAgentIds: ["agent-a", "agent-b"] }]; + const alone = [{ connection, grant: grant({}), dedicatedAgentIds: ["agent-a"] }]; + expect(dedicatedGitHubIdentityFor(shared, "agent-a").shared).toBe(true); + expect(dedicatedGitHubIdentityFor(alone, "agent-a")).toEqual({ row: alone[0], shared: false }); + }); + + it("prefers the agent's own account and ignores revoked grants", () => { + const own = { connection: { ...connection, id: "conn-2" }, grant: grant({ id: "grant-2", subjectAgentId: "agent-b" }), dedicatedAgentIds: ["agent-b"] }; + const rows = [ + { connection, grant: grant({ status: "revoked" }), dedicatedAgentIds: ["agent-a", "agent-b"] }, + { connection, grant: grant({}), dedicatedAgentIds: ["agent-a", "agent-b"] }, + own, + ]; + expect(dedicatedGitHubIdentityFor(rows, "agent-b").row).toBe(own); + expect(dedicatedGitHubIdentityFor(rows.slice(0, 2), "agent-b").row).toBe(rows[1]); + }); +}); diff --git a/ui/src/lib/dedicated-github-identity.ts b/ui/src/lib/dedicated-github-identity.ts new file mode 100644 index 00000000000..6183233f137 --- /dev/null +++ b/ui/src/lib/dedicated-github-identity.ts @@ -0,0 +1,14 @@ +import type { ConnectionGrant, ToolConnection } from "@paperclipai/shared"; + +export interface GitHubIdentityRow { + connection: ToolConnection; + grant: ConnectionGrant; + dedicatedAgentIds: string[]; +} + +export function dedicatedGitHubIdentityFor(rows: Row[], agentId: string) { + const row = rows.find(({ grant }) => grant.kind === "agent" && grant.subjectAgentId === agentId && grant.status === "active") + ?? rows.find(({ grant, dedicatedAgentIds }) => grant.kind === "agent" && grant.status === "active" && dedicatedAgentIds.includes(agentId)) + ?? null; + return { row, shared: (row?.dedicatedAgentIds.length ?? 0) > 1 }; +} diff --git a/ui/src/pages/AgentToolsTab.tsx b/ui/src/pages/AgentToolsTab.tsx index 8ae45f292a9..2e3494174c8 100644 --- a/ui/src/pages/AgentToolsTab.tsx +++ b/ui/src/pages/AgentToolsTab.tsx @@ -26,6 +26,7 @@ import { cn } from "../lib/utils"; import { brandChipBadge } from "../lib/status-colors"; import { installPayload, installStateFrom, isAgentInstalled, INSTALLED_HINT } from "../lib/tool-installs"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { dedicatedGitHubIdentityFor } from "@/lib/dedicated-github-identity"; function isGitHubConnection(connection: ToolConnection): boolean { return (connection.config?.sourceTemplateKey ?? connection.transportConfig?.sourceTemplateKey) === "github"; @@ -35,12 +36,13 @@ function isEligibleGitHubIdentityConnection(connection: ToolConnection, agentId: return isGitHubConnection(connection) && connection.enabled && connection.status === "active" - && isAgentInstalled(installStateFrom(connection.installs), agentId); + && (connection.credentialPolicy === "per_agent" || isAgentInstalled(installStateFrom(connection.installs), agentId)); } function GitHubIdentitySection({ agentName, dedicatedIdentity, + sharedIdentity = false, personalIdentity, loading, loadError, @@ -48,6 +50,7 @@ function GitHubIdentitySection({ }: { agentName: string; dedicatedIdentity: { connection: ToolConnection; grant: ConnectionGrant } | null; + sharedIdentity?: boolean; personalIdentity: { connection: ToolConnection; grant: ConnectionGrant } | null; loading: boolean; loadError: boolean; @@ -80,7 +83,9 @@ function GitHubIdentitySection({ {dedicatedLogin ? `@${dedicatedLogin}` : "Dedicated GitHub account"}

- Used only by {agentName}. This dedicated connection takes precedence over the responsible person's GitHub. + {sharedIdentity + ? `Shared by the agents picked for ${dedicatedIdentity.connection.name}.` + : `Used only by ${agentName}.`} This dedicated connection takes precedence over the responsible person's GitHub.

) : ( @@ -372,13 +377,10 @@ export function AgentToolsTab({ agent, companyId }: { agent: AgentDetailRecord; connection, grant, currentUserId: githubGrantQueries[index]?.data?.currentUserId, + dedicatedAgentIds: githubGrantQueries[index]?.data?.dedicatedAgentIds ?? [], })), ); - const dedicatedGitHubIdentity = githubIdentityRows.find(({ grant }) => ( - grant.kind === "agent" - && grant.subjectAgentId === agent.id - && grant.status === "active" - )) ?? null; + const { row: dedicatedGitHubIdentity, shared: sharedGitHubIdentity } = dedicatedGitHubIdentityFor(githubIdentityRows, agent.id); const personalGitHubIdentity = githubIdentityRows.find(({ grant, currentUserId }) => ( grant.kind === "user" && grant.subjectUserId === currentUserId @@ -579,6 +581,7 @@ export function AgentToolsTab({ agent, companyId }: { agent: AgentDetailRecord; query.isLoading)} loadError={connectionsQuery.isError || githubGrantQueries.some((query) => query.isError)} diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 0a29e841d44..96c4c7320fc 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -37,6 +37,7 @@ import { accessApi } from "@/api/access"; import { buildCompanyUserProfileMap } from "@/lib/company-members"; import { installStateFrom, type InstallState } from "@/lib/tool-installs"; import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow"; +import { useDedicatedAccountSharing } from "@/hooks/useDedicatedIdentityAgents"; import { useGoogleWorkspaceServiceGate } from "@/features/connections/GoogleWorkspaceServices"; import { connectionRemovalToast } from "@/features/connections/googleAccessRemoval"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; @@ -329,6 +330,8 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio const access = permissionDraft?.access ?? savedAccess; const managesRemoteMcpAccess = isRemoteMcpConnectorMethod(connection?.config?.sourceTemplateKey, connection?.config?.connectionMethodKey); const agents = agentsQuery.data ?? []; + const dedicatedSharing = useDedicatedAccountSharing(connectionId, agentsQuery.data, grantsQuery.data?.dedicatedAgentIds, + (error) => pushToast({ title: "Couldn't share this account", body: describeError(error).body, tone: "error" })); const disconnectRemote = useMutation({ mutationFn: () => toolsApi.archiveConnection(connectionId), onSuccess: (removed) => { @@ -691,6 +694,9 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio dedicatedAgent={managedIdentityGrant?.kind === "agent" ? agents.find((agent) => agent.id === managedIdentityGrant.subjectAgentId) ?? null : null} + sharedWithAgents={dedicatedSharing.identityAgents} + shareAgents={managedIdentityGrant?.kind === "agent" ? { agents: dedicatedSharing.shareableAgents, pending: dedicatedSharing.pending, + onSave: (agentIds) => dedicatedSharing.share(managedIdentityGrant.id, agentIds) } : undefined} grantsQuery={grantsQuery.data} loading={grantsPending} error={grantsView.kind === "error"} diff --git a/ui/src/pages/apps/app-detail/DedicatedIdentity.test.tsx b/ui/src/pages/apps/app-detail/DedicatedIdentity.test.tsx new file mode 100644 index 00000000000..00d902c5ad3 --- /dev/null +++ b/ui/src/pages/apps/app-detail/DedicatedIdentity.test.tsx @@ -0,0 +1,119 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ConnectionGrant, ConnectionGrantsResponse } from "@paperclipai/shared"; +import { IdentitiesSection } from "./IdentitiesSection"; + +vi.mock("@/components/ProviderToolIcon", () => ({ ProviderToolIcon: () => null })); +vi.mock("@/lib/router", async () => { + const actual = await vi.importActual("react-router-dom"); + return { + useSearchParams: actual.useSearchParams, + Link: ({ to, children }: { to: string; children: React.ReactNode }) => {children}, + }; +}); + +let root: ReturnType; +let container: HTMLDivElement; +afterEach(async () => { + await act(() => root?.unmount()); + container?.remove(); +}); + +async function render(node: React.ReactNode) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(() => root.render({node})); +} + +const oldBot = { id: "agent-old", name: "Review Bot", urlKey: "review-bot" }; +const newBot = { id: "agent-new", name: "Triage Bot", urlKey: "triage-bot" }; + +function identities( + sharedWithAgents: Array, + sharing: { canShare: boolean; shareAgents?: { agents: Array; pending: boolean; onSave: (agentIds: string[]) => void } } = { canShare: false }, +) { + const grant = { id: "grant-1", kind: "agent", subjectAgentId: oldBot.id, status: "active", providerTenant: {} } as unknown as ConnectionGrant; + return ( + + ); +} + +describe("dedicated GitHub identity shared by picked agents", () => { + it("names every agent that uses the dedicated account", async () => { + await render(identities([oldBot, newBot])); + expect(container.textContent).toContain("These agents use this GitHub account"); + expect(container.textContent).toContain("Used by Review Bot, Triage Bot"); + expect(container.textContent).not.toContain("Used only by"); + }); + + it("keeps the single-agent wording when only the signed-in agent uses it", async () => { + await render(identities([oldBot])); + expect(container.textContent).toContain("This agent uses this GitHub account"); + expect(container.textContent).toContain("Used only by Review Bot"); + }); + + it("offers the share control only to someone who can share the account", async () => { + const shareAgents = { agents: [oldBot, newBot], pending: false, onSave: vi.fn() }; + await render(identities([oldBot, newBot], { canShare: true, shareAgents })); + expect(container.textContent).toContain("Shared with 1 agent"); + await act(() => root.unmount()); + container.remove(); + await render(identities([oldBot], { canShare: true, shareAgents })); + expect(container.textContent).toContain("Share this account with other agents"); + await act(() => root.unmount()); + container.remove(); + await render(identities([oldBot, newBot], { canShare: false, shareAgents })); + expect(container.textContent).not.toContain("Shared with"); + expect(container.textContent).not.toContain("Share this account"); + }); + + it("keeps the sharing picker linear in a company with hundreds of agents and does no new sorting on rerenders", async () => { + const AGENT_COUNT = 800; + const SORT_READS_PER_AGENT = 64; + const RERENDER_READS_PER_AGENT = 8; + let reads = 0; + let limit = AGENT_COUNT * SORT_READS_PER_AGENT; + const counted = Array.from({ length: AGENT_COUNT }, (_, index) => new Proxy( + { id: index === 0 ? oldBot.id : `agent-${index}`, name: `Agent ${String(index).padStart(4, "0")}`, urlKey: `agent-${index}`, title: null }, + { + get(target, property, receiver) { + if (++reads > limit) throw new Error("Sharing picker exceeded its collection work limit"); + return Reflect.get(target, property, receiver); + }, + }, + )); + const shared = [oldBot, ...Array.from({ length: 300 }, (_, index) => ({ id: `agent-${index + 1}`, name: `Agent ${index + 1}`, urlKey: `agent-${index + 1}` }))]; + const sharing = { canShare: true, shareAgents: { agents: counted, pending: false, onSave: vi.fn() } }; + await render(identities(shared, sharing)); + expect(container.textContent).toContain("Shared with 300 agents"); + const firstRender = reads; + limit = firstRender + 20 * AGENT_COUNT * RERENDER_READS_PER_AGENT; + for (let index = 0; index < 20; index += 1) await act(() => root.render({identities(shared, sharing)})); + expect(reads - firstRender).toBeLessThanOrEqual(20 * AGENT_COUNT * RERENDER_READS_PER_AGENT); + }); +}); diff --git a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx b/ui/src/pages/apps/app-detail/IdentitiesSection.tsx index db929ab9cad..4efd8830052 100644 --- a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx +++ b/ui/src/pages/apps/app-detail/IdentitiesSection.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { Fragment, useEffect, useMemo, useState, type ReactNode } from "react"; import { Building2, Loader2, Lock, RefreshCw, TriangleAlert, UserRound } from "lucide-react"; import type { ConnectionAudienceMember, @@ -6,12 +6,14 @@ import type { ConnectionGrantsResponse, ToolConnectionCredentialPolicy, } from "@paperclipai/shared"; +import { DEDICATED_ACCOUNT_SHARE_LIMIT } from "@paperclipai/shared"; import { Button } from "@/components/ui/button"; import { Identity } from "@/components/Identity"; import { GithubIcon } from "@/components/icons/github-icon"; import { Skeleton } from "@/components/ui/skeleton"; import { InlineBanner } from "@/components/InlineBanner"; import { MemberMultiSelect } from "@/components/MemberMultiSelect"; +import { AgentMultiSelect, type AgentMultiSelectOption } from "@/components/AgentMultiSelect"; import { RadioCardGroup } from "@/components/ui/radio-card"; import { Dialog, @@ -48,6 +50,7 @@ import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** Section labels on the connection page match the plugin page: a quiet line over one grouped surface. */ const GROUP_LABEL = "px-4 text-sm text-muted-foreground"; +const NO_AGENTS: Array<{ id: string; name: string; urlKey?: string | null }> = []; const STATUS_CHIP: Record = { connected: brandChipBadge.green, @@ -84,6 +87,8 @@ export function IdentitiesSection({ ownerUserId, connectedUser, dedicatedAgent, + sharedWithAgents = NO_AGENTS, + shareAgents, grantsQuery, loading, error, @@ -105,6 +110,12 @@ export function IdentitiesSection({ ownerUserId: string | null; connectedUser: { label: string; image: string | null } | null; dedicatedAgent: { id: string; name: string; urlKey?: string | null } | null; + sharedWithAgents?: Array<{ id: string; name: string; urlKey?: string | null }>; + shareAgents?: { + agents: AgentMultiSelectOption[]; + pending: boolean; + onSave: (agentIds: string[]) => void; + }; grantsQuery: ConnectionGrantsResponse | undefined; loading: boolean; error: boolean; @@ -146,6 +157,15 @@ export function IdentitiesSection({ ?? null, [dedicatedAgent?.id, grants], ); + const [shareLimitError, setShareLimitError] = useState(null); + const shareOptions = useMemo( + () => shareAgents?.agents.filter((agent) => agent.id !== dedicatedAgent?.id) ?? [], + [dedicatedAgent?.id, shareAgents?.agents], + ); + const sharedAgentIds = useMemo( + () => new Set(sharedWithAgents.filter((agent) => agent.id !== dedicatedAgent?.id).map((agent) => agent.id)), + [dedicatedAgent?.id, sharedWithAgents], + ); const personalSubjectLabel = memberLabel( members, personalGrant?.subjectUserId ?? ownerUserId ?? currentUserId, @@ -178,20 +198,35 @@ export function IdentitiesSection({ if (credentialPolicy === "per_agent") { const github = agentGrant?.providerTenant?.github; + const identityAgents = dedicatedAgent + ? [dedicatedAgent, ...sharedWithAgents.filter((agent) => agent.id !== dedicatedAgent.id)] + : sharedWithAgents; return (

GitHub identity

-

This agent uses this GitHub account for everyone’s work, instead of the person giving instructions.

+

+ {identityAgents.length > 1 + ? "These agents use this GitHub account for everyone’s work, instead of the person giving instructions." + : "This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."} +

@{github.login} : "Dedicated GitHub account"} status={agentGrant?.status ?? null} - detail={dedicatedAgent ? ( - - Used only by {dedicatedAgent.name} - + detail={identityAgents.length > 0 ? ( + + {identityAgents.length > 1 ? "Used by " : "Used only by "} + {identityAgents.map((agent, index) => ( + + {index > 0 ? ", " : null} + + {agent.name} + + + ))} + ) : "Dedicated to one agent"} actions={!agentGrant && dedicatedAgent && capabilities?.canConfigure ? ( ) : null} /> + {shareAgents && dedicatedAgent && agentGrant?.status === "active" && grantsQuery?.canShareDedicatedIdentity ? ( +
+ 1 + ? `Shared with ${identityAgents.length - 1} ${identityAgents.length === 2 ? "agent" : "agents"}` + : "Share this account with other agents"} + emptyMessage="No other agents yet." + onSave={(agentIds) => { + if (agentIds.size > DEDICATED_ACCOUNT_SHARE_LIMIT) { + setShareLimitError(`Share this account with ${DEDICATED_ACCOUNT_SHARE_LIMIT} agents or fewer. Nothing was saved.`); + return; + } + setShareLimitError(null); + shareAgents.onSave([...agentIds]); + }} + /> + {shareLimitError ?

{shareLimitError}

: null} +
+ ) : null} {github ? : null}
);