From 582911ba74350dbe9029eb132d69a257edd9d26a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:55:38 -0500 Subject: [PATCH] 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 --- doc/SPEC-implementation.md | 12 +++ doc/SPEC.md | 6 ++ server/src/__tests__/access-service.test.ts | 44 +++++++++- server/src/__tests__/adapter-routes.test.ts | 11 +-- .../src/__tests__/invite-create-route.test.ts | 78 ++++++++++++++++- .../src/__tests__/invite-join-grants.test.ts | 23 ++++- server/src/routes/access.ts | 9 ++ server/src/services/company-member-roles.ts | 17 +++- .../SidebarAccountMenu.production.tsx | 4 +- ui/src/components/SidebarAccountMenu.test.tsx | 8 +- ui/src/components/SidebarAccountMenu.tsx | 4 +- ui/src/components/access/InvitesSection.tsx | 4 +- ui/src/hooks/useCompanyInviteAccess.test.ts | 4 +- ui/src/hooks/useCompanyInviteAccess.ts | 10 ++- ui/src/pages/InviteUxLab.tsx | 4 +- ui/src/pages/tools/AdvancedToolsRoute.tsx | 23 ++--- ui/src/pages/tools/ToolRoleAccess.test.tsx | 84 +++++++++++++++++++ .../pages/tools/profiles/ToolsAdminGate.tsx | 21 +++-- 18 files changed, 312 insertions(+), 54 deletions(-) create mode 100644 ui/src/pages/tools/ToolRoleAccess.test.tsx diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 0d7715e854e..3ea52f845f5 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -584,6 +584,18 @@ conversation lifecycles, and protection against replaying superseded requests. - Board has full read/write across all companies in deployment - Every board mutation writes to `activity_log` +Human invitations default to the Operator role. Its default grants allow agent +creation and configuration, skill editing, environment management, invitations, +task assignment, pipeline editing, connection and tool management/use, and tool +and agent-action audit views. Operators do not receive `joins:approve` or +`users:manage_permissions`. Explicit invitation grants remain authoritative. +Creating a human invitation also requires any of these two membership powers +included in its selected role. Operators can invite Operators and Viewers; +inviting an Admin requires join approval, and inviting an Owner also requires +member-permission management. +This preset change adds no database migration; existing role-default seeding +continues to insert missing grants without replacing custom scopes. + ## 9.2 Agent Auth - Bearer API key mapped to one agent and company diff --git a/doc/SPEC.md b/doc/SPEC.md index 5b949cc70f8..0a300c37373 100644 --- a/doc/SPEC.md +++ b/doc/SPEC.md @@ -21,6 +21,12 @@ A Company is a first-order object. One Paperclip instance runs multiple Companie Every Company has a **Board** that governs high-impact decisions. The Board is the human oversight layer. +Human invitations default to Operator, with company editing, invitations, +connections, tools, environments, pipelines, and audit views available by +default. Join approval and member-permission management remain separate grants. +An inviter must hold these membership grants to invite a role that includes them. +See [human Operator defaults](SPEC-implementation.md#91-board-auth). + **V1: Single human Board.** One human operator. #### Board Approval Gates (V1) diff --git a/server/src/__tests__/access-service.test.ts b/server/src/__tests__/access-service.test.ts index 3482a5784bc..2d81dba8bca 100644 --- a/server/src/__tests__/access-service.test.ts +++ b/server/src/__tests__/access-service.test.ts @@ -879,7 +879,7 @@ describeEmbeddedPostgres("access service", () => { .toHaveLength(1); }); - it("allows owner and admin role-default grants to manage environments", async () => { + it("allows owner, admin, and operator role-default grants to manage environments", async () => { const { company, owner } = await createCompanyWithOwner(db); const access = accessService(db); const roles = ["admin", "operator", "viewer"] as const; @@ -919,10 +919,50 @@ describeEmbeddedPostgres("access service", () => { await expect(access.canUser(company.id, owner.principalId, "environments:manage")).resolves.toBe(true); await expect(access.canUser(company.id, admin.principalId, "environments:manage")).resolves.toBe(true); - await expect(access.canUser(company.id, operator.principalId, "environments:manage")).resolves.toBe(false); + await expect(access.canUser(company.id, operator.principalId, "environments:manage")).resolves.toBe(true); await expect(access.canUser(company.id, viewer.principalId, "environments:manage")).resolves.toBe(false); }); + it("allows default operators to edit agents and company work without administering membership", async () => { + const { company, owner } = await createCompanyWithOwner(db); + const access = accessService(db); + const operator = await access.ensureMembership(company.id, "user", `operator-${randomUUID()}`, "operator"); + const agent = await db.insert(agents).values({ + companyId: company.id, + name: "Operator-editable agent", + role: "engineer", + adapterType: "process", + adapterConfig: {}, + }).returning().then((rows) => rows[0]!); + await access.setPrincipalGrants( + company.id, + "user", + operator.principalId, + grantsForHumanRole("operator"), + owner.principalId, + ); + + for (const permissionKey of [ + "agents:create", "agents:configure", "skills:create", "environments:manage", + "users:invite", "tasks:assign", "pipelines:write", "tools:manage_connections", + "tools:manage_profiles", "tools:manage_runtime", "tools:use", "tools:admin", + "tools:view_audit", "audit:view_agent_actions", + ] as const) { + await expect(access.canUser(company.id, operator.principalId, permissionKey)).resolves.toBe(true); + } + for (const permissionKey of ["joins:approve", "users:manage_permissions"] as const) { + await expect(access.canUser(company.id, operator.principalId, permissionKey)).resolves.toBe(false); + } + await expect(access.decide({ + actor: { type: "board", userId: operator.principalId, source: "session" }, + action: "agent_config:update", + resource: { type: "agent", companyId: company.id, agentId: agent.id }, + })).resolves.toMatchObject({ allowed: true, reason: "allow_direct_change" }); + + const otherCompany = await createCompanyWithOwner(db); + await expect(access.canUser(otherCompany.company.id, operator.principalId, "agents:configure")).resolves.toBe(false); + }); + it("backfills pre-upgrade human memberships with missing role grants without replacing custom grants", async () => { const { company, owner } = await createCompanyWithOwner(db); const scopedEnvironmentGrant = { environmentId: "env-1" }; diff --git a/server/src/__tests__/adapter-routes.test.ts b/server/src/__tests__/adapter-routes.test.ts index 73828da47ca..3fc3c55bd22 100644 --- a/server/src/__tests__/adapter-routes.test.ts +++ b/server/src/__tests__/adapter-routes.test.ts @@ -55,9 +55,6 @@ function registerModuleMocks() { vi.doMock("node:child_process", async () => vi.importActual("node:child_process")); vi.doMock("../adapters/plugin-loader.js", () => mockPluginLoader); vi.doMock("../services/adapter-plugin-store.js", () => mockAdapterPluginStore); - vi.doMock("../routes/adapters.js", async () => vi.importActual("../routes/adapters.js")); - vi.doMock("../routes/authz.js", async () => vi.importActual("../routes/authz.js")); - vi.doMock("../middleware/index.js", async () => vi.importActual("../middleware/index.js")); } function resetAdapterMocks() { @@ -104,11 +101,9 @@ describe("adapter routes", () => { beforeAll(async () => { registerModuleMocks(); resetAdapterMocks(); - const [registry, routes, middleware] = await Promise.all([ - vi.importActual("../adapters/registry.js"), - import("../routes/adapters.js"), - import("../middleware/index.js"), - ]); + const registry = await import("../adapters/registry.js"); + const routes = await import("../routes/adapters.js"); + const middleware = await import("../middleware/index.js"); registerServerAdapter = registry.registerServerAdapter; unregisterServerAdapter = registry.unregisterServerAdapter; findServerAdapter = registry.findServerAdapter; diff --git a/server/src/__tests__/invite-create-route.test.ts b/server/src/__tests__/invite-create-route.test.ts index 4ceedd38565..27372692df2 100644 --- a/server/src/__tests__/invite-create-route.test.ts +++ b/server/src/__tests__/invite-create-route.test.ts @@ -3,12 +3,14 @@ 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: vi.fn(), + canUser: (...args: unknown[]) => canUserMock(...args), hasPermission: vi.fn(), }), agentService: () => ({ @@ -44,6 +46,7 @@ function createDbStub() { return { insert() { + insertMock(); return { values() { return { @@ -75,7 +78,7 @@ function createDbStub() { }; } -async function createApp() { +async function createApp(source: "local_implicit" | "session" = "local_implicit") { const [{ accessRoutes }, { errorHandler }] = await Promise.all([ import("../routes/access.js"), import("../middleware/index.js"), @@ -85,9 +88,10 @@ async function createApp() { app.use((req, _res, next) => { (req as any).actor = { type: "board", - source: "local_implicit", - userId: null, + source, + userId: source === "session" ? "inviter-1" : null, companyIds: ["company-1"], + memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }], }; next(); }); @@ -114,6 +118,9 @@ describe("POST /companies/:companyId/invites", () => { 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 () => { @@ -133,4 +140,67 @@ describe("POST /companies/:companyId/invites", () => { 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"); + }); }); diff --git a/server/src/__tests__/invite-join-grants.test.ts b/server/src/__tests__/invite-join-grants.test.ts index 9c10d2d6367..63c614e66d2 100644 --- a/server/src/__tests__/invite-join-grants.test.ts +++ b/server/src/__tests__/invite-join-grants.test.ts @@ -98,6 +98,25 @@ describe("human invite roles", () => { ]); }); + it("maps operator to company editing grants without join approval or member permissions", () => { + expect(grantsForHumanRole("operator")).toEqual([ + { permissionKey: "agents:create", scope: null }, + { permissionKey: "agents:configure", scope: null }, + { permissionKey: "skills:create", scope: null }, + { permissionKey: "environments:manage", scope: null }, + { permissionKey: "users:invite", scope: null }, + { permissionKey: "tasks:assign", scope: null }, + { permissionKey: "pipelines:write", scope: null }, + { permissionKey: "tools:manage_connections", scope: null }, + { permissionKey: "tools:manage_profiles", scope: null }, + { permissionKey: "tools:manage_runtime", scope: null }, + { permissionKey: "tools:use", scope: null }, + { permissionKey: "tools:admin", scope: null }, + { permissionKey: "tools:view_audit", scope: null }, + { permissionKey: "audit:view_agent_actions", scope: null }, + ]); + }); + it("defaults legacy or missing roles to operator", () => { expect(normalizeHumanRole("member")).toBe("operator"); expect(resolveHumanInviteRole(null)).toBe("operator"); @@ -114,9 +133,7 @@ describe("human invite roles", () => { }); it("falls back to role grants when human invite defaults omit explicit grants", () => { - expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual([ - { permissionKey: "tasks:assign", scope: null }, - ]); + expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual(grantsForHumanRole("operator")); }); it("preserves explicit human invite grants", () => { diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts index 3aaa1df32e2..460cd3c3dd9 100644 --- a/server/src/routes/access.ts +++ b/server/src/routes/access.ts @@ -3073,6 +3073,15 @@ export function accessRoutes( input.allowedJoinTypes === "agent" ? null : input.humanRole ?? "operator"; + if (effectiveHumanRole) { + // An invitation must not delegate the membership powers its creator lacks. + const roleGrants = grantsForHumanRole(effectiveHumanRole); + for (const permissionKey of ["joins:approve", "users:manage_permissions"] as const) { + if (roleGrants.some((grant) => grant.permissionKey === permissionKey)) { + await assertCompanyPermission(input.req, input.companyId, permissionKey); + } + } + } const insertValues = { companyId: input.companyId, inviteType: "company_join" as const, diff --git a/server/src/services/company-member-roles.ts b/server/src/services/company-member-roles.ts index 2a9d781734e..d67ddbc90e7 100644 --- a/server/src/services/company-member-roles.ts +++ b/server/src/services/company-member-roles.ts @@ -55,7 +55,22 @@ export function grantsForHumanRole( { permissionKey: "tools:admin", scope: null }, ]; case "operator": - return [{ permissionKey: "tasks:assign", scope: null }]; + return [ + { permissionKey: "agents:create", scope: null }, + { permissionKey: "agents:configure", scope: null }, + { permissionKey: "skills:create", scope: null }, + { permissionKey: "environments:manage", scope: null }, + { permissionKey: "users:invite", scope: null }, + { permissionKey: "tasks:assign", scope: null }, + { permissionKey: "pipelines:write", scope: null }, + { permissionKey: "tools:manage_connections", scope: null }, + { permissionKey: "tools:manage_profiles", scope: null }, + { permissionKey: "tools:manage_runtime", scope: null }, + { permissionKey: "tools:use", scope: null }, + { permissionKey: "tools:admin", scope: null }, + { permissionKey: "tools:view_audit", scope: null }, + { permissionKey: "audit:view_agent_actions", scope: null }, + ]; case "viewer": return []; } diff --git a/ui/src/components/SidebarAccountMenu.production.tsx b/ui/src/components/SidebarAccountMenu.production.tsx index e0549e56fe7..c085b621173 100644 --- a/ui/src/components/SidebarAccountMenu.production.tsx +++ b/ui/src/components/SidebarAccountMenu.production.tsx @@ -131,8 +131,8 @@ export function SidebarAccountMenu({ // fallback there because it drives a different invitation flow. const cloudInviteUrl = useCloudInviteUrl(); // Self-hosted invites need the `users:invite` grant. Offer the shortcut only - // to boards that hold it (company owner/admin, instance admins, local - // boards) so a plain member is never sent to a permission error. + // to boards with role-default access (company owner/admin/operator, + // instance admins, local boards). The server checks the actual grants. const canInviteMembers = useCanInviteCompanyMembers(!isCloud); const inviteHref = isCloud ? cloudInviteUrl : canInviteMembers ? INVITES_PATH : null; const showInvite = diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsx index 008102b1f5e..897065b6034 100644 --- a/ui/src/components/SidebarAccountMenu.test.tsx +++ b/ui/src/components/SidebarAccountMenu.test.tsx @@ -144,7 +144,7 @@ describe("SidebarAccountMenu", () => { }); mockAuthApi.signOut.mockResolvedValue({ success: true, redirectTo: "/cloud/logout" }); // Default to a company owner: the self-hosted Invite shortcut needs the - // `users:invite` grant, which owners and admins hold. + // `users:invite` grant, which owners, admins, and operators hold by default. mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("owner")); }); @@ -665,9 +665,8 @@ describe("SidebarAccountMenu", () => { status: "ok", deploymentMode: "authenticated", }); - // Operators and viewers lack `users:invite`; the Invites tab would only - // show them a permission error, so the menu must not offer it. - mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("operator")); + // Viewers lack `users:invite`; the menu must not offer the shortcut. + mockGetCurrentBoardAccess.mockResolvedValue(boardAccess("viewer")); await act(async () => { root.render( @@ -697,6 +696,7 @@ describe("SidebarAccountMenu", () => { ["instance admin", boardAccess("viewer", { isInstanceAdmin: true })], ["local board", boardAccess("viewer", { source: "local_implicit" })], ["company admin", boardAccess("admin")], + ["company operator", boardAccess("operator")], ])("offers the self-hosted invite shortcut to a %s", async (_label, access) => { const root = createRoot(container); const queryClient = new QueryClient({ diff --git a/ui/src/components/SidebarAccountMenu.tsx b/ui/src/components/SidebarAccountMenu.tsx index f40959aa702..b87beea3610 100644 --- a/ui/src/components/SidebarAccountMenu.tsx +++ b/ui/src/components/SidebarAccountMenu.tsx @@ -130,8 +130,8 @@ export function SidebarAccountMenu({ // fallback there because it drives a different invitation flow. const cloudInviteUrl = useCloudInviteUrl(); // Self-hosted invites need the `users:invite` grant. Offer the shortcut only - // to boards that hold it (company owner/admin, instance admins, local - // boards) so a plain member is never sent to a permission error. + // to boards with role-default access (company owner/admin/operator, + // instance admins, local boards). The server checks the actual grants. const canInviteMembers = useCanInviteCompanyMembers(!isCloud); const inviteHref = isCloud ? cloudInviteUrl : canInviteMembers ? INVITES_PATH : null; const showInvite = diff --git a/ui/src/components/access/InvitesSection.tsx b/ui/src/components/access/InvitesSection.tsx index db6f22c76eb..6416952ec7c 100644 --- a/ui/src/components/access/InvitesSection.tsx +++ b/ui/src/components/access/InvitesSection.tsx @@ -21,8 +21,8 @@ const inviteRoleOptions = [ { value: "operator", label: "Operator", - description: "Recommended for people who need to help run work without managing access.", - gets: "Can assign tasks.", + description: "Can edit organization work and invite people.", + gets: "Full editing and audit access. Cannot approve join requests or manage member permissions.", }, { value: "admin", diff --git a/ui/src/hooks/useCompanyInviteAccess.test.ts b/ui/src/hooks/useCompanyInviteAccess.test.ts index 1939426a128..2a81b568e62 100644 --- a/ui/src/hooks/useCompanyInviteAccess.test.ts +++ b/ui/src/hooks/useCompanyInviteAccess.test.ts @@ -27,14 +27,14 @@ describe("canInviteCompanyMembers", () => { expect(canInviteCompanyMembers(null, snapshot({ isInstanceAdmin: true }))).toBe(true); }); - it.each(["owner", "admin"] as const)("passes an active company %s", (membershipRole) => { + it.each(["owner", "admin", "operator", "member"] as const)("passes an active company %s", (membershipRole) => { const access = snapshot({ memberships: [{ companyId: "company-1", membershipRole, status: "active" }], }); expect(canInviteCompanyMembers("company-1", access)).toBe(true); }); - it.each(["operator", "viewer", "member", null] as const)("rejects a company %s", (membershipRole) => { + it.each(["viewer", null] as const)("rejects a company %s", (membershipRole) => { const access = snapshot({ memberships: [{ companyId: "company-1", membershipRole, status: "active" }], }); diff --git a/ui/src/hooks/useCompanyInviteAccess.ts b/ui/src/hooks/useCompanyInviteAccess.ts index 7eec8933fc2..53b1f1cb50d 100644 --- a/ui/src/hooks/useCompanyInviteAccess.ts +++ b/ui/src/hooks/useCompanyInviteAccess.ts @@ -9,8 +9,9 @@ import { useOptionalCompany } from "@/context/CompanyContext"; * * Mirrors the other client-side role gates (`ToolsAdminGate`, the run * ledger): local implicit boards and instance admins always pass; otherwise - * the active company membership must be owner or admin, the roles that carry - * the `users:invite` grant. Resolves to false while the snapshot is unknown. + * the active company membership must be owner, admin, or operator, the roles + * that carry the default `users:invite` grant. Legacy members normalize to + * operator. Resolves to false while the snapshot is unknown. * The server stays authoritative; this only decides whether to offer a * shortcut that would otherwise end in a permission error. */ @@ -24,7 +25,10 @@ export function canInviteCompanyMembers( const membership = boardAccess.memberships?.find( (item) => item.companyId === companyId && item.status === "active", ); - return membership?.membershipRole === "owner" || membership?.membershipRole === "admin"; + return membership?.membershipRole === "owner" || + membership?.membershipRole === "admin" || + membership?.membershipRole === "operator" || + membership?.membershipRole === "member"; } /** diff --git a/ui/src/pages/InviteUxLab.tsx b/ui/src/pages/InviteUxLab.tsx index 9856eafb238..2737a1d05b2 100644 --- a/ui/src/pages/InviteUxLab.tsx +++ b/ui/src/pages/InviteUxLab.tsx @@ -33,8 +33,8 @@ const inviteRoleOptions = [ { value: "operator", label: "Operator", - description: "Recommended for people who need to help run work without managing access.", - gets: "Can assign tasks.", + description: "Can edit organization work and invite people.", + gets: "Full editing and audit access. Cannot approve join requests or manage member permissions.", }, { value: "admin", diff --git a/ui/src/pages/tools/AdvancedToolsRoute.tsx b/ui/src/pages/tools/AdvancedToolsRoute.tsx index 5659a0d1ba8..31acdcb8b33 100644 --- a/ui/src/pages/tools/AdvancedToolsRoute.tsx +++ b/ui/src/pages/tools/AdvancedToolsRoute.tsx @@ -8,10 +8,10 @@ import { ToolsAccess } from "./ToolsAccess"; /** * Admin gate for the Advanced door (PAP-10862, plan D8). The developer surface - * lives under `/apps/advanced` and is reserved for administrators (`tools:admin` - * on the server). This is a best-effort UX gate — the server is authoritative — - * derived from the caller's board access: instance admins and company - * owners/admins pass. Non-admins get a friendly explanation rather than a 403. + * lives under `/apps/advanced` and requires `tools:admin` on the server. + * This is a best-effort UX gate derived from role defaults: local boards, + * instance admins, and active company owners/admins/operators pass. + * The server is authoritative. */ export function AdvancedToolsRoute() { const { selectedCompanyId } = useCompany(); @@ -26,22 +26,25 @@ export function AdvancedToolsRoute() { } const data = boardAccess.data; - const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId); - const isAdmin = + const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId && m.status === "active"); + const canManageTools = + data?.source === "local_implicit" || Boolean(data?.isInstanceAdmin) || membership?.membershipRole === "owner" || - membership?.membershipRole === "admin"; + membership?.membershipRole === "admin" || + membership?.membershipRole === "operator" || + membership?.membershipRole === "member"; - if (!isAdmin) { + if (!canManageTools) { return (
-

