From b0447f3c76a57b67815e77dd53646deb2528fbe8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:56:13 -0600 Subject: [PATCH] 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 --- maps/agent-access-map/chat-channels.md | 2 +- .../connection-management.integration.test.ts | 13 ++ server/src/services/chat-github-management.ts | 32 ++-- .../src/services/chat-github-sponsor.test.ts | 139 ++++++++++++++++++ .../apps/chat/GitHubBotConfiguration.tsx | 80 +++++----- .../apps/chat/GitHubBotManagement.test.tsx | 20 ++- .../apps/chat/GitHubSponsorSelect.test.tsx | 94 ++++++++++++ .../pages/apps/chat/GitHubSponsorSelect.tsx | 46 ++++++ 8 files changed, 372 insertions(+), 54 deletions(-) create mode 100644 server/src/services/chat-github-sponsor.test.ts create mode 100644 ui/src/pages/apps/chat/GitHubSponsorSelect.test.tsx create mode 100644 ui/src/pages/apps/chat/GitHubSponsorSelect.tsx 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.

@@ -938,15 +938,16 @@ export function GitHubAccessEditor({ {error}

)} - {(membersView.kind === "error" || linksView.kind === "error") && ( + {(membersView.kind === "error" || linksView.kind === "error" || boardAccessView.kind === "error") && ( { membersView.retry(); linksView.retry(); + boardAccessView.retry(); }} - retrying={members.isFetching || links.isFetching} + retrying={members.isFetching || links.isFetching || boardAccess.isFetching} /> )}
- - + +
{candidate && (

@@ -1083,7 +1077,7 @@ export function GitHubAccessEditor({ disabled={ !candidate || !activeMembers.some( - (member) => member.principalId === sponsor, + (member) => member.principalId === guestSponsor, ) || configuration.people.some( (p) => p.githubUserId === candidate.githubUserId, @@ -1097,7 +1091,7 @@ export function GitHubAccessEditor({ updatePerson({ ...candidate, kind: "guest", - sponsorUserId: sponsor, + sponsorUserId: guestSponsor, permissionProfile: "restricted", }); setDialog(null); diff --git a/ui/src/pages/apps/chat/GitHubBotManagement.test.tsx b/ui/src/pages/apps/chat/GitHubBotManagement.test.tsx index 592bf3314f0..2ca2153d9a1 100644 --- a/ui/src/pages/apps/chat/GitHubBotManagement.test.tsx +++ b/ui/src/pages/apps/chat/GitHubBotManagement.test.tsx @@ -35,6 +35,7 @@ const mocks = vi.hoisted(() => ({ reviews: vi.fn(), review: vi.fn(), members: vi.fn(), + boardAccess: vi.fn(), links: vi.fn(), setBreadcrumbs: vi.fn(), })); @@ -58,7 +59,7 @@ vi.mock("@/api/chatEndpoints", () => ({ })); vi.mock("@/api/projects", () => ({ projectsApi: { list: mocks.projects } })); vi.mock("@/api/execution-workspaces", () => ({ executionWorkspacesApi: { listSummaries: mocks.workspaces } })); -vi.mock("@/api/access", () => ({ accessApi: { listMembers: mocks.members } })); +vi.mock("@/api/access", () => ({ accessApi: { listMembers: mocks.members, getCurrentBoardAccess: mocks.boardAccess } })); vi.mock("@/api/agents", () => ({ agentsApi: { get: vi.fn() } })); vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: mocks.setBreadcrumbs }), @@ -141,6 +142,8 @@ describe("GitHub bot management", () => { vi.clearAllMocks(); mocks.tab = "settings"; mocks.reviewId = undefined; + mocks.boardAccess.mockResolvedValue({ userId: "member", source: "session", isInstanceAdmin: false, + memberships: [{ companyId: "company", status: "active", membershipRole: "owner" }] }); mocks.get.mockResolvedValue(endpoint); mocks.projects.mockResolvedValue([]); mocks.workspaces.mockResolvedValue([]); @@ -567,6 +570,21 @@ describe("GitHub bot management", () => { await click("Save changes"); expect(mocks.save.mock.calls[0][2].people).toEqual([{ kind: "member", userId: "member", githubUserId: "42", login: "maya" }]); }); + it("defaults a new guest's sponsor to the signed-in person instead of the saved responsible member", async () => { + mocks.boardAccess.mockResolvedValue({ userId: "member", source: "session", isInstanceAdmin: false, + memberships: [{ companyId: "company", status: "active", membershipRole: "operator" }] }); + mocks.members.mockResolvedValue({ members: [ + { principalId: "member", companyId: "company", status: "active", membershipRole: "operator", user: { name: "Maya" } }, + { principalId: "other", companyId: "company", status: "active", membershipRole: "admin", user: { name: "Another Person" } }, + ] }); + mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, responsibleUserId: "other" } }); + await render("access"); + await click("Add external contributor"); + const sponsor = document.querySelector('[aria-label="Sponsor"]'); + expect(sponsor?.textContent).toContain("Maya"); + expect(sponsor?.textContent).not.toContain("Another Person"); + expect(mocks.save).not.toHaveBeenCalled(); + }); it("does not show an off switch or silently enable a retained disabled bot", async () => { mocks.config.mockResolvedValue({ revision: 4, diff --git a/ui/src/pages/apps/chat/GitHubSponsorSelect.test.tsx b/ui/src/pages/apps/chat/GitHubSponsorSelect.test.tsx new file mode 100644 index 00000000000..5b95d9ca6d8 --- /dev/null +++ b/ui/src/pages/apps/chat/GitHubSponsorSelect.test.tsx @@ -0,0 +1,94 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { CompanyMember, CurrentBoardAccess } from "@/api/access"; +import { GitHubSponsorSelect } from "./GitHubSponsorSelect"; + +const members = [ + { principalId: "self", companyId: "company", status: "active", membershipRole: "operator", user: { name: "My Name", image: "https://example.com/self.png" } }, + { principalId: "other", companyId: "company", status: "active", membershipRole: "operator", user: { name: "Other Person", image: "https://example.com/other.png" } }, + { principalId: "viewer", companyId: "company", status: "active", membershipRole: "viewer", user: { name: "Viewer" } }, + { principalId: "suspended", companyId: "company", status: "suspended", membershipRole: "admin", user: { name: "Suspended" } }, +] as CompanyMember[]; +const access = (role = "operator", overrides = {}): CurrentBoardAccess => ({ + user: null, userId: "self", source: "session", isInstanceAdmin: false, companyIds: ["company"], keyId: null, + memberships: [{ companyId: "company", status: "active", membershipRole: role as "operator" }], + ...overrides, +}); + +describe("GitHub sponsor picker", () => { + let root: Root; + let container: HTMLDivElement; + const onChange = vi.fn(); + beforeEach(() => { + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + onChange.mockClear(); + vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }); + vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {}); + }); + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + async function render(boardAccess: CurrentBoardAccess | undefined = access(), value = "self") { + await act(async () => root.render()); + } + async function open() { + await act(async () => container.querySelector('[aria-label="Sponsor"]')!.click()); + } + const options = () => [...document.querySelectorAll('[role="option"]')]; + + it("offers only self to an ordinary connection manager", async () => { + await render(); await open(); + expect(options().map((item) => item.textContent)).toEqual([expect.stringContaining("My Name")]); + await act(async () => (options()[0] as HTMLElement).click()); + expect(onChange).toHaveBeenCalledWith("self", expect.objectContaining({ value: "self" })); + }); + it.each(["owner", "admin", "instance_admin"])("offers active non-viewers to %s", async (role) => { + await render(access(role, { isInstanceAdmin: role === "instance_admin" })); + await open(); + expect(options()).toHaveLength(2); + expect(options()[1].textContent).toContain("Other Person"); + expect(options()[1].querySelector('[data-slot="avatar"]')).not.toBeNull(); + }); + it("keeps an existing other sponsor visible without offering them as a choice", async () => { + await render(access(), "other"); + expect(container.textContent).toContain("Other Person"); + expect(container.querySelector('[data-slot="avatar"]')).not.toBeNull(); + await open(); + expect(options()).toHaveLength(1); + expect(options()[0].textContent).toContain("My Name"); + }); + it("does not use an admin role from a different company", async () => { + await render(access("operator", { memberships: [{ companyId: "elsewhere", status: "active", membershipRole: "admin" }] })); + await open(); expect(options()).toHaveLength(1); + }); + it("keeps sponsor filtering linear for a large company", async () => { + const count = 600; + let identityReads = 0; + const largeMembers = Array.from({ length: count }, (_, index) => ({ + ...members[0], + get principalId() { + if (++identityReads > count * 4) throw new Error("Repeated member scans"); + return index === 0 ? "self" : `member-${index}`; + }, + user: { id: `member-${index}`, name: `Member ${index}`, email: null, image: null }, + })); + await act(async () => root.render()); + await open(); + expect(options()).toHaveLength(count); + expect(identityReads).toBeLessThanOrEqual(count * 4); + }); + it("disables the picker until access is known", async () => { + await act(async () => root.render()); + expect(container.querySelector('[aria-label="Sponsor"]')!.disabled).toBe(true); + }); +}); diff --git a/ui/src/pages/apps/chat/GitHubSponsorSelect.tsx b/ui/src/pages/apps/chat/GitHubSponsorSelect.tsx new file mode 100644 index 00000000000..ab068e1faeb --- /dev/null +++ b/ui/src/pages/apps/chat/GitHubSponsorSelect.tsx @@ -0,0 +1,46 @@ +import type { CompanyMember, CurrentBoardAccess } from "@/api/access"; +import { Identity } from "@/components/Identity"; +import { SearchableSelect } from "@/components/SearchableSelect"; + +export function GitHubSponsorSelect({ + companyId, members, access, value, onChange, label, +}: { + companyId: string; + members: CompanyMember[]; + access: CurrentBoardAccess | undefined; + value: string; + onChange: (value: string) => void; + label: string; +}) { + const membership = access?.memberships?.find( + (item) => item.companyId === companyId && item.status === "active", + ); + const canSelectOthers = access?.isInstanceAdmin === true || + membership?.membershipRole === "owner" || membership?.membershipRole === "admin"; + const options = members + .filter((member) => member.status === "active" && member.membershipRole !== "viewer" && + access && (canSelectOthers || member.principalId === access.userId)) + .map((member) => ({ + key: member.principalId, + value: member.principalId, + label: member.user?.name ?? member.user?.email ?? member.principalId, + avatarUrl: member.user?.image, + searchText: member.user?.email ?? undefined, + })); + const current = members.find((member) => member.principalId === value); + return ( + option + ? + : value ? : null} + renderOption={(option) => } + /> + ); +}