Files
PaperClipAI/server/src/services/chat-github-management.ts
T
DottaandPaperclip b0447f3c76 fix: restrict chat task sponsors to self or admins (#21218)
## Thinking Path

> - Paperclip manages AI agents and their authority to do work.
> - External chat channels can create tasks for those agents.
> - A task sponsor is the person responsible for that work.
> - GitHub bot settings accepted another member as a sponsor from any
connection manager.
> - Connection management must not grant authority to act as another
person.
> - This change checks each sponsor on the server and limits the picker
choices.
> - The benefit is that ordinary members cannot assign work to another
person's identity.

## Linked Issues or Issue Description

**What happened?**

A connection manager could save another member as a GitHub guest sponsor
or automatic-task responsible member. The server checked membership but
did not check authority to select that person.

**Expected behavior**

An ordinary manager can select only themselves. A company owner, company
admin, or instance admin can select another active non-viewer member of
the same company. The picker shows member avatars.

**Steps to reproduce**

1. Sign in as an ordinary member with connection-management permission.
2. Open a GitHub bot's Access settings.
3. Set another member as a guest sponsor or responsible member.
4. Save. The old server accepts the request. This change returns 403.

**Paperclip version or commit**

Base: `9a9cd20d91edc93dba4e2295e42f0f1f9fcd4862`.

**Deployment mode**

Built from source. The checks use local PostgreSQL and an assembled
authenticated API server.

Related work: #17737 adds delegated connection configuration. #16163
separates author selection from guest access. This fix preserves both
contracts. A search found no duplicate sponsor-permission fix.

## What Changed

- Check every submitted sponsor in the configuration transaction. Lock
the actor's membership and any required admin role through the save.
- Require self-selection unless the actor has a current admin role.
Check all target members in the same company.
- Keep delegated connection checks, authority notifications, tool
updates, and audit attribution.
- Use avatar pickers for guest sponsorship and automatic-task
responsibility. Default new guests to the signed-in member.
- Test service and HTTP denials, admin selection, role removal, invalid
targets, saved settings, and picker choices.
- Test forged sponsor changes with real agent API keys and run
credentials. Update the existing access-map policy.

## Verification

- 67 sponsor, HTTP, picker, and settings tests pass. The picker test
includes 600 members and bounds member lookups.
- 93 existing GitHub management, event, policy, and tool tests pass.
- The assembled connection-management fixture passes. Self-save
succeeds. Both credential types receive 403 for forged guest and
responsible-member sponsors. The saved revision stays unchanged.
- UI typecheck and production build pass. Token gates, map checks,
query-error policy, migration checks, and whitespace checks pass.
- Two broad chat-test shards pass: 720 cases. The local full-suite run
was then stopped; the complete local suite has no final verdict.
Current-head CI remains the full verification path.
- Full local typecheck and build reach Rust but cannot finish because
Cargo is absent.
- CI found the explicit retry override in the access query. Removed it;
all 45 affected UI tests pass and the CI policy gate passed on the next
commit.
- Historical head `4146c89f9345efd38a69739d17e3194a7cf91980` received
Greptile 5/5 and passed full CI:
https://github.com/paperclipai/paperclip/actions/runs/43330028028 .
Those results apply to that earlier head.
- Current head `890df0322f382bb8ccc0fd3d59b25ba1e0299c58` merges master
without conflicts. All eight changed files match the earlier reviewed
fix. The 67 focused sponsor, HTTP, picker, and settings tests pass
again. The production-bearer fixture also passes for both agent-key and
run-token requests. UI typecheck, token gates, map checks, query-error
policy, and whitespace checks pass.
- Greptile gives current head `890df0322f382bb8ccc0fd3d59b25ba1e0299c58`
5/5 with no open review threads. All checks for this head are complete
with no failures. The PR workflow passed:
https://github.com/paperclipai/paperclip/actions/runs/43363400247 . This
includes build, typecheck, general tests, serialized server suites,
Runner checks, policy checks, and all eight E2E shards. The Snyk status
also passed.
- `pnpm verify --explain` returns exit 2 because the access-map change
selects broad CI. The focused local checks pass. Broad checks are
assigned to the CI run above.
- The first broad checks inspected upstream migrations before the merge
commit existed and stopped at migration classification. After the merge
commit, the migration checks pass with zero new migrations.
- Earlier saved-session broad checks stopped because Cargo was absent or
memory was exhausted. These gaps are retained here. No live
external-provider delivery or staging deployment is claimed.

The configuration service owns sponsor authorization because both board
and delegated API requests use it. No provider protocol or execution
contract changes.

## Risks

- An ordinary manager cannot save a configuration that names another
sponsor, even when that sponsor is unchanged. They must select
themselves or have an admin save it.
- Membership and admin rows stay locked through the configuration write.
A concurrent role change can delay the save.
- Existing configurations are not rewritten. Each new save must pass the
current checks.
- Generic channel and AgentMail creation derive the sponsor from the
authenticated user. Their strict input schemas do not accept sponsor
overrides.

## Model Used

OpenAI Codex, based on GPT-6. The exact runtime model ID and
context-window size are not exposed in this session. Used reasoning,
repository inspection, tool calls, code execution, and tests.

## 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 available in this session)
- [x] I have checked ROADMAP.md and confirmed this fix does not
duplicate planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue with the bug-template field labels
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My published branch name describes the change and contains no
internal task details
- [x] I have run the focused tests locally and they pass
- [x] I have added relevant tests
- [x] I have updated the relevant access policy documentation
- [x] I have considered and documented the risks
- [x] All Paperclip CI gates are green for the current head
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-13 12:56:13 -06:00

720 lines
28 KiB
TypeScript

import type { ConnectionManagementContext } from "./connection-management.js";
import { githubBotCredentials } from "./chat-github-client.js";
import { toolAccessPolicyService } from "./tool-access-policy.js";
import { agents, toolCatalogEntries } from "@paperclipai/db";
import { GITHUB_BOT_TOOLS, syncGitHubBotTools } from "./chat-github-tools.js";
import { and, desc, eq, sql } from "drizzle-orm";
import {
chatEndpoints,
chatEndpointResources,
chatExternalPrincipals,
chatIdentityLinks,
chatGitHubConfigurations,
chatGitHubReviews,
companyMemberships,
instanceUserRoles,
connectionGrants,
toolConnections,
type Db,
} from "@paperclipai/db";
import {
defaultGitHubReviewPolicy,
updateGitHubChatConfigurationSchema,
type GitHubChatConfiguration,
} from "@paperclipai/shared";
import { HttpError, badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { toolAccessService } from "./tool-access.js";
import { logActivity } from "./activity-log.js";
import { notifyChatCompanyAuthorityChange } from "./chat-run-milestone-notifications.js";
import { githubBotRequest } from "./chat-github-client.js";
import { environmentService } from "./environments.js";
import { instanceSettingsService } from "./instance-settings.js";
import { resolveExecutionWorkspaceEnvironmentId } from "./execution-workspace-policy.js";
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
export function githubChatManagementService(db: Db, fetchImpl = fetch) {
async function endpoint(id: string) {
const [row] = await db
.select()
.from(chatEndpoints)
.where(
and(eq(chatEndpoints.id, id), eq(chatEndpoints.provider, "github")),
);
if (!row || row.status === "archived")
throw notFound("GitHub bot not found");
return row;
}
async function member(companyId: string, userId: string, executor: Db | DbTransaction = db) {
const [row] = await executor
.select()
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, userId),
eq(companyMemberships.status, "active"),
),
)
.for("share");
if (!row || row.membershipRole === "viewer")
throw forbidden(
"An active company member with permission to start work is required",
);
return row;
}
async function configuration(endpointId: string, userId: string) {
const bot = await endpoint(endpointId);
const [saved] = await db
.select()
.from(chatGitHubConfigurations)
.where(
and(
eq(chatGitHubConfigurations.companyId, bot.companyId),
eq(chatGitHubConfigurations.endpointId, endpointId),
),
);
return (
saved ?? {
endpointId,
companyId: bot.companyId,
revision: 0,
configuration: {
version: 1,
toolsEnabled: false,
responsibleUserId: userId,
memberAccess: "all_linked",
people: [],
defaults: defaultGitHubReviewPolicy(),
repositories: {},
} satisfies GitHubChatConfiguration,
}
);
}
async function saveConfiguration(
endpointId: string,
input: unknown,
userId: string,
managementContext?: ConnectionManagementContext,
) {
await managementContext?.reauthorize();
const bot = await endpoint(endpointId);
const parsed = updateGitHubChatConfigurationSchema.parse(input);
const config = parsed.configuration;
for (const person of config.people) {
if (person.kind === "guest") continue;
await member(bot.companyId, person.userId);
const [linked] = await db
.select({ externalId: chatExternalPrincipals.externalId })
.from(chatIdentityLinks)
.innerJoin(
chatExternalPrincipals,
eq(chatExternalPrincipals.id, chatIdentityLinks.principalId),
)
.where(
and(
eq(chatIdentityLinks.companyId, bot.companyId),
eq(chatIdentityLinks.endpointId, endpointId),
eq(chatIdentityLinks.paperclipUserId, person.userId),
eq(chatIdentityLinks.status, "linked"),
eq(chatExternalPrincipals.externalId, person.githubUserId),
),
);
if (!linked)
throw badRequest(
"Each member must connect and confirm their own GitHub account before being added",
);
}
const resources = await db
.select()
.from(chatEndpointResources)
.where(
and(
eq(chatEndpointResources.companyId, bot.companyId),
eq(chatEndpointResources.endpointId, endpointId),
),
);
const repositoryIds = new Set(
resources.map((resource) =>
String(resource.metadata?.providerRepositoryId ?? ""),
),
);
if (Object.keys(config.repositories).some((id) => !repositoryIds.has(id)))
throw badRequest(
"Repository overrides must refer to this App installation",
);
await db.transaction(async (tx) => {
const [currentEndpoint] = await tx
.select({ allowUnlinkedPeople: chatEndpoints.allowUnlinkedPeople, sponsorUserId: chatEndpoints.sponsorUserId })
.from(chatEndpoints)
.where(eq(chatEndpoints.id, endpointId))
.for("update");
if (!currentEndpoint) throw notFound("GitHub bot not found");
await tx.execute(
sql`select pg_advisory_xact_lock(hashtextextended(${`github-config:${endpointId}`}, 0))`,
);
const [current] = await tx
.select()
.from(chatGitHubConfigurations)
.where(eq(chatGitHubConfigurations.endpointId, endpointId))
.for("update");
if ((current?.revision ?? 0) !== parsed.expectedRevision)
throw conflict("This configuration changed. Refresh before saving.");
const actorMembership = await member(bot.companyId, userId, tx);
const sponsorIds = new Set([
config.responsibleUserId,
...config.people.flatMap((person) => person.kind === "guest" ? [person.sponsorUserId] : []),
]);
if ([...sponsorIds].some((sponsorId) => sponsorId !== userId) &&
actorMembership.membershipRole !== "owner" && actorMembership.membershipRole !== "admin") {
const [admin] = await tx.select({ id: instanceUserRoles.id }).from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.for("share");
if (!admin) throw forbidden("Only company owners, company admins, and instance admins can select another person as a task sponsor or responsible member");
}
for (const sponsorId of [...sponsorIds].sort()) {
if (sponsorId !== userId) await member(bot.companyId, sponsorId, tx);
}
const allowUnlinkedPeople = config.people.some((p) => p.kind === "guest");
if ((!currentEndpoint.allowUnlinkedPeople && allowUnlinkedPeople) ||
(allowUnlinkedPeople && currentEndpoint.sponsorUserId !== config.responsibleUserId)) {
await notifyChatCompanyAuthorityChange(tx, { companyId: bot.companyId });
}
const values = {
companyId: bot.companyId,
endpointId,
revision: parsed.expectedRevision + 1,
configuration: config,
updatedByUserId: userId,
updatedAt: new Date(),
};
await tx
.insert(chatGitHubConfigurations)
.values(values)
.onConflictDoUpdate({
target: chatGitHubConfigurations.endpointId,
set: values,
});
// The list controls admission; this flag enables the existing restricted
// guest execution path only when an explicit guest is present.
await tx
.update(chatEndpoints)
.set({
allowUnlinkedPeople,
sponsorUserId: config.responsibleUserId,
updatedAt: new Date(),
})
.where(eq(chatEndpoints.id, endpointId));
await syncGitHubBotTools(tx, bot, userId, config.toolsEnabled);
await logActivity(tx as unknown as Db, {
companyId: bot.companyId,
...(managementContext?.audit ?? { actorType: "user" as const, actorId: userId }),
action: "chat_github.configuration_updated",
entityType: "tool_connection",
entityId: bot.connectionId,
details: { endpointId, revision: values.revision },
});
});
return configuration(endpointId, userId);
}
async function personalConnections(endpointId: string, userId: string) {
const bot = await endpoint(endpointId);
await member(bot.companyId, userId);
const rows = await db
.select({ connection: toolConnections, grant: connectionGrants })
.from(connectionGrants)
.innerJoin(
toolConnections,
and(
eq(toolConnections.id, connectionGrants.connectionId),
eq(toolConnections.companyId, bot.companyId),
),
)
.where(
and(
eq(connectionGrants.companyId, bot.companyId),
eq(connectionGrants.kind, "user"),
eq(connectionGrants.subjectUserId, userId),
),
);
return rows
.filter(
({ connection }) =>
connection.config.sourceTemplateKey === "github" ||
connection.transportConfig?.sourceTemplateKey === "github",
)
.map(({ connection, grant }) => ({
connectionId: connection.id,
name: connection.name,
status: grant.status,
login: grant.providerTenant?.github?.login ?? null,
enabled: connection.enabled,
}));
}
async function identity(
endpointId: string,
connectionId: string,
userId: string,
confirmedGithubUserId?: string,
) {
const bot = await endpoint(endpointId);
await member(bot.companyId, userId);
if (!bot.providerAccountId)
throw conflict("Verify the bot App installation first");
const verified = await toolAccessService(db).verifyPersonalGitHubIdentity(
bot.companyId,
connectionId,
userId,
);
if (confirmedGithubUserId === undefined) return verified;
if (confirmedGithubUserId !== verified.githubUserId)
throw conflict(
"The connected GitHub account changed. Check and confirm its identity again.",
);
await linkObservedIdentity(endpointId, userId, verified);
return verified;
}
async function linkObservedIdentity(endpointId: string, userId: string, verified: { githubUserId: string; login: string; avatarUrl?: string | null; grantId?: string; connectionId?: string }) {
const bot = await endpoint(endpointId);
await member(bot.companyId, userId);
if (!bot.providerAccountId) throw conflict("Verify the App installation first");
await db.transaction(async (tx) => {
const [membership] = await tx.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, bot.companyId), eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId))).for("update");
if (!membership || membership.status !== "active" || membership.membershipRole === "viewer") throw forbidden("An active company manager is required");
const [principal] = await tx
.insert(chatExternalPrincipals)
.values({
companyId: bot.companyId,
provider: "github",
providerAccountId: bot.providerAccountId!,
externalId: verified.githubUserId,
kind: "user",
handle: verified.login,
displayName: verified.login,
})
.onConflictDoUpdate({
target: [
chatExternalPrincipals.companyId,
chatExternalPrincipals.provider,
chatExternalPrincipals.providerAccountId,
chatExternalPrincipals.externalId,
],
set: { handle: verified.login, updatedAt: new Date() },
})
.returning();
await tx.execute(
sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${bot.companyId}:${principal!.id}`}, 0))`,
);
const [prior] = await tx
.select()
.from(chatIdentityLinks)
.where(
and(
eq(chatIdentityLinks.endpointId, endpointId),
eq(chatIdentityLinks.principalId, principal!.id),
),
)
.for("update");
if (prior?.status === "linked" && prior.paperclipUserId !== userId)
throw conflict(
"This GitHub account is already linked to another Paperclip member",
);
if (verified.grantId) {
const [grant] = await tx
.select()
.from(connectionGrants)
.where(
and(
eq(connectionGrants.companyId, bot.companyId),
eq(connectionGrants.id, verified.grantId),
eq(connectionGrants.status, "active"),
eq(connectionGrants.subjectUserId, userId),
),
)
.for("update");
if (!grant)
throw forbidden("Your personal GitHub connection was revoked");
}
const values = {
companyId: bot.companyId,
endpointId,
principalId: principal!.id,
paperclipUserId: userId,
status: "linked" as const,
confirmedAt: new Date(),
revokedAt: null,
confirmationTokenHash: null,
expiresAt: null,
updatedAt: new Date(),
};
if (prior?.status !== "linked") {
await notifyChatCompanyAuthorityChange(tx, { companyId: bot.companyId });
}
await tx
.insert(chatIdentityLinks)
.values(values)
.onConflictDoUpdate({
target: [chatIdentityLinks.endpointId, chatIdentityLinks.principalId],
set: values,
});
await logActivity(tx as unknown as Db, {
companyId: bot.companyId,
actorType: "user",
actorId: userId,
action: "chat_github.identity_confirmed",
entityType: "tool_connection",
entityId: bot.connectionId,
details: {
endpointId,
connectionId: verified.connectionId ?? bot.connectionId,
githubUserId: verified.githubUserId,
},
});
});
}
return {
linkObservedIdentity,
verification: async (endpointId: string) => {
const bot = await endpoint(endpointId);
const checks: Array<{
key: string;
label: string;
ok: boolean;
detail: string;
}> = [];
checks.push({
key: "delivery",
label: "Signed webhook delivery",
ok: !!bot.setup.webhookVerifiedAt,
detail: bot.setup.webhookVerifiedAt
? "GitHub delivered a signed webhook to this instance."
: "Send or redeliver a ping from your App's webhook settings.",
});
const credentials = await githubBotCredentials(
db,
bot.companyId,
endpointId,
);
const app = await githubBotRequest<{
id?: number;
permissions?: Record<string, string>;
events?: string[];
}>(fetchImpl, credentials.appJwt, "/app");
checks.push({
key: "app",
label: "GitHub App identity",
ok: String(app.id) === bot.botExternalId,
detail:
String(app.id) === bot.botExternalId
? "The vaulted credentials identify this bot's App."
: "The vaulted credentials identify a different GitHub App.",
});
const installation = credentials.credentials.installationId
? await githubBotRequest<{
permissions?: Record<string, string>;
suspended_at?: string | null;
}>(
fetchImpl,
credentials.appJwt,
`/app/installations/${credentials.credentials.installationId}`,
)
: null;
const permissions = installation?.permissions ?? {};
const permissionsOk =
!!installation &&
!installation.suspended_at &&
permissions.contents === "read" &&
permissions.pull_requests === "write" &&
permissions.checks === "write" &&
app.events?.includes("pull_request") === true;
checks.push({
key: "permissions",
label: "Review installation permissions",
ok: permissionsOk,
detail: permissionsOk
? "Contents read, Pull requests write, Checks write, and PR events are enabled."
: "Set Contents to read-only and Checks to write, subscribe to pull_request, and approve the permission upgrade on GitHub.",
});
const resources = await db
.select()
.from(chatEndpointResources)
.where(
and(
eq(chatEndpointResources.companyId, bot.companyId),
eq(chatEndpointResources.endpointId, endpointId),
eq(chatEndpointResources.enabled, true),
),
);
const inaccessible: string[] = [];
// Ask GitHub to authorize the selected repository IDs now. A cached
// inventory alone cannot prove access after an installation is changed.
const verifiable = resources.filter((resource) => {
const repositoryId = String(resource.metadata?.providerRepositoryId ?? "");
if (
!permissionsOk ||
resource.availability !== "available" ||
!/^[1-9][0-9]*$/.test(repositoryId) ||
!Number.isSafeInteger(Number(repositoryId))
) {
inaccessible.push(resource.label ?? resource.providerResourceId);
return false;
}
return true;
});
// GitHub authorizes up to 500 explicit IDs in one scoped token request.
// Keep these tokens inside verification; task credentials remain scoped
// separately. Never omit repository_ids, which would request all access.
for (let offset = 0; offset < verifiable.length; offset += 500) {
const batch = verifiable.slice(offset, offset + 500);
try {
const issued = await githubBotRequest<{ token?: string }>(
fetchImpl,
credentials.appJwt,
`/app/installations/${credentials.credentials.installationId}/access_tokens`,
{
method: "POST",
body: {
repository_ids: batch.map((resource) =>
Number(resource.metadata!.providerRepositoryId),
),
permissions: {
contents: "read",
metadata: "read",
issues: "write",
pull_requests: "write",
checks: "write",
},
},
},
);
if (!issued.token) throw new Error("Missing installation token");
} catch {
// A rejected batch is unverified; do not activate from cached access.
inaccessible.push(
...batch.map((resource) => resource.label ?? resource.providerResourceId),
);
}
}
checks.push({
key: "repositories",
label: "Enabled repositories",
ok: resources.length > 0 && inaccessible.length === 0,
detail: inaccessible.length
? `Restore installation access and refresh: ${inaccessible.join(", ")}.`
: resources.length
? `GitHub confirmed review access to all ${resources.length} enabled repositories.`
: "Enable at least one repository from the App installation.",
});
const [agent] = await db
.select()
.from(agents)
.where(
and(
eq(agents.companyId, bot.companyId),
eq(agents.id, bot.assignedAgentId),
),
);
checks.push({
key: "runtime",
label: "Agent runtime supports bot tools",
ok:
!!agent &&
["paperclip_runner", "codex_local"].includes(agent.adapterType),
detail:
"Use Paperclip Runner or Codex with managed MCP tools. Low-trust execution also requires a valid scoped boundary and isolated sandbox; the test task proves runtime execution.",
});
const [savedConfig] = await db
.select()
.from(chatGitHubConfigurations)
.where(eq(chatGitHubConfigurations.endpointId, endpointId));
if (
agent &&
(agent.permissions.trustPreset === "low_trust_review" ||
savedConfig?.configuration.people.some(
(person) => person.kind === "guest",
))
) {
const settings = instanceSettingsService(db);
const experimental = await settings.getExperimental();
const environments = environmentService(db);
const local = await environments.ensureLocalEnvironment(bot.companyId);
const managed = experimental.enableManagedSandboxOnly
? await environments.findManagedSandboxEnvironment(bot.companyId)
: null;
const selected = resolveExecutionWorkspaceEnvironmentId({
agentDefaultEnvironmentId: agent.defaultEnvironmentId,
instanceDefaultEnvironmentId:
(await settings.get()).defaultEnvironmentId ?? null,
localDefaultEnvironmentId: local.id,
managedSandboxOnly: experimental.enableManagedSandboxOnly,
managedSandboxEnvironmentId: managed?.id,
});
const environment = await environments.getById(selected.environmentId);
const owners = environment
? await environments.listBoundCompanyIds(environment.id)
: [];
const sandboxOk =
experimental.enableIsolatedWorkspaces &&
environment?.driver === "sandbox" &&
environment.status === "active" &&
(!owners.length || owners.includes(bot.companyId));
checks.push({
key: "isolation",
label: "Low-trust and guest execution",
ok: !!sandboxOk,
detail: sandboxOk
? "An active sandbox environment is selected. Each task receives its own restricted trust boundary."
: "Enable isolated workspaces and select an active sandbox environment for this agent before running low-trust or guest tasks.",
});
}
const entries = await db
.select()
.from(toolCatalogEntries)
.where(
and(
eq(toolCatalogEntries.companyId, bot.companyId),
eq(toolCatalogEntries.connectionId, bot.connectionId),
eq(toolCatalogEntries.status, "active"),
),
);
const requiredTools = GITHUB_BOT_TOOLS.filter(
(tool) => tool.name !== "formal_review",
);
const denied: string[] = requiredTools
.filter(
(tool) =>
!entries.some(
(entry) =>
entry.toolName === tool.name &&
entry.name === `github_bot:${tool.name}`,
),
)
.map((tool) => tool.title);
let toolsOk = denied.length === 0;
for (const entry of entries) {
const decision = await toolAccessPolicyService(db).decide({
companyId: bot.companyId,
actor: {
actorType: "agent",
actorId: bot.assignedAgentId,
agentId: bot.assignedAgentId,
},
runContext: {},
request: {
toolName: `github-bot.${bot.id}:${entry.toolName}`,
applicationId: credentials.connection.applicationId,
applicationKey: "github-chat",
connectionId: bot.connectionId,
catalogEntryId: entry.id,
providerType: "paperclip_github_chat",
upstreamToolName: entry.toolName,
riskLevel: entry.riskLevel,
arguments: {},
sideEffecting: entry.riskLevel !== "read",
},
});
if (
entry.toolName !== "formal_review" &&
!decision.allowed &&
decision.decision !== "require_approval"
) {
toolsOk = false;
denied.push(entry.title ?? entry.toolName);
}
}
checks.push({
key: "tools",
label: "Assigned agent's effective GitHub tools",
ok: toolsOk,
detail: toolsOk
? "The bot App's task-scoped tools are assigned. Each run and publication rechecks access."
: denied.length
? `Repair tool policy for: ${denied.join(", ")}.`
: "Assign the bot's GitHub tools to this agent, then verify again.",
});
return { checks, ready: checks.every((check) => check.ok), connectionReady: checks.filter(check => !["runtime", "isolation"].includes(check.key)).every(check => check.ok) };
},
configuration,
saveConfiguration,
personalConnections,
identity,
lookupPerson: async (endpointId: string, login: string) => {
if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}(?:\[bot\])?$/.test(login))
throw badRequest("Enter a GitHub username");
const bot = await endpoint(endpointId);
const material = await githubBotCredentials(db, bot.companyId, endpointId);
if (
!material.connection.enabled ||
material.connection.status !== "active" ||
!["active", "verifying"].includes(material.endpoint.status)
)
throw conflict("GitHub bot connection is not active");
const installationId = material.credentials.installationId;
if (!installationId || !/^[1-9][0-9]*$/.test(installationId))
throw conflict("Verify the GitHub App installation before looking up people");
let lookingUpPerson = false;
try {
const issued = await githubBotRequest<{ token?: string }>(
fetchImpl,
material.appJwt,
`/app/installations/${installationId}/access_tokens`,
{ method: "POST", body: { permissions: { metadata: "read" } } },
);
if (!issued.token)
throw unprocessable("GitHub did not issue an installation token. Reconnect the bot and try again.");
lookingUpPerson = true;
const user = await githubBotRequest<{
id?: number;
login?: string;
type?: string;
}>(fetchImpl, issued.token, `/users/${encodeURIComponent(login)}`);
if (
!Number.isSafeInteger(user.id) ||
!user.id ||
!["User", "Bot"].includes(user.type ?? "") ||
!user.login
)
throw badRequest("Choose a GitHub person or bot account");
return { githubUserId: String(user.id), login: user.login };
} catch (error) {
if (!(error instanceof HttpError)) throw error;
const details = error.details as { code?: string; providerStatus?: number } | undefined;
if (details?.code === "github_bot_rate_limited")
throw unprocessable("GitHub's rate limit was reached. Wait and try the lookup again.", details);
if (details?.providerStatus === 404 && lookingUpPerson)
throw badRequest("GitHub could not find this account. Check the username and the bot's access to the account.", details);
if (details?.providerStatus === 401 || details?.providerStatus === 404)
throw unprocessable("GitHub could not authenticate this bot installation. Reconnect the bot and try again.", details);
if (details?.providerStatus === 403)
throw unprocessable("GitHub denied this bot installation access. Check its installation on GitHub and try again.", details);
throw error;
}
},
review: async (endpointId: string, reviewId: string) => {
const bot = await endpoint(endpointId);
const [review] = await db.select().from(chatGitHubReviews).where(and(
eq(chatGitHubReviews.companyId, bot.companyId),
eq(chatGitHubReviews.endpointId, endpointId),
eq(chatGitHubReviews.id, reviewId),
));
if (!review) throw notFound("This review was not found in this connection");
return review;
},
reviews: async (endpointId: string) => {
const bot = await endpoint(endpointId);
return db
.select()
.from(chatGitHubReviews)
.where(
and(
eq(chatGitHubReviews.companyId, bot.companyId),
eq(chatGitHubReviews.endpointId, endpointId),
),
)
.orderBy(desc(chatGitHubReviews.createdAt))
.limit(100);
},
};
}