Advanced setup is for administrators

+

Advanced setup requires editing access

- This area lets administrators wire up tools that aren't in the gallery. Ask an administrator if you + This area lets company editors wire up tools that aren't in the gallery. Ask a company editor if you need a new app connected, or head back to{" "} your apps diff --git a/ui/src/pages/tools/ToolRoleAccess.test.tsx b/ui/src/pages/tools/ToolRoleAccess.test.tsx new file mode 100644 index 00000000000..a0e362c7dae --- /dev/null +++ b/ui/src/pages/tools/ToolRoleAccess.test.tsx @@ -0,0 +1,84 @@ +// @vitest-environment jsdom + +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { CurrentBoardAccess } from "@/api/access"; +import { AdvancedToolsRoute } from "./AdvancedToolsRoute"; +import { ToolsAdminGate } from "./profiles/ToolsAdminGate"; + +const accessState = vi.hoisted(() => ({ data: undefined as CurrentBoardAccess | undefined })); + +vi.mock("@tanstack/react-query", () => ({ + useQuery: () => ({ data: accessState.data, isLoading: false }), +})); +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ selectedCompanyId: "company-1" }), +})); +vi.mock("@/lib/router", () => ({ + Link: ({ children, to }: { children: React.ReactNode; to: string }) => {children}, +})); +vi.mock("./ToolsAccess", () => ({ + ToolsAccess: () =>

