diff --git a/docs/api-reference.md b/docs/api-reference.md index df944d7c0..85e9cb991 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -405,6 +405,10 @@ Export your key as `AMCP_MCP_API_KEY` (or `AMCP_ACCESS_TOKEN` when the server op | GET | `/api/roles/:id/tools` | List tool access for a role | | PUT | `/api/roles/:id/tools` | Set tool access whitelist | | PUT | `/api/roles/:id/tools/:toolId/rate-limit` | Update rate limits on an existing tool grant | +| GET | `/api/roles/members` | List members with every MCP role they hold and the connectors those roles reach | +| GET | `/api/roles/assignments/:userId` | List a member's MCP roles, with where each comes from | +| PUT | `/api/roles/assignments/:userId` | Replace a member's manual MCP roles | +| PUT | `/api/roles/assign/:userId` | Deprecated: set one MCP role. Use `PUT /api/roles/assignments/:userId` | ### Create Role with Tool Whitelist @@ -423,12 +427,42 @@ curl -s -X PUT http://localhost:4000/api/roles/$ROLE_ID/tools \ -d '{"toolIds": ["tool-id-1", "tool-id-2", "tool-id-3"]}' ``` +### Assign roles to members + +A member can hold several MCP roles and may call the **union** of their tools: +each role adds tools, none takes any away. A role comes from one of two +sources: + +- `manual`: set by an admin, under **Settings → Roles** or with + `PUT /api/roles/assignments/:userId`. +- the single sign-on group sync (for example `entra`): set by the + provider's role mappings ([SSO guide](sso.md#3-map-directory-groups-to-roles)). + Change these in the mappings, not on the member. + +`PUT /api/roles/assignments/:userId` replaces only the member's **manual** +roles in your workspace; roles from group sync stay. + +```bash +curl -s -X PUT http://localhost:4000/api/roles/assignments/$USER_ID \ + -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{"roleIds": ["'$ROLE_ID'"]}' +``` + +`GET /api/roles/members` returns every member of your workspace with all their +roles (`roles[]`: `roleId`, `roleName`, `source`, and `global` for a grant that +applies in every workspace) and `connectors`, the connectors those roles reach. +`connectors` is `null` when roles do not limit the member: a workspace ADMIN, +or a member with no role while no role of the workspace has a tool list. +`GET /api/users` also returns all roles of each member in `mcpRoles`; its +`mcpRoleId` and `mcpRole` fields are deprecated and hold one role at most. + ### Per-tool rate limits An administrator can set optional minute and hour limits on an existing -role/tool grant. The editor UI is planned separately; configure limits through -the API for now. `GET /api/roles/:id/tools` returns `callsPerMinute` and -`callsPerHour` on each grant. +role/tool grant, under **Settings → Roles → Manage tools** or through the API. +`GET /api/roles/:id/tools` returns `callsPerMinute` and `callsPerHour` on each +grant. ```bash curl -s -X PUT "http://localhost:4000/api/roles/$ROLE_ID/tools/tool-id-1/rate-limit" \ diff --git a/docs/operations/member-visibility.md b/docs/operations/member-visibility.md index 1029b832e..e5bea4cf2 100644 --- a/docs/operations/member-visibility.md +++ b/docs/operations/member-visibility.md @@ -127,10 +127,15 @@ of its tools. So set up the roles first, then switch the mode: 2. **Make members Viewer** (or Editor if they create connectors themselves) under **Settings → Users**. Admins are never restricted, so keep the admin role for the people who manage the workspace. -3. **Assign the roles.** By hand under **Settings → Users**, or from your - directory: map SSO groups to MCP roles under **Settings → Single sign-on → - Role mappings** ([SSO guide](../sso.md#3-map-directory-groups-to-roles)). - Set the workspace role of those mappings to Viewer as well. +3. **Assign the roles.** By hand under **Settings → Roles → User MCP Role + Assignment**, or from your directory: map SSO groups to MCP roles under + **Settings → Single sign-on → Role mappings** + ([SSO guide](../sso.md#3-map-directory-groups-to-roles)). Set the workspace + role of those mappings to Viewer as well. A member can hold several roles + and reaches the connectors of all of them together. The assignment table + shows every role of each member: roles from a single sign-on group are + marked and can only be changed in the role mappings, and the last column + counts the connectors the member's roles reach. 4. **Switch to Restricted** under **Settings → Organization → Security → Member visibility**, and save. diff --git a/docs/sso.md b/docs/sso.md index b6bffcc72..66b743c7c 100644 --- a/docs/sso.md +++ b/docs/sso.md @@ -128,7 +128,9 @@ Resolution rules: - A user in several mapped groups receives the **union** of their MCP roles and the **most privileged** workspace role. - Roles an admin assigned by hand are **never** removed by a sync, and vice - versa. + versa. **Settings → Roles → User MCP Role Assignment** shows both kinds for + each member; synced roles are marked `from single sign-on group` and can + only be changed here, in the mappings. - A sync will **not** demote the last remaining admin of a workspace. The attempt is refused and audited as `LAST_ADMIN_PROTECTION_TRIGGERED`. diff --git a/llms-full.txt b/llms-full.txt index eb30de10a..1f970633d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -6943,10 +6943,15 @@ of its tools. So set up the roles first, then switch the mode: 2. **Make members Viewer** (or Editor if they create connectors themselves) under **Settings → Users**. Admins are never restricted, so keep the admin role for the people who manage the workspace. -3. **Assign the roles.** By hand under **Settings → Users**, or from your - directory: map SSO groups to MCP roles under **Settings → Single sign-on → - Role mappings** ([SSO guide]()). - Set the workspace role of those mappings to Viewer as well. +3. **Assign the roles.** By hand under **Settings → Roles → User MCP Role + Assignment**, or from your directory: map SSO groups to MCP roles under + **Settings → Single sign-on → Role mappings** + ([SSO guide]()). Set the workspace + role of those mappings to Viewer as well. A member can hold several roles + and reaches the connectors of all of them together. The assignment table + shows every role of each member: roles from a single sign-on group are + marked and can only be changed in the role mappings, and the last column + counts the connectors the member's roles reach. 4. **Switch to Restricted** under **Settings → Organization → Security → Member visibility**, and save. @@ -7522,7 +7527,9 @@ Resolution rules: - A user in several mapped groups receives the **union** of their MCP roles and the **most privileged** workspace role. - Roles an admin assigned by hand are **never** removed by a sync, and vice - versa. + versa. **Settings → Roles → User MCP Role Assignment** shows both kinds for + each member; synced roles are marked `from single sign-on group` and can + only be changed here, in the mappings. - A sync will **not** demote the last remaining admin of a workspace. The attempt is refused and audited as `LAST_ADMIN_PROTECTION_TRIGGERED`. @@ -8863,6 +8870,10 @@ Export your key as `AMCP_MCP_API_KEY` (or `AMCP_ACCESS_TOKEN` when the server op | GET | `/api/roles/:id/tools` | List tool access for a role | | PUT | `/api/roles/:id/tools` | Set tool access whitelist | | PUT | `/api/roles/:id/tools/:toolId/rate-limit` | Update rate limits on an existing tool grant | +| GET | `/api/roles/members` | List members with every MCP role they hold and the connectors those roles reach | +| GET | `/api/roles/assignments/:userId` | List a member's MCP roles, with where each comes from | +| PUT | `/api/roles/assignments/:userId` | Replace a member's manual MCP roles | +| PUT | `/api/roles/assign/:userId` | Deprecated: set one MCP role. Use `PUT /api/roles/assignments/:userId` | ### Create Role with Tool Whitelist @@ -8881,12 +8892,42 @@ curl -s -X PUT http://localhost:4000/api/roles/$ROLE_ID/tools \ -d '{"toolIds": ["tool-id-1", "tool-id-2", "tool-id-3"]}' ``` +### Assign roles to members + +A member can hold several MCP roles and may call the **union** of their tools: +each role adds tools, none takes any away. A role comes from one of two +sources: + +- `manual`: set by an admin, under **Settings → Roles** or with + `PUT /api/roles/assignments/:userId`. +- the single sign-on group sync (for example `entra`): set by the + provider's role mappings ([SSO guide]()). + Change these in the mappings, not on the member. + +`PUT /api/roles/assignments/:userId` replaces only the member's **manual** +roles in your workspace; roles from group sync stay. + +```bash +curl -s -X PUT http://localhost:4000/api/roles/assignments/$USER_ID \ + -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{"roleIds": ["'$ROLE_ID'"]}' +``` + +`GET /api/roles/members` returns every member of your workspace with all their +roles (`roles[]`: `roleId`, `roleName`, `source`, and `global` for a grant that +applies in every workspace) and `connectors`, the connectors those roles reach. +`connectors` is `null` when roles do not limit the member: a workspace ADMIN, +or a member with no role while no role of the workspace has a tool list. +`GET /api/users` also returns all roles of each member in `mcpRoles`; its +`mcpRoleId` and `mcpRole` fields are deprecated and hold one role at most. + ### Per-tool rate limits An administrator can set optional minute and hour limits on an existing -role/tool grant. The editor UI is planned separately; configure limits through -the API for now. `GET /api/roles/:id/tools` returns `callsPerMinute` and -`callsPerHour` on each grant. +role/tool grant, under **Settings → Roles → Manage tools** or through the API. +`GET /api/roles/:id/tools` returns `callsPerMinute` and `callsPerHour` on each +grant. ```bash curl -s -X PUT "http://localhost:4000/api/roles/$ROLE_ID/tools/tool-id-1/rate-limit" \ diff --git a/packages/backend/src/roles/roles.controller.ts b/packages/backend/src/roles/roles.controller.ts index 815031ef0..6b2514332 100644 --- a/packages/backend/src/roles/roles.controller.ts +++ b/packages/backend/src/roles/roles.controller.ts @@ -105,8 +105,9 @@ export class RolesController { summary: 'List all roles (ADMIN)', description: 'The MCP roles of your workspace plus the built-in system roles. An MCP role is a whitelist of tools: a member ' + - 'with one or more roles may call only the tools those roles allow (the union); a member with no MCP role keeps ' + - 'access to every tool of the servers they reach. Separate from the workspace role (ADMIN, EDITOR, VIEWER).', + 'with one or more roles may call only the tools those roles allow (the union). A member with no MCP role can call ' + + 'every tool while no role of the workspace has a tool list, and no tool once one has. Separate from the workspace ' + + 'role (ADMIN, EDITOR, VIEWER); a workspace ADMIN can call every tool.', }) async listRoles(@Req() req: any) { return this.rolesService.findAll(req.user.organizationId); @@ -129,6 +130,46 @@ export class RolesController { return this.rolesService.create({ ...dto, organizationId: req.user.organizationId }); } + // Declared before `GET :id`, which would otherwise capture "members". + @Get('members') + @ApiOperation({ + summary: 'List members with all their MCP roles (ADMIN)', + description: + 'Every member of your workspace with EVERY MCP role they hold in it: `roles[].source` is `manual` (set by an ' + + 'admin, editable with `PUT /api/roles/assignments/{userId}`) or the identity provider group sync (change it in ' + + 'the provider\'s role mappings); `roles[].global` marks a grant that applies in every workspace. A member may ' + + 'call the union of the tools of all their roles. `connectors` lists the connectors those roles grant tools of; ' + + 'it is null when roles do not limit the member (a workspace ADMIN, or no role while no role of the workspace ' + + 'has a tool list).', + }) + @ApiResponse({ + status: 200, + schema: { + type: 'array', + items: { type: 'object' }, + example: [ + { + id: 'cmo8a7b6c0000abcdx1y2z3w4', + email: 'ana@example.com', + name: 'Ana', + role: 'VIEWER', + active: true, + roles: [ + { roleId: 'cmoc1d2e300e01zrpr3s4t5u6', roleName: 'sales-read-only', source: 'manual', global: false }, + { roleId: 'cmoc1d2e300e11zrpa1b2c3d4', roleName: 'finance', source: 'entra', global: false }, + ], + connectors: [ + { id: 'cmob7a1b200c01zrp1a2b3c4d', name: 'CRM' }, + { id: 'cmob7a1b200c11zrp5e6f7g8h', name: 'ERP' }, + ], + }, + ], + }, + }) + async listMembers(@Req() req: any) { + return this.rolesService.getMemberAssignments(req.user.organizationId); + } + @Get(':id') @ApiOperation({ summary: 'Get role details with tool access (ADMIN)' }) async getRole(@Req() req: any, @Param('id') id: string) { @@ -265,6 +306,7 @@ export class RolesController { userId, req.user.organizationId, ); + if (!assignments) throw new NotFoundException('User not found'); return { roleIds: [...new Set(assignments.map((a) => a.roleId))], roles: assignments.map((a) => ({ diff --git a/packages/backend/src/roles/roles.service.spec.ts b/packages/backend/src/roles/roles.service.spec.ts index a69d32250..cb816a83e 100644 --- a/packages/backend/src/roles/roles.service.spec.ts +++ b/packages/backend/src/roles/roles.service.spec.ts @@ -40,6 +40,7 @@ describe('RolesService', () => { }, organizationMember: { findUnique: jest.fn(), + findMany: jest.fn().mockResolvedValue([]), }, userRoleAssignment: { findMany: jest.fn().mockResolvedValue([]), @@ -661,6 +662,142 @@ describe('RolesService', () => { }); }); + describe('getUserRoles', () => { + it('returns null for a user outside the organization', async () => { + // Grants with no organization apply everywhere; without the membership + // check an admin could read them for anyone on the instance. + mockPrisma.organizationMember.findUnique.mockResolvedValue(null); + expect(await service.getUserRoles('u1', 'org-1')).toBeNull(); + expect(mockPrisma.userRoleAssignment.findMany).not.toHaveBeenCalled(); + }); + + it('lists the org and workspace-independent grants of a member', async () => { + mockPrisma.organizationMember.findUnique.mockResolvedValue({ userId: 'u1' }); + mockPrisma.userRoleAssignment.findMany.mockResolvedValue([{ roleId: 'r1', source: 'manual', role: { id: 'r1', name: 'Sales' } }]); + expect(await service.getUserRoles('u1', 'org-1')).toHaveLength(1); + expect(mockPrisma.userRoleAssignment.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: 'u1', OR: [{ organizationId: 'org-1' }, { organizationId: null }] }, + }), + ); + }); + }); + + describe('getMemberAssignments', () => { + const member = (id: string, role: string, deactivatedAt: Date | null = null) => ({ + role, + deactivatedAt, + user: { id, email: `${id}@example.com`, name: null }, + }); + + it('returns every assignment of a member, not just one', async () => { + // The bug this guards: the roles page showed the deprecated single + // `users.mcpRoleId`, so an IdP-synced role widening access was invisible. + mockPrisma.organizationMember.findMany.mockResolvedValue([member('u1', 'VIEWER')]); + mockPrisma.userRoleAssignment.findMany.mockResolvedValue([ + { userId: 'u1', roleId: 'r1', source: 'manual', organizationId: 'org-1', role: { name: 'Support' } }, + { userId: 'u1', roleId: 'r2', source: 'entra', organizationId: 'org-1', role: { name: 'Finance' } }, + { userId: 'u1', roleId: 'sys', source: 'manual', organizationId: null, role: { name: 'Global' } }, + ]); + mockPrisma.toolRoleAccess.findMany.mockResolvedValue([ + { roleId: 'r1', tool: { connector: { id: 'c1', name: 'Helpdesk' } } }, + { roleId: 'r2', tool: { connector: { id: 'c2', name: 'ERP' } } }, + { roleId: 'r2', tool: { connector: { id: 'c3', name: 'CRM' } } }, + // Same connector through a second role and a second tool: counted once. + { roleId: 'r1', tool: { connector: { id: 'c3', name: 'CRM' } } }, + ]); + + const [row] = await service.getMemberAssignments('org-1'); + + expect(row.roles).toEqual([ + { roleId: 'r1', roleName: 'Support', source: 'manual', global: false }, + { roleId: 'r2', roleName: 'Finance', source: 'entra', global: false }, + { roleId: 'sys', roleName: 'Global', source: 'manual', global: true }, + ]); + expect(row.connectors).toEqual([ + { id: 'c3', name: 'CRM' }, + { id: 'c2', name: 'ERP' }, + { id: 'c1', name: 'Helpdesk' }, + ]); + expect(row.active).toBe(true); + }); + + it('keeps every query inside the organization', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([member('u1', 'EDITOR'), member('u2', 'VIEWER')]); + mockPrisma.userRoleAssignment.findMany.mockResolvedValue([ + { userId: 'u1', roleId: 'r1', source: 'manual', organizationId: 'org-1', role: { name: 'Support' } }, + ]); + + await service.getMemberAssignments('org-1'); + + expect(mockPrisma.organizationMember.findMany).toHaveBeenCalledWith( + expect.objectContaining({ where: { organizationId: 'org-1' } }), + ); + expect(mockPrisma.userRoleAssignment.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { userId: { in: ['u1', 'u2'] }, OR: [{ organizationId: 'org-1' }, { organizationId: null }] }, + }), + ); + expect(mockPrisma.toolRoleAccess.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { roleId: { in: ['r1'] }, tool: { connector: { organizationId: 'org-1' } } }, + }), + ); + }); + + it('reports admins as not limited by roles, even when they hold some', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([member('a1', 'ADMIN')]); + mockPrisma.userRoleAssignment.findMany.mockResolvedValue([ + { userId: 'a1', roleId: 'r1', source: 'entra', organizationId: 'org-1', role: { name: 'Support' } }, + ]); + + const [row] = await service.getMemberAssignments('org-1'); + + expect(row.connectors).toBeNull(); + expect(row.roles).toHaveLength(1); + }); + + it('a member with no role is unrestricted while the org has no whitelist', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([member('u1', 'EDITOR'), member('u2', 'VIEWER')]); + mockPrisma.toolRoleAccess.findFirst.mockResolvedValue(null); + + const rows = await service.getMemberAssignments('org-1'); + + expect(rows.map((r) => r.connectors)).toEqual([null, null]); + expect(mockPrisma.toolRoleAccess.findMany).not.toHaveBeenCalled(); + // The probe runs once for the whole list, not per member. + expect(mockPrisma.toolRoleAccess.findFirst).toHaveBeenCalledTimes(1); + }); + + it('a member with no role reaches nothing once the org uses whitelists', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([member('u1', 'EDITOR')]); + mockPrisma.toolRoleAccess.findFirst.mockResolvedValue({ id: 'g1' }); + + const [row] = await service.getMemberAssignments('org-1'); + + expect(row.connectors).toEqual([]); + expect(row.roles).toEqual([]); + }); + + it('a role with an empty whitelist reaches no connector', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([member('u1', 'VIEWER', new Date())]); + mockPrisma.userRoleAssignment.findMany.mockResolvedValue([ + { userId: 'u1', roleId: 'empty', source: 'manual', organizationId: 'org-1', role: { name: 'Empty' } }, + ]); + mockPrisma.toolRoleAccess.findMany.mockResolvedValue([]); + + const [row] = await service.getMemberAssignments('org-1'); + + expect(row.connectors).toEqual([]); + expect(row.active).toBe(false); + }); + + it('returns [] for an organization without members', async () => { + expect(await service.getMemberAssignments('org-1')).toEqual([]); + expect(mockPrisma.userRoleAssignment.findMany).not.toHaveBeenCalled(); + }); + }); + describe('getCapabilities', () => { it('returns {} for a non-member', async () => { mockPrisma.organizationMember.findUnique.mockResolvedValue(null); diff --git a/packages/backend/src/roles/roles.service.ts b/packages/backend/src/roles/roles.service.ts index 30fdc6c20..f556e9450 100644 --- a/packages/backend/src/roles/roles.service.ts +++ b/packages/backend/src/roles/roles.service.ts @@ -11,6 +11,28 @@ interface LimitPresence { value: Promise; } +/** One MCP role assignment as the dashboard shows it. */ +export interface MemberRoleAssignment { + roleId: string; + roleName: string; + /** 'manual' = set by an admin; anything else comes from an IdP group sync. */ + source: string; + /** True for a grant with no organization: it applies in every workspace. */ + global: boolean; +} + +export interface MemberRoleSummary { + id: string; + email: string; + name: string | null; + /** Workspace role (ADMIN, EDITOR, VIEWER). */ + role: string; + active: boolean; + roles: MemberRoleAssignment[]; + /** Connectors the roles reach; null when roles do not limit the member. */ + connectors: Array<{ id: string; name: string }> | null; +} + const LIMIT_PRESENCE_TTL_MS = 5_000; const MAX_LIMIT_PRESENCE_ENTRIES = 1_000; @@ -542,8 +564,17 @@ export class RolesService { return this.setUserRoles(userId, roleId ? [roleId] : [], organizationId); } - /** Role ids assigned to a user in an organization, with their provenance. */ + /** + * Role ids assigned to a user in an organization, with their provenance. + * Null when the user is not a member, so an admin cannot read the + * workspace-independent grants of someone outside their organization. + */ async getUserRoles(userId: string, organizationId: string) { + const membership = await this.prisma.organizationMember.findUnique({ + where: { userId_organizationId: { userId, organizationId } }, + select: { userId: true }, + }); + if (!membership) return null; return this.prisma.userRoleAssignment.findMany({ where: { userId, @@ -557,6 +588,119 @@ export class RolesService { }); } + /** + * Every member of an organization with EVERY MCP role they hold there, for + * the dashboard's role assignment table. + * + * Effective tool access is the union of all assignments (see + * getAllowedToolIds), so showing one of them — the deprecated scalar + * `users.mcpRoleId` — let an admin believe a member was limited to one role + * while an IdP-synced or workspace-independent role widened it unseen. + * + * `connectors` lists the connectors whose tools the member's roles grant. + * It is null when roles do not limit the member: an ADMIN of the + * organization, or a member with no role in an organization that has never + * created a tool whitelist. A member with no role in an organization that + * does use whitelists reaches nothing (`[]`), matching getAllowedToolIds. + */ + async getMemberAssignments(organizationId: string): Promise { + const memberships = await this.prisma.organizationMember.findMany({ + where: { organizationId }, + select: { + role: true, + deactivatedAt: true, + user: { select: { id: true, email: true, name: true } }, + }, + orderBy: { joinedAt: 'asc' }, + }); + if (memberships.length === 0) return []; + const userIds = memberships.map((m) => m.user.id); + + // Same scope as getAllowedToolIds: grants in this organization plus + // grants with no organization, which apply everywhere. + const assignments = await this.prisma.userRoleAssignment.findMany({ + where: { + userId: { in: userIds }, + OR: [{ organizationId }, { organizationId: null }], + }, + select: { + userId: true, + roleId: true, + source: true, + organizationId: true, + role: { select: { name: true } }, + }, + orderBy: { createdAt: 'asc' }, + }); + + // Tool grants of the assigned roles, limited to this organization's + // connectors: a tool of another workspace is never reachable from here. + const roleIds = [...new Set(assignments.map((a) => a.roleId))]; + const grants = roleIds.length + ? await this.prisma.toolRoleAccess.findMany({ + where: { + roleId: { in: roleIds }, + tool: { connector: { organizationId } }, + }, + select: { + roleId: true, + tool: { select: { connector: { select: { id: true, name: true } } } }, + }, + }) + : []; + const connectorsByRole = new Map>(); + for (const g of grants) { + const map = connectorsByRole.get(g.roleId) ?? new Map(); + map.set(g.tool.connector.id, g.tool.connector.name); + connectorsByRole.set(g.roleId, map); + } + + const byUser = new Map(); + for (const a of assignments) { + const list = byUser.get(a.userId) ?? []; + list.push(a); + byUser.set(a.userId, list); + } + + // Only needed for a non-admin member with no role at all. + let usesWhitelists: boolean | undefined; + + const result: MemberRoleSummary[] = []; + for (const m of memberships) { + const own = byUser.get(m.user.id) ?? []; + let connectors: Array<{ id: string; name: string }> | null; + if (m.role === 'ADMIN') { + connectors = null; + } else if (own.length === 0) { + usesWhitelists ??= await this.organizationUsesToolWhitelists(organizationId); + connectors = usesWhitelists ? [] : null; + } else { + const reach = new Map(); + for (const a of own) { + for (const [id, name] of connectorsByRole.get(a.roleId) ?? []) reach.set(id, name); + } + connectors = [...reach] + .map(([id, name]) => ({ id, name })) + .sort((x, y) => x.name.localeCompare(y.name)); + } + result.push({ + id: m.user.id, + email: m.user.email, + name: m.user.name, + role: m.role, + active: m.deactivatedAt === null, + roles: own.map((a) => ({ + roleId: a.roleId, + roleName: a.role.name, + source: a.source, + global: a.organizationId === null, + })), + connectors, + }); + } + return result; + } + // ── Seed system roles ───────────────────────────────────────────────────── // `ensureSystemRoles()` used to live here, seeding a system role named diff --git a/packages/backend/src/users/users.controller.ts b/packages/backend/src/users/users.controller.ts index 0c1290bd2..ea54d7fd4 100644 --- a/packages/backend/src/users/users.controller.ts +++ b/packages/backend/src/users/users.controller.ts @@ -305,8 +305,10 @@ export class UsersController { summary: 'List all users in organization (ADMIN only)', description: 'The members of your workspace, in the order they joined, with their workspace `role` (ADMIN, EDITOR, VIEWER), ' + - 'whether they are `active` (not deactivated), their legacy single MCP role and their memory access. Use the `id` ' + - 'with `/api/roles/assignments/{userId}` to manage MCP roles.', + 'whether they are `active` (not deactivated), every MCP role they hold (`mcpRoles`: `source` is `manual` or the ' + + 'identity provider group sync, `global` marks a grant that applies in every workspace; the member may call the ' + + 'union of their tools) and their memory access. `mcpRoleId` / `mcpRole` are deprecated: they hold one of the ' + + 'roles at most. Use the `id` with `/api/roles/assignments/{userId}` to manage MCP roles.', }) @ApiResponse({ status: 200, @@ -322,6 +324,7 @@ export class UsersController { organizationId: 'cmo8a7b6c0001abcdk5l6m7n8', mcpRoleId: null, mcpRole: null, + mcpRoles: [], joinedAt: '2026-03-02T08:15:00.000Z', deactivatedAt: null, active: true, diff --git a/packages/backend/src/users/users.service.spec.ts b/packages/backend/src/users/users.service.spec.ts index 370073de6..4a1c03b85 100644 --- a/packages/backend/src/users/users.service.spec.ts +++ b/packages/backend/src/users/users.service.spec.ts @@ -128,13 +128,13 @@ describe('UsersService', () => { role: 'VIEWER', joinedAt: new Date('2026-01-01'), deactivatedAt: null, - user: { id: 'u1', email: 'a@x', name: 'A', mcpRoleId: null, mcpRole: null, createdAt: new Date(), updatedAt: new Date() }, + user: { id: 'u1', email: 'a@x', name: 'A', mcpRoleId: null, mcpRole: null, createdAt: new Date(), updatedAt: new Date(), roleAssignments: [] }, }, { role: 'ADMIN', joinedAt: new Date('2026-01-02'), deactivatedAt: new Date('2026-02-01'), - user: { id: 'u2', email: 'b@x', name: 'B', mcpRoleId: null, mcpRole: null, createdAt: new Date(), updatedAt: new Date() }, + user: { id: 'u2', email: 'b@x', name: 'B', mcpRoleId: null, mcpRole: null, createdAt: new Date(), updatedAt: new Date(), roleAssignments: [] }, }, ]); const rows = await service.findAll('org-1'); @@ -147,6 +147,36 @@ describe('UsersService', () => { ]); expect(rows[1].deactivatedAt).toEqual(new Date('2026-02-01')); }); + + it('returns every MCP role of a member, not only the deprecated single one', async () => { + mockPrisma.organizationMember.findMany.mockResolvedValue([ + { + role: 'VIEWER', + joinedAt: new Date('2026-01-01'), + deactivatedAt: null, + user: { + id: 'u1', email: 'a@x', name: 'A', mcpRoleId: 'r1', mcpRole: { id: 'r1', name: 'Support' }, + createdAt: new Date(), updatedAt: new Date(), + roleAssignments: [ + { roleId: 'r1', source: 'manual', organizationId: 'org-1', role: { name: 'Support' } }, + { roleId: 'r2', source: 'entra', organizationId: 'org-1', role: { name: 'Finance' } }, + { roleId: 'sys', source: 'manual', organizationId: null, role: { name: 'Global' } }, + ], + }, + }, + ]); + const [row] = await service.findAll('org-1'); + expect(row.mcpRoles).toEqual([ + { roleId: 'r1', roleName: 'Support', source: 'manual', global: false }, + { roleId: 'r2', roleName: 'Finance', source: 'entra', global: false }, + { roleId: 'sys', roleName: 'Global', source: 'manual', global: true }, + ]); + // Grants of another workspace stay out: only this one or none. + const args = mockPrisma.organizationMember.findMany.mock.calls[0][0]; + expect(args.include.user.select.roleAssignments.where).toEqual({ + OR: [{ organizationId: 'org-1' }, { organizationId: null }], + }); + }); }); describe('deleteInOrg', () => { diff --git a/packages/backend/src/users/users.service.ts b/packages/backend/src/users/users.service.ts index c7f072ec6..96d76c553 100644 --- a/packages/backend/src/users/users.service.ts +++ b/packages/backend/src/users/users.service.ts @@ -72,6 +72,15 @@ export class UsersService { name: true, mcpRoleId: true, mcpRole: { select: { id: true, name: true } }, + // Every MCP role the member holds here: grants of this workspace + // plus grants with no workspace, which apply everywhere. Access + // is their union, so the deprecated single `mcpRole` alone hid + // roles granted by a single sign-on group. + roleAssignments: { + where: { OR: [{ organizationId }, { organizationId: null }] }, + select: { roleId: true, source: true, organizationId: true, role: { select: { name: true } } }, + orderBy: { createdAt: 'asc' }, + }, createdAt: true, updatedAt: true, }, @@ -87,6 +96,12 @@ export class UsersService { organizationId, mcpRoleId: m.user.mcpRoleId, mcpRole: m.user.mcpRole, + mcpRoles: m.user.roleAssignments.map((a) => ({ + roleId: a.roleId, + roleName: a.role.name, + source: a.source, + global: a.organizationId === null, + })), createdAt: m.user.createdAt, updatedAt: m.user.updatedAt, joinedAt: m.joinedAt, diff --git a/packages/cli/src/generated/operations.ts b/packages/cli/src/generated/operations.ts index b27975843..88b429ea0 100644 --- a/packages/cli/src/generated/operations.ts +++ b/packages/cli/src/generated/operations.ts @@ -2407,6 +2407,16 @@ export const OPERATIONS: readonly ApiOperation[] = [ ], "hasBody": true }, + { + "resource": "roles", + "action": "listMembers", + "method": "GET", + "path": "/api/roles/members", + "summary": "List members with all their MCP roles (ADMIN)", + "admin": true, + "pathParams": [], + "hasBody": false + }, { "resource": "settings", "action": "getFooterLinks", diff --git a/packages/frontend/messages/de.json b/packages/frontend/messages/de.json index d6c9f5312..20f1100a0 100644 --- a/packages/frontend/messages/de.json +++ b/packages/frontend/messages/de.json @@ -2399,7 +2399,7 @@ "confirmDelete": "Rolle „{name}“ löschen? Benutzern mit dieser Rolle wird sie entzogen.", "deleted": "Rolle gelöscht", "toolAccessUpdated": "Tool-Zugriff aktualisiert", - "assigned": "MCP-Rolle zugewiesen", + "assigned": "MCP-Rollen gespeichert", "accessDenied": { "title": "Zugriff verweigert", "body": "Nur Administratoren können diese Seite aufrufen.", @@ -2453,7 +2453,20 @@ "appRole": "App-Rolle", "mcpRole": "MCP-Tool-Rolle", "fullAccess": "Voller Zugriff (Admin)", - "noRestriction": "Keine Rolle" + "unionHint": "Ein Mitglied kann die Tools aller seiner Rollen zusammen nutzen. Jede Rolle fügt Tools hinzu, keine nimmt welche weg.", + "reach": "Erreichte Connectoren", + "fromSso": "aus Single-Sign-On-Gruppe", + "allWorkspaces": "alle Workspaces", + "allWorkspacesHint": "Diese Rolle gilt in jedem Workspace und kann hier nicht geändert werden.", + "ssoHint": "Rollen aus einer Single-Sign-On-Gruppe folgen der Gruppe. Ändern Sie sie unter", + "ssoLink": "Einstellungen → Single Sign-On → Rollenzuordnungen", + "manualPlaceholder": "Rollen auswählen", + "deactivated": "Deaktiviert", + "allConnectors": "Alle Connectoren", + "noConnectors": "Keine", + "connectorCount": "{count, plural, one {# Connector} other {# Connectoren}}", + "noRoleOpen": "Keine Rolle. Kann alle Tools nutzen, solange keine Rolle eine Tool-Liste hat.", + "noRoleClosed": "Keine Rolle, daher keine Tools." } }, "settingsAdmin": { diff --git a/packages/frontend/messages/en.json b/packages/frontend/messages/en.json index efeaa611a..053ad955e 100644 --- a/packages/frontend/messages/en.json +++ b/packages/frontend/messages/en.json @@ -2399,7 +2399,7 @@ "confirmDelete": "Delete role \"{name}\"? Users with this role will be unassigned.", "deleted": "Role deleted", "toolAccessUpdated": "Tool access updated", - "assigned": "MCP role assigned", + "assigned": "MCP roles saved", "accessDenied": { "title": "Access Denied", "body": "Only administrators can access this page.", @@ -2453,7 +2453,20 @@ "appRole": "App Role", "mcpRole": "MCP Tool Role", "fullAccess": "Full access (admin)", - "noRestriction": "No role" + "unionHint": "A member can use the tools of all their roles together. Each role adds tools; none takes any away.", + "reach": "Connectors reached", + "fromSso": "from single sign-on group", + "allWorkspaces": "all workspaces", + "allWorkspacesHint": "This role applies in every workspace and cannot be changed here.", + "ssoHint": "Roles from a single sign-on group follow the group. Change them in", + "ssoLink": "Settings → Single sign-on → Role mappings", + "manualPlaceholder": "Choose roles", + "deactivated": "Deactivated", + "allConnectors": "All connectors", + "noConnectors": "None", + "connectorCount": "{count, plural, one {# connector} other {# connectors}}", + "noRoleOpen": "No role. Can use every tool while no role has a tool list.", + "noRoleClosed": "No role, so no tools." } }, "settingsAdmin": { diff --git a/packages/frontend/messages/it.json b/packages/frontend/messages/it.json index 2b6bb0517..518eacf7d 100644 --- a/packages/frontend/messages/it.json +++ b/packages/frontend/messages/it.json @@ -2399,7 +2399,7 @@ "confirmDelete": "Eliminare il ruolo \"{name}\"? Gli utenti con questo ruolo non lo avranno più.", "deleted": "Ruolo eliminato", "toolAccessUpdated": "Accesso agli strumenti aggiornato", - "assigned": "Ruolo MCP assegnato", + "assigned": "Ruoli MCP salvati", "accessDenied": { "title": "Accesso negato", "body": "Solo gli amministratori possono accedere a questa pagina.", @@ -2453,7 +2453,20 @@ "appRole": "Ruolo nell'app", "mcpRole": "Ruolo per gli strumenti MCP", "fullAccess": "Accesso completo (admin)", - "noRestriction": "Nessun ruolo" + "unionHint": "Un membro può usare insieme gli strumenti di tutti i suoi ruoli. Ogni ruolo aggiunge strumenti, nessuno ne toglie.", + "reach": "Connettori raggiunti", + "fromSso": "da gruppo single sign-on", + "allWorkspaces": "tutti i workspace", + "allWorkspacesHint": "Questo ruolo vale in ogni workspace e non si può cambiare qui.", + "ssoHint": "I ruoli da un gruppo single sign-on seguono il gruppo. Si cambiano in", + "ssoLink": "Impostazioni → Single sign-on → Associazioni dei ruoli", + "manualPlaceholder": "Scegli i ruoli", + "deactivated": "Disattivato", + "allConnectors": "Tutti i connettori", + "noConnectors": "Nessuno", + "connectorCount": "{count, plural, one {# connettore} other {# connettori}}", + "noRoleOpen": "Nessun ruolo. Può usare tutti gli strumenti finché nessun ruolo ha un elenco di strumenti.", + "noRoleClosed": "Nessun ruolo, quindi nessuno strumento." } }, "settingsAdmin": { diff --git a/packages/frontend/src/app/admin/roles/page.tsx b/packages/frontend/src/app/admin/roles/page.tsx index d323d6583..da223ad56 100644 --- a/packages/frontend/src/app/admin/roles/page.tsx +++ b/packages/frontend/src/app/admin/roles/page.tsx @@ -4,8 +4,8 @@ import { useEffect, useState } from 'react'; import { useTranslations } from 'next-intl'; import Link from 'next/link'; import { useAuth } from '@/lib/auth-context'; -import { roles, connectors, tools as toolsApi, users } from '@/lib/api'; -import { AppSelect } from '@/components/ui/select'; +import { roles, connectors, tools as toolsApi } from '@/lib/api'; +import { MemberRoleAssignments } from '@/components/member-role-assignments'; import { AppShell } from '@/components/app-shell'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; @@ -25,22 +25,14 @@ interface ToolItem { connectorName: string; } -interface UserItem { - id: string; - email: string; - name: string | null; - role: string; - mcpRoleId: string | null; - mcpRole: { id: string; name: string } | null; -} - export default function AdminRolesPage() { const { token, user: currentUser } = useAuth(); const t = useTranslations('settingsRoles'); const ta = useTranslations('adminPages'); const [roleList, setRoleList] = useState([]); const [allTools, setAllTools] = useState([]); - const [userList, setUserList] = useState([]); + // Bumped on every reload so the member table refetches with the roles. + const [reloadKey, setReloadKey] = useState(0); const [loading, setLoading] = useState(true); const [msg, setMsg] = useState(''); @@ -59,19 +51,15 @@ export default function AdminRolesPage() { const [selectedToolIds, setSelectedToolIds] = useState([]); const [savingTools, setSavingTools] = useState(false); - // User assignment - const [assigningUser, setAssigningUser] = useState(false); - const loadData = async () => { if (!token) return; try { - const [roleData, connectorData, userData] = await Promise.all([ + const [roleData, connectorData] = await Promise.all([ roles.list(token), connectors.list(token), - users.list(token), ]); setRoleList(roleData); - setUserList(userData); + setReloadKey((k) => k + 1); // Flatten all tools from connectors const allToolsList: ToolItem[] = []; @@ -156,23 +144,6 @@ export default function AdminRolesPage() { } }; - const handleAssignRole = async (userId: string, roleId: string | null) => { - if (!token) return; - try { - await roles.assignToUser(userId, roleId, token); - setUserList((prev) => - prev.map((u) => - u.id === userId - ? { ...u, mcpRoleId: roleId, mcpRole: roleId ? roleList.find((r) => r.id === roleId) ? { id: roleId, name: roleList.find((r) => r.id === roleId)!.name } : null : null } - : u, - ), - ); - setMsg(t('assigned')); - } catch (err: any) { - setMsg(t('error', { message: err.message })); - } - }; - const toggleToolId = (toolId: string) => { setSelectedToolIds((prev) => prev.includes(toolId) ? prev.filter((id) => id !== toolId) : [...prev, toolId], @@ -411,47 +382,12 @@ export default function AdminRolesPage() {

{t('assign.intro')}

+

+ {t('assign.unionHint')} +

-
- - - - - - - - - - {userList.map((u) => ( - - - - - - ))} - -
{t('assign.user')}{t('assign.appRole')}{t('assign.mcpRole')}
- {u.email} - {u.name && {u.name}} - - {u.role} - - {u.role === 'ADMIN' ? ( - {t('assign.fullAccess')} - ) : ( - handleAssignRole(u.id, v || null)} - className="h-8 rounded-[9px] border border-[var(--border)] bg-[var(--surface)] px-2 text-xs text-[var(--text)]" - options={[ - { value: '', label: t('assign.noRestriction') }, - ...roleList.map((r) => ({ value: r.id, label: r.name })), - ]} - /> - )} -
-
+ )} diff --git a/packages/frontend/src/app/admin/users/page.tsx b/packages/frontend/src/app/admin/users/page.tsx index 3bd4e237e..7aee8ce5f 100644 --- a/packages/frontend/src/app/admin/users/page.tsx +++ b/packages/frontend/src/app/admin/users/page.tsx @@ -10,6 +10,7 @@ import { AppShell } from '@/components/app-shell'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; +import { RoleChips } from '@/components/member-role-assignments'; const ROLES = ['ADMIN', 'EDITOR', 'VIEWER'] as const; @@ -280,8 +281,9 @@ export default function AdminUsersPage() { {u.role === 'ADMIN' ? ( {t('table.fullAccess')} - ) : u.mcpRole ? ( - {u.mcpRole.name} + ) : u.mcpRoles?.length ? ( + // Every role, not the deprecated single `mcpRole`: access is their union. + ) : ( {ta('users.unrestricted')} )} diff --git a/packages/frontend/src/app/settings/roles/page.tsx b/packages/frontend/src/app/settings/roles/page.tsx index b3eb76f1f..005f97dd7 100644 --- a/packages/frontend/src/app/settings/roles/page.tsx +++ b/packages/frontend/src/app/settings/roles/page.tsx @@ -4,8 +4,8 @@ import { useEffect, useState } from 'react'; import Link from 'next/link'; import { useTranslations } from 'next-intl'; import { useAuth } from '@/lib/auth-context'; -import { roles, connectors, tools as toolsApi, users } from '@/lib/api'; -import { AppSelect } from '@/components/ui/select'; +import { roles, connectors, tools as toolsApi } from '@/lib/api'; +import { MemberRoleAssignments } from '@/components/member-role-assignments'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; @@ -41,21 +41,13 @@ function parseLimit(value: string): number | null | undefined { return n >= 1 && n <= 2147483647 ? n : undefined; } -interface UserItem { - id: string; - email: string; - name: string | null; - role: string; - mcpRoleId: string | null; - mcpRole: { id: string; name: string } | null; -} - export default function SettingsRolesPage() { const t = useTranslations('settingsRoles'); const { token, user: currentUser } = useAuth(); const [roleList, setRoleList] = useState([]); const [allTools, setAllTools] = useState([]); - const [userList, setUserList] = useState([]); + // Bumped on every reload so the member table refetches with the roles. + const [reloadKey, setReloadKey] = useState(0); const [loading, setLoading] = useState(true); const [msg, setMsg] = useState(''); @@ -82,13 +74,12 @@ export default function SettingsRolesPage() { const loadData = async () => { if (!token) return; try { - const [roleData, connectorData, userData] = await Promise.all([ + const [roleData, connectorData] = await Promise.all([ roles.list(token), connectors.list(token), - users.list(token), ]); setRoleList(roleData); - setUserList(userData); + setReloadKey((k) => k + 1); // Flatten all tools from connectors const allToolsList: ToolItem[] = []; @@ -211,23 +202,6 @@ export default function SettingsRolesPage() { } }; - const handleAssignRole = async (userId: string, roleId: string | null) => { - if (!token) return; - try { - await roles.assignToUser(userId, roleId, token); - setUserList((prev) => - prev.map((u) => - u.id === userId - ? { ...u, mcpRoleId: roleId, mcpRole: roleId ? roleList.find((r) => r.id === roleId) ? { id: roleId, name: roleList.find((r) => r.id === roleId)!.name } : null : null } - : u, - ), - ); - setMsg(t('assigned')); - } catch (err: any) { - setMsg(t('error', { message: err.message })); - } - }; - const setLimitDraft = (toolId: string, field: keyof LimitDraft, value: string) => { setLimitDrafts((prev) => ({ ...prev, @@ -605,47 +579,12 @@ export default function SettingsRolesPage() {

{t('assign.intro')}

+

+ {t('assign.unionHint')} +

-
- - - - - - - - - - {userList.map((u) => ( - - - - - - ))} - -
{t('assign.user')}{t('assign.appRole')}{t('assign.mcpRole')}
- {u.email} - {u.name && {u.name}} - - {u.role} - - {u.role === 'ADMIN' ? ( - {t('assign.fullAccess')} - ) : ( - handleAssignRole(u.id, v || null)} - className="h-8 rounded-[9px] border border-[var(--border)] px-2 text-xs bg-[var(--surface)] text-[var(--text)]" - options={[ - { value: '', label: t('assign.noRestriction') }, - ...roleList.map((r) => ({ value: r.id, label: r.name })), - ]} - /> - )} -
-
+ )} diff --git a/packages/frontend/src/app/settings/users/page.tsx b/packages/frontend/src/app/settings/users/page.tsx index 447a3e009..70aca4136 100644 --- a/packages/frontend/src/app/settings/users/page.tsx +++ b/packages/frontend/src/app/settings/users/page.tsx @@ -22,6 +22,7 @@ import { AppSelect } from '@/components/ui/select'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; import { Badge, StatusPill } from '@/components/ui/badge'; +import { RoleChips } from '@/components/member-role-assignments'; import { useEdition } from '@/lib/use-edition'; import { EnterpriseNotice } from '@/components/enterprise-notice'; @@ -615,8 +616,9 @@ export default function SettingsUsersPage() { {u.role === 'ADMIN' ? ( {t('table.fullAccess')} - ) : u.mcpRole ? ( - {u.mcpRole.name} + ) : u.mcpRoles?.length ? ( + // Every role, not the deprecated single `mcpRole`: access is their union. + ) : ( a.source === 'manual' && !a.global; + +const manualRoleIds = (m: MemberRoles) => [...new Set(m.roles.filter(isEditable).map((a) => a.roleId))]; + +const sameSet = (a: string[], b: string[]) => a.length === b.length && a.every((x) => b.includes(x)); + +/** + * Chips for every MCP role of a member. Roles from a single sign-on group and + * roles that apply in every workspace say so: they cannot be changed where an + * admin edits manual roles. + */ +export function RoleChips({ roles: list }: { roles: MemberRoleAssignment[] }) { + const t = useTranslations('settingsRoles'); + return ( +
+ {list.map((a) => ( + + {a.roleName} + {a.source !== 'manual' && ( + · {t('assign.fromSso')} + )} + {a.global && ( + + · {t('assign.allWorkspaces')} + + )} + + ))} +
+ ); +} + +/** + * The "User MCP Role Assignment" table of the roles pages. + * + * Shows EVERY MCP role a member holds in the workspace, because the member + * may call the union of the tools of all of them. Showing one role (the + * deprecated single `mcpRoleId`) hid roles granted by a single sign-on group + * sync, so a member looked limited to one role while reaching far more. + * Manual roles are edited with a multi-select; synced and all-workspace roles + * are shown read-only, with where to change them. + */ +export function MemberRoleAssignments({ + token, + roleList, + reloadKey, + onMessage, +}: { + token: string | null; + roleList: RoleOption[]; + /** Change it to reload, e.g. after a role was created, renamed or deleted. */ + reloadKey?: unknown; + onMessage: (msg: string) => void; +}) { + const t = useTranslations('settingsRoles'); + const [members, setMembers] = useState([]); + const [drafts, setDrafts] = useState>({}); + const [savingId, setSavingId] = useState(null); + + const load = useCallback(async () => { + if (!token) return; + try { + const data = await roles.members(token); + setMembers(Array.isArray(data) ? data : []); + setDrafts({}); + } catch (err: any) { + onMessage(t('error', { message: err.message })); + } + // onMessage is a setter from the parent; t is stable per locale. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [token]); + + useEffect(() => { + load(); + }, [load, reloadKey]); + + const save = async (m: MemberRoles) => { + if (!token) return; + const roleIds = drafts[m.id] ?? manualRoleIds(m); + setSavingId(m.id); + try { + await roles.setUserRoles(m.id, roleIds, token); + onMessage(t('assigned')); + await load(); + } catch (err: any) { + onMessage(t('error', { message: err.message })); + } finally { + setSavingId(null); + } + }; + + const reach = (m: MemberRoles) => { + if (m.connectors === null) { + return {t('assign.allConnectors')}; + } + if (m.connectors.length === 0) { + return {t('assign.noConnectors')}; + } + const names = m.connectors.map((c) => c.name).join(', '); + return ( + + {t('assign.connectorCount', { count: m.connectors.length })} + {names} + + ); + }; + + return ( +
+ + + + + + + + + + + {members.map((m) => { + const saved = manualRoleIds(m); + const draft = drafts[m.id] ?? saved; + const dirty = !sameSet(draft, saved); + const fromSso = m.roles.some((a) => a.source !== 'manual'); + return ( + + + + + + + ); + })} + +
{t('assign.user')}{t('assign.appRole')}{t('assign.mcpRole')}{t('assign.reach')}
+ {m.email} + {m.name && {m.name}} + {!m.active && ( +
+ {t('assign.deactivated')} +
+ )} +
+ {m.role} + + {m.role === 'ADMIN' ? ( + {t('assign.fullAccess')} + ) : ( + <> + {m.roles.length > 0 ? ( + + ) : ( +

+ {m.connectors === null ? t('assign.noRoleOpen') : t('assign.noRoleClosed')} +

+ )} +
+ setDrafts((prev) => ({ ...prev, [m.id]: v }))} + options={roleList.map((r) => ({ value: r.id, label: r.name }))} + placeholder={t('assign.manualPlaceholder')} + emptyMessage={t('empty')} + className="h-8 text-xs" + /> + {dirty && ( + + )} +
+ {fromSso && ( +

+ {t('assign.ssoHint')}{' '} + + {t('assign.ssoLink')} + + . +

+ )} + + )} +
{reach(m)}
+
+ ); +} diff --git a/packages/frontend/src/lib/api.ts b/packages/frontend/src/lib/api.ts index 7b456f124..bf4cbfb48 100644 --- a/packages/frontend/src/lib/api.ts +++ b/packages/frontend/src/lib/api.ts @@ -2373,10 +2373,40 @@ export const roles = { limits: { callsPerMinute: number | null; callsPerHour: number | null }, token: string, ) => request(`/api/roles/${id}/tools/${toolId}/rate-limit`, { method: 'PUT', body: limits, token }), - assignToUser: (userId: string, roleId: string | null, token: string) => - request(`/api/roles/assign/${userId}`, { method: 'PUT', body: { roleId }, token }), + /** Every member with every MCP role they hold in this workspace. */ + members: (token: string) => + request('/api/roles/members', { token }), + /** Replaces the member's MANUAL roles; roles from single sign-on groups stay. */ + setUserRoles: (userId: string, roleIds: string[], token: string) => + request<{ message: string; roleIds: string[] }>(`/api/roles/assignments/${userId}`, { + method: 'PUT', + body: { roleIds }, + token, + }), }; +/** One MCP role assignment of a member (`GET /api/roles/members`). */ +export interface MemberRoleAssignment { + roleId: string; + roleName: string; + /** 'manual' = set by an admin; anything else comes from a single sign-on group sync. */ + source: string; + /** A grant with no workspace: it applies in every workspace. */ + global: boolean; +} + +export interface MemberRoles { + id: string; + email: string; + name: string | null; + /** Workspace role (ADMIN, EDITOR, VIEWER). */ + role: string; + active: boolean; + roles: MemberRoleAssignment[]; + /** Connectors the member's roles reach; null when roles do not limit the member. */ + connectors: Array<{ id: string; name: string }> | null; +} + // MCP API Keys /** * Key scope. `MCP` keys call MCP tools on `/mcp` only (the default, and what diff --git a/packages/frontend/tests/e2e/role-assignments.spec.ts b/packages/frontend/tests/e2e/role-assignments.spec.ts new file mode 100644 index 000000000..a57118ce9 --- /dev/null +++ b/packages/frontend/tests/e2e/role-assignments.spec.ts @@ -0,0 +1,118 @@ +import { expect, test, type Page } from '@playwright/test'; + +/** + * Settings → Roles → User MCP Role Assignment. + * The table used to show the deprecated single `mcpRoleId`, so a role granted + * by a single sign-on group (and widening access) was invisible. + */ + +const USER = { + id: 'u1', + email: 'admin@example.com', + name: 'Admin', + role: 'ADMIN', + organizationId: 'o1', + emailVerified: true, +}; + +const MEMBERS = [ + { id: 'u1', email: 'admin@example.com', name: 'Admin', role: 'ADMIN', active: true, roles: [], connectors: null }, + { + id: 'u2', + email: 'ana@example.com', + name: 'Ana', + role: 'VIEWER', + active: true, + roles: [ + { roleId: 'r1', roleName: 'Sales', source: 'manual', global: false }, + { roleId: 'r2', roleName: 'Finance', source: 'entra', global: false }, + { roleId: 'r9', roleName: 'Everywhere', source: 'manual', global: true }, + ], + connectors: [ + { id: 'c1', name: 'CRM' }, + { id: 'c2', name: 'ERP' }, + ], + }, + { id: 'u3', email: 'bo@example.com', name: null, role: 'EDITOR', active: true, roles: [], connectors: [] }, +]; + +type Put = { url: string; body: unknown }; + +async function openRoles(page: Page) { + const puts: Put[] = []; + await page.context().addCookies([{ name: 'amcp_token', value: 'test-token', url: 'http://localhost:3100' }]); + await page.addInitScript((user) => { + localStorage.setItem('amcp_token', 'test-token'); + localStorage.setItem('amcp_user', JSON.stringify(user)); + }, USER); + + await page.route(/\/api\//, async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (body: unknown, status = 200) => + route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }); + + if (req.method() === 'PUT') { + puts.push({ url: url.pathname, body: req.postDataJSON() }); + return json({ message: 'Roles updated' }); + } + if (url.pathname === '/api/roles') { + return json([ + { id: 'r1', name: 'Sales', description: null, isSystem: false, _count: { users: 1, toolAccess: 1 } }, + { id: 'r2', name: 'Finance', description: null, isSystem: false, _count: { users: 1, toolAccess: 1 } }, + { id: 'r3', name: 'Support', description: null, isSystem: false, _count: { users: 0, toolAccess: 1 } }, + ]); + } + if (url.pathname === '/api/roles/members') return json(MEMBERS); + if (url.pathname === '/api/connectors') return json([]); + if (url.pathname.startsWith('/api/users/me/onboarding-state')) return json({ onboardingCompletedAt: '2026-01-01T00:00:00Z' }); + if (url.pathname === '/api/users/me') return json(USER); + if (url.pathname === '/api/organizations/current') return json({ id: 'o1', name: 'Acme', createdAt: '2026-01-01' }); + if (url.pathname === '/api/organizations/mine') return json([{ id: 'o1', name: 'Acme', role: 'ADMIN', joinedAt: '2026-01-01' }]); + if (url.pathname === '/api/license/status') return json({ plan: 'team', status: 'active' }); + return json({}); + }); + + await page.goto('/settings/roles'); + await expect(page.getByTestId('roles-union-hint')).toBeVisible(); + return puts; +} + +test.describe('member MCP role assignments', () => { + test('shows every role of a member, with where it comes from', async ({ page }) => { + await openRoles(page); + + const ana = page.getByTestId('member-ana@example.com'); + const chips = ana.getByTestId('mcp-role-chip'); + await expect(chips).toHaveCount(3); + await expect(chips.filter({ hasText: 'Sales' })).not.toContainText('single sign-on'); + await expect(chips.filter({ hasText: 'Finance' })).toContainText('from single sign-on group'); + await expect(chips.filter({ hasText: 'Everywhere' })).toContainText('all workspaces'); + await expect(ana.getByRole('link', { name: 'Settings → Single sign-on → Role mappings' })).toHaveAttribute( + 'href', + '/settings/identity-providers', + ); + await expect(ana.getByText('2 connectors')).toBeVisible(); + + await expect(page.getByTestId('member-admin@example.com')).toContainText('Full access (admin)'); + const bo = page.getByTestId('member-bo@example.com'); + await expect(bo).toContainText('No role, so no tools.'); + // No single sign-on role, so no hint about changing one. + await expect(bo.getByRole('link', { name: /Role mappings/ })).toHaveCount(0); + }); + + test('saves only the manual roles', async ({ page }) => { + const puts = await openRoles(page); + + const ana = page.getByTestId('member-ana@example.com'); + // The picker lists the manual roles of this workspace only. + await ana.getByRole('button', { name: 'Sales' }).click(); + await page.getByRole('menuitemcheckbox', { name: 'Support' }).click(); + await page.keyboard.press('Escape'); + await ana.getByRole('button', { name: 'Save' }).click(); + + await expect.poll(() => puts.length).toBe(1); + expect(puts[0]).toEqual({ url: '/api/roles/assignments/u2', body: { roleIds: ['r1', 'r3'] } }); + await expect(page.getByText('MCP roles saved')).toBeVisible(); + }); +});