Files
PaperClipAI/server/src/__tests__/agent-grant-scope.test.ts
T
Devin FoleyandPaperclip 725a9e36b6 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 fcb8fc5deb.

**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 <noreply@paperclip.ing>
2026-12-01 22:40:42 -08:00

180 lines
9.9 KiB
TypeScript

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<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
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<ReturnType<typeof seed>>, 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<string | null> = [];
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([]);
});
});