Advanced tool setup
, +})); + +function snapshot(role: "owner" | "admin" | "operator" | "member" | "viewer"): CurrentBoardAccess { + return { + user: { id: "user-1", email: "editor@example.com", name: "Editor", image: null }, + userId: "user-1", + isInstanceAdmin: false, + companyIds: ["company-1"], + memberships: [{ companyId: "company-1", membershipRole: role, status: "active" }], + source: "session", + keyId: null, + }; +} + +describe.each([ + ["advanced tool setup", , "Advanced tool setup"], + ["access profiles", Profile editor, "Profile editor"], +] as const)("%s role access", (_label, content, editorText) => { + let container: HTMLDivElement; + let root: ReturnType; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + accessState.data = undefined; + }); + + afterEach(() => { + flushSync(() => root.unmount()); + container.remove(); + }); + + function render(access: CurrentBoardAccess | undefined) { + accessState.data = access; + flushSync(() => root.render(content)); + } + + it.each(["owner", "admin", "operator", "member"] as const)("allows active %s defaults", (role) => { + render(snapshot(role)); + expect(container.textContent).toContain(editorText); + }); + + it("allows local boards and instance admins without company membership", () => { + render({ ...snapshot("viewer"), memberships: [], source: "local_implicit" }); + expect(container.textContent).toContain(editorText); + render({ ...snapshot("viewer"), memberships: [], isInstanceAdmin: true }); + expect(container.textContent).toContain(editorText); + }); + + it("rejects viewers, inactive memberships, and members of another company", () => { + render(snapshot("viewer")); + expect(container.textContent).not.toContain(editorText); + const operator = snapshot("operator"); + render({ ...operator, memberships: [{ ...operator.memberships![0]!, status: "suspended" }] }); + expect(container.textContent).not.toContain(editorText); + render({ ...operator, memberships: [{ ...operator.memberships![0]!, companyId: "company-2" }] }); + expect(container.textContent).not.toContain(editorText); + render(undefined); + expect(container.textContent).not.toContain(editorText); + }); +}); diff --git a/ui/src/pages/tools/profiles/ToolsAdminGate.tsx b/ui/src/pages/tools/profiles/ToolsAdminGate.tsx index 5f43cc2bbdb..4febb728b03 100644 --- a/ui/src/pages/tools/profiles/ToolsAdminGate.tsx +++ b/ui/src/pages/tools/profiles/ToolsAdminGate.tsx @@ -8,9 +8,9 @@ import { useCompany } from "@/context/CompanyContext"; /** * Best-effort admin gate for the access-profiles surface, mirroring - * `AdvancedToolsRoute` (PAP-10862, plan D8). Instance admins and company - * owners/admins pass; the server stays authoritative. Shared so the profiles - * index and the create wizard guard identically. + * `AdvancedToolsRoute` (PAP-10862, plan D8). Local boards, instance admins, + * and active company owners/admins/operators pass; the server stays + * authoritative. Shared so the profiles index and create wizard guard identically. */ export function ToolsAdminGate({ children }: { children: ReactNode }) { const { selectedCompanyId } = useCompany(); @@ -25,22 +25,25 @@ export function ToolsAdminGate({ children }: { children: ReactNode }) { } const data = boardAccess.data; - const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId); - const isAdmin = + const membership = data?.memberships?.find((m) => m.companyId === selectedCompanyId && m.status === "active"); + const canManageTools = + data?.source === "local_implicit" || Boolean(data?.isInstanceAdmin) || membership?.membershipRole === "owner" || - membership?.membershipRole === "admin"; + membership?.membershipRole === "admin" || + membership?.membershipRole === "operator" || + membership?.membershipRole === "member"; - if (!isAdmin) { + if (!canManageTools) { return (
-

Access profiles are for administrators

+

Access profiles require editing access

- Access profiles decide which tools your agents can use. Ask an administrator to set these up, or + Access profiles decide which tools your agents can use. Ask a company editor to set these up, or head back to{" "} your apps