diff --git a/maps/agent-access-map/chat-channels.md b/maps/agent-access-map/chat-channels.md
index 745d4de01b3..3a61ad6c461 100644
--- a/maps/agent-access-map/chat-channels.md
+++ b/maps/agent-access-map/chat-channels.md
@@ -133,7 +133,7 @@ Gaps: Provider fixtures do not qualify live provider setup or availability.
API: `present` — `PUT /api/chat-endpoints/{endpointId}/github/configuration`; JSON REST.
Agent access: `available` — agent REST and default native `search_api` / `call_api`.
-Policy: `tools:manage_connections`; [shared management policy](../../doc/plans/2026-10-13-connection-api-parity.md#authorization-contract). Resolved resources and every affected target are checked; personal ownership remains the responsible user.
+Policy: `tools:manage_connections`; [shared management policy](../../doc/plans/2026-10-13-connection-api-parity.md#authorization-contract). Resolved resources and every affected target are checked; personal ownership remains the responsible user. Sponsor and responsible-member selection is limited to self, unless the responsible user is a company owner/admin or instance admin; targets must be active non-viewer members of this company.
Evidence: `verified` — [route](../../server/src/routes/chat-channels.ts); reviewed in the working tree based on the source commit above. [Authenticated fixtures](../../server/src/__tests__/connection-management.integration.test.ts) passed with database persistence and actual bearer/session middleware.
Verification: `passed` — deterministic provider fixtures / local assembled server; no live provider qualification.
Gaps: Provider fixtures do not qualify live provider setup or availability.
diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts
index 4060ec0edd9..070ae0c35c7 100644
--- a/server/src/__tests__/connection-management.integration.test.ts
+++ b/server/src/__tests__/connection-management.integration.test.ts
@@ -987,6 +987,19 @@ describe("connection management with production default agents", () => {
const updated = await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, body);
expect(updated, JSON.stringify(updated)).toMatchObject({ status: 200, body: { revision: 1, configuration: { memberAccess: "selected" } } });
expect(await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, body)).toMatchObject({ status: 409 });
+ const otherUserId = randomUUID();
+ await accessService(server.db).ensureMembership(f.companyId, "user", otherUserId, "operator", "active");
+ for (const token of [f.key.token, f.jwt]) {
+ for (const field of ["responsible", "guest"]) {
+ const configuration = structuredClone(updated.body.configuration);
+ if (field === "responsible") configuration.responsibleUserId = otherUserId;
+ else configuration.people.push({ kind: "guest", githubUserId: "42", login: "guest", sponsorUserId: otherUserId, permissionProfile: "restricted" });
+ const denied = await f.request("PUT", `/chat-endpoints/${result.body.id}/github/configuration`, { expectedRevision: 1, configuration }, token);
+ expect(denied, JSON.stringify(denied)).toMatchObject({ status: 403 });
+ expect(JSON.stringify(denied.body)).toContain("task sponsor");
+ }
+ }
+ expect((await f.request("GET", `/chat-endpoints/${result.body.id}/github/configuration`)).body).toMatchObject({ revision: 1, configuration: updated.body.configuration });
const handoff = await f.request("POST", `/chat-endpoints/${result.body.id}/github/identity/start`, {});
expect(handoff).toMatchObject({ status: 200, body: { requiredUserAction: { userId: f.userId, resource: { id: result.body.id } } } });
}
diff --git a/server/src/services/chat-github-management.ts b/server/src/services/chat-github-management.ts
index 8c6c66ff9fb..c16df27ec10 100644
--- a/server/src/services/chat-github-management.ts
+++ b/server/src/services/chat-github-management.ts
@@ -12,6 +12,7 @@ import {
chatGitHubConfigurations,
chatGitHubReviews,
companyMemberships,
+ instanceUserRoles,
connectionGrants,
toolConnections,
type Db,
@@ -30,6 +31,8 @@ import { environmentService } from "./environments.js";
import { instanceSettingsService } from "./instance-settings.js";
import { resolveExecutionWorkspaceEnvironmentId } from "./execution-workspace-policy.js";
+type DbTransaction = Parameters[0]>[0];
+
export function githubChatManagementService(db: Db, fetchImpl = fetch) {
async function endpoint(id: string) {
const [row] = await db
@@ -42,8 +45,8 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
throw notFound("GitHub bot not found");
return row;
}
- async function member(companyId: string, userId: string) {
- const [row] = await db
+ async function member(companyId: string, userId: string, executor: Db | DbTransaction = db) {
+ const [row] = await executor
.select()
.from(companyMemberships)
.where(
@@ -53,7 +56,8 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
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",
@@ -96,15 +100,10 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
) {
await managementContext?.reauthorize();
const bot = await endpoint(endpointId);
- await member(bot.companyId, userId);
const parsed = updateGitHubChatConfigurationSchema.parse(input);
const config = parsed.configuration;
- await member(bot.companyId, config.responsibleUserId);
for (const person of config.people) {
- if (person.kind === "guest") {
- await member(bot.companyId, person.sponsorUserId);
- continue;
- }
+ if (person.kind === "guest") continue;
await member(bot.companyId, person.userId);
const [linked] = await db
.select({ externalId: chatExternalPrincipals.externalId })
@@ -162,6 +161,21 @@ export function githubChatManagementService(db: Db, fetchImpl = fetch) {
.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)) {
diff --git a/server/src/services/chat-github-sponsor.test.ts b/server/src/services/chat-github-sponsor.test.ts
new file mode 100644
index 00000000000..3b8ffc90291
--- /dev/null
+++ b/server/src/services/chat-github-sponsor.test.ts
@@ -0,0 +1,139 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import express from "express";
+import request from "supertest";
+import {
+ activityLog, agents, chatEndpoints, chatGitHubConfigurations, companies,
+ companyMemberships, createDb, instanceUserRoles, principalPermissionGrants, toolApplications, toolConnections,
+} from "@paperclipai/db";
+import {
+ CHAT_PROVIDERS, createChatEndpointSchema, defaultGitHubReviewPolicy,
+ updateChatEndpointSchema, type GitHubChatConfiguration,
+} from "@paperclipai/shared";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
+import { githubChatManagementService } from "./chat-github-management.js";
+import { chatChannelRoutes } from "../routes/chat-channels.js";
+import type { ChatChannelService } from "./chat-channels.js";
+import { errorHandler } from "../middleware/index.js";
+
+describe("chat sponsor input boundaries", () => {
+ it.each(CHAT_PROVIDERS.filter((provider) => provider !== "agentmail"))(
+ "%s does not accept a caller-selected endpoint sponsor", (provider) => {
+ expect(createChatEndpointSchema.safeParse({ provider, assignedAgentId: randomUUID(), sponsorUserId: "victim" }).success).toBe(false);
+ expect(updateChatEndpointSchema.safeParse({ allowUnlinkedPeople: true, sponsorUserId: "victim" }).success).toBe(false);
+ },
+ );
+});
+
+const support = await getEmbeddedPostgresTestSupport();
+(support.supported ? describe : describe.skip)("GitHub sponsor assignment authority", () => {
+ let database: Awaited>;
+ let db: ReturnType;
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-github-sponsor-");
+ db = createDb(database.connectionString);
+ }, 30_000);
+ afterAll(async () => { await database?.cleanup(); }, 60_000);
+
+ async function fixture(role = "operator") {
+ const userId = randomUUID();
+ const otherUserId = randomUUID();
+ const [company] = await db.insert(companies).values({ name: "Sponsor test", issuePrefix: randomUUID().slice(0, 8) }).returning();
+ await db.insert(companyMemberships).values([
+ { companyId: company.id, principalType: "user", principalId: userId, status: "active", membershipRole: role },
+ { companyId: company.id, principalType: "user", principalId: otherUserId, status: "active", membershipRole: "operator" },
+ ]);
+ await db.insert(principalPermissionGrants).values({ companyId: company.id, principalType: "user", principalId: userId, permissionKey: "tools:manage_connections" });
+ const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Reviewer", role: "general", adapterType: "codex_local" }).returning();
+ const [application] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: randomUUID(), name: "GitHub", type: "chat" }).returning();
+ const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: application.id, name: "GitHub", uid: randomUUID(), connectionPurpose: "channel", transport: "chat_sdk" }).returning();
+ const [endpoint] = await db.insert(chatEndpoints).values({ companyId: company.id, provider: "github", publicId: randomUUID(), connectionId: connection.id, assignedAgentId: agent.id, sponsorUserId: userId }).returning();
+ const management = githubChatManagementService(db);
+ const configuration: GitHubChatConfiguration = {
+ version: 1, toolsEnabled: false, responsibleUserId: userId,
+ memberAccess: "all_linked", people: [], defaults: defaultGitHubReviewPolicy(), repositories: {},
+ };
+ const save = (config = configuration, expectedRevision = 0) => management.saveConfiguration(endpoint.id, { configuration: config, expectedRevision }, userId);
+ return { company, endpoint, userId, otherUserId, configuration, save };
+ }
+
+ it.each(["responsible", "guest"])("rejects another person's %s sponsorship before any write", async (field) => {
+ const f = await fixture();
+ const config = structuredClone(f.configuration);
+ if (field === "responsible") config.responsibleUserId = f.otherUserId;
+ else config.people.push({ kind: "guest", githubUserId: "42", login: "guest", sponsorUserId: f.otherUserId, permissionProfile: "restricted" });
+ await expect(f.save(config)).rejects.toMatchObject({ status: 403 });
+ expect(await db.select().from(chatGitHubConfigurations).where(eq(chatGitHubConfigurations.endpointId, f.endpoint.id))).toEqual([]);
+ expect((await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpoint.id)))[0].sponsorUserId).toBe(f.userId);
+ expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.endpoint.connectionId))).toEqual([]);
+ });
+
+ it("allows a connection manager to sponsor themselves and records that actor", async () => {
+ const f = await fixture();
+ f.configuration.people.push({ kind: "guest", githubUserId: "42", login: "guest", sponsorUserId: f.userId, permissionProfile: "restricted" });
+ expect(await f.save()).toMatchObject({ revision: 1, configuration: f.configuration });
+ expect((await db.select().from(activityLog).where(eq(activityLog.entityId, f.endpoint.connectionId)))[0]).toMatchObject({ actorId: f.userId, action: "chat_github.configuration_updated" });
+ });
+
+ it.each(["owner", "admin", "instance_admin"])("allows a current %s to select another active member", async (role) => {
+ const f = await fixture(role === "instance_admin" ? "operator" : role);
+ if (role === "instance_admin") await db.insert(instanceUserRoles).values({ userId: f.userId, role });
+ f.configuration.responsibleUserId = f.otherUserId;
+ f.configuration.people.push({ kind: "guest", githubUserId: "42", login: "guest", sponsorUserId: f.otherUserId, permissionProfile: "restricted" });
+ expect(await f.save()).toMatchObject({ revision: 1, configuration: f.configuration });
+ expect((await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpoint.id)))[0].sponsorUserId).toBe(f.otherUserId);
+ });
+
+ it.each(["viewer", "suspended", "foreign"])("rejects a %s sponsor even for an admin", async (fault) => {
+ const f = await fixture("admin");
+ if (fault === "foreign") f.configuration.responsibleUserId = randomUUID();
+ else {
+ f.configuration.responsibleUserId = f.otherUserId;
+ await db.update(companyMemberships).set(fault === "viewer" ? { membershipRole: "viewer" } : { status: "suspended" }).where(eq(companyMemberships.principalId, f.otherUserId));
+ }
+ await expect(f.save()).rejects.toMatchObject({ status: 403 });
+ });
+
+ it.each(["admin", "instance_admin"])("rechecks revoked %s authority on the next save", async (role) => {
+ const f = await fixture(role === "admin" ? "admin" : "operator");
+ if (role === "instance_admin") await db.insert(instanceUserRoles).values({ userId: f.userId, role });
+ f.configuration.responsibleUserId = f.otherUserId;
+ await f.save();
+ await db.update(companyMemberships).set({ membershipRole: "operator" }).where(eq(companyMemberships.principalId, f.userId));
+ await db.delete(instanceUserRoles).where(eq(instanceUserRoles.userId, f.userId));
+ await expect(f.save(f.configuration, 1)).rejects.toMatchObject({ status: 403 });
+ expect((await db.select().from(chatGitHubConfigurations).where(eq(chatGitHubConfigurations.endpointId, f.endpoint.id)))[0].revision).toBe(1);
+ });
+
+ it("does not borrow an admin role from another company", async () => {
+ const f = await fixture();
+ const [other] = await db.insert(companies).values({ name: "Other company", issuePrefix: randomUUID().slice(0, 8) }).returning();
+ await db.insert(companyMemberships).values({ companyId: other.id, principalType: "user", principalId: f.userId, status: "active", membershipRole: "admin" });
+ f.configuration.responsibleUserId = f.otherUserId;
+ await expect(f.save()).rejects.toMatchObject({ status: 403 });
+ });
+
+ it.each(["operator", "admin", "agent"])("enforces sponsor authority through the HTTP API for %s", async (role) => {
+ const f = await fixture(role === "admin" ? "admin" : "operator");
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.actor = role === "agent"
+ ? { type: "agent", companyId: f.company.id, agentId: f.endpoint.assignedAgentId }
+ : { type: "board", source: "session", userId: f.userId, companyIds: [f.company.id] };
+ next();
+ });
+ app.use("/api", chatChannelRoutes(db, {
+ service: { get: async () => f.endpoint } as unknown as ChatChannelService,
+ heartbeat: { wakeup: vi.fn() },
+ }));
+ app.use(errorHandler);
+ const configuration = { ...f.configuration, responsibleUserId: f.otherUserId };
+ await request(app).put(`/api/chat-endpoints/${f.endpoint.id}/github/configuration`)
+ .send({ expectedRevision: 0, configuration }).expect(role === "admin" ? 200 : 403);
+ const saved = await db.select().from(chatGitHubConfigurations).where(eq(chatGitHubConfigurations.endpointId, f.endpoint.id));
+ expect(saved).toHaveLength(role === "admin" ? 1 : 0);
+ if (role === "admin") expect(saved[0].updatedByUserId).toBe(f.userId);
+ });
+});
diff --git a/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx b/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx
index 707169d3565..8ed4286eec0 100644
--- a/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx
+++ b/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx
@@ -9,6 +9,8 @@ import {
type GitHubAllowedPerson,
} from "@paperclipai/shared";
import { accessApi } from "@/api/access";
+import { queryKeys } from "@/lib/queryKeys";
+import { GitHubSponsorSelect } from "./GitHubSponsorSelect";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { githubChatApi } from "@/api/githubChat";
import { useOptionalCompany } from "@/context/CompanyContext";
@@ -592,15 +594,21 @@ export function GitHubAccessEditor({
queryKey: ["github-members", companyId],
queryFn: () => accessApi.listMembers(companyId),
});
+ const boardAccess = useQuery({
+ queryKey: queryKeys.access.currentBoardAccess,
+ queryFn: () => accessApi.getCurrentBoardAccess(),
+ });
const links = useQuery({
queryKey: ["github-linked-members", endpointId],
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
});
const membersView = useQueryView(members);
const linksView = useQueryView(links);
+ const boardAccessView = useQueryView(boardAccess);
const linksLoaded = linksView.kind === "ready" || linksView.kind === "stale";
const [login, setLogin] = useState("");
- const [sponsor, setSponsor] = useState(configuration.responsibleUserId);
+ const [sponsor, setSponsor] = useState("");
+ const guestSponsor = sponsor || boardAccess.data?.userId || "";
const [candidate, setCandidate] = useState<{
githubUserId: string;
login: string;
@@ -855,6 +863,7 @@ export function GitHubAccessEditor({
variant="outline"
size="sm"
onClick={() => {
+ setSponsor(boardAccess.data?.userId ?? "");
setDialog("guest");
setLookupError("");
}}
@@ -899,37 +908,28 @@ export function GitHubAccessEditor({
) : (
<>
-
-
+ />
>
)}
The member accountable for automatically created Paperclip tasks.
GitHub authors remain recorded separately. This grants no access to
the member’s personal credentials.
+ Only company owners, company admins, and instance admins can select
+ another person as a sponsor or responsible member.