Files
PaperClipAI/server/src/services/chat-github-sponsor.test.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

140 lines
9.1 KiB
TypeScript

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<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
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);
});
});