Files
PaperClipAI/server/src/__tests__/github-operation-credentials.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

926 lines
38 KiB
TypeScript

import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { githubCredentialsFixture } from "./helpers/github-credentials-fixture.js";
import { createNativeGitHubAccess } from "../services/native-runtime/native-github-access.js";
import express from "express";
import request from "supertest";
import { runtimeConnectionIntentRoutes } from "../routes/connection-intents.js";
import { createRuntimeToolsToken } from "../runtime-tools-token.js";
import { errorHandler } from "../middleware/index.js";
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
companies,
companyMemberships,
companySecrets,
connectionGrantDelegations,
connectionGrants,
createDb,
heartbeatRuns,
issueComments,
issues,
projects,
runIdentityContexts,
toolApplications,
toolConnectionInstalls,
toolConnections,
toolProfileBindings,
toolProfiles,
userSecretDefinitions,
} from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import {
initializeRunIdentity,
captureRunIdentity,
} from "../services/run-identity.js";
import { resolveGitHubOperationCredentials } from "../services/github-operation-credentials.js";
import {
filterResolvedGitHubConnectionsForRun,
resolveManagedGitHubIdentitySelection,
} from "../services/git-credentials.js";
const vault = vi.hoisted(() => ({
resolveUserSecretValue: vi.fn(
async (_company: string, input: { responsibleUserId: string }) => ({
value: `test-token-${input.responsibleUserId}`,
}),
),
resolveSecretValue: vi.fn(async () => "test-dedicated-token"),
}));
vi.mock("../services/secrets.js", () => ({ secretService: () => vault }));
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_GITHUB_CREDENTIAL_TEST_DATABASE_URL");
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)(
"operation-time GitHub credential resolution",
() => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined,
db: ReturnType<typeof createDb>;
beforeAll(async () => {
vi.stubEnv(
"PAPERCLIP_AGENT_JWT_SECRET",
"test-github-broker-signing-secret",
);
if (!external) database = await startEmbeddedPostgresTestDatabase(
"paperclip-github-operation-",
);
db = createDb(external ?? database!.connectionString);
}, 30_000);
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
vi.unstubAllEnvs();
}, 60_000);
const { seed, grant, switchTo } = githubCredentialsFixture(() => db);
it.each(["config", "transportConfig"] as const)("reads only current GitHub identity connections via %s", async location => {
const input = await seed(), selected = await grant(input, "A");
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, selected.connectionId));
await db.update(toolConnections).set({ config: {}, transportConfig: {}, [location]: { sourceTemplateKey: "github" } })
.where(eq(toolConnections.id, selected.connectionId));
const payload = "unrelated-connection-config🙂".repeat(10_000);
const irrelevant = [null, true, 42, ["github"], { name: "github" }, "GitHub", " github ", "other"].map(sourceTemplateKey => {
const id = randomUUID();
return { id, companyId: input.companyId, applicationId: connection.applicationId, name: id, uid: id,
transport: "mcp_remote" as const, config: { sourceTemplateKey, payload }, transportConfig: { sourceTemplateKey } };
});
await db.insert(toolConnections).values(irrelevant);
const observed = createDb(external ?? database!.connectionString), events: Array<Record<string, unknown>> = [], now = Date.now();
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));
installDatabaseResponseCapture(observed, { toolConnections }, capture);
try {
expect(await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" }))
.toMatchObject({ configured: true, grant: { id: selected.id } });
capture.flush();
const reads = events.filter(event => event.table === "tool_connections" && event.operation === "select");
expect(reads).toHaveLength(1);
expect(reads[0].rows).toBe(1);
expect(reads[0].responseValueBytes).toBeLessThan(8192);
await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, selected.connectionId));
expect((await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" })).grant)
.toBeUndefined();
await db.update(toolConnections).set({ [location]: { sourceTemplateKey: "other" } }).where(eq(toolConnections.id, selected.connectionId));
expect(await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" }))
.toEqual({ configured: false });
expect(await resolveManagedGitHubIdentitySelection(observed, randomUUID(), { agentId: input.agentId, responsibleUserId: "A" }))
.toEqual({ configured: false });
const saved = await db.select().from(toolConnections).where(eq(toolConnections.companyId, input.companyId));
for (const row of irrelevant) expect(saved.find(candidate => candidate.id === row.id)?.config).toEqual(row.config);
} finally { capture.flush(); await observed.$client.end(); }
});
it("resolves current GitHub credentials without transferring execution snapshots", async () => {
const input = await seed(), selected = await grant(input, "A");
const payload = "github-credential-saved-input🙂".repeat(25_000);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: input.issueId, prompt: payload },
runnerProfileJson: { nativeExecutionInput: { savedInput: payload }, savedInput: payload },
resultJson: { stdout: payload }, stdoutExcerpt: payload, stderrExcerpt: payload,
}).where(eq(heartbeatRuns.id, input.runId));
const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId));
const observed = createDb(external ?? database!.connectionString), events: Array<Record<string, unknown>> = [], now = Date.now();
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));
installDatabaseResponseCapture(observed, { heartbeatRuns }, capture);
try {
expect(await resolveGitHubOperationCredentials(observed, input)).toMatchObject({
status: "available", login: "A", grantId: selected.id,
});
capture.flush();
const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select");
expect(reads.length).toBeGreaterThan(0);
expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(8192);
expect(JSON.stringify(events)).not.toContain("github-credential-saved-input");
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)))[0]).toEqual(before);
const full = await captureRunIdentity(observed, input);
expect(full.run.runnerProfileJson).toEqual(before.runnerProfileJson);
expect(full.run.resultJson).toEqual(before.resultJson);
expect(full.run.contextSnapshot).toEqual(before.contextSnapshot);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, selected.id));
expect(await resolveGitHubOperationCredentials(observed, input)).toMatchObject({ status: "unavailable" });
} finally { capture.flush(); await observed.$client.end(); }
});
it("resolves A → B → A without retaining tokens, and records only redacted diagnostics", async () => {
const input = await seed();
await grant(input, "A");
await grant(input, "B");
for (const user of ["A", "B", "A"]) {
await switchTo(input, user);
const result = await resolveGitHubOperationCredentials(db, input);
expect(result).toMatchObject({
status: "available",
login: user,
source: "personal",
});
expect(result.env.GH_TOKEN).toBe(`test-token-${user}`);
expect(result.env.GIT_AUTHOR_EMAIL).toBe(
`${user}+${user}@users.noreply.github.com`,
);
}
const history = await db
.select()
.from(runIdentityContexts)
.where(eq(runIdentityContexts.runId, input.runId));
expect(JSON.stringify(history)).not.toContain("test-token-");
});
it("writes the GitHub summary only when it changes", async () => {
const input = await seed();
const selected = await grant(input, "A");
const update = vi.spyOn(db, "update");
const summaryWrites = () => update.mock.calls.filter(([table]) => table === runIdentityContexts).length;
const stored = async () => (await db.select().from(runIdentityContexts)
.where(eq(runIdentityContexts.runId, input.runId)))[0].github;
try {
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({ status: "available", grantId: selected.id });
expect(summaryWrites()).toBe(1);
expect(await stored()).toMatchObject({ status: "available", login: "A", grantId: selected.id });
for (let call = 0; call < 3; call++) {
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({ status: "available", grantId: selected.id });
}
expect(summaryWrites()).toBe(1);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, selected.id));
for (let call = 0; call < 2; call++) {
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({ status: "unavailable" });
}
expect(summaryWrites()).toBe(2);
expect(await stored()).toMatchObject({ status: "unavailable" });
await db.update(issues).set({ executionPolicy: { authorizationPolicy: { trustPreset: LOW_TRUST_REVIEW_PRESET,
trustBoundary: { mode: LOW_TRUST_REVIEW_PRESET, companyId: input.companyId, rootIssueId: input.issueId,
issueIds: [input.issueId], allowedAgentIds: [input.agentId], allowedToolClasses: ["git.read", "github.pr.read"] } } } })
.where(eq(issues.id, input.issueId));
for (let call = 0; call < 2; call++) {
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable", reason: expect.stringContaining("low-trust"),
});
}
expect(summaryWrites()).toBe(3);
expect(await stored()).toMatchObject({ status: "unavailable", reason: expect.stringContaining("low-trust") });
} finally {
update.mockRestore();
}
});
it("returns no credential for unconnected users, removed membership, or ambiguous personal accounts", async () => {
const input = await seed();
await grant(input, "A");
await switchTo(input, "B");
expect((await resolveGitHubOperationCredentials(db, input)).env).toEqual(
{},
);
await switchTo(input, "A");
await db
.update(companyMemberships)
.set({ status: "inactive" })
.where(eq(companyMemberships.companyId, input.companyId));
expect((await resolveGitHubOperationCredentials(db, input)).status).toBe(
"unavailable",
);
await db
.update(companyMemberships)
.set({ status: "active" })
.where(eq(companyMemberships.companyId, input.companyId));
const differentAccount = await grant(input, "A");
await db
.update(connectionGrants)
.set({
providerTenant: {
github: {
userId: "other-github-id",
login: "A",
installationCount: 1,
repositoryCount: 1,
repositorySelection: "selected",
installationIds: ["1"],
installationOwnerLogins: ["A"],
},
},
})
.where(eq(connectionGrants.id, differentAccount.id));
expect(
(await resolveGitHubOperationCredentials(db, input)).reason,
).toMatch(/More than one/);
await expect(
resolveGitHubOperationCredentials(db, {
...input,
companyId: randomUUID(),
}),
).rejects.toThrow();
});
it.each([true, false])(
"prefers the healthy duplicate regardless of grant age (%s)",
async (healthyNewer) => {
const input = await seed();
const healthy = await grant(input, "A");
const broken = await grant(input, "A");
await db
.update(toolConnections)
.set({ healthStatus: "ok" })
.where(eq(toolConnections.id, healthy.connectionId));
await db
.update(toolConnections)
.set({
healthStatus: "error",
healthMessage: "GitHub access changed during refresh. Try again.",
})
.where(eq(toolConnections.id, broken.connectionId));
await db
.update(connectionGrants)
.set({
createdAt: new Date(healthyNewer ? "2026-02-01" : "2026-01-01"),
})
.where(eq(connectionGrants.id, healthy.id));
await db
.update(connectionGrants)
.set({
createdAt: new Date(healthyNewer ? "2026-01-01" : "2026-02-01"),
})
.where(eq(connectionGrants.id, broken.id));
expect(
await resolveGitHubOperationCredentials(db, input),
).toMatchObject({
status: "available",
connectionId: healthy.connectionId,
grantId: healthy.id,
authenticationMode: "managed",
});
},
);
it("retries credential acquisition once using another grant for the same account", async () => {
const input = await seed();
const older = await grant(input, "A");
const newer = await grant(input, "A");
await db
.update(connectionGrants)
.set({ createdAt: new Date("2026-01-01") })
.where(eq(connectionGrants.id, older.id));
await db
.update(connectionGrants)
.set({ createdAt: new Date("2026-02-01") })
.where(eq(connectionGrants.id, newer.id));
vault.resolveUserSecretValue.mockRejectedValueOnce(
new Error("secret provider failed"),
);
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
grantId: older.id,
});
});
it("uses one stable grant when the same person connects the same GitHub account twice", async () => {
const input = await seed();
const first = await grant(input, "A");
const second = await grant(input, "A");
await db
.update(connectionGrants)
.set({
createdAt: new Date("2026-01-01"),
updatedAt: new Date("2027-01-01"),
})
.where(eq(connectionGrants.id, first.id));
await db
.update(connectionGrants)
.set({ createdAt: new Date("2026-02-01") })
.where(eq(connectionGrants.id, second.id));
const context = { ...input, responsibleUserId: "A" };
expect(
(
await resolveManagedGitHubIdentitySelection(
db,
input.companyId,
context,
)
).grant?.id,
).toBe(second.id);
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
login: "A",
source: "personal",
});
const connections = [first, second].map((row) => ({
id: row.connectionId,
config: { sourceTemplateKey: "github" },
}));
expect(
await filterResolvedGitHubConnectionsForRun({
db,
...context,
connections,
}),
).toEqual([connections[1]]);
// A newer webhook on the old connection must not change the selected policy.
await db
.update(connectionGrants)
.set({ updatedAt: new Date("2028-01-01") })
.where(eq(connectionGrants.id, first.id));
expect(
(
await resolveManagedGitHubIdentitySelection(
db,
input.companyId,
context,
)
).grant?.id,
).toBe(second.id);
await db
.update(connectionGrants)
.set({ status: "revoked" })
.where(eq(connectionGrants.id, second.id));
expect(
(
await resolveManagedGitHubIdentitySelection(
db,
input.companyId,
context,
)
).grant?.id,
).toBe(first.id);
await db
.update(toolConnections)
.set({ enabled: false })
.where(eq(toolConnections.id, first.connectionId));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
env: {},
});
});
it("does not conflate missing GitHub account IDs or another agent's connection audience", async () => {
const input = await seed();
const first = await grant(input, "A");
const duplicate = await grant(input, "A");
await db
.update(connectionGrants)
.set({ providerTenant: null })
.where(eq(connectionGrants.id, duplicate.id));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
env: {},
});
await db
.update(toolConnectionInstalls)
.set({ targetId: randomUUID() })
.where(eq(toolConnectionInstalls.connectionId, duplicate.connectionId));
expect(
(
await resolveManagedGitHubIdentitySelection(db, input.companyId, {
...input,
responsibleUserId: "A",
})
).grant?.id,
).toBe(first.id);
await switchTo(input, "B");
expect((await resolveGitHubOperationCredentials(db, input)).env).toEqual(
{},
);
});
it.each([
"missing-ref",
"disabled-secret",
"missing-secret",
"wrong-owner",
"disabled-definition",
"no-repositories",
])(
"ignores an incomplete newer duplicate when the same account has an eligible grant (%s)",
async (problem) => {
const input = await seed();
const first = await grant(input, "A");
const second = await grant(input, "A");
await db
.update(connectionGrants)
.set({ createdAt: new Date("2026-01-01") })
.where(eq(connectionGrants.id, first.id));
await db
.update(connectionGrants)
.set({ createdAt: new Date("2026-02-01") })
.where(eq(connectionGrants.id, second.id));
if (problem === "missing-ref")
await db
.update(connectionGrants)
.set({ credentialSecretRefs: [] })
.where(eq(connectionGrants.id, second.id));
if (problem === "disabled-secret")
await db
.update(companySecrets)
.set({ status: "disabled" })
.where(eq(companySecrets.id, second.secretId));
if (problem === "disabled-definition")
await db
.update(userSecretDefinitions)
.set({ status: "disabled" })
.where(eq(userSecretDefinitions.id, second.definitionId));
if (problem === "missing-secret")
await db
.delete(companySecrets)
.where(eq(companySecrets.id, second.secretId));
if (problem === "wrong-owner")
await db
.update(companySecrets)
.set({ ownerUserId: "B" })
.where(eq(companySecrets.id, second.secretId));
if (problem === "no-repositories")
await db
.update(connectionGrants)
.set({
providerTenant: {
github: {
userId: "A",
login: "A",
installationCount: 0,
repositoryCount: 0,
repositorySelection: "none",
installationIds: [],
installationOwnerLogins: [],
},
},
})
.where(eq(connectionGrants.id, second.id));
expect(
(
await resolveManagedGitHubIdentitySelection(db, input.companyId, {
...input,
responsibleUserId: "A",
})
).grant?.id,
).toBe(first.id);
expect(
await resolveGitHubOperationCredentials(db, input),
).toMatchObject({ status: "available", login: "A" });
const connections = [first, second].map((row) => ({
id: row.connectionId,
config: { sourceTemplateKey: "github" },
}));
expect(
await filterResolvedGitHubConnectionsForRun({
db,
...input,
responsibleUserId: "A",
connections,
}),
).toEqual([connections[0]]);
},
);
it("retains dedicated override semantics when the dedicated account has duplicate grants", async () => {
const input = await seed();
await grant(input, "A");
const first = await grant(input, "robot", true);
const second = await grant(input, "robot", true);
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
source: "dedicated",
login: "robot",
});
await db
.update(connectionGrants)
.set({ status: "revoked" })
.where(eq(connectionGrants.id, first.id));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
source: "dedicated",
login: "robot",
});
await db
.update(connectionGrants)
.set({ status: "revoked" })
.where(eq(connectionGrants.id, second.id));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
source: "dedicated",
env: {},
});
});
it("honors dedicated overrides and never substitutes personal credentials when revoked or disabled", async () => {
const input = await seed();
await grant(input, "A");
const dedicated = await grant(input, "robot", true);
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
source: "dedicated",
login: "robot",
});
await db
.update(connectionGrants)
.set({ status: "revoked" })
.where(eq(connectionGrants.id, dedicated.id));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
source: "dedicated",
env: {},
});
await db
.update(connectionGrants)
.set({ status: "active" })
.where(eq(connectionGrants.id, dedicated.id));
await db
.update(toolConnections)
.set({ enabled: false })
.where(eq(toolConnections.id, dedicated.connectionId));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
source: "dedicated",
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");
await db
.update(runIdentityContexts)
.set({ cause: "company_default" })
.where(eq(runIdentityContexts.runId, input.runId));
expect((await resolveGitHubOperationCredentials(db, input)).env).toEqual(
{},
);
});
it.each([false, true])(
"withholds sponsor and dedicated credentials from every low-trust policy source (dedicated=%s)",
async (dedicated) => {
for (const source of [
"issue",
"run",
"agent",
"project",
"quarantined",
"invalid",
"missing_issue",
] as const) {
const input = await seed();
await grant(input, "A");
if (dedicated) await grant(input, "robot", true);
// Sponsor attribution is deliberately retained: it must not become a
// credential grant just because the shared agent was dispatched for them.
await db
.update(issues)
.set({
originKind: "chat_channel",
responsibleUserId: "A",
createdByUserId: "A",
})
.where(eq(issues.id, input.issueId));
const policy = {
authorizationPolicy: {
trustPreset: LOW_TRUST_REVIEW_PRESET,
trustBoundary: {
mode: LOW_TRUST_REVIEW_PRESET,
companyId: input.companyId,
rootIssueId: input.issueId,
issueIds: [input.issueId],
allowedAgentIds: [input.agentId],
allowedToolClasses: ["git.read", "github.pr.read"],
},
},
};
if (source === "issue")
await db
.update(issues)
.set({ executionPolicy: policy })
.where(eq(issues.id, input.issueId));
if (source === "run")
await db
.update(heartbeatRuns)
.set({
contextSnapshot: {
issueId: input.issueId,
executionPolicy: policy,
},
})
.where(eq(heartbeatRuns.id, input.runId));
if (source === "agent")
await db
.update(agents)
.set({ permissions: policy })
.where(eq(agents.id, input.agentId));
if (source === "project") {
const projectId = randomUUID();
await db.insert(projects).values({
id: projectId,
companyId: input.companyId,
name: "Restricted",
executionWorkspacePolicy: policy,
});
await db
.update(issues)
.set({ projectId })
.where(eq(issues.id, input.issueId));
}
if (source === "quarantined")
await db
.update(issues)
.set({
sourceTrust: {
preset: LOW_TRUST_REVIEW_PRESET,
disposition: "quarantined",
sourceIssueId: input.issueId,
},
})
.where(eq(issues.id, input.issueId));
if (source === "invalid")
await db
.update(heartbeatRuns)
.set({
contextSnapshot: {
issueId: input.issueId,
executionPolicy: {
authorizationPolicy: { trustPreset: "unknown" },
},
},
})
.where(eq(heartbeatRuns.id, input.runId));
if (source === "missing_issue")
await db
.update(heartbeatRuns)
.set({ contextSnapshot: { issueId: randomUUID() } })
.where(eq(heartbeatRuns.id, input.runId));
vault.resolveSecretValue.mockClear();
vault.resolveUserSecretValue.mockClear();
expect(
await resolveGitHubOperationCredentials(db, input),
source,
).toMatchObject({
status: "unavailable",
env: {},
reason: expect.stringContaining("low-trust"),
});
expect(vault.resolveSecretValue, source).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue, source).not.toHaveBeenCalled();
const [history] = await db
.select()
.from(runIdentityContexts)
.where(eq(runIdentityContexts.runId, input.runId));
expect(history.github, source).toMatchObject({
status: "unavailable",
});
expect(JSON.stringify(history), source).not.toContain("test-token-");
}
},
);
it("rechecks a taskless run's current project policy before exporting credentials", async () => {
const input = await seed();
await grant(input, "A");
const projectId = randomUUID();
await db.insert(projects).values({
id: projectId,
companyId: input.companyId,
name: "Taskless project",
});
await db
.update(heartbeatRuns)
.set({ contextSnapshot: { projectId } })
.where(eq(heartbeatRuns.id, input.runId));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available",
login: "A",
});
await db
.update(projects)
.set({
executionWorkspacePolicy: {
authorizationPolicy: {
trustPreset: LOW_TRUST_REVIEW_PRESET,
trustBoundary: {
mode: LOW_TRUST_REVIEW_PRESET,
companyId: input.companyId,
projectIds: [projectId],
allowedAgentIds: [input.agentId],
},
},
},
})
.where(eq(projects.id, projectId));
vault.resolveSecretValue.mockClear();
vault.resolveUserSecretValue.mockClear();
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "unavailable",
env: {},
});
expect(vault.resolveSecretValue).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("fails closed for missing or malformed bound task/project references", async () => {
const input = await seed();
await grant(input, "A");
for (const contextSnapshot of [
{ projectId: randomUUID() },
{ projectId: "" },
{ projectId: false },
{ issueId: "" },
{ issueId: false },
]) {
await db
.update(heartbeatRuns)
.set({ contextSnapshot })
.where(eq(heartbeatRuns.id, input.runId));
vault.resolveUserSecretValue.mockClear();
if (Object.hasOwn(contextSnapshot, "issueId")) {
await expect(
resolveGitHubOperationCredentials(db, input),
).rejects.toMatchObject({
status: 403,
message: "Run task identity is invalid",
});
} else {
expect(
await resolveGitHubOperationCredentials(db, input),
).toMatchObject({ status: "unavailable", env: {} });
}
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
}
});
it("reuses a session broker across runs while rechecking live-run identity and revocation", async () => {
const input = await seed();
await grant(input, "A");
await grant(input, "B");
const broker = await createNativeGitHubAccess({
scope: input, target: null, cwd: process.cwd(), env: { PATH: process.env.PATH },
resolveCredentials: (binding) => resolveGitHubOperationCredentials(db, binding),
});
const post = () => fetch(`${broker.env.PAPERCLIP_GITHUB_BROKER_URL}/runtime-tools/github/credentials`, {
method: "POST", headers: { authorization: `Bearer ${broker.env.PAPERCLIP_GITHUB_BRIDGE_TOKEN}` },
});
try {
const releaseA = broker.activate(input);
const a = await post();
expect(a.status).toBe(200);
expect((await a.json()).login).toBe("A");
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, input.runId));
// Even a delayed controller release cannot authorize a finished DB run.
expect((await post()).status).toBe(403);
releaseA();
const next = { ...input, runId: randomUUID() };
await db.insert(heartbeatRuns).values({ id: next.runId, companyId: next.companyId, agentId: next.agentId, status: "running", contextSnapshot: { issueId: input.issueId } });
await initializeRunIdentity(db, { companyId: input.companyId, runId: next.runId, responsibleUserId: "B", cause: "instruction" });
broker.activate(next);
const b = await post();
expect(b.status).toBe(200);
expect((await b.json()).login).toBe("B");
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.companyId, input.companyId));
const revoked = await post();
expect((await revoked.json()).env).toEqual({});
} finally { await broker.stop(); }
});
it("requires a run-scoped runtime capability and never accepts browser authentication or supplied identities", async () => {
const input = await seed();
await grant(input, "A");
const app = express();
app.use(express.json());
app.use(runtimeConnectionIntentRoutes(db));
app.use(errorHandler);
const tokenInput = {
...input,
responsibleUserId: "A",
scope: "github_credentials" as const,
};
const token = createRuntimeToolsToken(tokenInput)!.token;
const post = () => request(app).post("/runtime-tools/github/credentials");
const a = await post()
.set("Authorization", `Bearer ${token}`)
.send({ responsibleUserId: "B" });
expect(
(
await post()
.set("Authorization", `Bearer ${token}`)
.set("Sec-Fetch-Mode", "cors")
).status,
).toBe(200);
expect(a.status).toBe(200);
expect(a.body.login).toBe("A");
expect(a.headers["cache-control"]).toBe("no-store");
for (const [header, value] of [
["Origin", "http://127.0.0.1"],
["Cookie", "session=test"],
["Sec-Fetch-Site", "same-origin"],
]) {
expect(
(
await post()
.set("Authorization", `Bearer ${token}`)
.set(header!, value!)
).status,
).toBe(403);
}
const wrongScope = createRuntimeToolsToken({
...tokenInput,
scope: "connection_intents",
})!.token;
expect(
(await post().set("Authorization", `Bearer ${wrongScope}`)).status,
).toBe(401);
const wrongAgent = createRuntimeToolsToken({
...tokenInput,
agentId: randomUUID(),
})!.token;
expect(
(await post().set("Authorization", `Bearer ${wrongAgent}`)).status,
).toBe(403);
// The runner bridge replaces Authorization, but forwards the separate run capability.
expect(
(
await post()
.set("Authorization", "Bearer bridge-host-token")
.set("x-paperclip-github-capability", token)
).status,
).toBe(200);
await switchTo(input, "B");
const b = await post().set("Authorization", `Bearer ${token}`);
expect(b.status).toBe(200);
expect(b.body.env).toEqual({});
await db
.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, input.runId));
expect(
(await post().set("Authorization", `Bearer ${token}`)).status,
).toBe(403);
});
},
);