Files
PaperClipAI/server/src/__tests__/invite-create-route.test.ts
T
DottaandPaperclip 582911ba74 fix(access): give Operators default company editing permissions (#15377)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Human company members receive permission grants from their role
preset.
> - Human invitations use the Operator role by default.
> - The old Operator preset only granted task assignment, so ordinary
members could not edit agents or manage connections.
> - This pull request gives Operators company editing and audit access
while keeping join approval and member-permission management separate.
> - Members can configure their agents and accounts without an Owner
role.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The default permission grants for human Operators and the invitation
role description.

**Subsystem affected**

server/ permission presets and invitation authorization, plus ui/
invitation and tool access gates.

**Current behavior**

Operators receive only `tasks:assign` as an explicit default grant.
Agent configuration and managed account setup fail their permission
checks.

**Proposed behavior**

Operators receive agent creation/configuration, skills, environments,
invitations, task assignment, pipelines, connections, tool
management/use, and audit grants. The preset excludes `joins:approve`
and `users:manage_permissions`. Operators can invite Operators and
Viewers. Inviting a role with either excluded power requires that power,
so invitations cannot bypass the restriction.

**Reason and benefit**

Ordinary company members can edit company work and connect accounts
through the existing routes.

**Breaking changes**

The Operator preset grants more permissions. The existing startup and
Cloud sign-in seeding paths can insert these missing grants for existing
Operators. They retain custom grant scopes. Explicit invitation grants
still take precedence. Inviting Admins now requires join approval;
inviting Owners also requires member-permission management. This PR adds
no migration or new backfill path.

Related: #5945 describes missing role grants in another membership entry
point. This PR changes the preset and does not change that endpoint.

## What Changed

- Expanded the Operator preset to 14 company editing, invitation, tool,
and audit grants.
- Kept join approval and member-permission management out of the preset.
- Required those powers when an invitation's selected human role
includes them, preventing Operators from delegating the excluded powers
through Owner/Admin invitations.
- Updated the invitation role copy and the product specifications.
- Allowed active Operators (including legacy Member roles) through the
invite shortcut and advanced tool/profile UI gates. Kept inactive
memberships, Viewers, and other companies excluded; API grants remain
authoritative.
- Added tests for the default Operator grants, both excluded actions,
agent editing, company boundaries, and invitation role authorization.
- Simplified adapter-route test imports so authorization errors and the
error handler use one module graph; retained the upstream
mock-initialization fix.
- Kept Owner/Admin/Viewer presets and explicit invitation grants
unchanged. Added no EE code or database migration.

## Verification

- Permission and invitation tests: 38 passed across access service,
invitation defaults, and invitation creation routes.
- UI access tests: 61 passed across invitation shortcuts, Operator
tool/profile access, and invitation UI.
- Adapter route tests: 15 passed after resolving the upstream test setup
conflict.
- `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates`:
passed on the final branch.
- The initial local `pnpm test:run` general-server batch reported three
tool-access failures and eight upload-helper timeouts. Both complete
affected suites passed in isolation on the final branch: 403 tests. The
initial full local run was not green.
- Both complete tool-access and adapter route suites also passed on an
untouched snapshot of base `88ff98b83`: 387 tests. The earlier tool
failures did not reproduce there.
- [All CI gates
passed](https://github.com/paperclipai/paperclip/actions/runs/37527422346)
for `068be153b9c2a064f2aaccc0627fdf458e73747e`, including the previously
failing serialized adapter lane, general tests, E2E, typecheck, build,
Runner checks, and canary dry run.
- Greptile scored that exact commit 5/5. Superagent passed. Both
invitation review threads are resolved.

## Risks

- Operators gain broad company editing and invitation access by design.
- Existing default seeding can add the new missing grants during startup
or Cloud sign-in. It does not replace existing scopes.
- Company boundaries and the two excluded permission checks still apply.
- An Admin without member-permission management can no longer invite an
Owner. Operators retain invitation access for Operator/Viewer roles and
agent-only invites.
- This PR changes company permissions. Cloud workspace invitation rules
remain separate.

## Model Used

OpenAI Codex, GPT-6. The exact deployment model ID and context window
were not exposed in this session. Used repository inspection, code
editing, shell execution, and test tools.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting a merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-06 15:55:38 -05:00

207 lines
6.7 KiB
TypeScript

import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const logActivityMock = vi.fn();
const canUserMock = vi.fn();
const insertMock = vi.fn();
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => ({
isInstanceAdmin: vi.fn(),
canUser: (...args: unknown[]) => canUserMock(...args),
hasPermission: vi.fn(),
}),
agentService: () => ({
getById: vi.fn(),
}),
boardAuthService: () => ({
createChallenge: vi.fn(),
resolveBoardAccess: vi.fn(),
assertCurrentBoardKey: vi.fn(),
revokeBoardApiKey: vi.fn(),
}),
deduplicateAgentName: vi.fn(),
logActivity: (...args: unknown[]) => logActivityMock(...args),
notifyHireApproved: vi.fn(),
}));
}
function createDbStub() {
const createdInvite = {
id: "invite-1",
companyId: "company-1",
inviteType: "company_join",
allowedJoinTypes: "human",
tokenHash: "hash",
defaultsPayload: { humanRole: "viewer" },
expiresAt: new Date("2027-03-10T00:00:00.000Z"),
invitedByUserId: null,
revokedAt: null,
acceptedAt: null,
createdAt: new Date("2026-03-07T00:00:00.000Z"),
updatedAt: new Date("2026-03-07T00:00:00.000Z"),
};
return {
insert() {
insertMock();
return {
values() {
return {
returning() {
return Promise.resolve([createdInvite]);
},
};
},
};
},
select(_shape?: unknown) {
return {
from() {
const query = {
leftJoin() {
return query;
},
where() {
return Promise.resolve([{
name: "Acme Robotics",
logoAssetId: "logo-1",
}]);
},
};
return query;
},
};
},
};
}
async function createApp(source: "local_implicit" | "session" = "local_implicit") {
const [{ accessRoutes }, { errorHandler }] = await Promise.all([
import("../routes/access.js"),
import("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
source,
userId: source === "session" ? "inviter-1" : null,
companyIds: ["company-1"],
memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }],
};
next();
});
app.use(
"/api",
accessRoutes(createDbStub() as any, {
deploymentMode: "local_trusted",
deploymentExposure: "private",
bindHost: "127.0.0.1",
allowedHostnames: [],
}),
);
app.use(errorHandler);
return app;
}
describe("POST /companies/:companyId/invites", () => {
beforeEach(() => {
vi.resetModules();
vi.doUnmock("../services/index.js");
vi.doUnmock("../routes/access.js");
vi.doUnmock("../routes/authz.js");
vi.doUnmock("../middleware/index.js");
registerModuleMocks();
vi.clearAllMocks();
logActivityMock.mockReset();
canUserMock.mockReset();
insertMock.mockReset();
canUserMock.mockImplementation(async (_companyId, _userId, permissionKey) => permissionKey === "users:invite");
});
it("returns an absolute invite URL using the request base URL", async () => {
const app = await createApp();
const res = await request(app)
.post("/api/companies/company-1/invites")
.set("host", "paperclip.example")
.set("x-forwarded-proto", "https")
.send({
allowedJoinTypes: "human",
humanRole: "viewer",
});
expect(res.status).toBe(201);
expect(res.body.companyName).toBe("Acme Robotics");
expect(res.body.invitePath).toMatch(/^\/invite\/pcp_invite_/);
expect(res.body.inviteUrl).toMatch(/^https:\/\/paperclip\.example\/invite\/pcp_invite_/);
});
it.each(["operator", "viewer"])("allows Operators to invite %s members", async (humanRole) => {
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "human", humanRole });
expect(res.status).toBe(201);
expect(insertMock).toHaveBeenCalledOnce();
});
it("allows the default Operator role for mixed human and agent invitations", async () => {
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "both" });
expect(res.status).toBe(201);
expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
});
it("does not require human membership permissions for agent-only invitations", async () => {
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "agent", humanRole: "owner" });
expect(res.status).toBe(201);
expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
expect(canUserMock).not.toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
});
it.each(["admin", "owner"])("prevents Operators from inviting %s members", async (humanRole) => {
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "human", humanRole });
expect(res.status).toBe(403);
expect(insertMock).not.toHaveBeenCalled();
expect(logActivityMock).not.toHaveBeenCalled();
});
it("requires member-permission management to invite Owners even when join approval is allowed", async () => {
canUserMock.mockImplementation(async (_companyId, _userId, permissionKey) =>
permissionKey === "users:invite" || permissionKey === "joins:approve",
);
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "human", humanRole: "owner" });
expect(res.status).toBe(403);
expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
expect(insertMock).not.toHaveBeenCalled();
});
it("allows Owner invitations when both membership permissions are granted", async () => {
canUserMock.mockResolvedValue(true);
const res = await request(await createApp("session"))
.post("/api/companies/company-1/invites")
.send({ allowedJoinTypes: "human", humanRole: "owner" });
expect(res.status).toBe(201);
expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "joins:approve");
expect(canUserMock).toHaveBeenCalledWith("company-1", "inviter-1", "users:manage_permissions");
});
});