From 373ba9759a6a2f0ed626f9d39e7c657d68dd8014 Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 19:35:58 +0100 Subject: [PATCH 1/6] Show every MCP role of a member on the roles and users pages Access is the union of all role assignments, but the roles pages showed and edited only the deprecated single users.mcpRoleId, so a role granted by a single sign-on group stayed invisible. Add GET /api/roles/members with all assignments and the connectors they reach, edit manual roles through PUT /api/roles/assignments/:userId, mark synced and all-workspace roles read-only, and return mcpRoles from GET /api/users. --- docs/api-reference.md | 40 +++- docs/operations/member-visibility.md | 13 +- docs/sso.md | 4 +- .../backend/src/roles/roles.controller.ts | 46 +++- .../backend/src/roles/roles.service.spec.ts | 137 ++++++++++++ packages/backend/src/roles/roles.service.ts | 146 +++++++++++- .../backend/src/users/users.controller.ts | 7 +- .../backend/src/users/users.service.spec.ts | 34 ++- packages/backend/src/users/users.service.ts | 15 ++ packages/frontend/messages/de.json | 17 +- packages/frontend/messages/en.json | 17 +- packages/frontend/messages/it.json | 17 +- .../frontend/src/app/admin/roles/page.tsx | 84 +------ .../frontend/src/app/admin/users/page.tsx | 6 +- .../frontend/src/app/settings/roles/page.tsx | 81 +------ .../frontend/src/app/settings/users/page.tsx | 6 +- .../components/member-role-assignments.tsx | 208 ++++++++++++++++++ packages/frontend/src/lib/api.ts | 34 ++- .../tests/e2e/role-assignments.spec.ts | 118 ++++++++++ 19 files changed, 858 insertions(+), 172 deletions(-) create mode 100644 packages/frontend/src/components/member-role-assignments.tsx create mode 100644 packages/frontend/tests/e2e/role-assignments.spec.ts 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/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/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(); + }); +}); From 97be15c31b5de8fe1819988569d96cd1df31b7d5 Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 19:53:35 +0100 Subject: [PATCH 2/6] Move secrets in HTTP base URLs into encrypted variables A hand-made REST connector whose base URL carries its credential in the path (a Bitrix24 inbound webhook, /rest///) kept the code in plaintext in connectors.base_url and returned it to admins and the owner. The secret-literal extraction on save did not know these shapes. - Detector: vendor-anchored rules for Bitrix24 (cloud and self-hosted), Slack, Discord, Microsoft Teams, Zapier and Make webhook URLs, and the password in scheme://user:password@ for every HTTP connector type. Power Automate sig=, Google Chat key/token and Telegram were already covered by the query and token rules. - Save: only the secret segment moves into a variable named so that isSecretName masks it; calls interpolate {{VAR}} verbatim, so the URL sent is unchanged. - Start-up pass repairBaseUrlSecrets, run after the database pass: same rules minus the long-random-token heuristic, compare-and-swap on base URL and updatedAt, strict decryption of the variables, one summary log line with ids and counts only. - API output masks a secret still in an HTTP base URL (and the catalog baseline) as ********; a form that sends the masked URL back keeps the stored one, a URL edited around the mask is refused. --- docs/api-reference.md | 4 +- docs/connectors/rest.md | 48 +++ llms-full.txt | 52 ++- .../src/common/secret-literals.util.spec.ts | 149 ++++++++ .../src/common/secret-literals.util.ts | 171 ++++++++- .../connectors/base-url-secrets.util.spec.ts | 97 +++++ .../src/connectors/base-url-secrets.util.ts | 61 +++ .../src/connectors/connector-export.util.ts | 7 +- .../src/connectors/connector-secrets.util.ts | 18 +- .../src/connectors/connectors.controller.ts | 13 + ...rs.service.base-url-secrets-repair.spec.ts | 350 ++++++++++++++++++ .../src/connectors/connectors.service.ts | 151 +++++++- .../connectors/secret-extraction.util.spec.ts | 78 ++++ .../src/connectors/secret-extraction.util.ts | 18 +- .../src/connectors/secret-guard.flows.spec.ts | 87 +++++ 15 files changed, 1289 insertions(+), 15 deletions(-) create mode 100644 packages/backend/src/connectors/base-url-secrets.util.spec.ts create mode 100644 packages/backend/src/connectors/base-url-secrets.util.ts create mode 100644 packages/backend/src/connectors/connectors.service.base-url-secrets-repair.spec.ts diff --git a/docs/api-reference.md b/docs/api-reference.md index 85e9cb991..379fe9fae 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -100,7 +100,9 @@ endpoint. `authConfig` (OAuth and other stored credentials) is never exported: re-authorize the connector after importing it. Secret environment variables and headers are included only for admins signed in to the dashboard or using a `MANAGEMENT_ADMIN` key. For other roles, and for any `MANAGEMENT_READ` key, they -are empty and named in `maskedEnvVars` / `maskedHeaders`. Per-tool `useProxy`, annotation +are empty and named in `maskedEnvVars` / `maskedHeaders`, and a secret still written in an HTTP +base URL (a webhook token, a key, `user:password@`) shows as `********`; see +[Secrets typed into the base URL](connectors/rest.md#secrets-typed-into-the-base-url). Per-tool `useProxy`, annotation overrides and role access are not exported. ```bash diff --git a/docs/connectors/rest.md b/docs/connectors/rest.md index 5b62fb6ed..7623515ce 100644 --- a/docs/connectors/rest.md +++ b/docs/connectors/rest.md @@ -467,6 +467,54 @@ curl -s -X PUT http://localhost:4000/api/connectors/$CONNECTOR_ID/env-vars \ Use `{{VAR_NAME}}` in endpoint mappings. Parameters matching env var names are automatically stripped from the tool schema. +### Secrets typed into the base URL + +Some services put the credential in the address itself: a Bitrix24 inbound webhook +(`https://portal.bitrix24.com/rest/1//`), a Slack, Discord, Microsoft Teams, Zapier or Make +webhook URL, a Telegram bot URL (`https://api.telegram.org/bot`), a key in the query string +(`?api_key=…`, `?token=…`, `?sig=…`), or `https://user:password@host`. Whoever holds such a URL can +use it like a password. + +When you save a REST, GraphQL, SOAP, OData or MCP connector with such a base URL, AnythingMCP moves +only the secret part into an encrypted variable and stores the rest of the URL with a reference: + +``` +typed: https://portal.bitrix24.com/rest/1/k2bx…vqgo/ +stored: https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/ +``` + +- The variable is named after the connector (`_WEBHOOK_TOKEN`, `_PASSWORD`, + `_API_KEY`, `TELEGRAM_BOT_TOKEN`) or reuses a variable that already holds the same value. + Its value is encrypted at rest and never returned by the connector API, to admins neither (only an + admin export with secrets carries it, like every other variable); the dashboard shows it as set. The save answers with `secretsMoved` and `secretsNotice`, naming the variable, + never the secret. +- Calls are unchanged: every call replaces `{{VAR}}` in the base URL with the variable's value as + stored, so the request goes to exactly the URL you typed. To change the secret, edit the variable, + or type the full URL again. +- The host and the rest of the path stay readable, so the connector page, error hints and logs still + show where the connector points. +- Headers and tool paths get the same treatment (`Authorization: Bearer ` becomes + `Bearer {{_TOKEN}}`). + +Connectors saved before a rule existed keep the secret in the stored base URL until they are +saved again. Until then the API shows it as `********` +(`https://portal.bitrix24.com/rest/1/********/`); saving the form with the URL as shown keeps the +stored secret and moves it into a variable, and a URL edited around `********` is refused, so type +the full address again. The backend also moves these at every start, the same way a save does, +except for long random path segments with no known shape (a save moves those and says so; the +start-up pass leaves them alone). This needs no setting and works the same on AnythingMCP Cloud and +self-hosted. The backend log shows the result with connector ids and counts, never a URL: + +``` +Base URL secrets: secrets of 2 connectors moved into encrypted variables (cm1…, cm2…); 0 left as is; 0 failed +``` + +"Left as is" are connectors that were saved while the pass ran; the next start checks them again. +"Failed" names connectors whose variables could not be decrypted (a changed `ENCRYPTION_KEY`) or +written; they stay unchanged, still masked in the API, and the next start tries again. +`scripts/secret-literals/report.ts` lists what is left, and `repair.ts` also cleans tool paths, +headers and tool names (dry run by default, with a backup table before `--apply`). + --- ## Example: Full REST API Setup diff --git a/llms-full.txt b/llms-full.txt index eb30de10a..fa469518e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -3378,6 +3378,54 @@ curl -s -X PUT http://localhost:4000/api/connectors/$CONNECTOR_ID/env-vars \ Use `{{VAR_NAME}}` in endpoint mappings. Parameters matching env var names are automatically stripped from the tool schema. +### Secrets typed into the base URL + +Some services put the credential in the address itself: a Bitrix24 inbound webhook +(`https://portal.bitrix24.com/rest/1//`), a Slack, Discord, Microsoft Teams, Zapier or Make +webhook URL, a Telegram bot URL (`https://api.telegram.org/bot`), a key in the query string +(`?api_key=…`, `?token=…`, `?sig=…`), or `https://user:password@host`. Whoever holds such a URL can +use it like a password. + +When you save a REST, GraphQL, SOAP, OData or MCP connector with such a base URL, AnythingMCP moves +only the secret part into an encrypted variable and stores the rest of the URL with a reference: + +``` +typed: https://portal.bitrix24.com/rest/1/k2bx…vqgo/ +stored: https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/ +``` + +- The variable is named after the connector (`_WEBHOOK_TOKEN`, `_PASSWORD`, + `_API_KEY`, `TELEGRAM_BOT_TOKEN`) or reuses a variable that already holds the same value. + Its value is encrypted at rest and never returned by the connector API, to admins neither (only an + admin export with secrets carries it, like every other variable); the dashboard shows it as set. The save answers with `secretsMoved` and `secretsNotice`, naming the variable, + never the secret. +- Calls are unchanged: every call replaces `{{VAR}}` in the base URL with the variable's value as + stored, so the request goes to exactly the URL you typed. To change the secret, edit the variable, + or type the full URL again. +- The host and the rest of the path stay readable, so the connector page, error hints and logs still + show where the connector points. +- Headers and tool paths get the same treatment (`Authorization: Bearer ` becomes + `Bearer {{_TOKEN}}`). + +Connectors saved before a rule existed keep the secret in the stored base URL until they are +saved again. Until then the API shows it as `********` +(`https://portal.bitrix24.com/rest/1/********/`); saving the form with the URL as shown keeps the +stored secret and moves it into a variable, and a URL edited around `********` is refused, so type +the full address again. The backend also moves these at every start, the same way a save does, +except for long random path segments with no known shape (a save moves those and says so; the +start-up pass leaves them alone). This needs no setting and works the same on AnythingMCP Cloud and +self-hosted. The backend log shows the result with connector ids and counts, never a URL: + +``` +Base URL secrets: secrets of 2 connectors moved into encrypted variables (cm1…, cm2…); 0 left as is; 0 failed +``` + +"Left as is" are connectors that were saved while the pass ran; the next start checks them again. +"Failed" names connectors whose variables could not be decrypted (a changed `ENCRYPTION_KEY`) or +written; they stay unchanged, still masked in the API, and the next start tries again. +`scripts/secret-literals/report.ts` lists what is left, and `repair.ts` also cleans tool paths, +headers and tool names (dry run by default, with a backup table before `--apply`). + --- ## Example: Full REST API Setup @@ -8558,7 +8606,9 @@ endpoint. `authConfig` (OAuth and other stored credentials) is never exported: re-authorize the connector after importing it. Secret environment variables and headers are included only for admins signed in to the dashboard or using a `MANAGEMENT_ADMIN` key. For other roles, and for any `MANAGEMENT_READ` key, they -are empty and named in `maskedEnvVars` / `maskedHeaders`. Per-tool `useProxy`, annotation +are empty and named in `maskedEnvVars` / `maskedHeaders`, and a secret still written in an HTTP +base URL (a webhook token, a key, `user:password@`) shows as `********`; see +[Secrets typed into the base URL](). Per-tool `useProxy`, annotation overrides and role access are not exported. ```bash diff --git a/packages/backend/src/common/secret-literals.util.spec.ts b/packages/backend/src/common/secret-literals.util.spec.ts index f1aba790b..89c02e102 100644 --- a/packages/backend/src/common/secret-literals.util.spec.ts +++ b/packages/backend/src/common/secret-literals.util.spec.ts @@ -128,6 +128,155 @@ describe('findSecretLiterals', () => { }); }); +// Webhook credentials of each vendor's shape, assembled at runtime too. +const BITRIX_CODE = ['k2bx', 'a8g5', 'n4gh', 'vqgo'].join(''); +const SLACK_HOOK = ['AbCdEfGh', 'IjKlMnOp', 'QrStUv12'].join(''); +const DISCORD_TOKEN = ['Xy1_Ab2-Cd3Ef4Gh5', 'Ij6Kl7Mn8Op9Qr0St', 'Uv1Wx2Yz3Ab4Cd5Ef', 'Gh6Ij7Kl8Mn9Op0Q'].join(''); +const TEAMS_HEX = ['0123456789ab', 'cdef01234567', '89abcdef'].join(''); +const TEAMS_GUID = '1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d'; +const ZAPIER_CODE = ['ab', 'c1d', '2e'].join(''); +const MAKE_TOKEN = ['h7k2m9p4q1', 'w8x3y6z5a0', 'b2c4d6e8f1'].join(''); +const SIG = ['aB3dE5gH7jK9mN1pQ3', 'sT5vW7yZ9bC1eF3hJ5', 'kL7n'].join(''); + +describe('webhook URLs and URL passwords', () => { + /** The URL, the secret it carries, and the kind of finding. */ + const POSITIVE: Array<[label: string, url: string, secret: string, kind: string]> = [ + ['Bitrix24 cloud portal', `https://portal.bitrix24.com/rest/1/${BITRIX_CODE}/`, BITRIX_CODE, 'webhook_token'], + ['Bitrix24 .de portal with a method', `https://acme.bitrix24.de/rest/27/${BITRIX_CODE}/crm.deal.list.json`, BITRIX_CODE, 'webhook_token'], + ['Bitrix24 .com.br portal, no trailing slash', `https://acme.bitrix24.com.br/rest/3/${BITRIX_CODE}`, BITRIX_CODE, 'webhook_token'], + ['Bitrix24 self-hosted portal', `https://crm.example.com/rest/12/${BITRIX_CODE}/`, BITRIX_CODE, 'webhook_token'], + ['Bitrix24 self-hosted, relative path', `/rest/12/${BITRIX_CODE}/crm.lead.add`, BITRIX_CODE, 'webhook_token'], + ['Slack incoming webhook', `https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/${SLACK_HOOK}`, SLACK_HOOK, 'webhook_token'], + ['Slack workflow trigger', `https://hooks.slack.com/workflows/T0A1B2C3D/A0E1F2G3H/456789012/${SLACK_HOOK}`, SLACK_HOOK, 'webhook_token'], + ['Slack triggers URL', `https://hooks.slack.com/triggers/T0A1B2C3D/456789012/${SLACK_HOOK}`, SLACK_HOOK, 'webhook_token'], + ['Discord webhook', `https://discord.com/api/webhooks/123456789012345678/${DISCORD_TOKEN}`, DISCORD_TOKEN, 'webhook_token'], + ['Discord webhook, versioned, old host', `https://discordapp.com/api/v10/webhooks/123456789012345678/${DISCORD_TOKEN}/slack`, DISCORD_TOKEN, 'webhook_token'], + [ + 'Teams Office 365 connector', + `https://acme.webhook.office.com/webhookb2/${TEAMS_GUID}@${TEAMS_GUID}/IncomingWebhook/${TEAMS_HEX}/${TEAMS_GUID}`, + `${TEAMS_HEX}/${TEAMS_GUID}`, + 'webhook_token', + ], + [ + 'Teams connector, legacy host, V2 suffix', + `https://outlook.office.com/webhook/${TEAMS_GUID}@${TEAMS_GUID}/IncomingWebhook/${TEAMS_HEX}/${TEAMS_GUID}/V2abcDEF123/`, + `${TEAMS_HEX}/${TEAMS_GUID}/V2abcDEF123`, + 'webhook_token', + ], + [ + 'Power Automate workflow (sig=)', + `https://prod-12.westeurope.logic.azure.com:443/workflows/0a1b2c3d4e5f/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=${SIG}`, + SIG, + 'secret_query_param', + ], + [ + 'Power Platform workflow (sig=)', + `https://default0a1b.2c.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/0a1b2c3d/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=${SIG}`, + SIG, + 'secret_query_param', + ], + ['Zapier catch hook', `https://hooks.zapier.com/hooks/catch/1234567/${ZAPIER_CODE}/`, ZAPIER_CODE, 'webhook_token'], + ['Zapier catch hook, silent', `https://hooks.zapier.com/hooks/catch/1234567/${ZAPIER_CODE}/silent/`, ZAPIER_CODE, 'webhook_token'], + ['Make webhook', `https://hook.eu1.make.com/${MAKE_TOKEN}`, MAKE_TOKEN, 'webhook_token'], + ['Integromat webhook', `https://hook.integromat.com/${MAKE_TOKEN}`, MAKE_TOKEN, 'webhook_token'], + ['Make on Celonis', `https://hook.us2.make.celonis.com/${MAKE_TOKEN}`, MAKE_TOKEN, 'webhook_token'], + ['REST API with user:password@', 'https://apiuser:Pa55w0rd-1@api.example.com/v1', 'Pa55w0rd-1', 'url_password'], + ['user:password@ with a port and an encoded character', 'https://svc:p%40ss42@erp.example.com:8443/odata/', 'p%40ss42', 'url_password'], + ['password next to a {{VAR}} user name', 'https://{{API_USER}}:hunter2pass@api.example.com', 'hunter2pass', 'url_password'], + ]; + + it.each(POSITIVE)('finds the secret of a %s', (_label, url, secret, kind) => { + const found = findSecretLiterals(url); + expect(found).toHaveLength(1); + expect(found[0].kind).toBe(kind); + expect(found[0].value).toBe(secret); + expect(url.slice(found[0].start, found[0].end)).toBe(secret); + expect(found[0].pattern).not.toContain(secret); + }); + + it('also finds the Telegram token and the Google Chat key and token it already knew', () => { + expect(findSecretLiterals(`https://api.telegram.org/bot${TG}`)[0].kind).toBe('telegram_bot_token'); + const chatToken = ['3D', 'aBcDeFgHiJkLmNoPqRsT', '_uVwXyZ0123456789%3D'].join(''); + const chat = findSecretLiterals( + `https://chat.googleapis.com/v1/spaces/AAAAbCdEfGh/messages?key=${GOOGLE}&token=${chatToken}`, + ); + expect(chat.map((f) => f.value)).toEqual([GOOGLE, chatToken]); + }); + + it('describes a finding without the secret', () => { + const [bitrix] = findSecretLiterals(`https://portal.bitrix24.com/rest/1/${BITRIX_CODE}/`); + expect(bitrix.pattern).toBe('Bitrix24 webhook ***(16)'); + const [password] = findSecretLiterals('https://apiuser:Pa55w0rd-1@api.example.com'); + expect(password.pattern).toBe('user:***(10)@'); + }); + + it.each([ + // plain API base URLs + 'https://api.example.com/v1', + 'https://api.example.com/rest/v1/users', + 'https://jira.example.com/rest/api/2/issue', + 'https://acme.atlassian.net/rest/agile/1.0/board/123', + 'https://shop.example.com/rest/V1/products', + 'https://shop.example.com/rest/default/V1/orders', + 'https://erp.example.com/rest/2.0/', + 'https://erp.example.com/rest/1/crm.deal.list', + 'https://erp.example.com/rest/1/abcdefghijklmnop/', + 'https://erp.example.com/rest/1/0123456789abcdef/', + 'https://erp.example.com/rest/1/1234567890123456/', + 'https://erp.example.com/rest/1/k2bxa8g5n4ghvqgoextra/', + 'https://portal.bitrix24.com/rest/', + 'https://portal.bitrix24.com/rest/1/', + 'https://portal.bitrix24.com/rest/api/crm.deal.list', + 'https://portal.bitrix24.com/rest/1/department/', + 'https://portal.bitrix24.com/rest/1/12345678/', + 'https://notbitrix24.example.com/rest/1/abc/', + 'https://slack.com/api/chat.postMessage', + 'https://hooks.slack.com/services/', + // Slack's own docs example, assembled so that push protection does not take it for a leak + `https://hooks.slack.com/services/T00000000/B00000000/${'X'.repeat(24)}`, + 'https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/short', + 'https://discord.com/api/v10/channels/123456789012345678/messages', + 'https://discord.com/api/webhooks/123456789012345678', + 'https://discord.com/api/webhooks/123456789012345678/short', + 'https://graph.microsoft.com/v1.0/teams/abc/channels', + 'https://acme.webhook.office.com/webhookb2/abc', + 'https://www.example.com/docs/IncomingWebhook/how-to-set-up-one', + 'https://outlook.office.com/api/v2.0/me/messages', + 'https://hooks.zapier.com/hooks/catch/', + 'https://hooks.zapier.com/hooks/catch/1234567/', + 'https://zapier.com/hooks/catch/1234567/abc1d2e/', + 'https://www.make.com/en/help/tools/webhooks', + 'https://eu1.make.com/api/v2/scenarios', + 'https://hook.eu1.make.com/short', + 'https://hook.eu1.make.com/{{MAKE_WEBHOOK_TOKEN}}', + 'https://logic.azure.com/workflows/abc/triggers/manual/paths/invoke?api-version=2016-06-01', + // placeholders, masks and user names alone + 'https://portal.bitrix24.com/rest/1/{{BITRIX24_WEBHOOK_CODE}}/', + '{{BITRIX24_WEBHOOK_URL}}', + 'https://{{API_USER}}:{{API_PASSWORD}}@api.example.com', + 'https://apiuser:{{API_PASSWORD}}@api.example.com', + 'https://apiuser:********@api.example.com', + 'https://apiuser@api.example.com', + 'https://apiuser:@api.example.com', + 'https://portal.bitrix24.com/rest/1/********/', + // an @ or a colon that is not userinfo + 'https://api.example.com:8443?email=someone@example.com', + 'https://api.example.com/users/someone@example.com', + 'https://api.example.com/v1?from=a:b@c', + 'mailto:someone@example.com', + 'someone:secretish@example.com', + ])('does not flag %s', (url) => { + expect(findSecretLiterals(url)).toEqual([]); + }); + + it('redacts a webhook URL quoted in free text', () => { + const text = `POST https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/${SLACK_HOOK} failed`; + expect(redactSecretLiterals(text)).toBe( + 'POST https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/[REDACTED] failed', + ); + }); +}); + describe('looksHighEntropy', () => { it('rejects UUIDs, hex and short tokens', () => { expect(looksHighEntropy('123e4567e89b12d3a456426614174000')).toBe(false); diff --git a/packages/backend/src/common/secret-literals.util.ts b/packages/backend/src/common/secret-literals.util.ts index 2692657f7..1fbb0bfa2 100644 --- a/packages/backend/src/common/secret-literals.util.ts +++ b/packages/backend/src/common/secret-literals.util.ts @@ -25,6 +25,8 @@ export type SecretKind = | 'jwt' | 'secret_query_param' | 'credential_header' + | 'webhook_token' + | 'url_password' | 'high_entropy'; export interface SecretFinding { @@ -301,6 +303,10 @@ function redactShape(kind: SecretKind, value: string, label: string): string { return `${label}=***(${n})`; case 'credential_header': return `${label}: ***(${n})`; + case 'webhook_token': + return `${label} webhook ***(${n})`; + case 'url_password': + return `user:***(${n})@`; case 'high_entropy': default: return `***(${n} chars, high-entropy)`; @@ -333,6 +339,167 @@ function dedupe(findings: SecretFinding[]): SecretFinding[] { return out; } +/** + * Webhook URLs whose path is the credential: whoever holds the URL can post + * as the account, so the token in it is a password, not an id. Each rule is + * tied to the vendor's own host and the exact path shape the vendor issues, + * so an ordinary API base URL never matches. Only the secret segment is + * returned; the host and the ids around it stay readable. + * + * Incoming webhooks that carry their secret in a query parameter (Power + * Automate and Logic Apps `sig=`, Google Chat `key=`/`token=`) are found by + * the query rule, and Telegram's `bot` by its own rule above. + */ +interface WebhookRule { + label: string; + host: RegExp; + /** The secret's offsets within the path, or null. */ + match: (path: string) => { start: number; end: number } | null; +} + +/** + * `prefix` then `secret` (then `/` or the end of the path): the secret's + * offsets. `accept`, when given, must also say yes to the secret. + */ +function segmentAfter(re: RegExp, accept?: (secret: string) => boolean): WebhookRule['match'] { + return (path) => { + const m = re.exec(path); + if (!m || (accept && !accept(m[2]))) return null; + const start = (m.index ?? 0) + m[1].length; + return { start, end: start + m[2].length }; + }; +} + +const WEBHOOK_RULES: WebhookRule[] = [ + // Bitrix24 inbound webhook: /rest///. The + // code is random letters and digits; a word there (`/rest/1/department/`) + // is not one. + { + label: 'Bitrix24', + host: /(?:^|\.)bitrix24\.[a-z]{2,3}(?:\.[a-z]{2})?$/, + match: segmentAfter( + /(\/rest\/\d{1,10}\/)([A-Za-z0-9_]{8,64})(?=\/|$)/, + (code) => /[A-Za-z]/.test(code) && /[0-9]/.test(code), + ), + }, + // Slack incoming webhook (/services/T…/B…/) and workflow triggers. + { + label: 'Slack', + host: /^hooks\.slack(?:-gov)?\.com$/, + match: segmentAfter( + /^(\/(?:services|workflows|triggers)\/(?:[A-Za-z0-9]{1,32}\/){1,4})([A-Za-z0-9]{16,128})(?=\/?$)/, + ), + }, + // Discord: /api[/v10]/webhooks// + { + label: 'Discord', + host: /^(?:(?:ptb|canary)\.)?discord(?:app)?\.com$/, + match: segmentAfter(/^(\/api(?:\/v\d{1,2})?\/webhooks\/\d{15,22}\/)([A-Za-z0-9_-]{20,128})(?=\/|$)/), + }, + // Microsoft Teams (Office 365 connector): …/IncomingWebhook//[/V2…] + { + label: 'Microsoft Teams', + host: /(?:^|\.)webhook\.office\.com$|^outlook\.office(?:365)?\.com$/, + match: (path) => { + const marker = '/IncomingWebhook/'; + const at = path.indexOf(marker); + if (at === -1) return null; + const start = at + marker.length; + const secret = path.slice(start).replace(/\/+$/, ''); + if (!/^[A-Za-z0-9@._/-]{16,512}$/.test(secret)) return null; + return { start, end: start + secret.length }; + }, + }, + // Zapier catch hook: /hooks/catch/// + { + label: 'Zapier', + host: /^hooks\.zapier\.com$/, + match: segmentAfter(/^(\/hooks\/(?:catch|standard)\/\d{1,15}\/)([A-Za-z0-9]{4,64})(?=\/|$)/), + }, + // Make (formerly Integromat) custom webhook: hook..make.com/ + { + label: 'Make', + host: /^hook\.(?:[a-z0-9-]{1,20}\.)?(?:make\.com|integromat\.com|make\.celonis\.com)$/, + match: segmentAfter(/^(\/)([A-Za-z0-9]{16,64})(?=\/|$)/), + }, +]; + +/** + * A Bitrix24 webhook on a self-hosted portal (any host): `/rest//` + * followed by the 16-character webhook code, lower case letters and digits, + * with both and not hex only (a hex id is a resource, not a code). + */ +const BITRIX_ANY_HOST = /\/rest\/\d{1,10}\/([a-z0-9]{16})(?=[/?#\s"'`]|$)/g; + +function isBitrixCode(code: string): boolean { + return /[a-z]/.test(code) && /[0-9]/.test(code) && !HEX.test(code); +} + +/** `XXXXXXXX…`, as in vendor docs: an example, not a credential. */ +function isRepeatedChar(value: string): boolean { + return /^(.)\1+$/.test(value); +} + +/** An absolute URL in free text: scheme, `://`, then up to the next space or quote. */ +const ABSOLUTE_URL = /(?`]{1,4096}/g; + +/** What a masked password slot holds (database-url-credentials.util.ts URL_PASSWORD_MASK). */ +const MASKED_PASSWORD = /^\*+$/; + +/** + * Secrets in an absolute URL's userinfo and in a known webhook path. + * `masked` has its placeholders blanked out; offsets refer to `text`. + */ +function findUrlSecrets(text: string, masked: string): SecretFinding[] { + const found: SecretFinding[] = []; + for (const m of masked.matchAll(ABSOLUTE_URL)) { + const url = m[0]; + const offset = m.index ?? 0; + const authStart = url.indexOf('://') + 3; + const rest = url.slice(authStart); + // The authority ends at the path, the query or the fragment: an `@` in + // `?email=a@b.example` is not userinfo. + const stop = rest.search(/[/?#]/); + const authority = stop === -1 ? rest : rest.slice(0, stop); + const at = authority.lastIndexOf('@'); + + // scheme://user:password@host: the password, never the user name. + if (at > 0) { + const userinfo = authority.slice(0, at); + const colon = userinfo.indexOf(':'); + const password = colon === -1 ? '' : userinfo.slice(colon + 1); + if (password && !password.includes(FILLER) && !MASKED_PASSWORD.test(password)) { + const start = offset + authStart + colon + 1; + found.push(finding('url_password', text, start, start + password.length, 'password')); + } + } + + const host = (at === -1 ? authority : authority.slice(at + 1)).replace(/:\d*$/, '').toLowerCase(); + if (host.includes(FILLER)) continue; + const tail = rest.slice(authority.length); + const queryAt = tail.search(/[?#]/); + const path = queryAt === -1 ? tail : tail.slice(0, queryAt); + const pathOffset = offset + authStart + authority.length; + for (const rule of WEBHOOK_RULES) { + if (!rule.host.test(host)) continue; + const span = rule.match(path); + if (!span) continue; + const secret = path.slice(span.start, span.end); + if (secret.includes(FILLER) || isRepeatedChar(secret)) continue; + found.push( + finding('webhook_token', text, pathOffset + span.start, pathOffset + span.end, rule.label), + ); + } + } + + for (const m of masked.matchAll(BITRIX_ANY_HOST)) { + if (!isBitrixCode(m[1])) continue; + const start = (m.index ?? 0) + m[0].length - m[1].length; + found.push(finding('webhook_token', text, start, start + m[1].length, 'Bitrix24')); + } + return found; +} + export interface FindOptions { /** Include the high-entropy heuristic (default true). */ highEntropy?: boolean; @@ -348,7 +515,9 @@ export function findSecretLiterals(input: string, opts: FindOptions = {}): Secre if (typeof input !== 'string' || input.length < 8) return []; const text = input.length > MAX_SCAN_LENGTH ? input.slice(0, MAX_SCAN_LENGTH) : input; const masked = maskPlaceholders(text); - const found: SecretFinding[] = []; + // First, so that a webhook token the long-random-token rule would also + // catch is reported (and named) as what it is. + const found: SecretFinding[] = findUrlSecrets(text, masked); for (const m of masked.matchAll(TELEGRAM)) { // Without `bot` in front, `:` is also an AWS ARN tail diff --git a/packages/backend/src/connectors/base-url-secrets.util.spec.ts b/packages/backend/src/connectors/base-url-secrets.util.spec.ts new file mode 100644 index 000000000..eb87a4ee0 --- /dev/null +++ b/packages/backend/src/connectors/base-url-secrets.util.spec.ts @@ -0,0 +1,97 @@ +import { + BASE_URL_SECRET_MASK, + baseUrlSecrets, + hasHttpBaseUrl, + keepMaskedBaseUrl, + maskBaseUrlSecrets, +} from './base-url-secrets.util'; +import { toPublicConnector } from './connector-secrets.util'; +import { toExportEntry } from './connector-export.util'; + +const BITRIX = ['k2bx', 'a8g5', 'n4gh', 'vqgo'].join(''); +const BITRIX_URL = `https://portal.bitrix24.com/rest/1/${BITRIX}/`; +const OPAQUE = 'q8ZtW3nRk2LxV9pMbH4cJs7YdF6gTe1A'; + +describe('base URL secrets', () => { + it('checks the HTTP connector types only', () => { + for (const type of ['REST', 'GRAPHQL', 'SOAP', 'MCP', 'ODATA']) expect(hasHttpBaseUrl(type)).toBe(true); + for (const type of ['DATABASE', 'EMAIL', 'FILE_SEARCH', 'WEBHOOK', undefined]) expect(hasHttpBaseUrl(type)).toBe(false); + }); + + it('uses every rule of a save but the long-random-token one', () => { + expect(baseUrlSecrets(BITRIX_URL)).toHaveLength(1); + expect(baseUrlSecrets('https://maps.example.com/api?key=a1b2c3d4e5f6')).toHaveLength(1); + expect(baseUrlSecrets(`https://api.example.com/files/x/${OPAQUE}`)).toEqual([]); + expect(baseUrlSecrets(null)).toEqual([]); + }); + + it('masks only the secret, and leaves references and clean URLs alone', () => { + expect(maskBaseUrlSecrets(BITRIX_URL)).toBe(`https://portal.bitrix24.com/rest/1/${BASE_URL_SECRET_MASK}/`); + expect(maskBaseUrlSecrets('https://u:Pa55w0rd-1@api.example.com/?token=abc123def456')).toBe( + 'https://u:********@api.example.com/?token=********', + ); + expect(maskBaseUrlSecrets('https://portal.bitrix24.com/rest/1/{{B_WEBHOOK_TOKEN}}/')).toBe( + 'https://portal.bitrix24.com/rest/1/{{B_WEBHOOK_TOKEN}}/', + ); + expect(maskBaseUrlSecrets('https://api.example.com/v1')).toBe('https://api.example.com/v1'); + }); + + describe('an edit made against the masked view', () => { + it('keeps the stored URL when the masked one comes back unchanged', () => { + expect(keepMaskedBaseUrl(maskBaseUrlSecrets(BITRIX_URL), BITRIX_URL)).toBe(BITRIX_URL); + }); + + it('takes a retyped URL as sent', () => { + const other = `https://portal.bitrix24.com/rest/2/${BITRIX}/`; + expect(keepMaskedBaseUrl(other, BITRIX_URL)).toBe(other); + }); + + it('cannot rebuild a URL edited around the mask', () => { + expect(keepMaskedBaseUrl(`https://other.bitrix24.com/rest/1/${BASE_URL_SECRET_MASK}/`, BITRIX_URL)).toBeNull(); + }); + + it('changes nothing when nothing stored was masked', () => { + expect(keepMaskedBaseUrl('https://api.example.com/v2', 'https://api.example.com/v1')).toBe( + 'https://api.example.com/v2', + ); + }); + }); + + describe('API output', () => { + const connector = { + id: 'c1', + name: 'Bitrix', + type: 'REST', + baseUrl: BITRIX_URL, + headers: null, + envVars: { BITRIX_WEBHOOK_TOKEN: BITRIX, PORTAL: 'portal' }, + config: { adapterSlug: 'custom', baseUrlBaseline: BITRIX_URL }, + authConfig: 'encrypted', + tools: [], + }; + + it('never returns the secret of a base URL, to anyone', () => { + const out = toPublicConnector(connector); + expect(out.baseUrl).toBe(`https://portal.bitrix24.com/rest/1/${BASE_URL_SECRET_MASK}/`); + expect((out.config as any).baseUrlBaseline).toBe(out.baseUrl); + expect((out.config as any).adapterSlug).toBe('custom'); + expect(out.envVars).toEqual({ BITRIX_WEBHOOK_TOKEN: '', PORTAL: 'portal' }); + expect(out.maskedEnvVars).toEqual(['BITRIX_WEBHOOK_TOKEN']); + expect(JSON.stringify(out)).not.toContain(BITRIX); + }); + + it('nor in an export without secrets', () => { + expect(JSON.stringify(toExportEntry(connector, false))).not.toContain(BITRIX); + }); + + it('shows a repaired connector as it is stored', () => { + const repaired = { ...connector, baseUrl: 'https://portal.bitrix24.com/rest/1/{{BITRIX_WEBHOOK_TOKEN}}/', config: null }; + expect(toPublicConnector(repaired).baseUrl).toBe(repaired.baseUrl); + }); + + it('leaves a DATABASE connection string to its own masking', () => { + const db = { ...connector, type: 'DATABASE', baseUrl: 'postgresql://u:s3cret@db.example.com/x', config: null }; + expect(toPublicConnector(db).baseUrl).toBe('postgresql://u:********@db.example.com/x'); + }); + }); +}); diff --git a/packages/backend/src/connectors/base-url-secrets.util.ts b/packages/backend/src/connectors/base-url-secrets.util.ts new file mode 100644 index 000000000..75f8d84da --- /dev/null +++ b/packages/backend/src/connectors/base-url-secrets.util.ts @@ -0,0 +1,61 @@ +import { findSecretLiterals, type FindOptions, type SecretFinding } from '../common/secret-literals.util'; +import { SECRET_GUARDED_TYPES } from './secret-extraction.util'; + +/** + * A secret written into an HTTP connector's base URL: a Bitrix24, Slack, + * Discord, Teams, Zapier or Make webhook URL, a Telegram bot token, a + * `?api_key=` style parameter, a known key shape, or `user:password@`. + * + * Saving a connector moves such a secret into an encrypted variable and + * stores `{{VAR}}` in its place (SecretExtractor). This file covers what was + * stored before that, or what a save could not move: + * + * - the start-up repair (`ConnectorsService.repairBaseUrlSecrets`) moves it, + * with these rules; + * - until then, the API shows the secret as `********` (`toPublicConnector`), + * and a form that sends the masked URL back unchanged keeps the stored one. + * + * These rules are every rule a save applies except the long-random-token + * heuristic: a save tells the user what moved, a start-up pass does it + * silently on every instance, so it only acts on shapes that are certain. + */ +export const BASE_URL_SECRET_RULES: FindOptions = { highEntropy: false }; + +/** What the API shows in place of a secret in a base URL. */ +export const BASE_URL_SECRET_MASK = '********'; + +/** Connector types whose base URL is an HTTP address (and so is checked). */ +export function hasHttpBaseUrl(type: unknown): boolean { + return typeof type === 'string' && SECRET_GUARDED_TYPES.has(type); +} + +/** The secrets in a base URL, by the rules above. */ +export function baseUrlSecrets(url: unknown): SecretFinding[] { + if (typeof url !== 'string' || !url) return []; + return findSecretLiterals(url, BASE_URL_SECRET_RULES); +} + +/** The base URL with every secret replaced by the mask. `{{VAR}}` references stay. */ +export function maskBaseUrlSecrets(url: string): string { + const found = baseUrlSecrets(url); + let out = url; + for (const f of [...found].sort((a, b) => b.start - a.start)) { + out = `${out.slice(0, f.start)}${BASE_URL_SECRET_MASK}${out.slice(f.end)}`; + } + return out; +} + +/** + * Apply an edit made against the masked view. The masked URL sent back as it + * was shown means "unchanged": the stored URL is kept (and the save then + * moves its secret into a variable). A URL that still holds the mask but was + * edited elsewhere cannot be put back together: null, and the caller asks for + * the full address. Anything else is taken as sent. + */ +export function keepMaskedBaseUrl(incoming: string, stored: string): string | null { + if (typeof incoming !== 'string' || typeof stored !== 'string') return incoming; + const masked = maskBaseUrlSecrets(stored); + if (masked === stored) return incoming; + if (incoming === masked) return stored; + return incoming.includes(BASE_URL_SECRET_MASK) ? null : incoming; +} diff --git a/packages/backend/src/connectors/connector-export.util.ts b/packages/backend/src/connectors/connector-export.util.ts index 2760dea0d..8b7595236 100644 --- a/packages/backend/src/connectors/connector-export.util.ts +++ b/packages/backend/src/connectors/connector-export.util.ts @@ -9,8 +9,9 @@ export const EXPORT_FORMAT_VERSION = '1.0'; * One connector as it appears in an export file. authConfig is never * exported. Secret env vars and headers are kept only when `includeSecrets` * is set (admins); otherwise they are left empty and named in - * `maskedEnvVars` / `maskedHeaders`, and a DATABASE connection string comes - * back with its password masked. + * `maskedEnvVars` / `maskedHeaders`, a DATABASE connection string comes + * back with its password masked, and a secret in an HTTP base URL as + * `********`. */ export function toExportEntry(c: any, includeSecrets: boolean) { const masked = includeSecrets ? null : toPublicConnector(c); @@ -22,7 +23,7 @@ export function toExportEntry(c: any, includeSecrets: boolean) { authType: c.authType, specUrl: c.specUrl, headers: masked ? masked.headers : c.headers, - config: c.config, + config: masked ? masked.config : c.config, envVars: masked ? masked.envVars : c.envVars, ...(masked ? { maskedEnvVars: masked.maskedEnvVars, maskedHeaders: masked.maskedHeaders } diff --git a/packages/backend/src/connectors/connector-secrets.util.ts b/packages/backend/src/connectors/connector-secrets.util.ts index a7a5edfff..0aa2fc3eb 100644 --- a/packages/backend/src/connectors/connector-secrets.util.ts +++ b/packages/backend/src/connectors/connector-secrets.util.ts @@ -1,5 +1,6 @@ import { getAdapter } from '../adapters/catalog'; import { maskUrlPassword } from './database-url-credentials.util'; +import { hasHttpBaseUrl, maskBaseUrlSecrets } from './base-url-secrets.util'; /** * Which connector environment variables and headers hold credentials, and how @@ -266,7 +267,9 @@ export function maskHeaders( * non-secret OAuth settings have their own endpoint (`GET :id/oauth-config`). * A DATABASE connection string comes back with its password masked; new * connectors no longer store one there (database-url-credentials.util.ts), - * this covers the ones saved before. + * this covers the ones saved before. Likewise a secret in an HTTP base URL + * (a webhook token, a key, `user:password@`) comes back as `********` + * (base-url-secrets.util.ts). */ export function toPublicConnector< T extends ConnectorLike & { envVars?: unknown; authConfig?: unknown }, @@ -285,12 +288,23 @@ export function toPublicConnector< webhookSecret: _webhookSecret, ...rest } = connector as T & { authStatusRef?: unknown; webhookSecret?: unknown }; - const { type, baseUrl } = connector as { type?: unknown; baseUrl?: unknown }; + const { type, baseUrl, config } = connector as { type?: unknown; baseUrl?: unknown; config?: unknown }; + // An HTTP base URL can carry a webhook token, a key or `user:password@` + // that was stored before saves moved it into a variable (the start-up + // repair moves it too): shown masked to everyone, admins included. + const httpMasked = hasHttpBaseUrl(type) && typeof baseUrl === 'string' ? maskBaseUrlSecrets(baseUrl) : null; + const baseline = (config as { baseUrlBaseline?: unknown } | null | undefined)?.baseUrlBaseline; + const maskedBaseline = + hasHttpBaseUrl(type) && typeof baseline === 'string' ? maskBaseUrlSecrets(baseline) : null; return { ...rest, ...(type === 'DATABASE' && typeof baseUrl === 'string' ? { baseUrl: maskUrlPassword(baseUrl) } : {}), + ...(httpMasked !== null && httpMasked !== baseUrl ? { baseUrl: httpMasked } : {}), + ...(maskedBaseline !== null && maskedBaseline !== baseline + ? { config: { ...(config as Record), baseUrlBaseline: maskedBaseline } } + : {}), envVars: env.envVars, headers: hdr.headers, maskedEnvVars: env.maskedEnvVars, diff --git a/packages/backend/src/connectors/connectors.controller.ts b/packages/backend/src/connectors/connectors.controller.ts index 3549295d9..870ac3fae 100644 --- a/packages/backend/src/connectors/connectors.controller.ts +++ b/packages/backend/src/connectors/connectors.controller.ts @@ -118,6 +118,7 @@ import { mergeSummaries, type SecretMoveSummary, } from './secret-extraction.util'; +import { hasHttpBaseUrl, keepMaskedBaseUrl } from './base-url-secrets.util'; import { MemberVisibilityService, canSeeConnector, @@ -1632,6 +1633,18 @@ export class ConnectorsController { // The connection string was shown with its password masked. data.baseUrl = keepMaskedUrlPassword(dto.baseUrl, connector.baseUrl); } + if (hasHttpBaseUrl(connector.type) && dto.baseUrl !== undefined) { + // A secret still stored in the base URL was shown as ********: the + // URL sent back as shown keeps the stored one (and the extraction + // below then moves the secret into a variable). + const kept = keepMaskedBaseUrl(dto.baseUrl, connector.baseUrl); + if (kept === null) { + throw new BadRequestException( + 'The base URL still contains a hidden secret (********). Type the full address again, secret included: it is then stored in an encrypted variable.', + ); + } + data.baseUrl = kept; + } if ((connector.type as string) === 'EMAIL') { data.authConfig = this.mergeEmailAuthConfig(connector.authConfig, dto.authConfig); } diff --git a/packages/backend/src/connectors/connectors.service.base-url-secrets-repair.spec.ts b/packages/backend/src/connectors/connectors.service.base-url-secrets-repair.spec.ts new file mode 100644 index 000000000..5fadd1e38 --- /dev/null +++ b/packages/backend/src/connectors/connectors.service.base-url-secrets-repair.spec.ts @@ -0,0 +1,350 @@ +import { Logger } from '@nestjs/common'; +import { ConnectorsService } from './connectors.service'; +import { openEnvVars, openEnvVarsStrict, sealEnvVars } from '../common/crypto/env-vars-at-rest'; +import { encrypt } from '../common/crypto/encryption.util'; +import { interpolateConnectorConfig } from '../common/env-interpolation.util'; +import { isSecretName } from './connector-secrets.util'; + +/** + * The boot pass for HTTP connectors whose base URL still carries a secret + * (a webhook token, a key, `user:password@`): it moves what a save would + * move into an encrypted variable, leaves `{{VAR}}` in the URL so calls are + * unchanged, and says nothing secret in the log. + */ +describe('ConnectorsService.repairBaseUrlSecrets', () => { + const KEY = 'k'.repeat(48); + const BITRIX = ['k2bx', 'a8g5', 'n4gh', 'vqgo'].join(''); + const SLACK = ['AbCdEfGh', 'IjKlMnOp', 'QrStUv12'].join(''); + const TG = `7123456789:${['AAH', 'k3jd9QwErTyUiOp', 'AsDfGhJkLzXcVbN', 'm12'].join('')}`; + const OPAQUE = 'q8ZtW3nRk2LxV9pMbH4cJs7YdF6gTe1A'; + const MCP_KEY = 'k3y4bc12def9'; + const PASSWORD = 'Pa55w0rd-1'; + + type Row = { + id: string; + name: string; + type: string; + baseUrl: string; + config: Record | null; + /** As stored: sealed, plain, or null. */ + envVars: unknown; + updatedAt: Date; + }; + + const at = new Date('2026-11-01T10:00:00.000Z'); + const make = (r: Omit & Partial): Row => ({ + config: null, + envVars: null, + updatedAt: at, + ...r, + }); + + /** Stored row, the base URL it ends with, and the variables it then has. */ + const MOVED: Array<[label: string, row: () => Row, baseUrl: string, envVars: Record]> = [ + [ + 'a Bitrix24 webhook URL', + () => make({ id: 'c-bitrix', name: 'Bitrix CRM', type: 'REST', baseUrl: `https://portal.bitrix24.com/rest/1/${BITRIX}/` }), + 'https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/', + { BITRIX_CRM_WEBHOOK_TOKEN: BITRIX }, + ], + [ + 'a Slack webhook URL, keeping the variables it has', + () => + make({ + id: 'c-slack', + name: 'Alerts', + type: 'REST', + baseUrl: `https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/${SLACK}`, + envVars: sealEnvVars({ CHANNEL: 'general', LIMIT: 5 }), + }), + 'https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/{{ALERTS_WEBHOOK_TOKEN}}', + { CHANNEL: 'general', LIMIT: 5, ALERTS_WEBHOOK_TOKEN: SLACK }, + ], + [ + 'a key in an MCP server URL', + () => make({ id: 'c-mcp', name: 'Gateway', type: 'MCP', baseUrl: `https://mcp.example.com/mcp?api_key=${MCP_KEY}` }), + 'https://mcp.example.com/mcp?api_key={{GATEWAY_API_KEY}}', + { GATEWAY_API_KEY: MCP_KEY }, + ], + [ + 'user:password@ in an OData URL, with plain stored variables', + () => + make({ + id: 'c-odata', + name: 'ERP', + type: 'ODATA', + baseUrl: `https://svc:${PASSWORD}@erp.example.com/odata/`, + envVars: { COMPANY: 'acme' }, + }), + 'https://svc:{{ERP_PASSWORD}}@erp.example.com/odata/', + { COMPANY: 'acme', ERP_PASSWORD: PASSWORD }, + ], + [ + 'a Telegram token a variable already holds', + () => + make({ + id: 'c-reuse', + name: 'Bot', + type: 'REST', + baseUrl: `https://api.telegram.org/bot${TG}`, + envVars: sealEnvVars({ TELEGRAM_BOT_TOKEN: TG }), + }), + 'https://api.telegram.org/bot{{TELEGRAM_BOT_TOKEN}}', + { TELEGRAM_BOT_TOKEN: TG }, + ], + ]; + + /** Never written: clean, references, the left-out heuristic, another type. */ + const UNTOUCHED: Array<() => Row> = [ + () => make({ id: 'c-clean', name: 'Clean', type: 'REST', baseUrl: 'https://api.example.com/v1' }), + () => + make({ + id: 'c-ref', + name: 'Ref', + type: 'REST', + baseUrl: 'https://portal.bitrix24.com/rest/1/{{B_WEBHOOK_TOKEN}}/', + envVars: sealEnvVars({ B_WEBHOOK_TOKEN: BITRIX }), + }), + () => make({ id: 'c-entropy', name: 'Opaque', type: 'REST', baseUrl: `https://api.example.com/hooks/${OPAQUE}` }), + () => make({ id: 'c-db', name: 'Db', type: 'DATABASE', baseUrl: `postgresql://u:${PASSWORD}@db.example.com/x` }), + ]; + + const SECRETS = [BITRIX, SLACK, TG.split(':')[1], MCP_KEY, PASSWORD, 'portal.bitrix24.com', '://']; + + let rows: Row[]; + let prisma: { connector: { findMany: jest.Mock; updateMany: jest.Mock }; $queryRaw: jest.Mock }; + let service: ConnectorsService; + let logged: string[]; + const row = (id: string) => rows.find((r) => r.id === id)!; + const envOf = (id: string) => openEnvVarsStrict(row(id).envVars); + + beforeEach(() => { + process.env.ENCRYPTION_KEY = KEY; + rows = [...MOVED.map(([, r]) => r()), ...UNTOUCHED.map((r) => r())]; + prisma = { + connector: { + findMany: jest.fn(async ({ where }: any) => + rows + .filter((r) => where.type.in.includes(r.type)) + .sort((a, b) => a.id.localeCompare(b.id)) + .map(({ id, name, type, baseUrl, config, updatedAt }) => ({ id, name, type, baseUrl, config, updatedAt })), + ), + // The guarded write, with the at-rest extension's encryption. + updateMany: jest.fn(async ({ where, data }: any) => { + const hit = rows.filter( + (r) => r.id === where.id && r.baseUrl === where.baseUrl && r.updatedAt.getTime() === where.updatedAt.getTime(), + ); + for (const r of hit) { + Object.assign(r, data, { updatedAt: new Date(r.updatedAt.getTime() + 1000) }); + if ('envVars' in data) r.envVars = sealEnvVars(data.envVars); + } + return { count: hit.length }; + }), + }, + $queryRaw: jest.fn(async (_strings: TemplateStringsArray, ids: string[]) => + rows.filter((r) => ids.includes(r.id)).map((r) => ({ id: r.id, env_vars: r.envVars })), + ), + }; + service = new ConnectorsService(prisma as any, { get: () => KEY } as any, {} as any, {} as any, {} as any, {} as any, {} as any); + logged = []; + for (const level of ['log', 'warn', 'error', 'debug', 'verbose'] as const) { + jest.spyOn(Logger.prototype, level).mockImplementation((...args: unknown[]) => { + logged.push(`${level}: ${args.map(String).join(' ')}`); + }); + } + }); + + afterEach(() => jest.restoreAllMocks()); + + it('reads the HTTP connectors, and the variables of the candidates only', async () => { + await service.repairBaseUrlSecrets(); + + expect(prisma.connector.findMany).toHaveBeenCalledTimes(1); + expect(prisma.connector.findMany.mock.calls[0][0].where.type.in.sort()).toEqual(['GRAPHQL', 'MCP', 'ODATA', 'REST', 'SOAP']); + expect(prisma.$queryRaw).toHaveBeenCalledTimes(1); + expect([...prisma.$queryRaw.mock.calls[0][1]].sort()).toEqual(['c-bitrix', 'c-mcp', 'c-odata', 'c-reuse', 'c-slack']); + }); + + it.each(MOVED)('moves %s into an encrypted variable', async (_label, stored, baseUrl, envVars) => { + const id = stored().id; + await service.repairBaseUrlSecrets(); + + expect(row(id).baseUrl).toBe(baseUrl); + expect(envOf(id)).toEqual(envVars); + // Encrypted at rest, and named so that the dashboard masks it. + for (const value of Object.values(envVars)) { + if (typeof value === 'string') expect(JSON.stringify(row(id).envVars)).not.toContain(value); + } + for (const name of Object.keys(envVars)) { + if (!['CHANNEL', 'LIMIT', 'COMPANY'].includes(name)) expect(isSecretName(name)).toBe(true); + } + }); + + it.each(MOVED)('keeps the URL a call sends for %s', async (_label, stored) => { + const before = stored().baseUrl; + const id = stored().id; + await service.repairBaseUrlSecrets(); + + const { config } = interpolateConnectorConfig( + { baseUrl: row(id).baseUrl }, + { method: 'GET', path: '/' }, + openEnvVars(row(id).envVars) as Record, + ); + expect(config.baseUrl).toBe(before); + }); + + it('does not rewrite the variables when one already holds the secret', async () => { + const sealed = row('c-reuse').envVars; + await service.repairBaseUrlSecrets(); + + const call = prisma.connector.updateMany.mock.calls.find(([arg]) => arg.where.id === 'c-reuse')![0]; + expect(call.data).toEqual({ baseUrl: 'https://api.telegram.org/bot{{TELEGRAM_BOT_TOKEN}}' }); + expect(row('c-reuse').envVars).toBe(sealed); + }); + + it('cleans the install-time baseline of a catalog connector with the same variable', async () => { + const url = `https://portal.bitrix24.com/rest/1/${BITRIX}/`; + row('c-bitrix').config = { adapterSlug: 'acme-crm', baseUrlBaseline: url, adapterVersion: '1.0.0' }; + + await service.repairBaseUrlSecrets(); + + expect(row('c-bitrix').config).toEqual({ + adapterSlug: 'acme-crm', + baseUrlBaseline: 'https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/', + adapterVersion: '1.0.0', + }); + expect(Object.keys(envOf('c-bitrix')!)).toEqual(['BITRIX_CRM_WEBHOOK_TOKEN']); + }); + + it('leaves everything else exactly as stored', async () => { + const before = UNTOUCHED.map((r) => ({ ...row(r().id) })); + await service.repairBaseUrlSecrets(); + + for (const stored of before) expect(row(stored.id)).toEqual(stored); + const written = prisma.connector.updateMany.mock.calls.map(([arg]) => arg.where.id); + expect(written).toEqual(expect.not.arrayContaining(before.map((r) => r.id))); + }); + + it('reports what it moved in one line with ids and counts', async () => { + const result = await service.repairBaseUrlSecrets(); + + expect(result).toEqual({ + moved: ['c-bitrix', 'c-mcp', 'c-odata', 'c-reuse', 'c-slack'], + leftAsIs: [], + failed: [], + }); + expect(logged).toEqual([ + 'log: Base URL secrets: secrets of 5 connectors moved into encrypted variables ' + + '(c-bitrix, c-mcp, c-odata, c-reuse, c-slack); 0 left as is; 0 failed', + ]); + }); + + it('changes nothing on a second run', async () => { + await service.repairBaseUrlSecrets(); + const after = rows.map((r) => ({ ...r })); + prisma.connector.updateMany.mockClear(); + prisma.$queryRaw.mockClear(); + + const second = await service.repairBaseUrlSecrets(); + + expect(prisma.connector.updateMany).not.toHaveBeenCalled(); + expect(prisma.$queryRaw).not.toHaveBeenCalled(); + expect(rows).toEqual(after); + expect(second).toEqual({ moved: [], leftAsIs: [], failed: [] }); + expect(logged.at(-1)).toBe( + 'log: Base URL secrets: secrets of 0 connectors moved into encrypted variables; 0 left as is; 0 failed', + ); + }); + + it('never writes a row whose variables it cannot decrypt', async () => { + row('c-slack').envVars = { $enc: encrypt(JSON.stringify({ CHANNEL: 'general' }), 'x'.repeat(48), 'connectors.env_vars') }; + const stored = { ...row('c-slack') }; + + const result = await service.repairBaseUrlSecrets(); + + expect(result.failed).toEqual(['c-slack']); + expect(row('c-slack')).toEqual(stored); + expect(result.moved).toContain('c-bitrix'); + expect(logged.at(-1)).toMatch(/^warn: Base URL secrets: .*; 1 failed \(c-slack\)$/); + }); + + it('leaves a row that was saved between the read and the write', async () => { + const read = prisma.connector.findMany.getMockImplementation()!; + prisma.connector.findMany.mockImplementation(async (arg: any) => { + const found = await read(arg); + row('c-bitrix').updatedAt = new Date(at.getTime() + 5000); + row('c-bitrix').envVars = sealEnvVars({ EDITED: 'yes' }); + return found; + }); + + const result = await service.repairBaseUrlSecrets(); + + expect(result.leftAsIs).toEqual(['c-bitrix']); + expect(row('c-bitrix').baseUrl).toBe(`https://portal.bitrix24.com/rest/1/${BITRIX}/`); + expect(envOf('c-bitrix')).toEqual({ EDITED: 'yes' }); + }); + + it('goes on with the other rows when one write fails', async () => { + const write = prisma.connector.updateMany.getMockImplementation()!; + prisma.connector.updateMany.mockImplementation(async (arg: any) => { + if (arg.where.id === 'c-mcp') { + // A Prisma message quotes the arguments of the call. + throw Object.assign(new Error(`Invalid invocation: where: { baseUrl: "${arg.where.baseUrl}" }`), { code: 'P2028' }); + } + return write(arg); + }); + + const result = await service.repairBaseUrlSecrets(); + + expect(result.failed).toEqual(['c-mcp']); + expect(result.moved).toEqual(['c-bitrix', 'c-odata', 'c-reuse', 'c-slack']); + expect(row('c-mcp').baseUrl).toBe(`https://mcp.example.com/mcp?api_key=${MCP_KEY}`); + expect(logged[0]).toBe( + 'warn: Connector c-mcp: moving the secret in its base URL failed (P2028), the connector is left as is', + ); + }); + + it('does not throw when the query fails, and says only what kind of error it was', async () => { + prisma.connector.findMany.mockRejectedValue( + Object.assign(new Error(`connect failed https://portal.bitrix24.com/rest/1/${BITRIX}/`), { code: 'P1001' }), + ); + + await expect(service.repairBaseUrlSecrets()).resolves.toEqual({ moved: [], leftAsIs: [], failed: [] }); + expect(logged).toEqual(['error: Base URL secrets not checked: P1001']); + }); + + it('runs at start-up after the database pass, without holding the start up', async () => { + const read = prisma.connector.findMany.getMockImplementation()!; + const order: string[] = []; + prisma.connector.findMany.mockImplementation(async (arg: any) => { + // The database pass filters on one type; this pass on a list. + if (typeof arg.where.type === 'string') { + order.push('database'); + return []; + } + order.push('base url'); + return read(arg); + }); + + expect(service.onApplicationBootstrap()).toBeUndefined(); + expect(order).toEqual(['database']); + for (let i = 0; i < 10; i++) await new Promise((resolve) => setImmediate(resolve)); + + expect(order).toEqual(['database', 'base url']); + expect(row('c-bitrix').baseUrl).toBe('https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/'); + }); + + it('logs no URL, host or secret, whatever happens', async () => { + row('c-slack').envVars = { $enc: encrypt('{}', 'x'.repeat(48), 'connectors.env_vars') }; + const write = prisma.connector.updateMany.getMockImplementation()!; + prisma.connector.updateMany.mockImplementation(async (arg: any) => { + if (arg.where.id === 'c-odata') throw new Error(`update failed for ${arg.where.baseUrl} -> ${arg.data.baseUrl}`); + return write(arg); + }); + + await service.repairBaseUrlSecrets(); + + const text = logged.join('\n'); + for (const secret of SECRETS) expect(text).not.toContain(secret); + }); +}); diff --git a/packages/backend/src/connectors/connectors.service.ts b/packages/backend/src/connectors/connectors.service.ts index 542bdf1a4..a96550923 100644 --- a/packages/backend/src/connectors/connectors.service.ts +++ b/packages/backend/src/connectors/connectors.service.ts @@ -19,6 +19,8 @@ import { SoapEngine, WsdlReadError } from './engines/soap.engine'; import { wsdlUrlForLog } from './parsers/wsdl.parser'; import { connectorSecretValues } from './connector-secrets.util'; import { moveUrlCredentials, urlUserinfo } from './database-url-credentials.util'; +import { BASE_URL_SECRET_RULES, baseUrlSecrets } from './base-url-secrets.util'; +import { SECRET_GUARDED_TYPES, SecretExtractor } from './secret-extraction.util'; import { GraphqlEngine } from './engines/graphql.engine'; import { DatabaseEngine, assertSafeSqlIdentifierVars } from './engines/database.engine'; import { McpClientEngine } from './engines/mcp-client.engine'; @@ -74,6 +76,12 @@ function errorKind(err: unknown): string { return typeof name === 'string' && name ? name : 'Error'; } +/** A catalog connector's install-time base URL (`config.baseUrlBaseline`), or null. */ +function baselineOf(config: unknown): string | null { + const value = (config as { baseUrlBaseline?: unknown } | null | undefined)?.baseUrlBaseline; + return typeof value === 'string' ? value : null; +} + /** Connector ids for a log line: the first few, then how many more. */ function idsForLog(ids: string[], max = 20): string { if (ids.length === 0) return ''; @@ -111,10 +119,14 @@ export class ConnectorsService implements OnApplicationBootstrap { onApplicationBootstrap() { // Not awaited, so a large table never holds up the start. The pass // catches its own errors; the catch here is for anything it did not - // foresee, so that nothing it does can stop the boot. - void this.repairDatabaseUrlCredentials().catch((err) => - this.logger.error(`Database connection strings not checked: ${errorKind(err)}`), - ); + // foresee, so that nothing it does can stop the boot. The base URL pass + // runs after the database one, so the two never read the table at once. + void this.repairDatabaseUrlCredentials() + .catch((err) => + this.logger.error(`Database connection strings not checked: ${errorKind(err)}`), + ) + .then(() => this.repairBaseUrlSecrets()) + .catch((err) => this.logger.error(`Base URL secrets not checked: ${errorKind(err)}`)); } async findAll(): Promise { @@ -445,6 +457,137 @@ export class ConnectorsService implements OnApplicationBootstrap { return { moved, leftAsIs, failed }; } + /** + * Move the secrets still written in stored HTTP base URLs (a Bitrix24, + * Slack, Discord, Teams, Zapier or Make webhook token, a Telegram bot + * token, a `?api_key=` value, `user:password@`) into the connector's + * encrypted variables, leaving `{{VAR}}` in the URL. A save has done this + * since the extraction existed (SecretExtractor), and for webhook URLs and + * userinfo since its rules learned them; connectors stored before kept the + * secret in the plaintext `base_url` until someone saved them. This does + * it for them at boot, like `repairDatabaseUrlCredentials`. + * + * - The rules are a save's, minus the long-random-token heuristic + * (base-url-secrets.util.ts): nobody sees a notice for what this pass + * moves, so it only moves shapes that are certain. Only the secret + * segment moves; host and path stay readable. `config.baseUrlBaseline` + * (catalog connectors) holds the same URL and gets the same variable. + * - Calls are unchanged: `{{VAR}}` in a base URL is replaced verbatim from + * the variables on every call (env-interpolation.util.ts), so the URL + * sent is byte for byte the one stored before. A variable that already + * holds the value is reused. + * - Variables are read as stored and decrypted strictly: a row whose + * variables cannot be decrypted is never written (its secret stays, and + * stays masked on read). + * - Instance-level maintenance, outside `tenantTx`, like the database + * pass. Each row is written by id, and only if its base URL and + * `updatedAt` are still what was read, so a save in between, or a + * second instance running the same pass, wins. A second run finds + * nothing to move. + * - Never throws. Logs connector ids and counts only: no URL, variable + * value or error message. + */ + async repairBaseUrlSecrets(): Promise<{ + moved: string[]; + leftAsIs: string[]; + failed: string[]; + }> { + const moved: string[] = []; + const leftAsIs: string[] = []; + const failed: string[] = []; + type Row = { + id: string; + name: string; + type: string; + baseUrl: string; + config: unknown; + updatedAt: Date; + }; + let candidates: Row[]; + let storedEnv: Map; + try { + const rows: Row[] = await this.prisma.connector.findMany({ + where: { type: { in: [...SECRET_GUARDED_TYPES] as ConnectorType[] } }, + select: { id: true, name: true, type: true, baseUrl: true, config: true, updatedAt: true }, + orderBy: { id: 'asc' }, + }); + candidates = rows.filter( + (r) => baseUrlSecrets(r.baseUrl).length > 0 || baseUrlSecrets(baselineOf(r.config)).length > 0, + ); + storedEnv = new Map(); + if (candidates.length > 0) { + // Raw on purpose: what is stored, before the at-rest extension, so + // that "cannot be decrypted" is told apart from "no variables". + const ids = candidates.map((r) => r.id); + const envRows = await this.prisma.$queryRaw>` + SELECT id, env_vars FROM connectors WHERE id = ANY(${ids})`; + for (const r of envRows) storedEnv.set(r.id, r.env_vars); + } + } catch (err) { + this.logger.error(`Base URL secrets not checked: ${errorKind(err)}`); + return { moved, leftAsIs, failed }; + } + + for (const row of candidates) { + const env = openEnvVarsStrict(storedEnv.get(row.id)); + if (env === null) { + failed.push(row.id); + this.logger.warn( + `Connector ${row.id}: its variables could not be read (wrong ENCRYPTION_KEY?), the secret in its base URL is left as is`, + ); + continue; + } + try { + const strings = Object.fromEntries( + Object.entries(env).filter(([, v]) => typeof v === 'string'), + ) as Record; + const secrets = new SecretExtractor(row.name, strings); + const baseUrl = secrets.extractUrl(row.baseUrl, 'baseUrl', BASE_URL_SECRET_RULES); + const baseline = baselineOf(row.config); + const cleanedBaseline = + baseline === null + ? null + : secrets.extractUrl(baseline, 'config.baseUrlBaseline', BASE_URL_SECRET_RULES); + if (baseUrl === row.baseUrl && cleanedBaseline === baseline) { + leftAsIs.push(row.id); + continue; + } + const data: Prisma.ConnectorUpdateManyMutationInput = { baseUrl }; + if (Object.keys(secrets.newEnvVars).length > 0) { + // Every stored key is kept, non-string values included; the + // extension encrypts the whole object on write. + data.envVars = { ...env, ...secrets.newEnvVars } as Prisma.InputJsonValue; + } + if (cleanedBaseline !== baseline) { + data.config = { + ...(row.config as Record), + baseUrlBaseline: cleanedBaseline, + } as Prisma.InputJsonValue; + } + const { count } = await this.prisma.connector.updateMany({ + where: { id: row.id, baseUrl: row.baseUrl, updatedAt: row.updatedAt }, + data, + }); + // No row: it was saved, or repaired by another instance, in between. + (count > 0 ? moved : leftAsIs).push(row.id); + } catch (err) { + failed.push(row.id); + this.logger.warn( + `Connector ${row.id}: moving the secret in its base URL failed (${errorKind(err)}), the connector is left as is`, + ); + } + } + + const summary = + `Base URL secrets: secrets of ${moved.length} connector${moved.length === 1 ? '' : 's'} ` + + `moved into encrypted variables${idsForLog(moved)}; ` + + `${leftAsIs.length} left as is${idsForLog(leftAsIs)}; ` + + `${failed.length} failed${idsForLog(failed)}`; + if (failed.length > 0) this.logger.warn(summary); + else this.logger.log(summary); + return { moved, leftAsIs, failed }; + } + /** * Merges `patch` into the connector's existing (decrypted) authConfig and * re-encrypts it, instead of replacing the whole object. Used by the OAuth diff --git a/packages/backend/src/connectors/secret-extraction.util.spec.ts b/packages/backend/src/connectors/secret-extraction.util.spec.ts index e98208edb..016da2999 100644 --- a/packages/backend/src/connectors/secret-extraction.util.spec.ts +++ b/packages/backend/src/connectors/secret-extraction.util.spec.ts @@ -6,6 +6,7 @@ import { } from './secret-extraction.util'; import { interpolateConnectorConfig } from '../common/env-interpolation.util'; import { CurlParser } from './parsers/curl.parser'; +import { isSecretName } from './connector-secrets.util'; const TG = `7123456789:${['AAH', 'k3jd9QwErTyUiOp', 'AsDfGhJkLzXcVbN', 'm12'].join('')}`; const GOOGLE = ['AI', 'zaSyB1x2y3z4A5B6C7D8E9F0gHiJkLmNoPqRs'].join(''); @@ -242,3 +243,80 @@ describe('SecretExtractor', () => { expect(mergeSummaries([{}, {}])).toEqual({}); }); }); + +describe('SecretExtractor: webhook URLs and URL passwords', () => { + const BITRIX = ['k2bx', 'a8g5', 'n4gh', 'vqgo'].join(''); + const SLACK = ['AbCdEfGh', 'IjKlMnOp', 'QrStUv12'].join(''); + const DISCORD = ['Xy1_Ab2-Cd3Ef4Gh5', 'Ij6Kl7Mn8Op9Qr0St', 'Uv1Wx2Yz3Ab4Cd5Ef', 'Gh6Ij7Kl8Mn9Op0Q'].join(''); + const GUID = '1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d'; + const HEX = ['0123456789ab', 'cdef01234567', '89abcdef'].join(''); + + /** Connector name, base URL as typed, what is stored, the variable and its value. */ + const CASES: Array<[name: string, typed: string, stored: string, variable: string, value: string]> = [ + [ + 'Bitrix CRM', + `https://portal.bitrix24.com/rest/1/${BITRIX}/`, + 'https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/', + 'BITRIX_CRM_WEBHOOK_TOKEN', + BITRIX, + ], + [ + 'Slack Webhook', + `https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/${SLACK}`, + 'https://hooks.slack.com/services/T0A1B2C3D/B0E1F2G3H/{{SLACK_WEBHOOK_TOKEN}}', + 'SLACK_WEBHOOK_TOKEN', + SLACK, + ], + [ + 'Alerts', + `https://discord.com/api/webhooks/123456789012345678/${DISCORD}`, + 'https://discord.com/api/webhooks/123456789012345678/{{ALERTS_WEBHOOK_TOKEN}}', + 'ALERTS_WEBHOOK_TOKEN', + DISCORD, + ], + [ + 'Teams', + `https://acme.webhook.office.com/webhookb2/${GUID}@${GUID}/IncomingWebhook/${HEX}/${GUID}/`, + `https://acme.webhook.office.com/webhookb2/${GUID}@${GUID}/IncomingWebhook/{{TEAMS_WEBHOOK_TOKEN}}/`, + 'TEAMS_WEBHOOK_TOKEN', + `${HEX}/${GUID}`, + ], + [ + 'Legacy ERP', + 'https://apiuser:Pa55w0rd-1@erp.example.com:8443/api/', + 'https://apiuser:{{LEGACY_ERP_PASSWORD}}@erp.example.com:8443/api/', + 'LEGACY_ERP_PASSWORD', + 'Pa55w0rd-1', + ], + ]; + + it.each(CASES)('%s: only the secret segment moves, into a variable the dashboard masks', (name, typed, stored, variable, value) => { + const x = new SecretExtractor(name, {}); + expect(x.extractUrl(typed, 'baseUrl')).toBe(stored); + expect(x.newEnvVars).toEqual({ [variable]: value }); + expect(isSecretName(variable)).toBe(true); + expect(JSON.stringify(x.summary())).not.toContain(value); + }); + + it.each(CASES)('%s: a call resolves the base URL exactly as typed', (name, typed) => { + const x = new SecretExtractor(name, {}); + const stored = x.extractUrl(typed, 'baseUrl'); + const { config } = interpolateConnectorConfig( + { baseUrl: stored }, + { method: 'POST', path: '/' }, + { OTHER: 'x', ...x.newEnvVars }, + ); + expect(config.baseUrl).toBe(typed); + }); + + it('leaves out the long-random-token rule when asked to (start-up repair)', () => { + const opaque = 'q8ZtW3nRk2LxV9pMbH4cJs7YdF6gTe1A'; + const x = new SecretExtractor('Acme', {}); + expect(x.extractUrl(`https://api.example.com/hooks/${opaque}`, 'baseUrl', { highEntropy: false })).toBe( + `https://api.example.com/hooks/${opaque}`, + ); + expect(x.extractUrl(`https://api.example.com/hooks/${opaque}`, 'baseUrl')).toBe( + 'https://api.example.com/hooks/{{ACME_SECRET_1}}', + ); + }); +}); diff --git a/packages/backend/src/connectors/secret-extraction.util.ts b/packages/backend/src/connectors/secret-extraction.util.ts index 07dd662ba..4620c7bf8 100644 --- a/packages/backend/src/connectors/secret-extraction.util.ts +++ b/packages/backend/src/connectors/secret-extraction.util.ts @@ -1,4 +1,5 @@ import { + type FindOptions, findSecretInHeader, findSecretInQueryParam, findSecretLiterals, @@ -224,6 +225,14 @@ export class SecretExtractor { case 'known_prefix': case 'jwt': return `${this.prefix}_${PREFIX_SUFFIX[f.label] ?? 'TOKEN'}`; + case 'webhook_token': + // `SLACK_WEBHOOK_TOKEN`, not `SLACK_WEBHOOK_WEBHOOK_TOKEN`. Either + // way the name holds WEBHOOK and TOKEN, so isSecretName masks it. + return /(^|_)WEBHOOK$/.test(this.prefix) + ? `${this.prefix}_TOKEN` + : `${this.prefix}_WEBHOOK_TOKEN`; + case 'url_password': + return `${this.prefix}_PASSWORD`; case 'high_entropy': default: return `${this.prefix}_SECRET_${++this.secretCounter}`; @@ -246,10 +255,13 @@ export class SecretExtractor { return out; } - /** A base URL, a path or a URL-valued setting. */ - extractUrl(url: string, field: string): string { + /** + * A base URL, a path or a URL-valued setting. `opts` narrows the rules + * (the start-up repair leaves out the long-random-token heuristic). + */ + extractUrl(url: string, field: string, opts?: FindOptions): string { if (typeof url !== 'string' || !url) return url; - return this.rewrite(url, findSecretLiterals(url), field); + return this.rewrite(url, findSecretLiterals(url, opts), field); } /** diff --git a/packages/backend/src/connectors/secret-guard.flows.spec.ts b/packages/backend/src/connectors/secret-guard.flows.spec.ts index fdc4c6302..88c075518 100644 --- a/packages/backend/src/connectors/secret-guard.flows.spec.ts +++ b/packages/backend/src/connectors/secret-guard.flows.spec.ts @@ -629,3 +629,90 @@ describe('logs', () => { expect(stripQuery('https://api.example.com/v1/users/123')).toBe('https://api.example.com/v1/users/123'); }); }); + +describe('a webhook URL as base URL (Bitrix24)', () => { + const CODE = ['k2bx', 'a8g5', 'n4gh', 'vqgo'].join(''); + const URL_TYPED = `https://portal.bitrix24.com/rest/1/${CODE}/`; + const URL_STORED = 'https://portal.bitrix24.com/rest/1/{{BITRIX_CRM_WEBHOOK_TOKEN}}/'; + + it('create: stores {{VAR}} and an encrypted variable, and answers without the code', async () => { + const { controller, connectorsService } = buildConnectors(); + const out: any = await controller.create(req(), { name: 'Bitrix CRM', type: 'REST' as any, baseUrl: URL_TYPED }); + const data = connectorsService.create.mock.calls[0][2]; + expect(data.baseUrl).toBe(URL_STORED); + expect(data.envVars).toEqual({ BITRIX_CRM_WEBHOOK_TOKEN: CODE }); + expect(out.baseUrl).toBe(URL_STORED); + expect(out.maskedEnvVars).toEqual(['BITRIX_CRM_WEBHOOK_TOKEN']); + expect(out.secretsNotice).toMatch(/BITRIX_CRM_WEBHOOK_TOKEN/); + expect(JSON.stringify(out)).not.toContain(CODE); + }); + + it('update: a retyped webhook URL moves the same way', async () => { + const { controller, connectorsService } = buildConnectors({ name: 'Bitrix CRM', baseUrl: URL_STORED, envVars: {} }); + await controller.update(req(), 'c1', { baseUrl: URL_TYPED } as any); + const data = connectorsService.update.mock.calls[0][1]; + expect(data.baseUrl).toBe(URL_STORED); + expect(data.envVars).toEqual({ BITRIX_CRM_WEBHOOK_TOKEN: CODE }); + }); + + it('update: an older connector saved with the masked URL keeps its code, now in a variable', async () => { + const { controller, connectorsService } = buildConnectors({ name: 'Bitrix CRM', baseUrl: URL_TYPED, envVars: {} }); + const out: any = await controller.update(req(), 'c1', { + name: 'Bitrix CRM', + baseUrl: 'https://portal.bitrix24.com/rest/1/********/', + } as any); + const data = connectorsService.update.mock.calls[0][1]; + expect(data.baseUrl).toBe(URL_STORED); + expect(data.envVars).toEqual({ BITRIX_CRM_WEBHOOK_TOKEN: CODE }); + expect(JSON.stringify(out)).not.toContain(CODE); + }); + + it('update: a URL edited around the mask is refused, without saving anything', async () => { + const { controller, connectorsService } = buildConnectors({ name: 'Bitrix CRM', baseUrl: URL_TYPED, envVars: {} }); + await expect( + controller.update(req(), 'c1', { baseUrl: 'https://other.bitrix24.com/rest/1/********/' } as any), + ).rejects.toThrow(/hidden secret/); + expect(connectorsService.update).not.toHaveBeenCalled(); + }); + + it('a tool call through the stored connector still goes to the URL as typed', async () => { + const tool = { + id: 't1', + connectorId: 'c1', + organizationId: 'org1', + name: 'crm_deal_list', + description: 'x', + parameters: { type: 'object', properties: {} }, + connectorType: 'REST', + connectorConfig: { + baseUrl: URL_STORED, + authType: 'NONE', + envVars: { BITRIX_CRM_WEBHOOK_TOKEN: CODE }, + }, + endpointMapping: { method: 'POST', path: 'crm.deal.list.json' }, + } as RegisteredTool; + const execute = jest.fn().mockResolvedValue({ result: [] }); + const executor = new DynamicMcpTools( + { getTool: () => tool, getToolForOrg: () => tool } as any, + { logInvocation: jest.fn().mockResolvedValue(undefined) } as any, + { get: jest.fn().mockResolvedValue(null), set: jest.fn() } as any, + { checkLicenseActive: jest.fn() } as any, + { isCloud: () => false } as any, + {} as any, + { execute } as any, + {} as any, + {} as any, + {} as any, + {} as any, + { scheduleObservationalIngest: jest.fn() } as any, + { recentEvents: jest.fn().mockResolvedValue([]) } as any, + ); + + const res = await executor.executeTool('crm_deal_list', {}); + + expect(res.isError).toBeFalsy(); + expect(execute).toHaveBeenCalledTimes(1); + expect(execute.mock.calls[0][0].baseUrl).toBe(URL_TYPED); + expect(execute.mock.calls[0][1].path).toBe('crm.deal.list.json'); + }); +}); From 2dc57a35e6a700402af3de206c0686d55091bddc Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:09 +0100 Subject: [PATCH 3/6] Show restricted members only their own MCP servers In a restricted workspace a member who is not an admin used to see every MCP server holding a connector they could see, with its name, owner, connectors, endpoint and usage. They now see only the servers they own, on every route that lists, reads, counts or reports servers: the servers API (reads and writes answer the unknown-id 404), the server picker and consent page, connections, API keys, connector detail, the audit log, tool performance and breakdowns, and the server links on the shared MCP endpoint. A restricted member with only their own server is granted the workspace connection, where their roles decide the tools. File Search detail routes answer 404 unless the member owns the connector, also for one shared through their roles. The catalog's installed flags count only connectors the member can see, and testing values for an existing connector is limited to its owner or an admin. --- .../src/adapters/adapters.controller.spec.ts | 3 +- .../src/adapters/adapters.controller.ts | 40 +++++- .../backend/src/adapters/adapters.module.ts | 3 +- .../backend/src/adapters/adapters.service.ts | 34 +++-- ...udit.member-visibility.integration.spec.ts | 40 ++++-- .../src/audit/audit.member-visibility.spec.ts | 84 ++++++++++++- packages/backend/src/audit/audit.service.ts | 68 ++++++++-- .../src/audit/tool-performance.query.ts | 41 +++++-- .../backend/src/auth/login.controller.spec.ts | 11 ++ packages/backend/src/auth/login.controller.ts | 14 ++- .../backend/src/auth/server-picker.spec.ts | 20 +++ ...tors.member-visibility.integration.spec.ts | 4 +- .../connectors.member-visibility.spec.ts | 37 ++++-- .../src/file-search/file-search.controller.ts | 112 ++++++++++++----- .../src/file-search/file-search.service.ts | 18 ++- .../mcp-server/chatgpt-app.controller.spec.ts | 2 +- .../file-search-app.controller.spec.ts | 2 +- .../src/mcp-server/mcp-endpoint.controller.ts | 3 +- .../shared-endpoint.assistant.spec.ts | 2 +- .../shared-endpoint.controller.spec.ts | 2 +- .../mcp-connection-grant.service.ts | 50 +++++++- .../mcp-servers/mcp-connections.controller.ts | 19 ++- .../src/mcp-servers/mcp-servers.controller.ts | 62 +++++++--- ...vers.member-visibility.integration.spec.ts | 52 ++++++-- .../mcp-servers.member-visibility.spec.ts | 116 ++++++++++++++---- .../src/mcp-servers/mcp-servers.service.ts | 23 +--- .../src/roles/mcp-api-keys.controller.ts | 61 ++++++++- .../backend/src/roles/mcp-api-keys.service.ts | 29 +++++ packages/backend/src/roles/roles.module.ts | 3 + .../member-visibility.service.spec.ts | 41 +++---- .../src/settings/member-visibility.service.ts | 30 +++-- 31 files changed, 806 insertions(+), 220 deletions(-) diff --git a/packages/backend/src/adapters/adapters.controller.spec.ts b/packages/backend/src/adapters/adapters.controller.spec.ts index 2c09da819..3fc20eb8a 100644 --- a/packages/backend/src/adapters/adapters.controller.spec.ts +++ b/packages/backend/src/adapters/adapters.controller.spec.ts @@ -111,7 +111,8 @@ describe('AdaptersController — starter pack', () => { items: pack, connectors: { current: 0, max: 2, remaining: 2 }, }); - expect((adaptersService as any).starterPack).toHaveBeenCalledWith('org1'); + // No member visibility service in this unit: every connector counts. + expect((adaptersService as any).starterPack).toHaveBeenCalledWith('org1', {}); }); it('reports an uncapped plan as unlimited remaining', async () => { diff --git a/packages/backend/src/adapters/adapters.controller.ts b/packages/backend/src/adapters/adapters.controller.ts index 2220ecc58..9751bd091 100644 --- a/packages/backend/src/adapters/adapters.controller.ts +++ b/packages/backend/src/adapters/adapters.controller.ts @@ -7,6 +7,7 @@ import { Req, UseGuards, ForbiddenException, + NotFoundException, BadRequestException, HttpCode, HttpException, @@ -24,6 +25,7 @@ import { McpServersService } from '../mcp-servers/mcp-servers.service'; import { ProductEventService, ProductEvents, scrubProviderMessage } from '../audit/product-event.service'; import { providerErrorCode } from '../mcp-server/error-hints'; import { STARTER_PACK_MAX_INSTALL } from './starter-pack'; +import { MemberVisibilityService, connectorWhere } from '../settings/member-visibility.service'; // Public endpoints (no auth required) — used by the marketing website. // @@ -160,8 +162,20 @@ export class AdaptersController { private readonly licenseGuard: LicenseGuardService, private readonly mcpServers: McpServersService, private readonly productEvents: ProductEventService, + // Not @Optional: Nest refuses to boot without it. It is missing only in + // unit specs that build the controller by hand and predate the setting. + private readonly visibility?: MemberVisibilityService, ) {} + /** + * Member visibility: the connectors whose adapter counts as "installed" for + * the caller. `{}` (every connector of the workspace) for admins and open + * workspaces; in a restricted one, only the connectors the member may see. + */ + private async visibleConnectors(req: any) { + return this.visibility ? connectorWhere(await this.visibility.scopeFor(req.user)) : {}; + } + // Declared before `:slug`, which would otherwise take these paths for an // adapter slug. @Get('popular-connectors') @@ -169,10 +183,14 @@ export class AdaptersController { summary: 'Apps new workspaces connect and get working', description: 'Catalog adapters ranked by how many workspaces had a successful call on them in the last 30 days ' + - '(aggregate counts only), with what each setup asks for and whether this workspace already has it.', + '(aggregate counts only), with what each setup asks for and whether this workspace already has it. ' + + 'In a workspace with restricted member visibility, a member who is not an admin gets `installed` only for ' + + 'connectors they can see.', }) async popularConnectors(@Req() req: any) { - return { items: await this.adaptersService.popularConnectors(req.user.organizationId) }; + return { + items: await this.adaptersService.popularConnectors(req.user.organizationId, await this.visibleConnectors(req)), + }; } @Get('match-url') @@ -193,11 +211,14 @@ export class AdaptersController { summary: 'Connectors offered to a new workspace', description: 'Keyless connectors that install in one click, with whether this workspace already has each one, ' + - 'plus the connector allowance of the current plan so the page never preselects more than will fit.', + 'plus the connector allowance of the current plan so the page never preselects more than will fit. ' + + 'In a workspace with restricted member visibility, a member who is not an admin gets `installed` only for ' + + 'connectors they can see.', }) async starterPack(@Req() req: any) { + const visible = await this.visibleConnectors(req); const [items, usage] = await Promise.all([ - this.adaptersService.starterPack(req.user.organizationId), + this.adaptersService.starterPack(req.user.organizationId, visible), // Usage is cloud/licence-specific; on a plan with no cap `max` is null. this.licenseGuard .getUsage(req.user.sub, req.user.organizationId) @@ -353,7 +374,8 @@ export class AdaptersController { description: 'Runs the adapter\'s safe read call against an in-memory connector. Nothing is stored. ' + 'ok=true: it worked; ok=false: a value is missing or the API refused; ok=null: nothing to try yet (needs a sign-in at the provider, or no safe call).\n\n' + - 'Pass `connectorId` to test new values for an existing connector of this adapter. Each try is a real call to the ' + + 'Pass `connectorId` to test new values for an existing connector of this adapter (its owner or an admin; 404 ' + + 'for anyone else). Each try is a real call to the ' + 'provider: at most 20 tries a minute per user (429 beyond). VIEWERs get 403.', }) @ApiBody({ @@ -389,6 +411,14 @@ export class AdaptersController { if (req.user.role === 'VIEWER') { throw new ForbiddenException('Viewers cannot modify connectors'); } + // Testing values for an existing connector fills the empty fields with + // what it stores, so it runs with that connector's credentials: only for + // its owner or an admin, like saving them. Anyone else gets the answer of + // an unknown connector. + if (typeof body?.connectorId === 'string' && req.user.role !== 'ADMIN') { + const owner = await this.adaptersService.connectorOwnerId(req.user.organizationId, body.connectorId); + if (owner !== req.user.sub) throw new NotFoundException('Connector not found'); + } // Each try is a real call to the provider; a form does not need more. if (!this.verifyLimiter.take(req.user.sub)) { throw new HttpException('Too many attempts. Wait a minute and try again.', 429); diff --git a/packages/backend/src/adapters/adapters.module.ts b/packages/backend/src/adapters/adapters.module.ts index 7bd0c1408..b7946eff3 100644 --- a/packages/backend/src/adapters/adapters.module.ts +++ b/packages/backend/src/adapters/adapters.module.ts @@ -17,9 +17,10 @@ import { LicenseModule } from '../license/license.module'; import { McpServersModule } from '../mcp-servers/mcp-servers.module'; import { ConnectorsModule } from '../connectors/connectors.module'; import { SettingsModule } from '../settings/settings.module'; +import { MemberVisibilityModule } from '../settings/member-visibility.module'; @Module({ - imports: [McpServerModule, LicenseModule, McpServersModule, ConnectorsModule, SettingsModule], + imports: [McpServerModule, LicenseModule, McpServersModule, ConnectorsModule, SettingsModule, MemberVisibilityModule], controllers: [ AdaptersPublicController, AdaptersController, diff --git a/packages/backend/src/adapters/adapters.service.ts b/packages/backend/src/adapters/adapters.service.ts index 031e0f97b..58e541ad5 100644 --- a/packages/backend/src/adapters/adapters.service.ts +++ b/packages/backend/src/adapters/adapters.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import { PrismaService } from '../common/prisma.service'; +import type { Prisma } from '../generated/prisma/client'; import { McpServerService } from '../mcp-server/mcp-server.service'; import { encrypt } from '../common/crypto/encryption.util'; import { ConfigService } from '@nestjs/config'; @@ -198,8 +199,8 @@ export class AdaptersService { * `installed` marks the ones the workspace already has, so the page can * show them as done instead of offering a duplicate. */ - async starterPack(organizationId: string): Promise { - const installed = await this.installedAdapterSlugs(organizationId); + async starterPack(organizationId: string, visible: Prisma.ConnectorWhereInput = {}): Promise { + const installed = await this.installedAdapterSlugs(organizationId, visible); const items: StarterPackItem[] = []; for (const entry of STARTER_PACK) { const adapter = getAdapter(entry.slug); @@ -226,10 +227,13 @@ export class AdaptersService { * ./popular-connectors.ts), each with what its setup asks for and whether * this workspace already has it. */ - async popularConnectors(organizationId: string): Promise { + async popularConnectors( + organizationId: string, + visible: Prisma.ConnectorWhereInput = {}, + ): Promise { const [ranked, installed] = await Promise.all([ this.rankedPopularSlugs(), - this.installedAdapterSlugs(organizationId), + this.installedAdapterSlugs(organizationId, visible), ]); const items: PopularConnectorItem[] = []; for (const slug of [...ranked, ...POPULAR_FALLBACK]) { @@ -329,10 +333,26 @@ export class AdaptersService { } } - /** Catalog slugs this workspace already has a connector for. */ - async installedAdapterSlugs(organizationId: string): Promise> { + /** The owner of a connector of this workspace, or null when there is none. */ + async connectorOwnerId(organizationId: string, connectorId: string): Promise { + const row = await this.prisma.connector.findFirst({ + where: { id: connectorId, organizationId }, + select: { userId: true }, + }); + return row?.userId ?? null; + } + + /** + * Catalog slugs this workspace already has a connector for. `visible` + * (member visibility's `connectorWhere`) narrows it to the connectors the + * caller may see, so "installed" never reveals a connector hidden from them. + */ + async installedAdapterSlugs( + organizationId: string, + visible: Prisma.ConnectorWhereInput = {}, + ): Promise> { const rows = await this.prisma.connector.findMany({ - where: { organizationId }, + where: Object.keys(visible).length ? { AND: [{ organizationId }, visible] } : { organizationId }, select: { config: true }, }); const slugs = new Set(); diff --git a/packages/backend/src/audit/audit.member-visibility.integration.spec.ts b/packages/backend/src/audit/audit.member-visibility.integration.spec.ts index efb863a0a..be782a123 100644 --- a/packages/backend/src/audit/audit.member-visibility.integration.spec.ts +++ b/packages/backend/src/audit/audit.member-visibility.integration.spec.ts @@ -254,7 +254,8 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; [`toolId=${ids.toolMine}`, 2], [`connectorId=${ids.connector}`, 2], [`connectorId=${ids.otherConnector}`, 0], - [`mcpServerId=${ids.server}`, 1], + // The admin's server: not the viewer's, so it filters like an unknown id. + [`mcpServerId=${ids.server}`, 0], ['search=export', 0], ['search=crm', 2], ['status=TIMEOUT', 0], @@ -283,19 +284,36 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; expect(body.topTools).toEqual([{ name: 'crm_search', count: 3, errors: 2, avgDuration: expect.any(Number) }]); }); + it('names the server of an own call only when the caller owns that server', async () => { + const inv = await get('VIEWER', 'invocations'); + expect(inv.body).toHaveLength(2); // three calls: one row stands for a repeat + // The call through the admin's "Sales" server: counted, server not named. + for (const row of inv.body) { + expect(row.mcpServerId).toBeNull(); + expect(row.mcpServer).toBeNull(); + } + expect(JSON.stringify(inv.body)).not.toContain('Sales'); + // Admins still see it. + const adminRows = (await get('ADMIN', 'invocations')).body; + expect(adminRows.some((r: any) => r.mcpServer?.name === 'Sales')).toBe(true); + }); + it('tool performance holds only the caller’s calls, and their own last error', async () => { const { body } = await get('VIEWER', 'tool-performance?hours=24'); - expect(body.items).toHaveLength(2); - expect(body.items.every((i: any) => i.toolName === 'crm_search')).toBe(true); - const direct = body.items.find((i: any) => i.mcpServerId === null); - expect(direct).toMatchObject({ calls: 2, errors: 2, lastError: 'viewer error' }); - const viaServer = body.items.find((i: any) => i.mcpServerId === ids.server); - // The other member's newer TIMEOUT on the same tool and server stays hidden. - expect(viaServer).toMatchObject({ calls: 1, errors: 0, lastError: null }); + // The call through the admin's server joins the calls without a server. + expect(body.items).toHaveLength(1); + expect(body.items[0]).toMatchObject({ + toolName: 'crm_search', + mcpServerId: null, + mcpServerName: null, + calls: 3, + errors: 2, + // The other member's newer TIMEOUT on the same tool stays hidden. + lastError: 'viewer error', + }); const filtered = await get('VIEWER', `tool-performance?connectorId=${ids.connector}&mcpServerId=${ids.server}`); - expect(filtered.body.items).toHaveLength(1); - expect(filtered.body.items[0]).toMatchObject({ calls: 1, lastError: null }); + expect(filtered.body.items).toHaveLength(0); }); it('breakdowns hold only the caller’s calls, byUser only their own row', async () => { @@ -303,6 +321,8 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; expect(body).toMatchObject({ total: 3, errors: 2 }); expect(body.byUser).toEqual([{ id: ids.viewer, label: 'viewer', count: 3, errors: 2 }]); expect(body.byConnector).toEqual([{ id: ids.connector, label: 'CRM', count: 3, errors: 2 }]); + // The admin's server is not named: its call joins the row without a server. + expect(body.byServer).toEqual([{ id: null, label: 'Other server or none', count: 3, errors: 2 }]); }); it.each(['invocations', 'stats', 'analytics', 'tool-performance', 'breakdowns'])( diff --git a/packages/backend/src/audit/audit.member-visibility.spec.ts b/packages/backend/src/audit/audit.member-visibility.spec.ts index e29e29c41..07ce4cf69 100644 --- a/packages/backend/src/audit/audit.member-visibility.spec.ts +++ b/packages/backend/src/audit/audit.member-visibility.spec.ts @@ -50,6 +50,8 @@ describe('AuditService own-calls filter', () => { toolId: 'tool-1', status: 'ERROR', mcpServerId: 'srv-1', + // A server filter matches only a server the member owns. + mcpServer: { userId: ME }, tool: { connector: { organizationId: ORG }, name: { contains: 'crm', mode: 'insensitive' }, @@ -67,11 +69,40 @@ describe('AuditService own-calls filter', () => { }); it('has no user filter on the open path', async () => { - await service.getRecentInvocations(10, 0, { organizationId: ORG }); + await service.getRecentInvocations(10, 0, { organizationId: ORG, mcpServerId: 'srv-1' }); expect(prisma.toolInvocation.findMany.mock.calls[0][0].where).toEqual({ + mcpServerId: 'srv-1', tool: { connector: { organizationId: ORG } }, }); }); + + it('names a server only when the member owns it', async () => { + prisma.toolInvocation.findMany.mockResolvedValue([ + { id: 'c1', mcpServerId: 'srv-mine', mcpServer: { id: 'srv-mine', name: 'Mine', slug: 'mine', userId: ME } }, + { id: 'c2', mcpServerId: 'srv-team', mcpServer: { id: 'srv-team', name: 'Default (Alice)', slug: 'default-alice', userId: 'alice' } }, + { id: 'c3', mcpServerId: null, mcpServer: null }, + ]); + const rows = await service.getRecentInvocations(10, 0, { organizationId: ORG, onlyUserId: ME }); + expect(prisma.toolInvocation.findMany.mock.calls[0][0].include.mcpServer.select).toEqual({ + id: true, + name: true, + slug: true, + userId: true, + }); + expect(rows).toEqual([ + { id: 'c1', mcpServerId: 'srv-mine', mcpServer: { id: 'srv-mine', name: 'Mine', slug: 'mine' } }, + { id: 'c2', mcpServerId: null, mcpServer: null }, + { id: 'c3', mcpServerId: null, mcpServer: null }, + ]); + expect(JSON.stringify(rows)).not.toContain('Alice'); + }); + + it('returns rows untouched on the open path', async () => { + const row = { id: 'c2', mcpServerId: 'srv-team', mcpServer: { id: 'srv-team', name: 'Default (Alice)', slug: 'default-alice' } }; + prisma.toolInvocation.findMany.mockResolvedValue([row]); + expect(await service.getRecentInvocations(10, 0, { organizationId: ORG })).toEqual([row]); + expect(prisma.toolInvocation.findMany.mock.calls[0][0].include.mcpServer.select).toEqual({ id: true, name: true, slug: true }); + }); }); describe('getStats', () => { @@ -108,6 +139,38 @@ describe('AuditService own-calls filter', () => { expect(args.where).toMatchObject({ organizationId: ORG }); } }); + + describe('byServer', () => { + const rows = (errors: boolean) => [ + { mcpServerId: 'srv-mine', _count: { _all: errors ? 1 : 5 }, _sum: { repeatCount: errors ? 1 : 5 } }, + { mcpServerId: 'srv-alice', _count: { _all: errors ? 2 : 4 }, _sum: { repeatCount: errors ? 2 : 4 } }, + { mcpServerId: null, _count: { _all: errors ? 0 : 3 }, _sum: { repeatCount: errors ? 0 : 3 } }, + ]; + beforeEach(() => { + prisma.toolInvocation.groupBy.mockImplementation(async (args: any) => + args.by[0] === 'mcpServerId' ? rows(args.where.status === 'ERROR') : [], + ); + prisma.mcpServerConfig.findMany.mockResolvedValue([ + { id: 'srv-mine', name: 'Mine', userId: ME }, + { id: 'srv-alice', name: 'Default (Alice)', userId: 'alice' }, + ]); + }); + + it('names only servers the member owns; the others join the row without a server', async () => { + const out = await service.getBreakdowns(ORG, 30, ME); + expect(out.byServer).toEqual([ + { id: null, label: 'Other server or none', count: 7, errors: 2 }, + { id: 'srv-mine', label: 'Mine', count: 5, errors: 1 }, + ]); + expect(JSON.stringify(out)).not.toContain('Alice'); + expect(JSON.stringify(out)).not.toContain('srv-alice'); + }); + + it('lists every server on the open path', async () => { + const out = await service.getBreakdowns(ORG, 30); + expect(out.byServer.map((r: any) => r.label)).toEqual(['Mine', 'Default (Alice)', 'Direct / no server']); + }); + }); }); describe('getAnalytics / analyticsQuery', () => { @@ -137,7 +200,24 @@ describe('AuditService own-calls filter', () => { it('passes the user to the query', async () => { await service.getToolPerformance(ORG, {}, ME); const sql = prisma.$queryRaw.mock.calls[0][0]; - expect(sql.values.filter((v: unknown) => v === ME)).toHaveLength(2); + // Two call filters, and three server expressions (id and name in the + // groups, id in the latest-error lookup). + expect(sql.values.filter((v: unknown) => v === ME)).toHaveLength(5); + }); + + it('names only servers the member owns, in the groups and in the latest-error lookup', () => { + const sql = toolPerformanceQuery(ORG, since, until, {}, 25, ME); + expect(sql.text).toMatch(/CASE WHEN s\.user_id = \$\d+ THEN ti\.mcp_server_id END AS mcp_server_id/); + expect(sql.text).toMatch(/CASE WHEN s\.user_id = \$\d+ THEN s\.name END AS mcp_server_name/); + expect(sql.text).toMatch(/GROUP BY 1, 2, 3, 4, 5, 6/); + const lateral = sql.text.slice(sql.text.indexOf('LEFT JOIN LATERAL')); + expect(lateral).toMatch(/LEFT JOIN mcp_server_configs ls ON ls\.id = ti\.mcp_server_id/); + expect(lateral).toMatch(/CASE WHEN ls\.user_id = \$\d+ THEN ti\.mcp_server_id END IS NOT DISTINCT FROM page\.mcp_server_id/); + }); + + it('a server filter matches only a server the member owns', () => { + const sql = toolPerformanceQuery(ORG, since, until, { mcpServerId: 'srv-1' }, 25, ME); + expect(sql.text).toMatch(/AND ti\.mcp_server_id = \$\d+ AND s\.user_id = \$\d+/); }); it('filters both the groups and the latest-error lookup, with bound values', () => { diff --git a/packages/backend/src/audit/audit.service.ts b/packages/backend/src/audit/audit.service.ts index cb760476e..ab8487997 100644 --- a/packages/backend/src/audit/audit.service.ts +++ b/packages/backend/src/audit/audit.service.ts @@ -365,18 +365,25 @@ export class AuditService implements OnModuleDestroy { mcpServerId?: string; organizationId?: string; /** - * Restricted member visibility: only calls made by this user. Absent on - * the open path; when present (even empty) it is always applied, so a - * bad value matches nothing instead of everything. + * Restricted member visibility: only calls made by this user, and only + * the MCP servers this user owns are named (`mcpServer` and + * `mcpServerId` are null on a call made through another member's + * server; filtering by such a server matches nothing). Absent on the + * open path; when present (even empty) it is always applied, so a bad + * value matches nothing instead of everything. */ onlyUserId?: string; }, ) { + const restricted = filters?.onlyUserId !== undefined; const where: any = { ...this.orgScope(filters?.organizationId) }; - if (filters?.onlyUserId !== undefined) where.userId = filters.onlyUserId; + if (restricted) where.userId = filters!.onlyUserId; if (filters?.toolId) where.toolId = filters.toolId; if (filters?.status) where.status = filters.status; - if (filters?.mcpServerId) where.mcpServerId = filters.mcpServerId; + if (filters?.mcpServerId) { + where.mcpServerId = filters.mcpServerId; + if (restricted) where.mcpServer = { userId: filters!.onlyUserId }; + } if (filters?.search) { where.tool = { ...where.tool, name: { contains: filters.search, mode: 'insensitive' } }; } @@ -384,7 +391,7 @@ export class AuditService implements OnModuleDestroy { where.tool = { ...where.tool, connectorId: filters.connectorId }; } - return this.prisma.toolInvocation.findMany({ + const rows = await this.prisma.toolInvocation.findMany({ where, take: limit, skip: offset, @@ -401,10 +408,18 @@ export class AuditService implements OnModuleDestroy { select: { id: true, email: true, name: true }, }, mcpServer: { - select: { id: true, name: true, slug: true }, + // The owner only to decide below whether the server may be named. + select: { id: true, name: true, slug: true, ...(restricted ? { userId: true } : {}) }, }, }, }); + if (!restricted) return rows; + return rows.map((row: any) => { + const own = !!row.mcpServer && row.mcpServer.userId === filters!.onlyUserId; + if (!own) return { ...row, mcpServerId: null, mcpServer: null }; + const { userId: _owner, ...server } = row.mcpServer; + return { ...row, mcpServer: server }; + }); } /** @@ -574,7 +589,10 @@ export class AuditService implements OnModuleDestroy { * (both env-configurable, default 0 → shows 0 until an operator sets rates). * * `onlyUserId` (restricted member visibility) narrows every list and total - * to that user's calls, so `byUser` holds at most the caller's own row. + * to that user's calls, so `byUser` holds at most the caller's own row, and + * `byServer` names only the servers that user owns: calls through any other + * server are counted in one row with `id: null` together with the calls + * made without a server. */ async getBreakdowns(organizationId: string, days = 30, onlyUserId?: string) { const safeDays = Math.min(Math.max(days || 30, 1), 365); @@ -609,7 +627,7 @@ export class AuditService implements OnModuleDestroy { ? this.prisma.connector.findMany({ where: { id: { in: connIds } }, select: { id: true, name: true } }) : [], srvIds.length - ? this.prisma.mcpServerConfig.findMany({ where: { id: { in: srvIds } }, select: { id: true, name: true } }) + ? this.prisma.mcpServerConfig.findMany({ where: { id: { in: srvIds } }, select: { id: true, name: true, userId: true } }) : [], userIds.length ? this.prisma.user.findMany({ where: { id: { in: userIds } }, select: { id: true, email: true, name: true } }) @@ -617,6 +635,30 @@ export class AuditService implements OnModuleDestroy { ]); const connName = new Map(conns.map((c) => [c.id, c.name])); const srvName = new Map(srvs.map((s) => [s.id, s.name])); + // Restricted member visibility: a server the caller does not own is not + // named; its calls join the row of calls without a server. + const ownServers = new Set( + (srvs as Array<{ id: string; userId?: string }>).filter((s) => s.userId === onlyUserId).map((s) => s.id), + ); + const serverRows = ( + rows: T[], + ) => { + if (onlyUserId === undefined) return rows; + const calls = (r: T) => r._sum?.repeatCount ?? r._count._all; + const out: Array<{ mcpServerId: string | null; _count: { _all: number }; _sum: { repeatCount: number | null } }> = []; + let other = 0; + let hasOther = false; + for (const r of rows) { + if (r.mcpServerId && ownServers.has(r.mcpServerId)) { + out.push({ mcpServerId: r.mcpServerId, _count: { _all: calls(r) }, _sum: { repeatCount: calls(r) } }); + } else { + other += calls(r); + hasOther = true; + } + } + if (hasOther) out.push({ mcpServerId: null, _count: { _all: other }, _sum: { repeatCount: other } }); + return out; + }; const userName = new Map(users.map((u) => [u.id, u.name || u.email])); const merge = ( @@ -655,8 +697,12 @@ export class AuditService implements OnModuleDestroy { byConnector: merge(byConnector, byConnectorErr, 'connectorId', (id) => id ? (connName.get(id) ?? 'Unknown connector') : 'No connector', ), - byServer: merge(byServer, byServerErr, 'mcpServerId', (id) => - id ? (srvName.get(id) ?? 'Unknown server') : 'Direct / no server', + byServer: merge(serverRows(byServer), serverRows(byServerErr), 'mcpServerId', (id) => + id + ? (srvName.get(id) ?? 'Unknown server') + : onlyUserId !== undefined + ? 'Other server or none' + : 'Direct / no server', ), byUser: merge(byUser, byUserErr, 'userId', (id) => id ? (userName.get(id) ?? 'Unknown user') : 'Anonymous', diff --git a/packages/backend/src/audit/tool-performance.query.ts b/packages/backend/src/audit/tool-performance.query.ts index f5061b279..e9686a6dc 100644 --- a/packages/backend/src/audit/tool-performance.query.ts +++ b/packages/backend/src/audit/tool-performance.query.ts @@ -21,7 +21,11 @@ export interface ToolPerformanceRow { * * `onlyUserId` (restricted member visibility) keeps only that user's calls, in * the groups and in the latest-error lookup, so another member's error text - * never shows. It is a bound value; without it the query is the workspace-wide one. + * never shows. It also names only the MCP servers that user owns: a call made + * through another member's server is grouped with the calls made without a + * server (`mcp_server_id` and `mcp_server_name` null), and filtering by such a + * server matches nothing. It is a bound value; without it the query is the + * workspace-wide one. */ export function toolPerformanceQuery( organizationId: string, @@ -34,11 +38,27 @@ export function toolPerformanceQuery( const connectorFilter = options.connectorId ? Prisma.sql`AND c.id = ${options.connectorId}` : Prisma.empty; + const restricted = onlyUserId !== undefined; const serverFilter = options.mcpServerId - ? Prisma.sql`AND ti.mcp_server_id = ${options.mcpServerId}` + ? restricted + ? Prisma.sql`AND ti.mcp_server_id = ${options.mcpServerId} AND s.user_id = ${onlyUserId}` + : Prisma.sql`AND ti.mcp_server_id = ${options.mcpServerId}` : Prisma.empty; - const userFilter = - onlyUserId !== undefined ? Prisma.sql`AND ti.user_id = ${onlyUserId}` : Prisma.empty; + const userFilter = restricted ? Prisma.sql`AND ti.user_id = ${onlyUserId}` : Prisma.empty; + // The server as reported: restricted, only one the caller owns. + const serverId = restricted + ? Prisma.sql`CASE WHEN s.user_id = ${onlyUserId} THEN ti.mcp_server_id END` + : Prisma.sql`ti.mcp_server_id`; + const serverName = restricted + ? Prisma.sql`CASE WHEN s.user_id = ${onlyUserId} THEN s.name END` + : Prisma.sql`s.name`; + // The same expression in the latest-error lookup, over its own join. + const latestServerJoin = restricted + ? Prisma.sql`LEFT JOIN mcp_server_configs ls ON ls.id = ti.mcp_server_id` + : Prisma.empty; + const latestServerId = restricted + ? Prisma.sql`CASE WHEN ls.user_id = ${onlyUserId} THEN ti.mcp_server_id END` + : Prisma.sql`ti.mcp_server_id`; return Prisma.sql` WITH page AS ( @@ -47,8 +67,8 @@ export function toolPerformanceQuery( t.name AS tool_name, c.id AS connector_id, c.name AS connector_name, - ti.mcp_server_id, - s.name AS mcp_server_name, + ${serverId} AS mcp_server_id, + ${serverName} AS mcp_server_name, SUM(ti.repeat_count)::bigint AS calls, COALESCE(SUM(ti.repeat_count) FILTER (WHERE ti.status IN ('ERROR', 'TIMEOUT')), 0)::bigint AS errors, COUNT(ti.duration_ms)::bigint AS latency_sample_count, @@ -66,8 +86,10 @@ export function toolPerformanceQuery( ${connectorFilter} ${serverFilter} ${userFilter} - GROUP BY t.id, t.name, c.id, c.name, ti.mcp_server_id, s.name - ORDER BY calls DESC, c.id, t.id, ti.mcp_server_id NULLS FIRST + -- By position: the server columns are expressions with bound values, + -- which Postgres would not match to a repeated expression. + GROUP BY 1, 2, 3, 4, 5, 6 + ORDER BY calls DESC, c.id, t.id, mcp_server_id NULLS FIRST LIMIT ${limit + 1} OFFSET ${options.offset ?? 0} ) SELECT page.*, latest.last_error, latest.last_error_at @@ -77,8 +99,9 @@ export function toolPerformanceQuery( ti.error AS last_error, ti.created_at AT TIME ZONE 'UTC' AS last_error_at FROM tool_invocations ti + ${latestServerJoin} WHERE ti.tool_id = page.tool_id - AND ti.mcp_server_id IS NOT DISTINCT FROM page.mcp_server_id + AND ${latestServerId} IS NOT DISTINCT FROM page.mcp_server_id AND ti.status IN ('ERROR', 'TIMEOUT') AND ti.error IS NOT NULL AND ti.error <> '' AND ti.created_at >= (${since.toISOString()}::timestamptz AT TIME ZONE 'UTC') diff --git a/packages/backend/src/auth/login.controller.spec.ts b/packages/backend/src/auth/login.controller.spec.ts index fb754a4bc..5e1c69590 100644 --- a/packages/backend/src/auth/login.controller.spec.ts +++ b/packages/backend/src/auth/login.controller.spec.ts @@ -86,6 +86,8 @@ describe('LoginController', () => { grantWholeOrganization: jest.Mock; listSelectableTargets: jest.Mock; resolve: jest.Mock; + keepVisible: jest.Mock; + restrictedIn: jest.Mock; }; beforeEach(() => { @@ -105,6 +107,9 @@ describe('LoginController', () => { listSelectableTargets: jest.fn().mockResolvedValue([]), // No grant: the user's own organization, as before grants existed. resolve: jest.fn().mockResolvedValue(null), + // Member visibility hides nothing unless a test says so. + keepVisible: jest.fn(async (_userId: string, servers: unknown[]) => servers), + restrictedIn: jest.fn().mockResolvedValue(false), }; controller = new LoginController( @@ -2903,6 +2908,12 @@ describe('LoginController', () => { expect.objectContaining({ where: expect.objectContaining({ userId: 'u1', organizationId: 'org-1' }) }), ); + // A member who may not see the server (restricted member visibility). + grants.keepVisible.mockResolvedValueOnce([]); + const hidden = await page(make(DEPLOY.cloud, p), req as any); + expect(hidden).not.toContain('Sales'); + expect(grants.keepVisible).toHaveBeenLastCalledWith('u1', [{ id: 'srv-1', organizationId: 'org-1' }]); + p.organizationMember.findFirst.mockResolvedValue(null); const outsider = await page(make(DEPLOY.cloud, p), req as any); expect(outsider).not.toContain('Sales'); diff --git a/packages/backend/src/auth/login.controller.ts b/packages/backend/src/auth/login.controller.ts index 64372debc..e80057d75 100644 --- a/packages/backend/src/auth/login.controller.ts +++ b/packages/backend/src/auth/login.controller.ts @@ -306,7 +306,8 @@ export class LoginController { /** * The name of the MCP server this client asked for (RFC 8707 `resource`), * for the consent text. Only for a signed-in user who belongs to that - * server's workspace: the page is otherwise unauthenticated. + * server's workspace and may see it (member visibility: a restricted member + * is shown only their own servers): the page is otherwise unauthenticated. */ private async requestedServerName(req: Request, userId: string | undefined): Promise { if (!userId) return null; @@ -323,7 +324,9 @@ export class LoginController { where: { userId, organizationId: server.organizationId, deactivatedAt: null }, select: { userId: true }, }); - return member ? server.name : null; + if (!member) return null; + const visible = await this.grants.keepVisible(userId, [{ id: serverId, organizationId: server.organizationId }]); + return visible.length > 0 ? server.name : null; } catch { return null; } @@ -1615,7 +1618,12 @@ export class LoginController { // Nothing to choose between: one server, or one workspace whose servers are // the only thing on offer. Grant it and carry on without a screen. if (servers.length <= 1) { - if (servers.length === 1) { + if (targets.length === 1 && (await this.grants.restrictedIn(userId, targets[0].organizationId))) { + // Member visibility: a restricted member is offered only their own + // server, which often holds none of the connectors shared with them. + // The whole workspace gives them every tool their roles allow. + await this.grants.grantWholeOrganization(consent.clientId, userId, targets[0].organizationId); + } else if (servers.length === 1) { await this.grants.grantServers(consent.clientId, userId, [servers[0].id]); } else if (targets.length === 1) { // No servers yet — grant the workspace, so a server created later is diff --git a/packages/backend/src/auth/server-picker.spec.ts b/packages/backend/src/auth/server-picker.spec.ts index ec31d0296..736da92f9 100644 --- a/packages/backend/src/auth/server-picker.spec.ts +++ b/packages/backend/src/auth/server-picker.spec.ts @@ -18,12 +18,15 @@ function build( targets?: any[]; consent?: any; requestedServerId?: string; + /** Member visibility narrows the user's view of the workspace. */ + restricted?: boolean; } = {}, ) { const grants = { grantServers: jest.fn().mockResolvedValue(['srv-1']), grantWholeOrganization: jest.fn().mockResolvedValue(true), listSelectableTargets: jest.fn().mockResolvedValue(opts.targets ?? []), + restrictedIn: jest.fn().mockResolvedValue(!!opts.restricted), }; const store = { getOAuthSession: jest.fn().mockResolvedValue( @@ -86,6 +89,23 @@ describe('choosing what a client may reach', () => { expect(res.send).not.toHaveBeenCalled(); }); + it('grants a restricted member the whole workspace instead of their one own server', async () => { + // Member visibility offers them only their own server, which often holds + // none of the connectors shared with them; the workspace connection gives + // every tool their roles allow. + const { controller, grants, req, res } = build({ + targets: [workspace('org-A', 'Acme', [server('srv-own', 'Default (Vera)', 0)])], + restricted: true, + }); + + await expect(ask(controller, req, res)).resolves.toBe(false); + + expect(grants.restrictedIn).toHaveBeenCalledWith('u1', 'org-A'); + expect(grants.grantWholeOrganization).toHaveBeenCalledWith('client-1', 'u1', 'org-A'); + expect(grants.grantServers).not.toHaveBeenCalled(); + expect(res.send).not.toHaveBeenCalled(); + }); + it('asks once there is more than one server to choose between', async () => { const { controller, grants, req, res } = build({ targets: [ diff --git a/packages/backend/src/connectors/connectors.member-visibility.integration.spec.ts b/packages/backend/src/connectors/connectors.member-visibility.integration.spec.ts index 6c78205ce..3965aac5e 100644 --- a/packages/backend/src/connectors/connectors.member-visibility.integration.spec.ts +++ b/packages/backend/src/connectors/connectors.member-visibility.integration.spec.ts @@ -318,7 +318,9 @@ const KEY = 'k'.repeat(48); }); it.each(['ADMIN', 'EDITOR', 'VIEWER'])('%s: File Search read routes', async (who) => { - const expected = visibleFor(who, mode, state); + // Restricted: File Search detail only for a connector the member owns, + // never for one shared through their roles. Both fixtures are OTHER's. + const expected = mode === 'restricted' && who !== 'ADMIN' ? [] : visibleFor(who, mode, state); expect(await get(who, '/api/file-search/connectors/no-such-connector/tree')).toEqual({ status: 404, body: unknownFsBody }); for (const c of ['fs', 'fsHidden']) { for (const path of ['', '/tree', '/problems', '/runs', '/access-rules', '/scans/no-such-scan']) { diff --git a/packages/backend/src/connectors/connectors.member-visibility.spec.ts b/packages/backend/src/connectors/connectors.member-visibility.spec.ts index 781acfcf3..e40f71ad7 100644 --- a/packages/backend/src/connectors/connectors.member-visibility.spec.ts +++ b/packages/backend/src/connectors/connectors.member-visibility.spec.ts @@ -82,15 +82,18 @@ const RULES: Record> = { getAnnotations: { path: ':toolId/annotations', rule: 'visible-then-owner' }, getResponseMapping: { path: ':toolId/response-mapping', rule: 'visible-then-owner' }, }, + // File Search detail describes the source beyond what the tools return + // (address, every folder and file, role rules): restricted members reach + // it only for a connector they own, even one shared with them. FileSearchController: { capabilities: { path: 'capabilities', rule: 'no-connector-data' }, getPolicy: { path: 'policy', rule: 'no-connector-data' }, - overview: { path: 'connectors/:id', rule: 'visible' }, - getScan: { path: 'connectors/:id/scans/:scanId', rule: 'visible' }, - tree: { path: 'connectors/:id/tree', rule: 'visible' }, - problems: { path: 'connectors/:id/problems', rule: 'visible' }, - runs: { path: 'connectors/:id/runs', rule: 'visible' }, - getRules: { path: 'connectors/:id/access-rules', rule: 'visible' }, + overview: { path: 'connectors/:id', rule: 'owned' }, + getScan: { path: 'connectors/:id/scans/:scanId', rule: 'owned' }, + tree: { path: 'connectors/:id/tree', rule: 'owned' }, + problems: { path: 'connectors/:id/problems', rule: 'owned' }, + runs: { path: 'connectors/:id/runs', rule: 'owned' }, + getRules: { path: 'connectors/:id/access-rules', rule: 'owned' }, }, }; @@ -163,10 +166,12 @@ function world() { const servers = [ { id: 'srv-shared', userId: OTHER, organizationId: ORG, connectorIds: ['shared'] }, { id: 'srv-hidden', userId: OTHER, organizationId: ORG, connectorIds: ['hidden', 'shared'] }, - { id: 'srv-mine', userId: OTHER, organizationId: ORG, connectorIds: ['mine'] }, + { id: 'srv-mine', userId: ME, organizationId: ORG, connectorIds: ['mine'] }, + // Another member's server holding the caller's own connector. + { id: 'srv-team', userId: OTHER, organizationId: ORG, connectorIds: ['mine'] }, ]; connectors.find((c) => c.id === 'shared')!.mcpServers = [{ mcpServerId: 'srv-shared' }, { mcpServerId: 'srv-hidden' }]; - connectors.find((c) => c.id === 'mine')!.mcpServers = [{ mcpServerId: 'srv-mine' }]; + connectors.find((c) => c.id === 'mine')!.mcpServers = [{ mcpServerId: 'srv-mine' }, { mcpServerId: 'srv-team' }]; return { connectors, servers }; } @@ -329,7 +334,7 @@ const BY_ID: Record Promise = { 'ConnectorsController.deleteMyCredential': 'visible', 'ConnectorsController.initiateOAuth': 'visible', - 'FileSearchController.syncNow': 'visible', + 'FileSearchController.syncNow': 'owned', }; function firstToolOf(c: Ctx, connectorId: string): string { @@ -469,9 +474,12 @@ describe.each(['open', 'restricted'] as const)('%s workspace', (mode) => { }); it('GET /api/connectors/:id names only MCP servers the caller can see', async () => { - // The caller's own connector: the server that holds it, in every mode. + // The caller's own connector: restricted, only the servers they own + // hold it as far as they can tell; otherwise every server that does. const own: any = await c.connectors.findOne(req(role), 'mine'); - expect(own.mcpServers).toEqual([{ mcpServerId: 'srv-mine' }]); + expect(own.mcpServers).toEqual( + restricted ? [{ mcpServerId: 'srv-mine' }] : [{ mcpServerId: 'srv-mine' }, { mcpServerId: 'srv-team' }], + ); const got = await outcome(c.connectors.findOne(req(role), 'shared')); if (!visible.includes('shared')) { expect(got.ok).toBe(false); @@ -845,11 +853,16 @@ describe('reduced view of a connector the restricted member does not own', () => const text = async (c: Ctx, r: string) => JSON.stringify([ ((await c.connectors.list(req(r), {} as any)) as any[]).find((x) => x.id === 'mine'), - await c.connectors.findOne(req(r), 'mine'), await c.tools.list(req(r), 'mine'), ]); const own = await text(member, role); expect(own).toBe(await text(admin, 'ADMIN')); + // The detail too, except for the MCP servers holding it: another + // member's server is not named to a restricted member. + const memberDetail: any = await member.connectors.findOne(req(role), 'mine'); + const adminDetail: any = await admin.connectors.findOne(req('ADMIN'), 'mine'); + expect(adminDetail.mcpServers).toEqual([{ mcpServerId: 'srv-mine' }, { mcpServerId: 'srv-team' }]); + expect(memberDetail).toEqual({ ...adminDetail, mcpServers: [{ mcpServerId: 'srv-mine' }] }); expect(own).toContain('"baseUrl":"https://api.example.invalid"'); expect(own).toContain('"endpointMapping"'); expect(own).not.toContain('memberView'); diff --git a/packages/backend/src/file-search/file-search.controller.ts b/packages/backend/src/file-search/file-search.controller.ts index dc315e47c..cd522113c 100644 --- a/packages/backend/src/file-search/file-search.controller.ts +++ b/packages/backend/src/file-search/file-search.controller.ts @@ -23,9 +23,11 @@ import { * * Member visibility (settings/member-visibility.service.ts): in a workspace * set to `restricted`, a member who is not an admin gets 404 (the body an - * unknown id gets) on every route with a connector id they cannot see, before - * the route's own checks. Admins and open workspaces: today's path. The - * route-by-route rules are listed in connectors.member-visibility.spec.ts. + * unknown id gets) on every route with a connector id, unless they own that + * connector, before the route's own checks. A connector shared with them + * through their roles is reachable through its tools only. Admins and open + * workspaces: today's path. The route-by-route rules are listed in + * settings/member-visibility.routes.ts. */ @ApiTags('File Search') @ApiBearerAuth() @@ -38,7 +40,7 @@ export class FileSearchController { private readonly visibility: MemberVisibilityService, ) {} - /** 404 for a connector a restricted member cannot see; nothing for admins and open workspaces. */ + /** 404 for a connector a restricted member does not own; nothing for admins and open workspaces. */ private async hideUnlessVisible(req: any, id: string): Promise { const scope = await this.visibility.scopeFor(req.user); if (!scope.restricted) return; @@ -78,7 +80,7 @@ export class FileSearchController { @Get('connectors/:id') @ApiOperation({ summary: 'Get a File Search connector overview', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async overview(@Req() req: any, @Param('id') id: string) { await this.hideUnlessVisible(req, id); @@ -86,21 +88,29 @@ export class FileSearchController { } @Put('connectors/:id/source') - @ApiOperation({ summary: "Update a connector's source and connection settings" }) - updateSource(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchUpdateSourceDto) { + @ApiOperation({ + summary: "Update a connector's source and connection settings", + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async updateSource(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchUpdateSourceDto) { + await this.hideUnlessVisible(req, id); return this.svc.updateSource(req.user, id, body); } @Post('connectors/:id/scans') - @ApiOperation({ summary: 'Start a scan of a connector' }) - startScan(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchScanDto) { + @ApiOperation({ + summary: 'Start a scan of a connector', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async startScan(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchScanDto) { + await this.hideUnlessVisible(req, id); return this.svc.startScan(req.user, id, body); } @Get('connectors/:id/scans/:scanId') @ApiOperation({ summary: 'Get the status and results of a scan', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async getScan(@Req() req: any, @Param('id') id: string, @Param('scanId') scanId: string) { await this.hideUnlessVisible(req, id); @@ -108,33 +118,49 @@ export class FileSearchController { } @Delete('connectors/:id/scans/:scanId') - @ApiOperation({ summary: 'Cancel a running scan' }) - cancelScan(@Req() req: any, @Param('id') id: string, @Param('scanId') scanId: string) { + @ApiOperation({ + summary: 'Cancel a running scan', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async cancelScan(@Req() req: any, @Param('id') id: string, @Param('scanId') scanId: string) { + await this.hideUnlessVisible(req, id); return this.svc.cancelScan(req.user, id, scanId); } @Post('connectors/:id/scans/:scanId/describe') - @ApiOperation({ summary: 'Regenerate AI descriptions for a scan' }) - redescribe(@Req() req: any, @Param('id') id: string, @Param('scanId') scanId: string, @Body() body: FileSearchScanDto) { + @ApiOperation({ + summary: 'Regenerate AI descriptions for a scan', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async redescribe(@Req() req: any, @Param('id') id: string, @Param('scanId') scanId: string, @Body() body: FileSearchScanDto) { + await this.hideUnlessVisible(req, id); return this.svc.redescribe(req.user, id, scanId, body); } @Put('connectors/:id/selection') - @ApiOperation({ summary: 'Set which folders and files the connector indexes' }) - setSelection(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchSelectionDto) { + @ApiOperation({ + summary: 'Set which folders and files the connector indexes', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async setSelection(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchSelectionDto) { + await this.hideUnlessVisible(req, id); return this.svc.setSelection(req.user, id, body); } @Post('connectors/:id/activate') - @ApiOperation({ summary: 'Activate a drafted connector' }) - activate(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchActivateDto) { + @ApiOperation({ + summary: 'Activate a drafted connector', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async activate(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchActivateDto) { + await this.hideUnlessVisible(req, id); return this.svc.activate(req.user, id, body); } @Get('connectors/:id/tree') @ApiOperation({ summary: 'Get the folder tree of a connector', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async tree(@Req() req: any, @Param('id') id: string) { await this.hideUnlessVisible(req, id); @@ -144,7 +170,7 @@ export class FileSearchController { @Get('connectors/:id/problems') @ApiOperation({ summary: 'List indexing problems for a connector', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async problems(@Req() req: any, @Param('id') id: string, @Query() query: PageQueryDto) { await this.hideUnlessVisible(req, id); @@ -154,7 +180,7 @@ export class FileSearchController { @Get('connectors/:id/runs') @ApiOperation({ summary: 'List sync runs for a connector', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async runs(@Req() req: any, @Param('id') id: string) { await this.hideUnlessVisible(req, id); @@ -164,7 +190,7 @@ export class FileSearchController { @Post('connectors/:id/sync') @ApiOperation({ summary: 'Trigger an immediate sync', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async syncNow(@Req() req: any, @Param('id') id: string) { await this.hideUnlessVisible(req, id); @@ -172,33 +198,49 @@ export class FileSearchController { } @Post('connectors/:id/pause') - @ApiOperation({ summary: 'Pause automatic syncing' }) - pause(@Req() req: any, @Param('id') id: string) { + @ApiOperation({ + summary: 'Pause automatic syncing', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async pause(@Req() req: any, @Param('id') id: string) { + await this.hideUnlessVisible(req, id); return this.svc.pause(req.user, id); } @Post('connectors/:id/resume') - @ApiOperation({ summary: 'Resume automatic syncing' }) - resume(@Req() req: any, @Param('id') id: string) { + @ApiOperation({ + summary: 'Resume automatic syncing', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async resume(@Req() req: any, @Param('id') id: string) { + await this.hideUnlessVisible(req, id); return this.svc.resume(req.user, id); } @Put('connectors/:id/schedule') - @ApiOperation({ summary: 'Set the automatic sync schedule' }) - schedule(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchScheduleDto) { + @ApiOperation({ + summary: 'Set the automatic sync schedule', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async schedule(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchScheduleDto) { + await this.hideUnlessVisible(req, id); return this.svc.setSchedule(req.user, id, body); } @Put('connectors/:id/description') - @ApiOperation({ summary: 'Set the connector description shown to agents' }) - description(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchDescriptionDto) { + @ApiOperation({ + summary: 'Set the connector description shown to agents', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async description(@Req() req: any, @Param('id') id: string, @Body() body: FileSearchDescriptionDto) { + await this.hideUnlessVisible(req, id); return this.svc.setDescription(req.user, id, body); } @Get('connectors/:id/access-rules') @ApiOperation({ summary: 'Get per-connector access rules', - description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they cannot see.', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', }) async getRules(@Req() req: any, @Param('id') id: string) { await this.hideUnlessVisible(req, id); @@ -206,8 +248,12 @@ export class FileSearchController { } @Put('connectors/:id/access-rules') - @ApiOperation({ summary: 'Set per-connector access rules' }) - setRules(@Req() req: any, @Param('id') id: string, @Body() body: FileAccessRulesDto) { + @ApiOperation({ + summary: 'Set per-connector access rules', + description: 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a connector they do not own.', + }) + async setRules(@Req() req: any, @Param('id') id: string, @Body() body: FileAccessRulesDto) { + await this.hideUnlessVisible(req, id); return this.svc.setAccessRules(req.user, id, body); } } diff --git a/packages/backend/src/file-search/file-search.service.ts b/packages/backend/src/file-search/file-search.service.ts index f7b37780c..c3ce852e2 100644 --- a/packages/backend/src/file-search/file-search.service.ts +++ b/packages/backend/src/file-search/file-search.service.ts @@ -31,7 +31,7 @@ import { buildFileSearchBuiltinTools } from './file-search-builtins'; import { clampInterval, nextPlan, SYNC_INTERVALS } from './file-search-quotas'; import { applySelection, checkQuota, estimate, selectionOf, type CompactListing, type Selection } from './file-search-selection'; import { CLOUD_PROTOCOLS, FILE_SEARCH_PROTOCOLS, isPausedState, type FileSearchConfig } from './file-search.types'; -import { connectorWhere, type VisibilityScope } from '../settings/member-visibility.service'; +import type { VisibilityScope } from '../settings/member-visibility.service'; /** * The setup wizard and the Files tab (#1385). Orchestration only: tests, @@ -184,14 +184,20 @@ export class FileSearchService { } /** - * Member visibility: a File Search connector a restricted member cannot see - * (not theirs, and no tool of it allowed by their roles) answers exactly - * the 404 of an unknown id. Called by the controller for restricted scopes - * only; the workspace filter stays, the visibility filter is added with AND. + * Member visibility: in a restricted workspace a member who is not an admin + * reaches the File Search routes of a connector only when they own it. + * Every other connector answers exactly the 404 of an unknown id, including + * one shared with them through their roles: the overview, tree, problems, + * runs, scans and access rules describe the source (its address, every + * folder and file name, the role rules) beyond what their AI client may + * read through the tools, which apply the folder rules. Called by the + * controller for restricted scopes only; the workspace filter stays, the + * owner filter is added with AND. */ async assertVisible(actor: Actor, id: string, scope: VisibilityScope): Promise { + if (!scope.restricted) return; const c = await this.prisma.connector.findFirst({ - where: { AND: [{ id, organizationId: actor.organizationId, type: 'FILE_SEARCH' as any }, connectorWhere(scope)] }, + where: { AND: [{ id, organizationId: actor.organizationId, type: 'FILE_SEARCH' as any }, { userId: scope.userId }] }, select: { id: true }, }); if (!c) throw new NotFoundException(FILE_SEARCH_CONNECTOR_NOT_FOUND); diff --git a/packages/backend/src/mcp-server/chatgpt-app.controller.spec.ts b/packages/backend/src/mcp-server/chatgpt-app.controller.spec.ts index cd76be53f..21dcf6288 100644 --- a/packages/backend/src/mcp-server/chatgpt-app.controller.spec.ts +++ b/packages/backend/src/mcp-server/chatgpt-app.controller.spec.ts @@ -55,7 +55,6 @@ function build(opts: { allowedByOrg?: Record } = {}) { ), getSharedGuide: jest.fn(async () => undefined), getServerNames: jest.fn(async () => []), - getServerNamesByOrg: jest.fn(async () => []), activityByConnector: jest.fn(async () => []), }; const setup = { get: jest.fn(() => ({ canSetUp: jest.fn(async () => true) })) }; @@ -73,6 +72,7 @@ function build(opts: { allowedByOrg?: Record } = {}) { { resolve: jest.fn().mockResolvedValue(null), clientRedirectUris: jest.fn(async () => ['https://claude.ai/api/mcp/auth_callback']), + serverNamesFor: jest.fn(async () => []), } as any, { create: jest.fn(), hasVisible: jest.fn().mockResolvedValue(false) } as any, setup as any, diff --git a/packages/backend/src/mcp-server/file-search-app.controller.spec.ts b/packages/backend/src/mcp-server/file-search-app.controller.spec.ts index 1e12baab3..2c37cd877 100644 --- a/packages/backend/src/mcp-server/file-search-app.controller.spec.ts +++ b/packages/backend/src/mcp-server/file-search-app.controller.spec.ts @@ -53,7 +53,6 @@ function build(opts: { allowedByOrg?: Record } = {}) { ), getSharedGuide: jest.fn(async () => undefined), getServerNames: jest.fn(async () => []), - getServerNamesByOrg: jest.fn(async () => []), activityByConnector: jest.fn(async () => []), }; const setup = { get: jest.fn(() => ({ canSetUp: jest.fn(async () => true) })) }; @@ -71,6 +70,7 @@ function build(opts: { allowedByOrg?: Record } = {}) { { resolve: jest.fn().mockResolvedValue(null), clientRedirectUris: jest.fn(async () => ['https://chatgpt.com/connector_platform_oauth_redirect']), + serverNamesFor: jest.fn(async () => []), } as any, { create: jest.fn(), hasVisible: jest.fn().mockResolvedValue(false) } as any, setup as any, diff --git a/packages/backend/src/mcp-server/mcp-endpoint.controller.ts b/packages/backend/src/mcp-server/mcp-endpoint.controller.ts index 4106d1303..2cc795259 100644 --- a/packages/backend/src/mcp-server/mcp-endpoint.controller.ts +++ b/packages/backend/src/mcp-server/mcp-endpoint.controller.ts @@ -765,7 +765,8 @@ export class McpEndpointController { const servers = serverIds.length ? await this.mcpServersService.getServerNames(serverIds) : organizationId - ? await this.mcpServersService.getServerNamesByOrg(organizationId) + ? // Member visibility: a restricted member is shown only their own servers. + await this.grants.serverNamesFor(user.sub, organizationId) : []; return { dashboardUrl: `${dashboardBase}/connectors`, diff --git a/packages/backend/src/mcp-server/shared-endpoint.assistant.spec.ts b/packages/backend/src/mcp-server/shared-endpoint.assistant.spec.ts index e7ce988e2..bff9397a8 100644 --- a/packages/backend/src/mcp-server/shared-endpoint.assistant.spec.ts +++ b/packages/backend/src/mcp-server/shared-endpoint.assistant.spec.ts @@ -24,7 +24,6 @@ function build(setup: unknown) { getConnectorSummaries: jest.fn(async () => []), getSharedGuide: jest.fn(async () => undefined), getServerNames: jest.fn(async () => []), - getServerNamesByOrg: jest.fn(async () => []), }; const controller = new McpEndpointController( servers as any, @@ -36,6 +35,7 @@ function build(setup: unknown) { { resolve: jest.fn().mockResolvedValue(null), clientRedirectUris: jest.fn(async (id?: string) => (id ? (REDIRECTS[id] ?? []) : [])), + serverNamesFor: jest.fn(async () => []), } as any, { create: jest.fn(), hasVisible: jest.fn().mockResolvedValue(false) } as any, { get: () => setup } as any, diff --git a/packages/backend/src/mcp-server/shared-endpoint.controller.spec.ts b/packages/backend/src/mcp-server/shared-endpoint.controller.spec.ts index 1beb53955..9bf67fe83 100644 --- a/packages/backend/src/mcp-server/shared-endpoint.controller.spec.ts +++ b/packages/backend/src/mcp-server/shared-endpoint.controller.spec.ts @@ -82,7 +82,6 @@ function build( ), getSharedGuide: jest.fn(async () => undefined), getServerNames: jest.fn(async () => []), - getServerNamesByOrg: jest.fn(async (org: string) => [{ id: `srv-${org}`, name: 'Default' }]), }; const controller = new McpEndpointController( servers as any, @@ -98,6 +97,7 @@ function build( { resolve: jest.fn().mockResolvedValue(opts.grant ?? null), clientRedirectUris: jest.fn(async (id?: string) => (id ? (REDIRECTS[id] ?? []) : [])), + serverNamesFor: jest.fn(async (_userId: string, org: string) => [{ id: `srv-${org}`, name: 'Default' }]), } as any, { create: jest.fn(), hasVisible: jest.fn().mockResolvedValue(false) } as any, ); diff --git a/packages/backend/src/mcp-servers/mcp-connection-grant.service.ts b/packages/backend/src/mcp-servers/mcp-connection-grant.service.ts index 6f59fdbcb..3e1420c3d 100644 --- a/packages/backend/src/mcp-servers/mcp-connection-grant.service.ts +++ b/packages/backend/src/mcp-servers/mcp-connection-grant.service.ts @@ -176,8 +176,8 @@ export class McpConnectionGrantService { * * Member visibility is decided per workspace, by that workspace's own mode * and the user's role there: in a restricted workspace where the user is not - * an admin, only the servers they own or that hold a connector they may see - * are listed, each with the count of those connectors. Feeds both + * an admin, only the servers they own are listed, each with the count of its + * connectors they may see. Feeds both * `GET /api/mcp-connections/targets` and the OAuth consent page's picker. */ async listSelectableTargets(userId: string): Promise< @@ -261,11 +261,13 @@ export class McpConnectionGrantService { /** * Of servers the user can already reach (see {@link validateServers}), the * ones member visibility lets them see, in the same order. A workspace in - * open mode, or where the user is an admin, keeps all of its servers. The + * open mode, or where the user is an admin, keeps all of its servers; in a + * restricted one a member who is not an admin keeps only their own. The * role comes from the membership row; a server whose membership row is - * gone is dropped (fail closed). + * gone is dropped (fail closed). Also used to name servers to the user + * (connections list, consent page). */ - private async keepVisible( + async keepVisible( userId: string, servers: { id: string; organizationId: string }[], ): Promise<{ id: string; organizationId: string }[]> { @@ -297,6 +299,44 @@ export class McpConnectionGrantService { return servers.filter((s) => keep.has(s.id)); } + /** + * The active servers of one workspace this user may be shown, oldest first: + * all of them in open mode or for an admin there, only their own in a + * restricted workspace. Empty when they are not an active member. For the + * server links handed to the model on the shared endpoint. + */ + async serverNamesFor(userId: string, organizationId: string): Promise> { + if (!userId || !organizationId) return []; + const membership = await this.prisma.organizationMember.findFirst({ + where: { userId, organizationId, deactivatedAt: null }, + select: { role: true }, + }); + if (!membership) return []; + const scope: VisibilityScope = this.visibility + ? await this.scopeIn(userId, membership.role as string, organizationId) + : { restricted: false }; + return this.prisma.mcpServerConfig.findMany({ + where: { AND: [{ organizationId, isActive: true }, serverWhere(scope)] }, + select: { id: true, name: true }, + orderBy: { createdAt: 'asc' }, + }); + } + + /** + * Whether member visibility narrows this user's view of one workspace (a + * member who is not an admin there, in a restricted workspace). False when + * they are not an active member. + */ + async restrictedIn(userId: string, organizationId: string): Promise { + if (!this.visibility || !userId || !organizationId) return false; + const membership = await this.prisma.organizationMember.findFirst({ + where: { userId, organizationId, deactivatedAt: null }, + select: { role: true }, + }); + if (!membership) return false; + return (await this.scopeIn(userId, membership.role as string, organizationId)).restricted; + } + /** Everything this user has granted, for the dashboard's revoke list. */ async listForUser(userId: string) { return this.prisma.mcpConnectionGrant.findMany({ diff --git a/packages/backend/src/mcp-servers/mcp-connections.controller.ts b/packages/backend/src/mcp-servers/mcp-connections.controller.ts index ebb7da0cd..6fc1b31e9 100644 --- a/packages/backend/src/mcp-servers/mcp-connections.controller.ts +++ b/packages/backend/src/mcp-servers/mcp-connections.controller.ts @@ -50,7 +50,12 @@ export class McpConnectionsController { ) {} @Get() - @ApiOperation({ summary: 'AI clients connected to the shared /mcp endpoint' }) + @ApiOperation({ + summary: 'AI clients connected to the shared /mcp endpoint', + description: + 'Your own connections only. In a workspace with restricted member visibility where you are not an admin, a ' + + 'granted server you do not own is left out of `servers`.', + }) async list(@Req() req: any) { const userId = req.user.sub; const grants = await this.grants.listForUser(userId); @@ -79,7 +84,9 @@ export class McpConnectionsController { ]); const clientName = new Map(clients.map((c) => [c.clientId, c.clientName])); - const serverById = new Map(servers.map((s) => [s.id, s])); + // Named only when member visibility lets this user see the server. + const shown = new Set((await this.grants.keepVisible(userId, servers)).map((s) => s.id)); + const serverById = new Map(servers.filter((s) => shown.has(s.id)).map((s) => [s.id, s])); const orgName = new Map(organizations.map((o) => [o.id, o.name])); return grants.map((g) => ({ @@ -104,9 +111,9 @@ export class McpConnectionsController { @ApiOperation({ summary: 'Workspaces and MCP servers this user can grant access to', description: - 'In a workspace with restricted member visibility where you are not an admin, only the servers you own or that ' + - 'hold a connector you can see are listed, each counting only those connectors; every workspace follows its own ' + - 'setting and your role there.', + 'In a workspace with restricted member visibility where you are not an admin, only the servers you own are ' + + 'listed, each counting only the connectors you can see; every workspace follows its own setting and your role ' + + 'there. The whole-workspace choice stays available.', }) async targets(@Req() req: any) { return this.grants.listSelectableTargets(req.user.sub); @@ -121,7 +128,7 @@ export class McpConnectionsController { 'When both are given, `organizationId` wins. The change applies from the client\'s next request.\n\n' + 'Answers `{ "ok": true }`, or `{ "ok": false, "reason": … }`: `not-a-member` (you are not in that workspace), ' + '`nothing-granted` (you can reach none of the servers; unreachable ids are dropped) or `empty-selection` (neither field given). ' + - 'In a workspace with restricted member visibility where you are not an admin, a server you cannot see is dropped like an unknown id.\n\n' + + 'In a workspace with restricted member visibility where you are not an admin, a server you do not own is dropped like an unknown id.\n\n' + '```bash\namcp api PUT /api/mcp-connections/$CLIENT_ID --data \'{"serverIds":["cmo9x1k2a0001abcdpq7rs8tu"]}\' --yes\n```', }) @ApiBody({ diff --git a/packages/backend/src/mcp-servers/mcp-servers.controller.ts b/packages/backend/src/mcp-servers/mcp-servers.controller.ts index 0d2fec374..1d1a67bdb 100644 --- a/packages/backend/src/mcp-servers/mcp-servers.controller.ts +++ b/packages/backend/src/mcp-servers/mcp-servers.controller.ts @@ -21,7 +21,12 @@ import { CODE_MODE_MODES, type CodeMode } from '../mcp-server/code-tool.util'; import { McpServersService } from './mcp-servers.service'; import { LicenseGuardService } from '../license/license-guard.service'; import { PrismaService } from '../common/prisma.service'; -import { MemberVisibilityService, type VisibilityScope } from '../settings/member-visibility.service'; +import { + MemberVisibilityService, + canSeeServer, + connectorWhere, + type VisibilityScope, +} from '../settings/member-visibility.service'; class CreateMcpServerDto { @ApiProperty({ description: 'Human-readable name.', example: 'Sales Workspace' }) @@ -114,12 +119,12 @@ const UNRESTRICTED_SCOPE: VisibilityScope = Object.freeze({ restricted: false as /** * Member visibility (settings/member-visibility.service.ts) on this * controller: in a workspace set to `restricted`, a member who is not an admin - * reads only the servers they own or that hold a connector they may see, and - * in each server only those connectors. A hidden server answers exactly the - * 404 an unknown id gets. Admins and open workspaces take today's code path. - * Writes keep their owner-or-admin rule; a VIEWER cannot create a server in - * any mode. The route-by-route rules are listed in - * mcp-servers.member-visibility.spec.ts. + * reads, changes and counts only the servers they own, and in each one only + * the connectors they may see. Another member's server answers exactly the + * 404 an unknown id gets, on reads and writes alike. Admins and open + * workspaces take today's code path. Writes keep their owner-or-admin rule; a + * VIEWER cannot create a server in any mode. The route-by-route rules are + * listed in settings/member-visibility.routes.ts. */ @ApiTags('MCP Servers') @ApiBearerAuth() @@ -147,6 +152,18 @@ export class McpServersController { } } + /** + * Restricted member visibility: another member's server answers the 404 of + * an unknown id, before the owner-or-admin rule could answer 403 and so + * confirm that it exists. Nothing for admins and open workspaces. + */ + private async hideUnlessVisible(server: any, req: any): Promise { + this.assertOrgMatch(server, req); + const scope = await this.scopeFor(req); + if (!canSeeServer(scope, server)) throw new NotFoundException('MCP server not found'); + return scope; + } + private assertCanWrite(server: any, req: any) { this.assertOrgMatch(server, req); if (req.user.role === 'VIEWER') { @@ -166,7 +183,8 @@ export class McpServersController { '(`calls30d`, `lastCallAt`). Without `limit` all servers are returned.\n\n' + '```bash\namcp api GET /api/mcp-servers\n```\n\n' + 'In a workspace with restricted member visibility, a member who is not an admin gets only the servers they own ' + - 'or that hold a connector they can see, each with only those connectors in its names and counts.', + '(never another member\'s server, not even one holding a connector they can see), each with only the connectors ' + + 'they can see in its names and counts.', }) @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Page size, 1..200. Omit for all.', example: 50 }) @ApiQuery({ name: 'offset', required: false, type: Number, description: 'Rows to skip.', example: 0 }) @@ -224,8 +242,8 @@ export class McpServersController { @ApiOperation({ summary: 'Get MCP server detail', description: - 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a server they ' + - 'cannot see, and only the connectors they can see on the others.', + 'In a workspace with restricted member visibility, a member who is not an admin gets 404 (the body of an unknown ' + + 'id) for every server they do not own, and on their own servers only the connectors they can see.', }) async get(@Req() req: any, @Param('id') id: string) { const scope = await this.scopeFor(req); @@ -248,7 +266,7 @@ export class McpServersController { description: 'Tool calls made through this server in the last 30 days and when the last one happened. Polled by the connect ' + 'page to show when the first request from an AI client arrives; also a cheap way to check a server is in use. ' + - 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for a server they cannot see.', + 'In a workspace with restricted member visibility, a member who is not an admin gets 404 for every server they do not own.', }) @ApiResponse({ status: 200, @@ -277,7 +295,8 @@ export class McpServersController { '`code_propose_tool` (propose a program as a saved code tool for an admin to approve).\n\n' + 'Code runs in an isolated sandbox and needs a configured code-runner. `skillsDelivery` sets how applied skills ' + 'reach clients (`auto`, `inline`, `index`); `isActive: false` switches the endpoint off. Only the server owner or ' + - 'an admin may change it; a slug already used in the workspace answers 409.\n\n' + + 'an admin may change it; a slug already used in the workspace answers 409. In a workspace with restricted member ' + + 'visibility, a member who is not an admin gets 404 for a server they do not own.\n\n' + '```bash\namcp api PUT /api/mcp-servers/ --data \'{"codeMode":"inline"}\' --yes\n```', }) @ApiBody({ @@ -294,6 +313,7 @@ export class McpServersController { async update(@Req() req: any, @Param('id') id: string, @Body() dto: UpdateMcpServerDto) { const server = await this.mcpServersService.findById(id); if (!server) throw new NotFoundException('MCP server not found'); + await this.hideUnlessVisible(server, req); this.assertCanWrite(server, req); // Switching a paused server back on counts against the plan's cap (Cloud). if (dto.isActive === true && !server.isActive) { @@ -303,10 +323,16 @@ export class McpServersController { } @Delete(':id') - @ApiOperation({ summary: 'Delete MCP server' }) + @ApiOperation({ + summary: 'Delete MCP server', + description: + 'Only the server owner or an admin. In a workspace with restricted member visibility, a member who is not an ' + + 'admin gets 404 for a server they do not own.', + }) async delete(@Req() req: any, @Param('id') id: string) { const server = await this.mcpServersService.findById(id); if (!server) throw new NotFoundException('MCP server not found'); + await this.hideUnlessVisible(server, req); this.assertCanWrite(server, req); await this.mcpServersService.delete(id); return { message: 'MCP server deleted' }; @@ -319,7 +345,8 @@ export class McpServersController { 'Sets the connectors whose tools this server exposes. The list **replaces** the current assignment: send every ' + 'connector that should stay, or `[]` to remove them all. Connected AI clients are told the tool list changed. ' + '404 when an id is not a connector of your workspace. Which tools each user may call is then decided by roles ' + - '(`/api/roles`).\n\n' + + '(`/api/roles`). In a workspace with restricted member visibility, a member who is not an admin gets 404 for a ' + + 'server they do not own and for a connector they cannot see.\n\n' + '```bash\namcp api PUT /api/mcp-servers//connectors --data \'{"connectorIds":[""]}\' --yes\n```', }) @ApiResponse({ status: 200, schema: { type: 'object', example: { message: 'Connectors assigned' } } }) @@ -330,12 +357,15 @@ export class McpServersController { ) { const server = await this.mcpServersService.findById(id); if (!server) throw new NotFoundException('MCP server not found'); + const scope = await this.hideUnlessVisible(server, req); this.assertCanWrite(server, req); - // Validate that all connectors belong to the same organization + // Validate that all connectors belong to the same organization and, for a + // restricted member, that they can see each one: a hidden connector + // answers like an unknown id. if (dto.connectorIds.length > 0) { const orgCount = await this.prisma.connector.count({ - where: { id: { in: dto.connectorIds }, organizationId: req.user.organizationId }, + where: { AND: [{ id: { in: dto.connectorIds }, organizationId: req.user.organizationId }, connectorWhere(scope)] }, }); if (orgCount !== dto.connectorIds.length) { throw new NotFoundException('One or more connectors not found'); diff --git a/packages/backend/src/mcp-servers/mcp-servers.member-visibility.integration.spec.ts b/packages/backend/src/mcp-servers/mcp-servers.member-visibility.integration.spec.ts index bf2a65056..33bab2dbd 100644 --- a/packages/backend/src/mcp-servers/mcp-servers.member-visibility.integration.spec.ts +++ b/packages/backend/src/mcp-servers/mcp-servers.member-visibility.integration.spec.ts @@ -191,11 +191,10 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; const IN_ORG = ['srvEditor', 'srvViewerDefault', 'srvShared', 'srvHidden', 'srvOther2Default', 'srvOtherDefault']; const visibleFor = (who: string, mode: string, state: string): string[] => { if (who === 'ADMIN' || mode === 'open') return IN_ORG; - const own = who === 'EDITOR' ? 'srvEditor' : 'srvViewerDefault'; - // D4: no whitelist, every server with a connector; D9: other members' empty defaults stay hidden. - if (state === 'none') return IN_ORG.filter((s) => s === own || !['srvViewerDefault', 'srvOther2Default'].includes(s)); - const viaRole = state === 'with tools' ? ['srvShared', 'srvOtherDefault'] : []; - return IN_ORG.filter((s) => s === own || viaRole.includes(s)); + // Restricted: only the member's own server, whatever the whitelist. Not + // srvShared or srvOtherDefault, although they hold `shared`. + void state; + return [who === 'EDITOR' ? 'srvEditor' : 'srvViewerDefault']; }; const name = (id: string) => Object.keys(ids).find((k) => ids[k] === id); const unknownBody = { statusCode: 404, message: 'MCP server not found', error: 'Not Found' }; @@ -253,7 +252,8 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; const second = targets.body.find((t: any) => t.organizationId === ids.org2); if (who === 'ADMIN') expect(second).toBeUndefined(); if (who === 'EDITOR') expect(second.servers.map((s: any) => name(s.id))).toEqual(['srvO2', 'srvO2Empty']); - if (who === 'VIEWER') expect(second.servers.map((s: any) => name(s.id))).toEqual(['srvO2']); + // Restricted there and owning nothing there: no server to offer. + if (who === 'VIEWER') expect(second.servers).toEqual([]); // Grants: a hidden server is refused exactly like an unknown id. const clientId = `client-${who}-${mode}-${state}`; @@ -271,6 +271,19 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; expect(stored!.serverIds.map(name).sort()).toEqual([...expected].sort()); }); + it.each(['ADMIN', 'EDITOR', 'VIEWER'])('%s: writes on another member\'s server', async (who) => { + const restricted = mode === 'restricted' && who !== 'ADMIN'; + for (const [method, path, body] of [ + ['PUT', `/api/mcp-servers/${ids.srvHidden}`, { description: 'changed' }], + ['PUT', `/api/mcp-servers/${ids.srvHidden}/connectors`, { connectorIds: [ids.hidden] }], + ] as const) { + const r = await call(who, method, path, body); + if (restricted) expect(r).toEqual({ status: 404, body: unknownBody }); + else if (who === 'ADMIN') expect(r.status).toBe(200); + else expect(r.status).toBe(403); + } + }); + it.each(['ADMIN', 'EDITOR', 'VIEWER'])('%s: POST /api/mcp-servers (D10)', async (who) => { const r = await call(who, 'POST', '/api/mcp-servers', { name: `created by ${who} ${mode} ${state}` }); if (who === 'VIEWER') { @@ -290,10 +303,29 @@ const url = process.env.AUDIT_TEST_DATABASE_URL; it('pages over visible servers only: limit and offset are applied after the filter', async () => { await setMode('restricted'); await setWhitelist('with tools'); - const all = (await get('VIEWER', '/api/mcp-servers')).body.map((s: any) => name(s.id)); - expect(all).toEqual(['srvViewerDefault', 'srvShared', 'srvOtherDefault']); - const page = await get('VIEWER', '/api/mcp-servers?limit=2&offset=1'); - expect(page.body.map((s: any) => name(s.id))).toEqual(['srvShared', 'srvOtherDefault']); + // Two more servers of the viewer, created after every other one. + const extra: string[] = []; + for (const [i, n] of ['viewer-second', 'viewer-third'].entries()) { + const s = await prisma.mcpServerConfig.create({ + data: { + userId: ids.VIEWER, + organizationId: ids.org, + name: n, + slug: `${n}-${randomUUID().slice(0, 8)}`, + createdAt: new Date(Date.UTC(2027, 0, 1, 0, i)), + }, + }); + extra.push(s.id); + ids[n] = s.id; + } + try { + const all = (await get('VIEWER', '/api/mcp-servers')).body.map((s: any) => name(s.id)); + expect(all).toEqual(['srvViewerDefault', 'viewer-second', 'viewer-third']); + const page = await get('VIEWER', '/api/mcp-servers?limit=2&offset=1'); + expect(page.body.map((s: any) => name(s.id))).toEqual(['viewer-second', 'viewer-third']); + } finally { + await prisma.mcpServerConfig.deleteMany({ where: { id: { in: extra } } }); + } }); it('fails closed: a role lookup that throws answers 500, never the unrestricted result', async () => { diff --git a/packages/backend/src/mcp-servers/mcp-servers.member-visibility.spec.ts b/packages/backend/src/mcp-servers/mcp-servers.member-visibility.spec.ts index d1f203e6a..a54239e02 100644 --- a/packages/backend/src/mcp-servers/mcp-servers.member-visibility.spec.ts +++ b/packages/backend/src/mcp-servers/mcp-servers.member-visibility.spec.ts @@ -14,9 +14,12 @@ import { McpServersService } from './mcp-servers.service'; * in RULES below, so a new read route cannot ship without one. * 2. Matrix: ADMIN / EDITOR / VIEWER x open / restricted x (no whitelist, * role with tools, role without tools), over servers the caller owns, - * other members' servers and other members' default servers (D9). A hidden - * server answers exactly the 404 an unknown id gets; admins and open - * workspaces never read their roles. + * other members' servers and other members' default servers. A restricted + * member sees only the servers they own, whatever their roles allow: a + * server of someone else answers exactly the 404 an unknown id gets, on + * reads and writes, even when it holds a connector they may see. Inside + * their own servers they see only the connectors they may see. Admins and + * open workspaces never read their roles. * 3. Server picker and grants: every workspace follows its own mode and the * caller's role there; a hidden server is dropped from a grant like an * unknown id. @@ -40,9 +43,9 @@ const OTHER = 'user-other'; const OTHER2 = 'user-other-2'; type Rule = - /** A list narrowed in the query: owned servers or those with a visible connector. */ + /** A list narrowed in the query: owned servers only, connectors narrowed. */ | 'list' - /** 404 (unknown-id body) for a hidden server, connectors narrowed. */ + /** 404 (unknown-id body) for a server the member does not own, connectors narrowed. */ | 'visible' /** Per workspace, by that workspace's mode and the caller's role there. */ | 'per-workspace' @@ -265,6 +268,10 @@ function makePrisma(w: World, myRoles: Record) { count: jest.fn(async (args: any) => members.filter((x) => x.userId === args.where.userId && x.organizationId === args.where.organizationId).length, ), + findFirst: jest.fn(async (args: any) => { + const x = members.find((mm) => mm.userId === args.where.userId && mm.organizationId === args.where.organizationId); + return x ? { role: x.role } : null; + }), }, mcpConnectionGrant: { findUnique: jest.fn(async () => null), @@ -273,6 +280,7 @@ function makePrisma(w: World, myRoles: Record) { }), }, mcpApiKey: { findMany: jest.fn(async () => []) }, + connector: { count: jest.fn(async (args: any) => w.connectors.filter((c) => m(c, args.where)).length) }, toolInvocation: { groupBy: jest.fn(async (args: any) => args.where.mcpServerId.in.map((id: string) => ({ @@ -386,31 +394,30 @@ const ALL_NAMES: Record = { 'srv-inactive': ['shared'], }; +/** What a restricted member sees: their own servers, whatever their roles allow. */ +const OWN = ['srv-mine', 'srv-mine-hidden']; + const CASES: Array<{ name: string; allowed: string[] | null; visible: string[]; names: Record }> = [ { - // D4: no whitelist, every connector is visible; D9: an empty server of - // another member is still hidden. + // No whitelist: every connector is visible, but another member's server + // stays hidden even when it holds them. name: 'no whitelist', allowed: null, - visible: IN_ORG.filter((s) => s !== 'srv-default-empty'), - names: ALL_NAMES, + visible: OWN, + names: { 'srv-mine': ['mine'], 'srv-mine-hidden': ['hidden'] }, }, { + // The role reaches `shared`, yet srv-shared and Default (other) stay + // hidden: holding a visible connector no longer shows a server. name: 'role with tools', allowed: ['s1'], - visible: ['srv-mine', 'srv-mine-hidden', 'srv-shared', 'srv-default-with', 'srv-inactive'], - names: { - 'srv-mine': ['mine'], - 'srv-mine-hidden': [], - 'srv-shared': ['shared'], - 'srv-default-with': ['shared'], - 'srv-inactive': ['shared'], - }, + visible: OWN, + names: { 'srv-mine': ['mine'], 'srv-mine-hidden': [] }, }, { name: 'role without tools', allowed: ['t-unrelated'], - visible: ['srv-mine', 'srv-mine-hidden'], + visible: OWN, names: { 'srv-mine': ['mine'], 'srv-mine-hidden': [] }, }, ]; @@ -516,6 +523,47 @@ describe.each(['open', 'restricted'] as const)('%s workspace', (mode) => { ]); }); + it.each(IN_ORG)('PUT, DELETE and PUT connectors on %s: the unknown-id 404 for a server the member does not own', async (id) => { + jest.spyOn(c.service, 'update').mockResolvedValue({ id } as any); + jest.spyOn(c.service, 'delete').mockResolvedValue(undefined); + jest.spyOn(c.service, 'assignConnectors').mockResolvedValue(undefined); + const owned = OWN.includes(id); + const ops = { + update: (r: any, x: string) => c.servers.update(r, x, { name: 'renamed' } as any), + delete: (r: any, x: string) => c.servers.delete(r, x), + assignConnectors: (r: any, x: string) => c.servers.assignConnectors(r, x, { connectorIds: ['mine'] }), + }; + for (const [op, run] of Object.entries(ops)) { + const unknown = await run(req('ADMIN'), 'no-such-id').catch((e: unknown) => e); + const got = await outcome(run(req(role), id)); + if (restricted && !visible.includes(id)) { + expect({ op, error: (got as any).error }).toEqual({ op, error: expect.any(NotFoundException) }); + expect((got as any).error.getResponse()).toEqual((unknown as NotFoundException).getResponse()); + } else if (role === 'VIEWER' || (role !== 'ADMIN' && !owned)) { + expect({ op, error: (got as any).error }).toEqual({ op, error: expect.any(ForbiddenException) }); + } else { + expect({ op, ok: got.ok }).toEqual({ op, ok: true }); + } + } + }); + + it('PUT /api/mcp-servers/srv-mine/connectors: a connector the member cannot see answers like an unknown one', async () => { + if (role === 'VIEWER') return; // a VIEWER cannot write at all (above) + jest.spyOn(c.service, 'assignConnectors').mockResolvedValue(undefined); + const unknown = await c.servers + .assignConnectors(req(role), 'srv-mine', { connectorIds: ['no-such-connector'] }) + .catch((e: unknown) => e); + expect(unknown).toBeInstanceOf(NotFoundException); + const got = await outcome(c.servers.assignConnectors(req(role), 'srv-mine', { connectorIds: ['mine', 'hidden'] })); + if (restricted && allowed !== null) { + expect(got.ok).toBe(false); + expect((got as any).error.getResponse()).toEqual((unknown as NotFoundException).getResponse()); + expect(c.service.assignConnectors).not.toHaveBeenCalled(); + } else { + expect(got).toEqual({ ok: true, value: { message: 'Connectors assigned' } }); + } + }); + it('POST /api/mcp-servers: refused for a VIEWER (D10), unchanged for EDITOR and ADMIN', async () => { const got = await outcome(c.servers.create(req(role), { name: 'Sales' })); if (role === 'VIEWER') { @@ -539,10 +587,11 @@ describe.each(['open', 'restricted'] as const)('%s workspace', (mode) => { // ── 3. Grants across workspaces ─────────────────────────────────────────── describe('grants across workspaces', () => { - it('a member admin elsewhere grants every server there, and only visible ones here', async () => { + it('a member admin elsewhere grants every server there, and only their own ones here', async () => { const c = build({ mode: 'restricted', role: 'VIEWER', allowed: ['s1'] }); - const granted = await c.grants.grantServers('client-1', ME, ['srv-hidden', 'srv-shared', 'srv-o2', 'srv-o3']); - expect(granted).toEqual(['srv-shared', 'srv-o2', 'srv-o3']); + const granted = await c.grants.grantServers('client-1', ME, ['srv-hidden', 'srv-shared', 'srv-mine', 'srv-o2', 'srv-o3']); + // srv-shared holds a connector the role reaches, and is still not granted. + expect(granted).toEqual(['srv-mine', 'srv-o2', 'srv-o3']); // The role lookup ran for the restricted workspace only. expect(c.roles.getAllowedToolIds).toHaveBeenCalledTimes(1); expect(c.roles.getAllowedToolIds).toHaveBeenCalledWith(ME, ORG); @@ -560,6 +609,31 @@ describe('grants across workspaces', () => { }); }); +// ── 3b. Server links for the model, and the consent default ─────────────── + +describe('server names for the shared endpoint and the consent page', () => { + it('names only the member\'s own active servers in a restricted workspace, every one otherwise', async () => { + const restricted = build({ mode: 'restricted', role: 'VIEWER', allowed: ['s1'] }); + expect((await restricted.grants.serverNamesFor(ME, ORG)).map((s) => s.id)).toEqual(OWN); + const open = build({ mode: 'open', role: 'VIEWER', allowed: ['s1'] }); + expect((await open.grants.serverNamesFor(ME, ORG)).map((s) => s.id)).toEqual( + IN_ORG.filter((s) => s !== 'srv-inactive'), + ); + // Admin in a restricted workspace: every active server. + expect((await restricted.grants.serverNamesFor(ME, ORG_ADMIN)).map((s) => s.id)).toEqual(['srv-o2']); + // Not a member: nothing. + expect(await restricted.grants.serverNamesFor(ME, FOREIGN)).toEqual([]); + }); + + it('restrictedIn follows each workspace\'s mode and the role there', async () => { + const c = build({ mode: 'restricted', role: 'EDITOR', allowed: null }); + expect(await c.grants.restrictedIn(ME, ORG)).toBe(true); + expect(await c.grants.restrictedIn(ME, ORG_ADMIN)).toBe(false); + expect(await c.grants.restrictedIn(ME, ORG_OPEN)).toBe(false); + expect(await c.grants.restrictedIn(ME, FOREIGN)).toBe(false); + }); +}); + // ── 4. Fail closed ──────────────────────────────────────────────────────── describe('fail closed', () => { diff --git a/packages/backend/src/mcp-servers/mcp-servers.service.ts b/packages/backend/src/mcp-servers/mcp-servers.service.ts index 123f7cffd..319bccc3c 100644 --- a/packages/backend/src/mcp-servers/mcp-servers.service.ts +++ b/packages/backend/src/mcp-servers/mcp-servers.service.ts @@ -169,9 +169,9 @@ export class McpServersService { /** * `findAllByOrg` for a member whose view is narrowed by member visibility: - * only the servers they own or that hold a connector they may see, and in - * each one only those connectors (names and `_count.connectors`). Filtered - * in the query, so `limit` and `offset` page over visible servers only. + * only the servers they own (`serverWhere`), and in each one only the + * connectors they may see (names and `_count.connectors`). Filtered in the + * query, so `limit` and `offset` page over visible servers only. */ async findAllVisibleByOrg( organizationId: string, @@ -202,9 +202,9 @@ export class McpServersService { /** * `findById` for a member whose view is narrowed by member visibility: - * null when the server is not in the workspace or not visible to them (the - * caller answers both with the unknown-id 404), otherwise the server with - * only the connectors they may see. + * null when the server is not in the workspace or not theirs (the caller + * answers both with the unknown-id 404), otherwise the server with only the + * connectors they may see. */ async findVisibleById(id: string, organizationId: string, scope: VisibilityScope) { const visibleConnector = { connector: connectorWhere(scope) }; @@ -578,17 +578,6 @@ export class McpServersService { }); } - /** Active servers of one workspace, for links handed to the model. */ - async getServerNamesByOrg( - organizationId: string, - ): Promise> { - return this.prisma.mcpServerConfig.findMany({ - where: { organizationId, isActive: true }, - select: { id: true, name: true }, - orderBy: { createdAt: 'asc' }, - }); - } - async getVisibleContent( serverId: string, visibleConnectorIds: string[], diff --git a/packages/backend/src/roles/mcp-api-keys.controller.ts b/packages/backend/src/roles/mcp-api-keys.controller.ts index f9b32d6cf..86cf2dde2 100644 --- a/packages/backend/src/roles/mcp-api-keys.controller.ts +++ b/packages/backend/src/roles/mcp-api-keys.controller.ts @@ -7,12 +7,18 @@ import { Param, Req, UseGuards, + NotFoundException, } from '@nestjs/common'; import { ForbiddenException } from '@nestjs/common'; import { ApiTags, ApiBearerAuth, ApiOperation, ApiProperty, ApiPropertyOptional, ApiSecurity, ApiBody, ApiResponse } from '@nestjs/swagger'; import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard'; import { IsString, IsOptional, IsIn } from 'class-validator'; import { McpApiKeysService } from './mcp-api-keys.service'; +import { + MemberVisibilityService, + canSeeServer, + type VisibilityScope, +} from '../settings/member-visibility.service'; import type { McpApiKeyScope } from '../generated/prisma/client'; class CreateKeyDto { @@ -49,20 +55,62 @@ class CreateKeyDto { @UseGuards(JwtOrManagementKeyGuard) @Controller('api/mcp-keys') export class McpApiKeysController { - constructor(private readonly keysService: McpApiKeysService) {} + constructor( + private readonly keysService: McpApiKeysService, + // Not @Optional: Nest refuses to boot without it. It is missing only in + // unit specs that build the controller by hand and predate the setting. + private readonly visibility?: MemberVisibilityService, + ) {} + + /** + * Member visibility: of `serverIds`, the servers the caller may not see. In + * a restricted workspace where the caller is not an admin, that is every + * server they do not own; each workspace follows its own mode and the + * caller's role there. A server in a workspace the caller is not an active + * member of counts as hidden. Empty for admins and open workspaces. + */ + private async hiddenServers(req: any, serverIds: string[]): Promise> { + const hidden = new Set(); + if (!this.visibility || serverIds.length === 0) return hidden; + const scopes = new Map(); + for (const server of await this.keysService.serverFacts(req.user.sub, serverIds)) { + if (server.ownerId === req.user.sub) continue; + if (!server.role) { + hidden.add(server.id); + continue; + } + let scope = scopes.get(server.organizationId); + if (!scope) { + scope = await this.visibility.scopeFor({ + sub: req.user.sub, + role: server.role, + organizationId: server.organizationId, + }); + scopes.set(server.organizationId, scope); + } + if (!canSeeServer(scope, { userId: server.ownerId })) hidden.add(server.id); + } + return hidden; + } @Get() @ApiOperation({ summary: 'List my MCP API keys', description: 'Your own keys in every scope, with name, scope, server, active flag and last use. The key value is masked ' + - '(only its last 8 characters are shown); the full value is returned once, at creation.', + '(only its last 8 characters are shown); the full value is returned once, at creation. In a workspace with ' + + 'restricted member visibility where you are not an admin, `mcpServer` is null on a key for a server you do not own.', }) async listKeys(@Req() req: any) { const keys = await this.keysService.listByUser(req.user.sub); + const hidden = await this.hiddenServers( + req, + keys.map((k) => k.mcpServerId).filter((id): id is string => !!id), + ); // Mask keys for display: show only last 8 chars return keys.map((k) => ({ ...k, + ...(k.mcpServerId && hidden.has(k.mcpServerId) ? { mcpServer: null } : {}), key: `mcp_${'•'.repeat(24)}${k.key.slice(-8)}`, })); } @@ -77,7 +125,9 @@ export class McpApiKeysController { '- `scope: "MANAGEMENT_READ"`: this API, `GET`/`HEAD` only, e.g. for dashboards and audits.\n' + '- `scope: "MANAGEMENT_ADMIN"`: this API, any method. Only admins can create one (403 otherwise).\n\n' + 'A key always acts with its owner\'s role and never grants more. `amcp login --browser` creates a management key ' + - 'for the CLI the same way. Revoke with `POST /api/mcp-keys/{id}/revoke`.', + 'for the CLI the same way. Revoke with `POST /api/mcp-keys/{id}/revoke`.\n\n' + + '404 when `mcpServerId` is not a server of a workspace you belong to; in a workspace with restricted member ' + + 'visibility where you are not an admin, also for a server you do not own.', }) @ApiBody({ type: CreateKeyDto, @@ -114,6 +164,11 @@ export class McpApiKeysController { if (scope === 'MANAGEMENT_ADMIN' && req.user.role !== 'ADMIN') { throw new ForbiddenException('MANAGEMENT_ADMIN scope requires an admin role'); } + // Restricted member visibility: another member's server answers like an + // unknown one (the service's 404). + if (dto.mcpServerId && (await this.hiddenServers(req, [dto.mcpServerId])).has(dto.mcpServerId)) { + throw new NotFoundException('MCP server not found'); + } // Returns the full key — user must save it, it won't be shown again return this.keysService.generate( req.user.sub, diff --git a/packages/backend/src/roles/mcp-api-keys.service.ts b/packages/backend/src/roles/mcp-api-keys.service.ts index c39722d8e..fb227054a 100644 --- a/packages/backend/src/roles/mcp-api-keys.service.ts +++ b/packages/backend/src/roles/mcp-api-keys.service.ts @@ -101,6 +101,35 @@ export class McpApiKeysService implements OnApplicationBootstrap { }); } + /** + * For member visibility: each of `serverIds` that exists, with its workspace, + * its owner and the caller's role in that workspace (null when the caller is + * not an active member there). + */ + async serverFacts( + userId: string, + serverIds: string[], + ): Promise> { + const ids = [...new Set(serverIds.filter(Boolean))]; + if (ids.length === 0) return []; + const servers = await this.prisma.mcpServerConfig.findMany({ + where: { id: { in: ids } }, + select: { id: true, organizationId: true, userId: true }, + }); + if (servers.length === 0) return []; + const memberships = await this.prisma.organizationMember.findMany({ + where: { userId, organizationId: { in: [...new Set(servers.map((s) => s.organizationId))] }, deactivatedAt: null }, + select: { organizationId: true, role: true }, + }); + const roleIn = new Map(memberships.map((m) => [m.organizationId, m.role as string])); + return servers.map((s) => ({ + id: s.id, + organizationId: s.organizationId, + ownerId: s.userId, + role: roleIn.get(s.organizationId) ?? null, + })); + } + async listByUser(userId: string) { return this.prisma.mcpApiKey.findMany({ // Support keys are an operator's, not the user's (see support-keys.ts). diff --git a/packages/backend/src/roles/roles.module.ts b/packages/backend/src/roles/roles.module.ts index 40b20b2a3..e5ce6e209 100644 --- a/packages/backend/src/roles/roles.module.ts +++ b/packages/backend/src/roles/roles.module.ts @@ -3,9 +3,12 @@ import { RolesService } from './roles.service'; import { RolesController } from './roles.controller'; import { McpApiKeysService } from './mcp-api-keys.service'; import { McpApiKeysController } from './mcp-api-keys.controller'; +import { MemberVisibilityModule } from '../settings/member-visibility.module'; @Global() @Module({ + // For McpApiKeysController (member visibility of the server a key is for). + imports: [MemberVisibilityModule], controllers: [RolesController, McpApiKeysController], providers: [RolesService, McpApiKeysService], exports: [RolesService, McpApiKeysService], diff --git a/packages/backend/src/settings/member-visibility.service.spec.ts b/packages/backend/src/settings/member-visibility.service.spec.ts index c14550391..c66f2c54a 100644 --- a/packages/backend/src/settings/member-visibility.service.spec.ts +++ b/packages/backend/src/settings/member-visibility.service.spec.ts @@ -5,6 +5,7 @@ import { MemberVisibilityService, VisibilityScope, canSeeConnector, + canSeeServer, connectorWhere, parseMemberVisibilityMode, serverWhere, @@ -351,33 +352,23 @@ describe('visibility helpers', () => { expect(serverWhere(open)).toEqual({}); }); - it('matches owned servers or servers holding a visible connector', () => { - expect(serverWhere(someTools)).toEqual({ - OR: [ - { userId: 'u1' }, - { - connectors: { - some: { - connector: { - OR: [{ userId: 'u1' }, { tools: { some: { id: { in: ['t1', 't3'] } } } }], - }, - }, - }, - }, - ], - }); - }); - - it('with no whitelist: owned servers or servers with any connector', () => { - expect(serverWhere(noWhitelist)).toEqual({ - OR: [{ userId: 'u1' }, { connectors: { some: { connector: {} } } }], - }); + it.each([ + ['a tool whitelist', 'someTools'], + ['no whitelist', 'noWhitelist'], + ['no allowed tool', 'noTools'], + ])('with %s: only the servers the member owns, never one that merely holds a visible connector', (_label, name) => { + const scope = { someTools, noWhitelist, noTools }[name as 'someTools' | 'noWhitelist' | 'noTools']; + expect(serverWhere(scope)).toEqual({ userId: 'u1' }); }); - it('with no allowed tool: owned servers or servers holding an owned connector', () => { - expect(serverWhere(noTools)).toEqual({ - OR: [{ userId: 'u1' }, { connectors: { some: { connector: { userId: 'u1' } } } }], - }); + it('canSeeServer is the in-memory twin', () => { + for (const scope of [open, someTools, noWhitelist, noTools]) { + for (const owner of ['u1', 'u9']) { + const where = serverWhere(scope); + const viaWhere = !('userId' in where) || where.userId === owner; + expect(canSeeServer(scope, { userId: owner })).toBe(viaWhere); + } + } }); }); }); diff --git a/packages/backend/src/settings/member-visibility.service.ts b/packages/backend/src/settings/member-visibility.service.ts index 25ffe98e0..380811400 100644 --- a/packages/backend/src/settings/member-visibility.service.ts +++ b/packages/backend/src/settings/member-visibility.service.ts @@ -11,7 +11,8 @@ import { OrgSettingsService } from './org-settings.service'; * workspace (the behaviour before this setting existed) * restricted a member who is not an admin sees only what their AI client * can use: their own calls, the connectors their roles reach, - * and the servers that hold one of those connectors + * and the MCP servers they own (never another member's server, + * even one holding a connector they may see) * * Stored in `org_settings` under `member_visibility`. No row, or any value * other than `restricted`, reads as `open`, so a workspace that never touched @@ -107,19 +108,26 @@ export function toolWhere(scope: VisibilityScope, connector: { userId: string }) } /** - * Prisma `where` for MCP servers the scope may see: owned by the caller, or - * holding at least one connector the caller may see. `{}` when not - * restricted. A server with no connector is visible to its owner only. Always - * combine it with the `organizationId` filter using AND. + * Prisma `where` for MCP servers the scope may see: in restricted mode only the + * servers the caller owns. `{}` when not restricted. + * + * A server's name ("Default (Alice)"), its endpoint path, its connectors and + * its usage describe another member's setup, so a restricted member never + * sees a server of someone else, not even one holding a connector they may + * see: they reach shared connectors through the workspace connection or their + * own server. Inside their own servers they still see only the connectors + * `connectorWhere` allows. Always combine it with the `organizationId` filter + * using AND. */ export function serverWhere(scope: VisibilityScope): Prisma.McpServerConfigWhereInput { if (!scope.restricted) return {}; - return { - OR: [ - { userId: scope.userId }, - { connectors: { some: { connector: connectorWhere(scope) } } }, - ], - }; + return { userId: scope.userId }; +} + +/** In-memory twin of `serverWhere` for one server row. */ +export function canSeeServer(scope: VisibilityScope, server: { userId: string | null }): boolean { + if (!scope.restricted) return true; + return server.userId === scope.userId; } /** From 6e057b69c248ed77d179a97b0b28c80a86de885c Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:18 +0100 Subject: [PATCH 4/6] Require a member-visibility decision for every API route member-visibility.routes.ts records, for each controller handler, what a member who is not an admin gets in a restricted workspace. A spec reads every controller through Nest route metadata and fails on a route without a decision or a decision without a route, and checks admin-only and scoped decisions against the code. MemberVisibilityInterceptor enforces the admin-when-restricted decisions (knowledge graph and skills reads, learning projects, plan fit) without changing those controllers. An integration spec runs the restricted VIEWER scenario against PostgreSQL. --- .../settings/member-visibility.interceptor.ts | 38 ++ .../src/settings/member-visibility.module.ts | 8 +- ...lity.restricted-viewer.integration.spec.ts | 403 ++++++++++++++ .../settings/member-visibility.routes.spec.ts | 246 +++++++++ .../src/settings/member-visibility.routes.ts | 503 ++++++++++++++++++ 5 files changed, 1197 insertions(+), 1 deletion(-) create mode 100644 packages/backend/src/settings/member-visibility.interceptor.ts create mode 100644 packages/backend/src/settings/member-visibility.restricted-viewer.integration.spec.ts create mode 100644 packages/backend/src/settings/member-visibility.routes.spec.ts create mode 100644 packages/backend/src/settings/member-visibility.routes.ts diff --git a/packages/backend/src/settings/member-visibility.interceptor.ts b/packages/backend/src/settings/member-visibility.interceptor.ts new file mode 100644 index 000000000..4425e43c9 --- /dev/null +++ b/packages/backend/src/settings/member-visibility.interceptor.ts @@ -0,0 +1,38 @@ +import { CallHandler, ExecutionContext, ForbiddenException, Injectable, NestInterceptor } from '@nestjs/common'; +import type { Observable } from 'rxjs'; +import { MemberVisibilityService } from './member-visibility.service'; +import { routeVisibility } from './member-visibility.routes'; + +/** What a restricted member gets on an `admin-when-restricted` route. */ +export const ADMIN_WHEN_RESTRICTED_MESSAGE = + 'In this workspace, members see only what their roles share with them. Ask a workspace admin.'; + +/** + * Enforces the `admin-when-restricted` decisions of member-visibility.routes.ts: + * a member who is not an admin, in a workspace set to `restricted`, gets 403 + * before the handler runs. Every other route, every admin and every open + * workspace pass through untouched (a map lookup, no database read). + * + * An interceptor rather than a guard because interceptors run after the + * controller's own guards, so `req.user` is set; and because it applies the + * decision without changing the controllers it protects (some live under + * ee/). Fails closed like `scopeFor`: if the mode or role lookup throws, the + * request fails. + */ +@Injectable() +export class MemberVisibilityInterceptor implements NestInterceptor { + constructor(private readonly visibility: MemberVisibilityService) {} + + async intercept(context: ExecutionContext, next: CallHandler): Promise> { + if (context.getType() !== 'http') return next.handle(); + const rule = routeVisibility(context.getClass().name, context.getHandler().name); + if (rule?.decision !== 'admin-when-restricted') return next.handle(); + const user = context.switchToHttp().getRequest()?.user; + // No user: the route's own guard decides (it has already run and let the + // request through only if the route allows that). + if (!user || user.role === 'ADMIN') return next.handle(); + const scope = await this.visibility.scopeFor(user); + if (scope.restricted) throw new ForbiddenException(ADMIN_WHEN_RESTRICTED_MESSAGE); + return next.handle(); + } +} diff --git a/packages/backend/src/settings/member-visibility.module.ts b/packages/backend/src/settings/member-visibility.module.ts index 8015c7868..b15d1e6d0 100644 --- a/packages/backend/src/settings/member-visibility.module.ts +++ b/packages/backend/src/settings/member-visibility.module.ts @@ -1,6 +1,8 @@ import { Module } from '@nestjs/common'; +import { APP_INTERCEPTOR } from '@nestjs/core'; import { SettingsModule } from './settings.module'; import { MemberVisibilityService } from './member-visibility.service'; +import { MemberVisibilityInterceptor } from './member-visibility.interceptor'; import { MemberVisibilityAdminController, MemberVisibilityMemberController, @@ -15,11 +17,15 @@ import { * API app, so nothing is imported for them here, and a module that imports * this one (audit, connectors, tools, MCP servers, File Search) creates no * import cycle. + * + * Also registers MemberVisibilityInterceptor app-wide: it refuses the + * `admin-when-restricted` routes of member-visibility.routes.ts to restricted + * members and passes every other request through. */ @Module({ imports: [SettingsModule], controllers: [MemberVisibilityMemberController, MemberVisibilityAdminController], - providers: [MemberVisibilityService], + providers: [MemberVisibilityService, { provide: APP_INTERCEPTOR, useClass: MemberVisibilityInterceptor }], exports: [MemberVisibilityService], }) export class MemberVisibilityModule {} diff --git a/packages/backend/src/settings/member-visibility.restricted-viewer.integration.spec.ts b/packages/backend/src/settings/member-visibility.restricted-viewer.integration.spec.ts new file mode 100644 index 000000000..bf2bcf4da --- /dev/null +++ b/packages/backend/src/settings/member-visibility.restricted-viewer.integration.spec.ts @@ -0,0 +1,403 @@ +import { randomUUID } from 'node:crypto'; +import { ExecutionContext, INestApplication, ValidationPipe } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { APP_INTERCEPTOR } from '@nestjs/core'; +import { Test } from '@nestjs/testing'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { PrismaClient } from '../generated/prisma/client'; +import { AuditController } from '../audit/audit.controller'; +import { AuditService } from '../audit/audit.service'; +import { SecurityEventService } from '../audit/security-event.service'; +import { JwtOrManagementKeyGuard } from '../auth/jwt-or-management-key.guard'; +import { PrismaService } from '../common/prisma.service'; +import { CatalogResyncService } from '../connectors/catalog-resync.service'; +import { ConnectorsController } from '../connectors/connectors.controller'; +import { ConnectorsService } from '../connectors/connectors.service'; +import { UserCredentialsService } from '../connectors/user-credentials.service'; +import { WebhookEventsService } from '../connectors/webhook-events.service'; +import { EditionService } from '../ee/licensing/edition.service'; +import { LicenseGuardService } from '../license/license-guard.service'; +import { McpConnectionGrantService } from '../mcp-servers/mcp-connection-grant.service'; +import { McpConnectionsController } from '../mcp-servers/mcp-connections.controller'; +import { McpServersController } from '../mcp-servers/mcp-servers.controller'; +import { McpServersService } from '../mcp-servers/mcp-servers.service'; +import { McpApiKeysController } from '../roles/mcp-api-keys.controller'; +import { McpApiKeysService } from '../roles/mcp-api-keys.service'; +import { RolesService } from '../roles/roles.service'; +import { MemberVisibilityInterceptor } from './member-visibility.interceptor'; +import { MemberVisibilityService } from './member-visibility.service'; +import { OrgSettingsService } from './org-settings.service'; +import { SiteSettingsService } from './site-settings.service'; + +/** + * The evaluator's scenario, end to end against PostgreSQL: a workspace in + * restricted mode, six connectors owned by an admin, one role that whitelists + * the tools of one of them, a VIEWER with that role, and MCP servers owned by + * the admin, by another member and by the viewer. + * + * The viewer must get exactly one connector (in the reduced view), only their + * own MCP server (holding that connector), the unknown-id 404 on every other + * server, and no address, no other member's server name, endpoint or usage + * anywhere in what they read: connectors, servers, the server picker, their + * keys and connections, and their audit log, analytics and breakdowns. + * + * Needs a migrated PostgreSQL in AUDIT_TEST_DATABASE_URL (as in CI). Every + * row it creates belongs to fixture workspaces and users it deletes again. + */ +const url = process.env.AUDIT_TEST_DATABASE_URL; +const KEY = 'k'.repeat(48); +/** Where the admin's connectors connect; must never reach the viewer. */ +const ADDRESS = 'erp-db.internal.example.invalid'; + +(url ? describe : describe.skip)('restricted VIEWER: one shared connector, only own servers (PostgreSQL)', () => { + let prisma: PrismaClient; + let app: INestApplication; + let base: string; + let audit: AuditService; + + const ids: Record = {}; + const users: Record = {}; + /** Everything the viewer read, to scan for leaks at the end. */ + const viewerSaw: string[] = []; + + const call = async (who: string, method: string, path: string, body?: unknown) => { + const res = await fetch(`${base}${path}`, { + method, + headers: { 'x-test-user': who, ...(body ? { 'content-type': 'application/json' } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + if (who === 'VIEWER') viewerSaw.push(text); + return { status: res.status, body: text ? JSON.parse(text) : null }; + }; + const get = (who: string, path: string) => call(who, 'GET', path); + + beforeAll(async () => { + process.env.ENCRYPTION_KEY = process.env.ENCRYPTION_KEY ?? KEY; + prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: url }) }); + await prisma.$connect(); + const tag = randomUUID(); + const prismaService = prisma as unknown as PrismaService; + + ids.org = (await prisma.organization.create({ data: { name: 'restricted viewer scenario' } })).id; + for (const [key, role, name] of [ + ['ADMIN', 'ADMIN', 'Alice'], + ['OTHER', 'EDITOR', 'Bob'], + ['VIEWER', 'VIEWER', 'Vera'], + ] as const) { + const id = ( + await prisma.user.create({ + data: { email: `mv-scenario-${key.toLowerCase()}-${tag}@example.invalid`, name }, + }) + ).id; + ids[key] = id; + await prisma.user.update({ where: { id }, data: { organizationId: ids.org, role } }); + await prisma.organizationMember.create({ data: { userId: id, organizationId: ids.org, role } }); + users[key] = { sub: id, role, organizationId: ids.org, email: 'member@example.invalid' }; + } + + // Six connectors of the admin, each with two tools, all pointing at an + // internal address. + for (let i = 1; i <= 6; i++) { + const c = await prisma.connector.create({ + data: { + userId: ids.ADMIN, + organizationId: ids.org, + name: `Connector ${i}`, + type: 'DATABASE', + baseUrl: `postgresql://reporting@${ADDRESS}:5432/erp${i}`, + createdAt: new Date(Date.UTC(2026, 0, 1, 0, i)), + }, + }); + ids[`c${i}`] = c.id; + for (const t of ['a', 'b']) { + ids[`c${i}${t}`] = ( + await prisma.mcpTool.create({ + data: { + connectorId: c.id, + name: `c${i}_${t}_${tag.slice(0, 6)}`, + description: 'fixture', + parameters: {}, + endpointMapping: { method: 'query', sql: `SELECT * FROM ${ADDRESS.split('.')[0]}_t${i}` }, + }, + }) + ).id; + } + } + + // One role that whitelists the tools of connector 1, given to the viewer. + ids.role = (await prisma.role.create({ data: { name: 'Sales', organizationId: ids.org } })).id; + await prisma.toolRoleAccess.createMany({ + data: [ids.c1a, ids.c1b].map((toolId) => ({ roleId: ids.role, toolId })), + }); + await prisma.userRoleAssignment.create({ data: { userId: ids.VIEWER, roleId: ids.role, organizationId: ids.org } }); + + // Servers: the admin's default (all six), the admin's team server and the + // other member's default (both holding connector 1), the viewer's default + // (connector 1). + const mkServer = async (key: string, owner: string, name: string, connectors: string[], minute: number) => { + ids[key] = ( + await prisma.mcpServerConfig.create({ + data: { + userId: owner, + organizationId: ids.org, + name, + slug: `${key.toLowerCase()}-${tag.slice(0, 8)}`, + createdAt: new Date(Date.UTC(2026, 0, 2, 0, minute)), + }, + }) + ).id; + for (const c of connectors) { + await prisma.mcpServerConnector.create({ data: { mcpServerId: ids[key], connectorId: ids[c] } }); + } + }; + await mkServer('srvAdmin', ids.ADMIN, 'Default (Alice)', ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'], 0); + await mkServer('srvTeam', ids.ADMIN, 'Finance team', ['c1'], 1); + await mkServer('srvOther', ids.OTHER, 'Default (Bob)', ['c1'], 2); + await mkServer('srvViewer', ids.VIEWER, 'Default (Vera)', ['c1'], 3); + + // The viewer's own calls, through their server and through the team + // server; and calls of the others on the team and Bob's server. + const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000); + const invoke = (userId: string, toolId: string, mcpServerId: string, m: number, status: 'SUCCESS' | 'ERROR' = 'SUCCESS') => + prisma.toolInvocation.create({ + data: { + toolId, + connectorId: ids.c1, + userId, + mcpServerId, + organizationId: ids.org, + status, + durationMs: 100, + input: { q: 'fixture' }, + error: status === 'ERROR' ? `failed on ${ADDRESS}` : null, + createdAt: minutesAgo(m), + }, + }); + await invoke(ids.VIEWER, ids.c1a, ids.srvViewer, 30); + await invoke(ids.VIEWER, ids.c1a, ids.srvTeam, 20); + await invoke(ids.ADMIN, ids.c1a, ids.srvTeam, 10, 'ERROR'); + await invoke(ids.OTHER, ids.c1b, ids.srvOther, 5); + + // A grant the viewer made before the workspace was restricted, naming + // the team server and their own. + await prisma.mcpConnectionGrant.create({ + data: { clientId: `client-${tag}`, userId: ids.VIEWER, serverIds: [ids.srvTeam, ids.srvViewer] }, + }); + + const roles = new RolesService(prismaService); + const visibility = new MemberVisibilityService(new OrgSettingsService(prismaService, {} as SiteSettingsService), roles); + await visibility.setMode(ids.org, 'restricted'); + const servers = new McpServersService(prismaService, {} as any, { notifyToolsChanged: async () => undefined } as any); + const grants = new McpConnectionGrantService(prismaService, undefined, visibility); + const configService = { get: (k: string) => (k === 'ENCRYPTION_KEY' ? KEY : undefined) }; + const connectorsService = new ConnectorsService( + prismaService, + configService as unknown as ConfigService, + {} as any, + {} as any, + {} as any, + {} as any, + {} as any, + ); + audit = new AuditService(prismaService); + + const moduleRef = await Test.createTestingModule({ + controllers: [ConnectorsController, McpServersController, McpConnectionsController, AuditController, McpApiKeysController], + providers: [ + { provide: PrismaService, useValue: prisma }, + { provide: ConfigService, useValue: configService }, + { provide: ConnectorsService, useValue: connectorsService }, + { provide: McpServersService, useValue: servers }, + { provide: McpConnectionGrantService, useValue: grants }, + { provide: MemberVisibilityService, useValue: visibility }, + { provide: AuditService, useValue: audit }, + { provide: McpApiKeysService, useValue: new McpApiKeysService(prismaService) }, + { provide: LicenseGuardService, useValue: { checkCanCreateMcpServer: async () => undefined } }, + { provide: SecurityEventService, useValue: { log: async () => undefined } }, + { provide: EditionService, useValue: { hasEnterprise: async () => true, assertEnterprise: async () => undefined } }, + { provide: UserCredentialsService, useValue: { status: async () => ({ connected: false }), remove: async () => false } }, + { provide: WebhookEventsService, useValue: { recentEvents: async () => [] } }, + { provide: CatalogResyncService, useValue: { computeDiff: async () => null } }, + { provide: APP_INTERCEPTOR, useClass: MemberVisibilityInterceptor }, + ], + }) + .useMocker(() => ({})) + .overrideGuard(JwtOrManagementKeyGuard) + .useValue({ + canActivate(context: ExecutionContext) { + const req = context.switchToHttp().getRequest(); + req.user = users[req.headers['x-test-user']]; + return true; + }, + }) + .compile(); + app = moduleRef.createNestApplication({ logger: false }); + app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); + await app.listen(0, '127.0.0.1'); + base = await app.getUrl(); + }); + + afterAll(async () => { + await app?.close(); + await audit?.onModuleDestroy(); + if (prisma) { + await prisma.organization.deleteMany({ where: { id: ids.org } }); + await prisma.user.deleteMany({ where: { id: { in: ['ADMIN', 'OTHER', 'VIEWER'].map((k) => ids[k]).filter(Boolean) } } }); + await prisma.$disconnect(); + } + }); + + const unknownServer = { statusCode: 404, message: 'MCP server not found', error: 'Not Found' }; + + it('the admin sees the whole workspace (sanity check of the fixture)', async () => { + expect((await get('ADMIN', '/api/connectors')).body).toHaveLength(6); + expect((await get('ADMIN', '/api/mcp-servers')).body.map((s: any) => s.name)).toEqual([ + 'Default (Alice)', + 'Finance team', + 'Default (Bob)', + 'Default (Vera)', + ]); + }); + + it('gets exactly the one connector their role reaches, in the reduced view', async () => { + const list = await get('VIEWER', '/api/connectors'); + expect(list.status).toBe(200); + expect(list.body.map((c: any) => c.id)).toEqual([ids.c1]); + expect(list.body[0].memberView).toBe(true); + expect(list.body[0].tools.map((t: any) => t.id).sort()).toEqual([ids.c1a, ids.c1b].sort()); + expect(list.body[0]).not.toHaveProperty('baseUrl'); + + const detail = await get('VIEWER', `/api/connectors/${ids.c1}`); + expect(detail.status).toBe(200); + expect(detail.body.memberView).toBe(true); + expect(detail.body).not.toHaveProperty('mcpServers'); + + for (const c of ['c2', 'c3', 'c4', 'c5', 'c6']) { + const hidden = await get('VIEWER', `/api/connectors/${ids[c]}`); + expect(hidden.status).toBe(404); + expect(hidden.body).toEqual({ statusCode: 404, message: `Connector ${ids[c]} not found`, error: 'Not Found' }); + } + }); + + it('lists only their own MCP server, holding only the connector they can see', async () => { + const list = await get('VIEWER', '/api/mcp-servers'); + expect(list.status).toBe(200); + expect(list.body).toHaveLength(1); + expect(list.body[0]).toMatchObject({ id: ids.srvViewer, name: 'Default (Vera)', _count: { connectors: 1 } }); + expect(list.body[0].connectors).toEqual([{ connector: { name: 'Connector 1' } }]); + expect(list.body[0].usage.calls30d).toBe(1); + + const detail = await get('VIEWER', `/api/mcp-servers/${ids.srvViewer}`); + expect(detail.status).toBe(200); + expect(detail.body.connectors.map((c: any) => c.connector.id)).toEqual([ids.c1]); + }); + + it.each(['srvAdmin', 'srvTeam', 'srvOther'])('answers %s, with any route, exactly like an unknown id', async (key) => { + const id = ids[key]; + for (const [method, path, body] of [ + ['GET', `/api/mcp-servers/${id}`, undefined], + ['GET', `/api/mcp-servers/${id}/activity`, undefined], + ['PUT', `/api/mcp-servers/${id}`, { name: 'renamed' }], + ['PUT', `/api/mcp-servers/${id}/connectors`, { connectorIds: [ids.c1] }], + ['DELETE', `/api/mcp-servers/${id}`, undefined], + ] as const) { + const unknown = await call('VIEWER', method, path.replace(id, 'no-such-server'), body); + expect(await call('VIEWER', method, path, body)).toEqual(unknown); + expect(unknown).toEqual({ status: 404, body: unknownServer }); + } + // Nothing was changed. + expect((await prisma.mcpServerConfig.findUnique({ where: { id } }))?.name).not.toBe('renamed'); + }); + + it('offers only their own server in the picker, and grants nothing else', async () => { + const targets = await get('VIEWER', '/api/mcp-connections/targets'); + expect(targets.body).toEqual([ + { + organizationId: ids.org, + organizationName: 'restricted viewer scenario', + servers: [{ id: ids.srvViewer, name: 'Default (Vera)', connectorCount: 1 }], + }, + ]); + const grant = await call('VIEWER', 'PUT', '/api/mcp-connections/client-new', { serverIds: [ids.srvTeam] }); + expect(grant.body).toEqual({ ok: false, reason: 'nothing-granted' }); + }); + + it('names in their connections only the servers they own', async () => { + const list = await get('VIEWER', '/api/mcp-connections'); + expect(list.body).toHaveLength(1); + expect(list.body[0].servers).toEqual([{ id: ids.srvViewer, name: 'Default (Vera)' }]); + }); + + it('creates a key only for their own server, and names no other server on their keys', async () => { + const refused = await call('VIEWER', 'POST', '/api/mcp-keys', { name: 'team', mcpServerId: ids.srvTeam }); + const unknown = await call('VIEWER', 'POST', '/api/mcp-keys', { name: 'none', mcpServerId: 'no-such-server' }); + expect(refused).toEqual(unknown); + expect(refused.status).toBe(404); + const own = await call('VIEWER', 'POST', '/api/mcp-keys', { name: 'mine', mcpServerId: ids.srvViewer }); + expect(own.status).toBe(201); + // A key made for the team server earlier (open mode) stays theirs, unnamed. + await prisma.mcpApiKey.create({ + data: { + userId: ids.VIEWER, + organizationId: ids.org, + key: `mcp_${randomUUID().replace(/-/g, '')}`, + name: 'older', + mcpServerId: ids.srvTeam, + }, + }); + const keys = (await get('VIEWER', '/api/mcp-keys')).body; + const byName = Object.fromEntries(keys.map((k: any) => [k.name, k])); + expect(byName.mine.mcpServer).toEqual({ id: ids.srvViewer, name: 'Default (Vera)' }); + expect(byName.older.mcpServer).toBeNull(); + }); + + it('sees their own calls, with only their own server named, in every audit view', async () => { + const inv = await get('VIEWER', '/api/audit/invocations'); + expect(inv.body).toHaveLength(2); + expect(inv.body.every((r: any) => r.user.id === ids.VIEWER)).toBe(true); + expect(inv.body.map((r: any) => r.mcpServer?.name ?? null).sort()).toEqual(['Default (Vera)', null].sort()); + expect((await get('VIEWER', `/api/audit/invocations?mcpServerId=${ids.srvTeam}`)).body).toEqual([]); + + const breakdowns = await get('VIEWER', '/api/audit/breakdowns'); + expect(breakdowns.body.byServer.sort((a: any, b: any) => String(a.id).localeCompare(String(b.id)))).toEqual( + [ + { id: ids.srvViewer, label: 'Default (Vera)', count: 1, errors: 0 }, + { id: null, label: 'Other server or none', count: 1, errors: 0 }, + ].sort((a, b) => String(a.id).localeCompare(String(b.id))), + ); + expect(breakdowns.body.byUser).toEqual([{ id: ids.VIEWER, label: 'Vera', count: 1 + 1, errors: 0 }]); + + const perf = await get('VIEWER', '/api/audit/tool-performance?hours=24'); + expect(perf.body.items.map((i: any) => [i.mcpServerId, i.mcpServerName, i.calls]).sort()).toEqual( + [ + [ids.srvViewer, 'Default (Vera)', 1], + [null, null, 1], + ].sort(), + ); + expect(perf.body.items.every((i: any) => i.lastError === null)).toBe(true); + const filtered = await get('VIEWER', `/api/audit/tool-performance?mcpServerId=${ids.srvTeam}`); + expect(filtered.body.items).toEqual([]); + + expect((await get('VIEWER', '/api/audit/stats')).body.invocations24h).toBe(2); + }); + + it('never read an address, another member\'s server, its endpoint or a hidden connector', () => { + const all = viewerSaw.join('\n'); + expect(all.length).toBeGreaterThan(0); + for (const secret of [ + ADDRESS, + 'Default (Alice)', + 'Finance team', + 'Default (Bob)', + 'Alice', + 'Bob', + ids.srvAdmin, + ids.srvOther, + `/mcp/${ids.srvTeam}`, + ...['c2', 'c3', 'c4', 'c5', 'c6'].flatMap((c) => [`Connector ${c.slice(1)}`]), + ]) { + expect({ secret, found: all.includes(secret) }).toEqual({ secret, found: false }); + } + }); +}); diff --git a/packages/backend/src/settings/member-visibility.routes.spec.ts b/packages/backend/src/settings/member-visibility.routes.spec.ts new file mode 100644 index 000000000..c95cedbf9 --- /dev/null +++ b/packages/backend/src/settings/member-visibility.routes.spec.ts @@ -0,0 +1,246 @@ +// ESM-only, and only needed to run SSO flows; the routes are read, never run. +jest.mock('openid-client', () => ({})); + +import 'reflect-metadata'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { ForbiddenException, Logger, RequestMethod } from '@nestjs/common'; +import { METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants'; +import { of } from 'rxjs'; +import { ROLES_KEY } from '../auth/roles.guard'; +import { ADMIN_WHEN_RESTRICTED_MESSAGE, MemberVisibilityInterceptor } from './member-visibility.interceptor'; +import { MEMBER_VISIBILITY_DECISIONS, MEMBER_VISIBILITY_ROUTES } from './member-visibility.routes'; +import { MemberVisibilityService } from './member-visibility.service'; + +/** + * Every HTTP route of the API must carry an explicit member-visibility + * decision in member-visibility.routes.ts. + * + * The routes are read the way Nest reads them: every source file that + * declares a controller is loaded, and every handler with route metadata on + * a class marked as a controller counts. A route that returns workspace data + * and has no decision fails this spec, so it cannot reach a restricted member + * unnoticed. A decision for a route that no longer exists fails it too, so + * the table stays the list of real routes. + * + * Where reflection can check a decision, it does: `admin-only` without a note + * must carry `@Roles('ADMIN')`, and a `scoped` route's controller must inject + * MemberVisibilityService (three listed routes delegate to a service that does). `admin-when-restricted` is enforced by + * MemberVisibilityInterceptor, tested below on every such route. + */ + +const SRC = join(__dirname, '..'); + +interface Route { + key: string; + controller: any; + handler: (...args: unknown[]) => unknown; + method: string; + path: string; +} + +/** Source files that declare a controller (generated code and specs excluded). */ +function controllerFiles(dir: string): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) { + if (entry.name !== 'generated' && entry.name !== 'node_modules') out.push(...controllerFiles(path)); + } else if ( + entry.name.endsWith('.ts') && + !entry.name.endsWith('.spec.ts') && + !entry.name.endsWith('.d.ts') && + readFileSync(path, 'utf8').includes('@Controller(') + ) { + out.push(path); + } + } + return out.sort(); +} + +function joinPath(base: unknown, sub: unknown): string { + const parts = [base, sub].filter((p): p is string => typeof p === 'string' && p !== '' && p !== '/'); + return ('/' + parts.join('/')).replace(/\/+/g, '/'); +} + +function collectRoutes(): { routes: Route[]; controllers: Set } { + const routes: Route[] = []; + const controllers = new Set(); + for (const file of controllerFiles(SRC)) { + + const mod = require(file) as Record; + for (const [name, value] of Object.entries(mod)) { + if (typeof value !== 'function' || !Reflect.getMetadata('__controller__', value)) continue; + controllers.add(name); + const base = Reflect.getMetadata(PATH_METADATA, value); + const proto = (value as { prototype: Record }).prototype; + for (const prop of Object.getOwnPropertyNames(proto)) { + const handler = proto[prop]; + if (prop === 'constructor' || typeof handler !== 'function') continue; + const method = Reflect.getMetadata(METHOD_METADATA, handler); + if (method === undefined) continue; + routes.push({ + key: `${name}.${prop}`, + controller: value, + handler: handler as (...args: unknown[]) => unknown, + method: RequestMethod[method as RequestMethod], + path: joinPath(base, Reflect.getMetadata(PATH_METADATA, handler)), + }); + } + } + } + return { routes, controllers }; +} + +// Loading every controller compiles most of the backend once. +jest.setTimeout(180_000); + +let ROUTES: Route[]; +let CONTROLLERS: Set; +beforeAll(() => { + jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined); + jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + ({ routes: ROUTES, controllers: CONTROLLERS } = collectRoutes()); +}); +afterAll(() => jest.restoreAllMocks()); + +describe('member visibility: a decision for every route', () => { + it('finds the controllers (the scan cannot silently come back empty)', () => { + expect(CONTROLLERS.size).toBeGreaterThan(50); + expect(ROUTES.length).toBeGreaterThan(350); + expect(CONTROLLERS).toContain('McpServersController'); + expect(CONTROLLERS).toContain('FileSearchController'); + // ee/ controllers are part of the API too. + expect(CONTROLLERS).toContain('LearningController'); + }); + + it('every route has a registered decision', () => { + const missing = ROUTES.filter((r) => !MEMBER_VISIBILITY_ROUTES[r.key]).map((r) => `${r.key} (${r.method} ${r.path})`); + // A new route: decide what a member who is not an admin gets from it in a + // restricted workspace, then add it to member-visibility.routes.ts. + expect(missing).toEqual([]); + }); + + it('every registered decision belongs to a route that exists', () => { + const keys = new Set(ROUTES.map((r) => r.key)); + expect(Object.keys(MEMBER_VISIBILITY_ROUTES).filter((k) => !keys.has(k))).toEqual([]); + }); + + it('every decision is one of the known ones', () => { + const known = new Set(MEMBER_VISIBILITY_DECISIONS); + const unknown = Object.entries(MEMBER_VISIBILITY_ROUTES) + .filter(([, v]) => !known.has(v.decision)) + .map(([k]) => k); + expect(unknown).toEqual([]); + }); + + it('admin-only without a note carries @Roles(\'ADMIN\')', () => { + const wrong = ROUTES.filter((r) => { + const rule = MEMBER_VISIBILITY_ROUTES[r.key]; + if (rule?.decision !== 'admin-only' || rule.note) return false; + const roles = Reflect.getMetadata(ROLES_KEY, r.handler) ?? Reflect.getMetadata(ROLES_KEY, r.controller); + return !(Array.isArray(roles) && roles.length === 1 && roles[0] === 'ADMIN'); + }).map((r) => r.key); + expect(wrong).toEqual([]); + }); + + it('scoped routes inject MemberVisibilityService, unless they delegate to a service that does', () => { + // A note explains the decision; it does not excuse the controller from + // asking the service. These routes delegate to McpConnectionGrantService. + const delegated = new Set([ + 'LoginController.handleServerSelection', + 'McpConnectionsController.targets', + 'McpConnectionsController.update', + ]); + const wrong = ROUTES.filter((r) => { + if (MEMBER_VISIBILITY_ROUTES[r.key]?.decision !== 'scoped' || delegated.has(r.key)) return false; + const params: unknown[] = Reflect.getMetadata('design:paramtypes', r.controller) ?? []; + return !params.includes(MemberVisibilityService); + }).map((r) => r.key); + expect(wrong).toEqual([]); + }); +}); + +describe('MemberVisibilityInterceptor', () => { + const ORG = 'org-1'; + const build = (mode: 'open' | 'restricted') => { + const orgSettings = { get: jest.fn(async () => (mode === 'restricted' ? 'restricted' : null)) }; + const roles = { getAllowedToolIds: jest.fn(async () => ['t1']) }; + const visibility = new MemberVisibilityService(orgSettings as any, roles as any); + return { interceptor: new MemberVisibilityInterceptor(visibility), orgSettings, roles }; + }; + const context = (route: Route, role: string | null) => + ({ + getType: () => 'http', + getClass: () => route.controller, + getHandler: () => route.handler, + switchToHttp: () => ({ + getRequest: () => (role ? { user: { sub: 'user-1', role, organizationId: ORG } } : {}), + }), + }) as any; + const next = () => ({ handle: jest.fn(() => of('handled')) }); + + const adminWhenRestricted = () => + ROUTES.filter((r) => MEMBER_VISIBILITY_ROUTES[r.key]?.decision === 'admin-when-restricted'); + + it('has routes to enforce', () => { + expect(adminWhenRestricted().map((r) => r.key)).toEqual( + expect.arrayContaining(['KgController.getGraph', 'LearningController.list', 'LicenseController.planFitForUser']), + ); + }); + + it.each(['EDITOR', 'VIEWER'])('refuses every admin-when-restricted route to a restricted %s, before the handler', async (role) => { + const { interceptor } = build('restricted'); + for (const route of adminWhenRestricted()) { + const n = next(); + const err = await interceptor.intercept(context(route, role), n).catch((e: unknown) => e); + expect(err).toBeInstanceOf(ForbiddenException); + expect((err as ForbiddenException).message).toBe(ADMIN_WHEN_RESTRICTED_MESSAGE); + expect(n.handle).not.toHaveBeenCalled(); + } + }); + + it('lets admins through in a restricted workspace without reading the mode', async () => { + const { interceptor, orgSettings } = build('restricted'); + for (const route of adminWhenRestricted()) { + const n = next(); + await interceptor.intercept(context(route, 'ADMIN'), n); + expect(n.handle).toHaveBeenCalledTimes(1); + } + expect(orgSettings.get).not.toHaveBeenCalled(); + }); + + it.each(['EDITOR', 'VIEWER'])('lets a %s through in an open workspace', async (role) => { + const { interceptor, roles } = build('open'); + for (const route of adminWhenRestricted()) { + const n = next(); + await interceptor.intercept(context(route, role), n); + expect(n.handle).toHaveBeenCalledTimes(1); + } + expect(roles.getAllowedToolIds).not.toHaveBeenCalled(); + }); + + it('passes every other route through without a database read', async () => { + const { interceptor, orgSettings } = build('restricted'); + const others = ROUTES.filter((r) => MEMBER_VISIBILITY_ROUTES[r.key]?.decision !== 'admin-when-restricted'); + for (const route of others) { + const n = next(); + await interceptor.intercept(context(route, 'VIEWER'), n); + expect(n.handle).toHaveBeenCalledTimes(1); + } + expect(orgSettings.get).not.toHaveBeenCalled(); + }); + + it('fails closed when the mode lookup throws', async () => { + const boom = new Error('settings unavailable'); + const visibility = new MemberVisibilityService( + { get: jest.fn(async () => Promise.reject(boom)) } as any, + { getAllowedToolIds: jest.fn() } as any, + ); + const interceptor = new MemberVisibilityInterceptor(visibility); + const route = adminWhenRestricted()[0]; + const n = next(); + await expect(interceptor.intercept(context(route, 'VIEWER'), n)).rejects.toBe(boom); + expect(n.handle).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/backend/src/settings/member-visibility.routes.ts b/packages/backend/src/settings/member-visibility.routes.ts new file mode 100644 index 000000000..9ec6015a6 --- /dev/null +++ b/packages/backend/src/settings/member-visibility.routes.ts @@ -0,0 +1,503 @@ +/** + * Member visibility: the decision taken for every HTTP route of the API. + * + * In a workspace set to `restricted`, a member who is not an admin must see + * only what their AI client can use: their own calls, the connectors their + * roles reach and the MCP servers they own. Every route that could answer + * with workspace data therefore needs an explicit decision, and this table is + * where it is written down. member-visibility.routes.spec.ts reads every + * controller through Nest's route metadata and fails when a route is missing + * here (or listed here but gone), so a new route cannot ship without someone + * deciding what a restricted member gets from it. + * + * Keys are `.`. Decisions: + * + * - `scoped`: the route narrows its answer through MemberVisibilityService + * (or a service that does, named in the note). Hidden ids answer the 404 of + * an unknown id. + * - `admin-when-restricted`: refused (403) to a member who is not an admin in a + * restricted workspace, by MemberVisibilityInterceptor, before the handler + * runs. Open workspaces and admins are unchanged. For routes whose answer is + * other members' work (the knowledge graph, learning projects) or the whole + * workspace's inventory (plan fit), where narrowing makes no sense. + * - `admin-only`: ADMIN only in every mode (`@Roles('ADMIN')`, or a check in + * code named in the note). + * - `owner-or-admin`: reads or changes one resource the caller owns, or any as + * an admin; others get 403/404. Returns nothing of anyone else's resources. + * - `own-data`: only the caller's own records (profile, keys, grants, links), + * or a new resource the caller creates and owns. + * - `role-governed`: governed by an access model admins assign explicitly + * (memory access, knowledge-folder roles, EDITOR curation). Member + * visibility does not narrow it further. + * - `workspace-config`: workspace settings, the public catalog, plan and + * licence state or aggregate counts: no other member's records, the same + * answer for every member. + * - `no-member-session`: not reached with a member's dashboard session: public + * pages and catalog, signed or token links, provider webhooks and OAuth, + * SSO and SCIM flows, cron and internal secrets. + * - `mcp-roles`: the MCP endpoint; MCP roles decide which tools a client can + * list and call, in both modes. + */ +export const MEMBER_VISIBILITY_DECISIONS = [ + 'scoped', + 'admin-when-restricted', + 'admin-only', + 'owner-or-admin', + 'own-data', + 'role-governed', + 'workspace-config', + 'no-member-session', + 'mcp-roles', +] as const; +export type MemberVisibilityDecision = (typeof MEMBER_VISIBILITY_DECISIONS)[number]; + +export interface RouteVisibility { + decision: MemberVisibilityDecision; + /** Why, or where the check lives when reflection cannot see it. */ + note?: string; +} + +const d = (decision: MemberVisibilityDecision, note?: string): RouteVisibility => + note ? { decision, note } : { decision }; +const scoped = (note?: string) => d('scoped', note); +const adminWhenRestricted = (note?: string) => d('admin-when-restricted', note); +const admin = (note?: string) => d('admin-only', note); +const ownerOrAdmin = (note?: string) => d('owner-or-admin', note); +const own = (note?: string) => d('own-data', note); +const roleGoverned = (note: string) => d('role-governed', note); +const config = (note?: string) => d('workspace-config', note); +const noSession = (note: string) => d('no-member-session', note); +const mcpRoles = () => d('mcp-roles'); + +const CONNECTOR_404 = 'hidden connector answers 404; a visible one it does not own comes back in the reduced view'; +const OWNER_OR_ADMIN_404 = 'owner or admin; a connector the member cannot see answers 404 first'; +const PROVIDER_FLOW = 'provider redirect, authenticated by the signed one-time state'; +const FILE_SEARCH_OWNER = '404 unless the member owns the connector (File Search detail is never shared)'; + +export const MEMBER_VISIBILITY_ROUTES: Readonly> = { + // ── adapters ─────────────────────────────────────────────────────────── + 'AdaptersPublicController.list': noSession('public catalog'), + 'AdaptersPublicController.installRanking': noSession('public catalog, aggregate counts'), + 'AdaptersPublicController.instructions': noSession('public catalog'), + 'AdaptersController.popularConnectors': scoped('`installed` only for connectors the member can see'), + 'AdaptersController.matchUrl': config('catalog lookup'), + 'AdaptersController.starterPack': scoped('`installed` only for connectors the member can see; plan usage counts'), + 'AdaptersController.installStarterPack': own('creates connectors owned by the caller'), + 'AdaptersController.getBySlug': config('catalog entry'), + 'AdaptersController.verify': ownerOrAdmin('tries credentials; with connectorId only for its owner or an admin'), + 'AdaptersController.importAdapter': own('creates a connector owned by the caller'), + 'SetupLinksController.resolve': own('the caller\'s own setup link (signed token)'), + 'SetupLinksController.open': noSession('signed setup link'), + 'TelegramManagedBotController.receive': noSession('Telegram webhook, secret token'), + 'TikTokShopInstallController.install': own('installs into a connector owned by the caller'), + + // ── alerts ───────────────────────────────────────────────────────────── + 'AlertsAdminController.getConfig': admin(), + 'AlertsAdminController.saveConfig': admin(), + 'AlertsAdminController.deleteConfig': admin(), + 'AlertsAdminController.testWebhook': admin(), + + // ── audit ────────────────────────────────────────────────────────────── + 'AuditController.listInvocations': scoped('own calls only; servers named only when the member owns them'), + 'AuditController.getStats': scoped('own calls only'), + 'AuditController.getAnalytics': scoped('own calls only'), + 'AuditController.getToolPerformance': scoped('own calls only; servers named only when the member owns them'), + 'AuditController.getBreakdowns': scoped('own calls only; byServer names only own servers, byUser only the caller'), + 'ProductEventController.record': own('records an event for the caller'), + 'SignupAttributionController.clickIds': own(), + + // ── auth ─────────────────────────────────────────────────────────────── + 'AuthController.loginWithRecoveryCode': noSession('sign-in'), + 'AuthController.login': noSession('sign-in'), + 'AuthController.register': noSession('sign-up'), + 'AuthController.verifyEmail': own(), + 'AuthController.verifyEmailLink': noSession('signed e-mail link'), + 'AuthController.resendVerification': own(), + 'AuthController.inviteUser': admin(), + 'AuthController.verifyInvite': noSession('invitation token'), + 'AuthController.acceptInvite': noSession('invitation token'), + 'AuthController.forgotPassword': noSession('sign-in'), + 'AuthController.resetPassword': noSession('reset token'), + 'AuthController.recoveryCodeStatus': own(), + 'AuthController.generateRecoveryCodes': own(), + 'LoginController.showLoginPage': noSession('OAuth sign-in and consent page'), + 'LoginController.socialCallback': noSession(PROVIDER_FLOW), + 'LoginController.handleLogin': noSession('OAuth sign-in'), + 'LoginController.handleEmailCode': noSession('OAuth sign-in'), + 'LoginController.resendEmailCode': noSession('OAuth sign-in'), + 'LoginController.continueAfterEmailLink': noSession('OAuth sign-in'), + 'LoginController.socialFromEmailCode': noSession('OAuth sign-in'), + 'LoginController.fileSearchSetupSession': noSession('signed setup session'), + 'LoginController.fileSearchSetupContinue': noSession('signed setup session'), + 'LoginController.handleServerSelection': scoped( + 'consent picker; offers and grants only servers McpConnectionGrantService lets the user see', + ), + 'LoginController.pickFirstApp': noSession('OAuth consent flow'), + 'LoginController.telegramOneTapQr': noSession('one-time code'), + 'LoginController.telegramOneTapStatus': noSession('one-time code'), + 'LoginController.telegramOneTapToken': noSession('one-time code'), + 'RecentSignInController.who': noSession('signed device cookie'), + 'RecentSignInController.continue': noSession('signed device cookie'), + 'RecentSignInController.forget': noSession('signed device cookie'), + 'SocialAuthController.start': noSession('sign-in'), + 'SocialAuthController.exchange': noSession('sign-in'), + 'SocialAuthController.identities': own(), + 'SocialAuthController.link': own(), + 'SocialAuthController.unlink': own(), + 'UserInfoController.get': own('OIDC userinfo of the token holder'), + 'UserInfoController.post': own('OIDC userinfo of the token holder'), + + // ── connectors ───────────────────────────────────────────────────────── + 'ConnectorsController.list': scoped('owned or holding an allowed tool; reduced view for the ones not owned'), + 'ConnectorsController.create': own('creates a connector owned by the caller'), + 'ConnectorsController.proxyAvailability': config(), + 'ConnectorsController.healthCheck': scoped('visible connectors only; fixed message for the ones not owned'), + 'ConnectorsController.exportAll': scoped('only connectors the member owns'), + 'ConnectorsController.exportOne': scoped('404 unless the member owns the connector'), + 'ConnectorsController.findOne': scoped(`${CONNECTOR_404}; its MCP servers only when the member owns them`), + 'ConnectorsController.webhookUrl': scoped(OWNER_OR_ADMIN_404), + 'ConnectorsController.webhookEventsList': scoped(OWNER_OR_ADMIN_404), + 'ConnectorsController.update': ownerOrAdmin(), + 'ConnectorsController.getOAuthConfig': scoped('404 unless the member owns the connector'), + 'ConnectorsController.updateCredentialScope': ownerOrAdmin(), + 'ConnectorsController.getMyCredential': scoped('the caller\'s own credential; hidden connector answers 404'), + 'ConnectorsController.deleteMyCredential': scoped('the caller\'s own credential; hidden connector answers 404'), + 'ConnectorsController.updateOAuthConfig': ownerOrAdmin(), + 'ConnectorsController.updateOAuth1Config': ownerOrAdmin(), + 'ConnectorsController.remove': ownerOrAdmin(), + 'ConnectorsController.test': scoped(OWNER_OR_ADMIN_404), + 'ConnectorsController.oauthRedirectUri': config(), + 'ConnectorsController.initiateOAuth': scoped('owner or admin, or the caller\'s own per-user sign-in; hidden answers 404'), + 'ConnectorsController.discoverMcpTools': ownerOrAdmin(), + 'ConnectorsController.importAll': own('creates connectors owned by the caller'), + 'ConnectorsController.importFile': own('creates connectors owned by the caller'), + 'ConnectorsController.importSpec': ownerOrAdmin(), + 'ConnectorsController.importTools': ownerOrAdmin(), + 'ConnectorsController.updateEnvVars': ownerOrAdmin(), + 'ConnectorsController.catalogDiff': scoped(OWNER_OR_ADMIN_404), + 'ConnectorsController.resyncCatalog': ownerOrAdmin(), + 'IopAuthController.redirectUri': config(), + 'IopAuthController.authorize': ownerOrAdmin(), + 'IopAuthController.callback': noSession(PROVIDER_FLOW), + 'IopAuthController.complete': own('completes the caller\'s own pending flow'), + 'McpOAuthCallbackController.acknowledgeNotification': noSession('provider notification'), + 'McpOAuthCallbackController.oauthCallback': noSession(PROVIDER_FLOW), + 'McpOAuthCallbackController.complete': own('completes the caller\'s own pending flow'), + 'McpOAuthCallbackController.connectPageComplete': noSession(PROVIDER_FLOW), + 'McpOAuthCallbackController.connectPage': noSession('per-user sign-in page of a connector link, its own session'), + 'McpOAuthCallbackController.connectPageSignIn': noSession('per-user sign-in page of a connector link'), + 'McpOAuthCallbackController.connectPageConnect': noSession('per-user sign-in page of a connector link'), + 'McpOAuthCallbackController.connectPageSwitch': noSession('per-user sign-in page of a connector link'), + 'MetaAuthController.platform': config(), + 'MetaAuthController.authorize': ownerOrAdmin(), + 'MetaAuthController.callback': noSession(PROVIDER_FLOW), + 'MetaAuthController.complete': own('completes the caller\'s own pending flow'), + 'MetaAuthController.listAccounts': ownerOrAdmin(), + 'MetaAuthController.chooseAccount': ownerOrAdmin(), + 'SheinAuthController.redirectUri': config(), + 'SheinAuthController.authorize': ownerOrAdmin(), + 'SheinAuthController.callback': noSession(PROVIDER_FLOW), + 'SheinAuthController.complete': own('completes the caller\'s own pending flow'), + 'ShopeeAuthController.authorize': ownerOrAdmin(), + 'ShopeeAuthController.callback': noSession(PROVIDER_FLOW), + 'ShopeeAuthController.complete': own('completes the caller\'s own pending flow'), + 'TikTokShopAuthController.platform': config(), + 'TikTokShopAuthController.authorize': ownerOrAdmin(), + 'TikTokShopAuthController.callback': noSession(PROVIDER_FLOW), + 'TikTokShopAuthController.complete': own('completes the caller\'s own pending flow'), + 'ToolsController.list': scoped('allowed tools only on a connector the member does not own; hidden answers 404'), + 'ToolsController.create': ownerOrAdmin(), + 'ToolsController.bulkCreate': ownerOrAdmin(), + 'ToolsController.update': ownerOrAdmin(), + 'ToolsController.getAnnotations': scoped(OWNER_OR_ADMIN_404), + 'ToolsController.setAnnotations': ownerOrAdmin(), + 'ToolsController.getResponseMapping': scoped(OWNER_OR_ADMIN_404), + 'ToolsController.setResponseMapping': ownerOrAdmin(), + 'ToolsController.previewMapping': ownerOrAdmin(), + 'ToolsController.setProxy': ownerOrAdmin(), + 'ToolsController.testTool': ownerOrAdmin(), + 'ToolsController.remove': ownerOrAdmin(), + 'WebhookIngestController.receive': noSession('provider webhook, signature checked'), + 'WooCommerceAuthController.oneClick': own('starts the caller\'s own install flow'), + 'WooCommerceAuthController.authorize': ownerOrAdmin(), + 'WooCommerceAuthController.callback': noSession(PROVIDER_FLOW), + 'WooCommerceAuthController.oneClickStatus': own('status of the caller\'s own pending flow'), + + // ── ee/ (Commercial License; decided here, enforced without changing ee/) ── + 'KgCronController.run': noSession('cron secret'), + 'OnboardingCronController.run': noSession('cron secret'), + 'LearningController.allowance': config('plan allowance and counts'), + 'LearningController.mine': own('the caller\'s own learning projects'), + 'LearningController.consent': own('the caller\'s own learning project'), + 'LearningController.withdraw': own('the caller\'s own learning project'), + 'LearningController.list': adminWhenRestricted('other members\' learning projects'), + 'LearningController.create': admin(), + 'LearningController.get': adminWhenRestricted('another member\'s learning project'), + 'LearningController.update': admin(), + 'LearningController.pause': admin(), + 'LearningController.resume': admin(), + 'LearningController.end': admin(), + 'LearningController.remove': admin(), + 'LearningController.lessons': adminWhenRestricted('lessons drawn from another member\'s requests'), + 'LearningController.setLesson': adminWhenRestricted('lessons drawn from another member\'s requests'), + 'LearningController.addTopic': admin(), + 'LearningController.updateTopic': admin(), + 'LearningController.preview': adminWhenRestricted('skill text drawn from another member\'s lessons'), + 'LearningController.publish': adminWhenRestricted('publishes another member\'s lessons'), + 'EditionController.getEdition': config('edition and user limit'), + 'EditionController.startTrial': admin(), + 'SupportController.widget': own('support identity of the caller'), + 'SupportController.webhook': noSession('support desk webhook, secret'), + 'SupportController.deskConnector': noSession('support desk, secret'), + + // ── File Search and File Share ───────────────────────────────────────── + 'FileSearchController.capabilities': config('plan, limits, worker health and aggregate usage'), + 'FileSearchController.test': admin('FileSearchService.assertAdmin'), + 'FileSearchController.createDraft': admin('FileSearchService.assertAdmin'), + 'FileSearchController.getPolicy': config(), + 'FileSearchController.setPolicy': admin('FileSearchService.assertAdmin'), + 'FileSearchController.overview': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.updateSource': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.startScan': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.getScan': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.cancelScan': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.redescribe': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.setSelection': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.activate': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.tree': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.problems': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.runs': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.syncNow': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.pause': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.resume': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.schedule': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.description': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.getRules': scoped(FILE_SEARCH_OWNER), + 'FileSearchController.setRules': scoped(FILE_SEARCH_OWNER), + 'FileShareController.list': own('a member gets only their own links; usage counts and the built-in File Share connector'), + 'FileShareController.revoke': ownerOrAdmin('FileShareService.revoke'), + 'FileShareController.createConnector': admin('checked in the handler'), + 'FileShareController.describe': noSession('share token'), + 'FileShareController.download': noSession('share token'), + 'FileShareController.downloadInternal': noSession('share token, plus a signed-in member of the workspace'), + 'FileShareController.stream': noSession('signed download link'), + 'FileShareController.limits': config('limits and aggregate usage'), + 'FileUploadController.status': noSession('upload token'), + 'FileUploadController.put': noSession('upload token'), + 'FileUploadController.post': noSession('upload token'), + 'FileUploadController.download': noSession('signed download link'), + + // ── health ───────────────────────────────────────────────────────────── + 'HealthController.getServerInfo': noSession('public health'), + 'HealthController.check': noSession('public health'), + 'SentryVerifyController.verify': noSession('operator check'), + 'VersionController.getVersion': config('version'), + + // ── identity providers, SSO, SCIM ────────────────────────────────────── + 'IdentityProvidersController.list': admin(), + 'IdentityProvidersController.get': admin(), + 'IdentityProvidersController.create': admin(), + 'IdentityProvidersController.update': admin(), + 'IdentityProvidersController.remove': admin(), + 'IdentityProvidersController.listRoleMappings': admin(), + 'IdentityProvidersController.replaceRoleMappings': admin(), + 'IdentityProvidersController.setEnforceSso': admin(), + 'IdentityProvidersController.resyncRoles': admin(), + 'IdentityProvidersController.scimStatus': admin(), + 'IdentityProvidersController.setScim': admin(), + 'IdentityProvidersController.rotateScim': admin(), + 'IdentityProvidersController.removeScim': admin(), + 'IdentityProvidersController.test': admin(), + 'ScimController.serviceProviderConfig': noSession('SCIM bearer token of an identity provider'), + 'ScimController.resourceTypes': noSession('SCIM bearer token of an identity provider'), + 'ScimController.resourceType': noSession('SCIM bearer token of an identity provider'), + 'ScimController.schemas': noSession('SCIM bearer token of an identity provider'), + 'ScimController.schema': noSession('SCIM bearer token of an identity provider'), + 'ScimController.listUsers': noSession('SCIM bearer token of an identity provider'), + 'ScimController.getUser': noSession('SCIM bearer token of an identity provider'), + 'ScimController.createUser': noSession('SCIM bearer token of an identity provider'), + 'ScimController.replaceUser': noSession('SCIM bearer token of an identity provider'), + 'ScimController.patchUser': noSession('SCIM bearer token of an identity provider'), + 'ScimController.deleteUser': noSession('SCIM bearer token of an identity provider'), + 'ScimController.listGroups': noSession('SCIM bearer token of an identity provider'), + 'ScimController.getGroup': noSession('SCIM bearer token of an identity provider'), + 'ScimController.createGroup': noSession('SCIM bearer token of an identity provider'), + 'ScimController.replaceGroup': noSession('SCIM bearer token of an identity provider'), + 'ScimController.patchGroup': noSession('SCIM bearer token of an identity provider'), + 'ScimController.deleteGroup': noSession('SCIM bearer token of an identity provider'), + 'SsoController.start': noSession('SSO sign-in'), + 'SsoController.callback': noSession('SSO sign-in'), + 'SsoController.startLink': own(), + 'SsoController.unlink': own(), + 'SsoController.myProviders': config('the workspace\'s sign-in options, and whether the caller linked each'), + 'SsoController.exchange': noSession('one-time sign-in code'), + + // ── knowledge folders, knowledge graph, memory ───────────────────────── + 'KnowledgeFoldersController.list': roleGoverned('folders the caller\'s roles may see'), + 'KnowledgeFoldersController.create': roleGoverned('ADMIN or EDITOR'), + 'KnowledgeFoldersController.update': roleGoverned('ADMIN or EDITOR'), + 'KnowledgeFoldersController.remove': roleGoverned('ADMIN or EDITOR'), + 'KnowledgeFoldersController.setRoles': admin(), + 'KnowledgeFoldersController.move': roleGoverned('ADMIN or EDITOR'), + 'KgController.getGraph': adminWhenRestricted('nodes and links of every connector and tool'), + 'KgController.stats': roleGoverned('ADMIN or EDITOR; counts only'), + 'KgController.getSettings': roleGoverned('ADMIN or EDITOR; whether the graph is on'), + 'KgController.setSettings': admin(), + 'KgController.enrich': admin(), + 'KgController.listSkills': adminWhenRestricted('skills learned from every member\'s requests'), + 'KgController.createSkill': admin(), + 'KgController.generateSkills': admin(), + 'KgController.proposeFromErrors': admin(), + 'KgController.consolidateSkills': admin(), + 'KgController.applySkill': admin(), + 'KgController.dismissSkill': admin(), + 'KgController.updateSkill': admin(), + 'KgController.skillVersions': adminWhenRestricted('skills learned from every member\'s requests'), + 'KgController.getMyLearning': own(), + 'KgController.setMyLearning': own(), + 'KgController.setMembersLearning': admin(), + 'KgController.deleteSkill': admin(), + 'KgController.rebuild': admin(), + 'KgController.createNode': admin(), + 'KgController.createEdge': admin(), + 'KgController.updateEdge': admin(), + 'KgController.deleteEdge': admin(), + 'KgController.updateNode': admin(), + 'KgController.deleteNode': admin(), + 'MemoryController.status': roleGoverned('licence, the caller\'s memory access and the workspace settings'), + 'MemoryController.list': roleGoverned('personal: the caller\'s own; company: by memory access and folder roles'), + 'MemoryController.create': roleGoverned('personal: the caller\'s own; company: by memory access'), + 'MemoryController.update': roleGoverned('the caller\'s own item, or a curator'), + 'MemoryController.remove': roleGoverned('the caller\'s own item, or a curator'), + 'MemoryController.approve': roleGoverned('ADMIN or EDITOR curators'), + 'MemoryController.reject': roleGoverned('ADMIN or EDITOR curators'), + 'MemoryController.updateSettings': admin(), + 'MemoryController.setAccess': admin(), + 'MemoryController.erasePersonal': admin(), + + // ── licence ──────────────────────────────────────────────────────────── + 'LicenseController.getStatus': config('licence state'), + 'LicenseController.refresh': admin(), + 'LicenseController.syncFromSite': noSession('licence site, signed request'), + 'LicenseController.getInstanceId': config(), + 'LicenseController.getUsage': config('aggregate counts of connectors, servers and users'), + 'LicenseController.setLicenseKey': admin(), + 'LicenseController.billingPortal': admin(), + 'LicenseController.getInvoiceEmail': admin(), + 'LicenseController.setInvoiceEmail': admin(), + 'LicenseController.dpaLink': admin(), + 'LicenseController.checkoutLink': admin(), + 'LicenseController.pricingLinkToken': own('token for the caller\'s own address'), + 'LicenseController.cardTrialEligibilityForUser': admin(), + 'LicenseController.cardTrialOfferForUser': config('null for members who are not admins'), + 'LicenseController.planFitForUser': adminWhenRestricted('names every connector and MCP server of the workspace'), + 'LicenseController.wallForUser': admin('null unless the caller is an admin (checked in the handler)'), + 'LicenseController.verifyLicense': admin(), + 'LicenseController.activateTrial': config('starts the workspace trial; answers licence state'), + 'LicenseController.registerCommunity': admin(), + 'ReactivationController.view': noSession('reactivation token'), + 'ReactivationController.checkout': noSession('reactivation token'), + 'ReactivationController.event': noSession('reactivation token'), + 'TrialExtensionController.confirm': noSession('signed e-mail link'), + 'TrialExtensionController.extend': noSession('signed e-mail link'), + + // ── MCP endpoint ─────────────────────────────────────────────────────── + 'McpEndpointController.handleGlobalPost': mcpRoles(), + 'McpEndpointController.handleGlobalGet': mcpRoles(), + 'McpEndpointController.handleGlobalDelete': mcpRoles(), + 'McpEndpointController.handleChatgptAppPost': mcpRoles(), + 'McpEndpointController.handleChatgptAppGet': mcpRoles(), + 'McpEndpointController.handleChatgptAppDelete': mcpRoles(), + 'McpEndpointController.handleFileSearchAppPost': mcpRoles(), + 'McpEndpointController.handleFileSearchAppGet': mcpRoles(), + 'McpEndpointController.handleFileSearchAppDelete': mcpRoles(), + 'McpEndpointController.handleDemoPost': mcpRoles(), + 'McpEndpointController.handleDemoGet': mcpRoles(), + 'McpEndpointController.handlePost': mcpRoles(), + 'McpEndpointController.handleGet': mcpRoles(), + 'McpEndpointController.handleDelete': mcpRoles(), + 'RegistryCatchUpController.catchUp': noSession('internal secret'), + 'WellKnownOAuthController.openaiAppsChallenge': noSession('public discovery'), + 'WellKnownOAuthController.openidConfiguration': noSession('public discovery'), + 'WellKnownOAuthController.openidConfigurationScoped': noSession('public discovery'), + 'WellKnownOAuthController.authorizationServerScoped': noSession('public discovery'), + 'WellKnownOAuthController.protectedResourceShared': noSession('public discovery'), + 'WellKnownOAuthController.protectedResourceScoped': noSession('public discovery'), + + // ── MCP servers and connections ──────────────────────────────────────── + 'McpConnectionsController.list': own('the caller\'s grants; a granted server is named only when visible to them'), + 'McpConnectionsController.targets': scoped('per workspace, via McpConnectionGrantService: only own servers'), + 'McpConnectionsController.update': scoped('via McpConnectionGrantService: a hidden server is dropped like an unknown id'), + 'McpConnectionsController.revoke': own(), + 'McpServersController.list': scoped('only servers the member owns, with only the connectors they can see'), + 'McpServersController.create': own('creates a server owned by the caller; refused to a VIEWER'), + 'McpServersController.get': scoped('404 unless the member owns the server'), + 'McpServersController.activity': scoped('404 unless the member owns the server'), + 'McpServersController.update': scoped('404 unless the member owns the server; then owner or admin'), + 'McpServersController.delete': scoped('404 unless the member owns the server; then owner or admin'), + 'McpServersController.assignConnectors': scoped('404 for a server not owned and for a connector the member cannot see'), + + // ── organizations ────────────────────────────────────────────────────── + 'OrganizationsController.listMine': own('the caller\'s memberships'), + 'OrganizationsController.getCurrent': config('the workspace row'), + 'OrganizationsController.updateCurrent': admin('checked in the handler'), + 'OrganizationsController.deleteCurrent': admin('checked in the handler'), + 'OrganizationsController.revokeWorkspaceSessions': admin('checked in the handler'), + 'OrganizationsController.switchOrg': own('switches the caller\'s active workspace'), + 'OrganizationsController.createOrg': own('creates a workspace the caller owns'), + 'PublicStatsController.getStats': noSession('public aggregate counts'), + + // ── roles and keys ───────────────────────────────────────────────────── + 'McpApiKeysController.listKeys': scoped('the caller\'s own keys; mcpServer null for a server they may not see'), + 'McpApiKeysController.generateKey': scoped('a key for a server the member may not see answers 404'), + 'McpApiKeysController.revokeKey': own(), + 'McpApiKeysController.deleteKey': own(), + 'RolesController.listRoles': admin(), + 'RolesController.createRole': admin(), + 'RolesController.getRole': admin(), + 'RolesController.updateRole': admin(), + 'RolesController.deleteRole': admin(), + 'RolesController.getToolAccess': admin(), + 'RolesController.setToolAccess': admin(), + 'RolesController.setToolRateLimits': admin(), + 'RolesController.assignRole': admin(), + 'RolesController.getAssignments': admin(), + 'RolesController.setAssignments': admin(), + + // ── settings ─────────────────────────────────────────────────────────── + 'MemberVisibilityMemberController.getMemberVisibility': own('the mode and whether it narrows the caller'), + 'MemberVisibilityAdminController.setMemberVisibility': admin(), + 'SiteSettingsPublicController.getFooterLinks': noSession('public footer links'), + 'SiteSettingsMemberController.getFooterLinks': config('footer links'), + 'SiteSettingsAdminController.getSmtpConfig': admin(), + 'SiteSettingsAdminController.updateSmtpConfig': admin(), + 'SiteSettingsAdminController.deleteSmtpConfig': admin(), + 'SiteSettingsAdminController.testSmtp': admin(), + 'SiteSettingsAdminController.getFooterLinks': admin(), + 'SiteSettingsAdminController.updateFooterLinks': admin(), + 'SiteSettingsAdminController.getSsrfAllowedHosts': admin(), + 'SiteSettingsAdminController.setSsrfAllowedHosts': admin(), + 'UnsubscribeController.confirm': noSession('signed unsubscribe link'), + 'UnsubscribeController.unsubscribe': noSession('signed unsubscribe link'), + + // ── users ────────────────────────────────────────────────────────────── + 'UsersController.getProfile': own(), + 'UsersController.getOnboardingState': own(), + 'UsersController.updateOnboardingState': own(), + 'UsersController.updateProfile': own(), + 'UsersController.deleteSelf': own(), + 'UsersController.changePassword': own(), + 'UsersController.listUsers': admin(), + 'UsersController.listInvitations': admin(), + 'UsersController.deleteInvitation': admin(), + 'UsersController.updateRole': admin(), + 'UsersController.revokeUserSessions': admin(), + 'UsersController.deactivateUser': admin(), + 'UsersController.reactivateUser': admin(), + 'UsersController.deleteUser': admin(), +}; + +/** The decision for one handler, or undefined when none is registered. */ +export function routeVisibility(controller: string, handler: string): RouteVisibility | undefined { + return MEMBER_VISIBILITY_ROUTES[`${controller}.${handler}`]; +} From 2ab4251b28ead57611c5fa67621d2ead900b2e1c Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:18 +0100 Subject: [PATCH 5/6] Document own-servers-only member visibility and route decisions --- docs/api-reference.md | 4 +- docs/operations/member-visibility.md | 86 ++++++++++++++++++++-------- docs/sso.md | 2 +- 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/docs/api-reference.md b/docs/api-reference.md index 379fe9fae..8e34a2268 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -525,8 +525,8 @@ call, so cached presence never replaces the caller's current role policy. | PUT | `/api/admin/settings/member-visibility` | Admin: set `{ "mode": "open" }` or `{ "mode": "restricted" }` | In a workspace set to `restricted`, a member who is not an admin gets only -their own calls from the audit endpoints, only the connectors and MCP servers -their roles reach, and 404 for the others. A connector they can see but do not +their own calls from the audit endpoints, only the connectors their roles +reach, only the MCP servers they own, and 404 for the others. A connector they can see but do not own comes back in a reduced view marked `memberView: true`: `id`, `name`, `type`, `icon`, `isActive`, `credentialScope`, `setupStatus`, `authStatus`, `authStatusCode`, and of each allowed tool `id`, `name`, `description` and diff --git a/docs/operations/member-visibility.md b/docs/operations/member-visibility.md index e5bea4cf2..a04224f22 100644 --- a/docs/operations/member-visibility.md +++ b/docs/operations/member-visibility.md @@ -11,7 +11,7 @@ should see what their AI client can use, and their own calls, nothing more. | Mode | What a member who is not an admin sees | |---|---| | **Open** (default) | Everything in the workspace, as before this setting existed. | -| **Restricted** | Only their own tool calls, the connectors their MCP roles reach, and the MCP servers that hold one of those connectors. Of a connector they do not own: its name, its status and the tools they may use, not its settings. | +| **Restricted** | Only their own tool calls, the connectors their MCP roles reach, and the MCP servers they own. Of a connector they do not own: its name, its status and the tools they may use, not its settings. Never another member's MCP server. | Admins always see everything, in both modes. "Member" below means a VIEWER or an EDITOR of the workspace. An EDITOR also keeps seeing what they own. @@ -24,23 +24,31 @@ workspace until an admin switches it. | Area | Open | Restricted, member | |---|---|---| -| Audit log (`GET /api/audit/invocations`) | Every call of the workspace, with the caller and the full input and output | Only the calls the member made. Calls without a user (for example a static key) are hidden. The page says "You see your own calls. Workspace admins see all calls." | -| Analytics, stats, tool performance (`/api/audit/stats`, `/analytics`, `/breakdowns`, `/tool-performance`) | Workspace-wide numbers, including calls per user | The same numbers, counted over the member's own calls only. The "by user" panel is hidden; the API's `byUser` holds only the member's own row. | +| Audit log (`GET /api/audit/invocations`) | Every call of the workspace, with the caller and the full input and output | Only the calls the member made. Calls without a user (for example a static key) are hidden. A call made through an MCP server the member does not own keeps its content, but `mcpServer` and `mcpServerId` are null; `mcpServerId=` of such a server matches nothing. The page says "You see your own calls. Workspace admins see all calls." | +| Analytics, stats, tool performance (`/api/audit/stats`, `/analytics`, `/breakdowns`, `/tool-performance`) | Workspace-wide numbers, including calls per user and per server | The same numbers, counted over the member's own calls only. The "by user" panel is hidden; the API's `byUser` holds only the member's own row. Only the member's own servers are named: `byServer` counts calls through any other server in one row with `id: null` ("Other server or none"), and tool performance reports them with `mcpServerId: null`. | | Connectors (`GET /api/connectors`, `/health-check`) | Every connector with all of its tools and settings | Connectors the member owns, or that hold at least one tool their roles allow. A connector they own comes back in full. One they do not own comes back in the [reduced view](#what-a-member-sees-of-a-shared-connector), with only the allowed tools. | -| Connector and tool detail (`/api/connectors/:id`, its per-user sign-in, tools) | Any connector of the workspace | 404 for a connector the member cannot see, with the same body as an unknown id. A member cannot tell "hidden" from "does not exist". A connector they can see but do not own comes back in the reduced view. | +| Connector and tool detail (`/api/connectors/:id`, its per-user sign-in, tools) | Any connector of the workspace | 404 for a connector the member cannot see, with the same body as an unknown id. A member cannot tell "hidden" from "does not exist". A connector they can see but do not own comes back in the reduced view. On a connector they own, `mcpServers` lists only the servers they own. | | Connector settings (`/api/connectors/:id/oauth-config`) | Any connector of the workspace | Only for a connector the member owns; 404 for the others, visible or not. | | Owner-or-admin reads (`/api/connectors/:id/webhook/url`, `/webhook/events`, `/catalog-diff`, a tool's `/annotations` and `/response-mapping`) | Owner or admin only (403 for other members) | 404 for a connector the member cannot see, and for a tool outside their roles on a connector they do not own; otherwise as in Open. | | Exports (`/api/connectors/export-all`, `/:id/export`) | Every connector, secrets masked unless admin | Only connectors the member owns; 404 for the others. | -| File Search (`/api/file-search/connectors/:id` and its tree, problems, runs, scans and access rules) | Any File Search connector of the workspace | 404 for a connector the member cannot see. | -| MCP servers (`GET /api/mcp-servers`, `/:id`, `/:id/activity`) | Every server, with the names of all its connectors | Servers the member owns, or that hold a connector they can see. Connector names and counts list only those connectors. 404 for the others. | -| Server picker (`GET /api/mcp-connections/targets`, the OAuth consent page) | Every active server of each workspace the user belongs to | Per workspace, by that workspace's own mode and the user's role there. A grant (`PUT /api/mcp-connections/:clientId`) drops a hidden server like an unknown id. | +| File Search (`/api/file-search/connectors/:id` and everything below it: overview, tree, problems, runs, scans, sync, schedule, description, access rules) | Any File Search connector of the workspace | 404 unless the member owns the connector, including a File Search connector shared with them through their roles: these routes show the source's address, every folder and file name and the role rules, more than the tools let their AI client read. They use the File Search tools instead. `capabilities` and `policy` (plan, limits, aggregate usage) are unchanged. | +| MCP servers (`GET /api/mcp-servers`, `/:id`, `/:id/activity`, and `PUT`/`DELETE` `/:id`, `PUT /:id/connectors`) | Every server, with the names of all its connectors | Only the servers the member owns, never another member's server, not even one holding a connector they can see. On their own servers, connector names and counts list only the connectors they can see. Every other server answers 404 with the body of an unknown id, on reads and writes. Assigning a connector they cannot see to their own server answers 404 like an unknown connector. | +| Server picker (`GET /api/mcp-connections/targets`, the OAuth consent page) | Every active server of each workspace the user belongs to | Per workspace, by that workspace's own mode and the user's role there: only their own servers, plus the whole-workspace choice. A grant (`PUT /api/mcp-connections/:clientId`) drops another member's server like an unknown id. The consent page does not name a requested server the user may not see. | +| Connections and keys (`GET /api/mcp-connections`, `GET`/`POST /api/mcp-keys`) | The user's own connections and keys | Still only their own. A server they do not own is left out of a connection's `servers` and is `null` as a key's `mcpServer`. Creating a key for such a server answers 404, like an unknown server. | +| Knowledge graph and skills (`GET /api/knowledge-graph`, `/skills`, `/skills/:id/versions`), learning projects (`/api/learning/projects`, `/:id`, `/:id/lessons`, lessons, topic preview and publish) | Admins and editors | Admins only: 403 for editors. These answers are other members' work (skills and lessons learned from their requests, the graph of every connector). A member's own learning projects (`/api/learning/me`) and their own learning setting are unchanged. | +| Plan fit (`GET /api/license/plan-fit`, Cloud) | Any member | Admins only (403): it names every connector and MCP server of the workspace. | +| Catalog (`/api/adapters/popular-connectors`, `/starter-pack`) | `installed` for every connector of the workspace | `installed` only for connectors the member can see. | | Members, invitations, roles, identity providers (`/api/users`, `/api/roles`, ...) | Admins only | Admins only (unchanged) | -| MCP endpoint (`/mcp`, `/mcp/`) | Tools filtered by MCP roles | Unchanged: roles already decide what an AI client can list and call. | +| MCP endpoint (`/mcp`, `/mcp/`) | Tools filtered by MCP roles | Unchanged: roles already decide what an AI client can list and call. The server links the workspace connection hands to the model (`anythingmcp_get_configuration_url`) list only the member's own servers. | -Writes are not part of this setting. Changing or deleting a connector or a -server stays limited to its owner or an admin, in both modes. The dashboard -shows Edit, Test, Variables, Delete and the other controls that change a -connector only to its owner and to admins, in both modes. +Writes keep their rules: changing or deleting a connector or a server stays +limited to its owner or an admin, in both modes. In restricted mode a server +the member does not own answers 404 before that rule could answer 403. The +dashboard shows Edit, Test, Variables, Delete and the other controls that +change a connector only to its owner and to admins, in both modes. Testing new +values for an existing connector (`POST /api/adapters/:slug/verify` with +`connectorId`) runs with that connector's stored credentials, so it is +limited to its owner or an admin as well, in both modes (404 for anyone else). ### What a member sees of a shared connector @@ -82,9 +90,8 @@ endpoint it gets the allowed tools with their parameters, as before. File Search connectors: the reduced view applies to the connector itself, and the dashboard does not show its Files panel in the reduced view. The File -Search endpoints of a connector a member can see -(`/api/file-search/connectors/:id` and below) still answer as described in the -table above. +Search endpoints (`/api/file-search/connectors/:id` and below) answer 404 for +every File Search connector the member does not own, as in the table above. A restricted member who sees no connector or server gets "Nothing has been shared with you yet. Ask a workspace admin for a role." on the Connectors and @@ -104,16 +111,33 @@ Restricted mode hides identities and content, not every number: - **Aggregate counts.** `GET /api/license/usage` keeps returning the workspace's number of connectors, servers and users. These carry no identity. -- **A server's own activity.** For a server the member can see, - `GET /api/mcp-servers/:id/activity` returns the server's two numbers (calls - in the last 30 days, time of the last call), counted over all callers. -- **Other members' default servers.** Each invited member gets a server named - `Default ()`. In restricted mode it stays hidden unless it holds a - connector the caller can see; then the caller sees it, and with it the - member's name. To avoid this, put shared connectors on **team servers** - (for example "Sales", "Finance") instead of on members' default servers. +- **Their own servers' activity.** For a server the member owns, + `GET /api/mcp-servers/:id/activity` and the list's `usage` return the + server's two numbers (calls in the last 30 days, time of the last call), + counted over all callers. - **The member's own calls**, with their full input and output. They made - those calls. + those calls, including through a server they do not own (that server is not + named). + +## How a restricted member connects their AI client + +A restricted member never sees another member's MCP server, so team servers +(for example "Sales", "Finance") and other members' `Default ()` servers +are not listed to them and cannot be picked when they connect. They connect +in one of two ways: + +- **The workspace connection** (the shared `/mcp` endpoint, "Everything in + this workspace" on the consent page): every tool their roles allow, from + every connector, with no server to pick. When their own server is the only + one on offer, the consent page grants the workspace connection without + asking. +- **Their own server**, typically the `Default ()` server every invited + member gets. An admin can put shared connectors on it; the member then sees + those connectors on it as far as their roles reach. + +Connections made before the workspace was switched to restricted keep working: +the MCP endpoint is unchanged and roles still decide the tools. The dashboard +just no longer names a server the member does not own. ## Set it up with roles and SSO group mapping @@ -148,6 +172,20 @@ Once any role in the workspace has a tool list, a member with **no** role gets no tools on the MCP endpoint, and so sees only the connectors they own in restricted mode. +## Route decisions (for contributors) + +Every HTTP route of the API has a written member-visibility decision in +`packages/backend/src/settings/member-visibility.routes.ts`: narrowed by +member visibility (`scoped`), refused to restricted members +(`admin-when-restricted`, enforced by `MemberVisibilityInterceptor`), +admin-only, owner-or-admin, the caller's own data, governed by its own access +model, workspace settings and aggregate counts, not reached with a member's +session (public, token or provider routes), or the MCP endpoint (roles). +`member-visibility.routes.spec.ts` reads every controller through Nest's +route metadata and fails when a route has no decision, so a new route that +returns workspace data cannot reach a restricted member unnoticed. Add the +decision when you add the route. + ## Propagation The mode is kept in memory for **30 seconds** per server process. After an diff --git a/docs/sso.md b/docs/sso.md index 66b743c7c..5ae134294 100644 --- a/docs/sso.md +++ b/docs/sso.md @@ -137,7 +137,7 @@ Resolution rules: The same MCP roles can also decide what members see in the dashboard: with [member visibility](operations/member-visibility.md) set to Restricted, a member who is not an admin sees only their own tool calls, the connectors -their roles reach and the MCP servers that hold one of them. Map groups to +their roles reach and the MCP servers they own. Map groups to the Viewer workspace role and to MCP roles with tool lists, then switch the mode under **Settings → Organization → Security**. From c2be03d1e1507446e3950095ef672139a61987a3 Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:15:17 +0100 Subject: [PATCH 6/6] Release v0.55.4 --- llms-full.txt | 149 ++++++++++++++---- package-lock.json | 8 +- package.json | 2 +- packages/backend/package.json | 2 +- .../src/settings/member-visibility.routes.ts | 1 + packages/cli/src/generated/operations.ts | 10 ++ packages/frontend/package.json | 2 +- 7 files changed, 132 insertions(+), 42 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index fa469518e..c51f05b61 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -6875,7 +6875,7 @@ should see what their AI client can use, and their own calls, nothing more. | Mode | What a member who is not an admin sees | |---|---| | **Open** (default) | Everything in the workspace, as before this setting existed. | -| **Restricted** | Only their own tool calls, the connectors their MCP roles reach, and the MCP servers that hold one of those connectors. Of a connector they do not own: its name, its status and the tools they may use, not its settings. | +| **Restricted** | Only their own tool calls, the connectors their MCP roles reach, and the MCP servers they own. Of a connector they do not own: its name, its status and the tools they may use, not its settings. Never another member's MCP server. | Admins always see everything, in both modes. "Member" below means a VIEWER or an EDITOR of the workspace. An EDITOR also keeps seeing what they own. @@ -6888,23 +6888,31 @@ workspace until an admin switches it. | Area | Open | Restricted, member | |---|---|---| -| Audit log (`GET /api/audit/invocations`) | Every call of the workspace, with the caller and the full input and output | Only the calls the member made. Calls without a user (for example a static key) are hidden. The page says "You see your own calls. Workspace admins see all calls." | -| Analytics, stats, tool performance (`/api/audit/stats`, `/analytics`, `/breakdowns`, `/tool-performance`) | Workspace-wide numbers, including calls per user | The same numbers, counted over the member's own calls only. The "by user" panel is hidden; the API's `byUser` holds only the member's own row. | +| Audit log (`GET /api/audit/invocations`) | Every call of the workspace, with the caller and the full input and output | Only the calls the member made. Calls without a user (for example a static key) are hidden. A call made through an MCP server the member does not own keeps its content, but `mcpServer` and `mcpServerId` are null; `mcpServerId=` of such a server matches nothing. The page says "You see your own calls. Workspace admins see all calls." | +| Analytics, stats, tool performance (`/api/audit/stats`, `/analytics`, `/breakdowns`, `/tool-performance`) | Workspace-wide numbers, including calls per user and per server | The same numbers, counted over the member's own calls only. The "by user" panel is hidden; the API's `byUser` holds only the member's own row. Only the member's own servers are named: `byServer` counts calls through any other server in one row with `id: null` ("Other server or none"), and tool performance reports them with `mcpServerId: null`. | | Connectors (`GET /api/connectors`, `/health-check`) | Every connector with all of its tools and settings | Connectors the member owns, or that hold at least one tool their roles allow. A connector they own comes back in full. One they do not own comes back in the [reduced view](), with only the allowed tools. | -| Connector and tool detail (`/api/connectors/:id`, its per-user sign-in, tools) | Any connector of the workspace | 404 for a connector the member cannot see, with the same body as an unknown id. A member cannot tell "hidden" from "does not exist". A connector they can see but do not own comes back in the reduced view. | +| Connector and tool detail (`/api/connectors/:id`, its per-user sign-in, tools) | Any connector of the workspace | 404 for a connector the member cannot see, with the same body as an unknown id. A member cannot tell "hidden" from "does not exist". A connector they can see but do not own comes back in the reduced view. On a connector they own, `mcpServers` lists only the servers they own. | | Connector settings (`/api/connectors/:id/oauth-config`) | Any connector of the workspace | Only for a connector the member owns; 404 for the others, visible or not. | | Owner-or-admin reads (`/api/connectors/:id/webhook/url`, `/webhook/events`, `/catalog-diff`, a tool's `/annotations` and `/response-mapping`) | Owner or admin only (403 for other members) | 404 for a connector the member cannot see, and for a tool outside their roles on a connector they do not own; otherwise as in Open. | | Exports (`/api/connectors/export-all`, `/:id/export`) | Every connector, secrets masked unless admin | Only connectors the member owns; 404 for the others. | -| File Search (`/api/file-search/connectors/:id` and its tree, problems, runs, scans and access rules) | Any File Search connector of the workspace | 404 for a connector the member cannot see. | -| MCP servers (`GET /api/mcp-servers`, `/:id`, `/:id/activity`) | Every server, with the names of all its connectors | Servers the member owns, or that hold a connector they can see. Connector names and counts list only those connectors. 404 for the others. | -| Server picker (`GET /api/mcp-connections/targets`, the OAuth consent page) | Every active server of each workspace the user belongs to | Per workspace, by that workspace's own mode and the user's role there. A grant (`PUT /api/mcp-connections/:clientId`) drops a hidden server like an unknown id. | +| File Search (`/api/file-search/connectors/:id` and everything below it: overview, tree, problems, runs, scans, sync, schedule, description, access rules) | Any File Search connector of the workspace | 404 unless the member owns the connector, including a File Search connector shared with them through their roles: these routes show the source's address, every folder and file name and the role rules, more than the tools let their AI client read. They use the File Search tools instead. `capabilities` and `policy` (plan, limits, aggregate usage) are unchanged. | +| MCP servers (`GET /api/mcp-servers`, `/:id`, `/:id/activity`, and `PUT`/`DELETE` `/:id`, `PUT /:id/connectors`) | Every server, with the names of all its connectors | Only the servers the member owns, never another member's server, not even one holding a connector they can see. On their own servers, connector names and counts list only the connectors they can see. Every other server answers 404 with the body of an unknown id, on reads and writes. Assigning a connector they cannot see to their own server answers 404 like an unknown connector. | +| Server picker (`GET /api/mcp-connections/targets`, the OAuth consent page) | Every active server of each workspace the user belongs to | Per workspace, by that workspace's own mode and the user's role there: only their own servers, plus the whole-workspace choice. A grant (`PUT /api/mcp-connections/:clientId`) drops another member's server like an unknown id. The consent page does not name a requested server the user may not see. | +| Connections and keys (`GET /api/mcp-connections`, `GET`/`POST /api/mcp-keys`) | The user's own connections and keys | Still only their own. A server they do not own is left out of a connection's `servers` and is `null` as a key's `mcpServer`. Creating a key for such a server answers 404, like an unknown server. | +| Knowledge graph and skills (`GET /api/knowledge-graph`, `/skills`, `/skills/:id/versions`), learning projects (`/api/learning/projects`, `/:id`, `/:id/lessons`, lessons, topic preview and publish) | Admins and editors | Admins only: 403 for editors. These answers are other members' work (skills and lessons learned from their requests, the graph of every connector). A member's own learning projects (`/api/learning/me`) and their own learning setting are unchanged. | +| Plan fit (`GET /api/license/plan-fit`, Cloud) | Any member | Admins only (403): it names every connector and MCP server of the workspace. | +| Catalog (`/api/adapters/popular-connectors`, `/starter-pack`) | `installed` for every connector of the workspace | `installed` only for connectors the member can see. | | Members, invitations, roles, identity providers (`/api/users`, `/api/roles`, ...) | Admins only | Admins only (unchanged) | -| MCP endpoint (`/mcp`, `/mcp/`) | Tools filtered by MCP roles | Unchanged: roles already decide what an AI client can list and call. | +| MCP endpoint (`/mcp`, `/mcp/`) | Tools filtered by MCP roles | Unchanged: roles already decide what an AI client can list and call. The server links the workspace connection hands to the model (`anythingmcp_get_configuration_url`) list only the member's own servers. | -Writes are not part of this setting. Changing or deleting a connector or a -server stays limited to its owner or an admin, in both modes. The dashboard -shows Edit, Test, Variables, Delete and the other controls that change a -connector only to its owner and to admins, in both modes. +Writes keep their rules: changing or deleting a connector or a server stays +limited to its owner or an admin, in both modes. In restricted mode a server +the member does not own answers 404 before that rule could answer 403. The +dashboard shows Edit, Test, Variables, Delete and the other controls that +change a connector only to its owner and to admins, in both modes. Testing new +values for an existing connector (`POST /api/adapters/:slug/verify` with +`connectorId`) runs with that connector's stored credentials, so it is +limited to its owner or an admin as well, in both modes (404 for anyone else). ### What a member sees of a shared connector @@ -6946,9 +6954,8 @@ endpoint it gets the allowed tools with their parameters, as before. File Search connectors: the reduced view applies to the connector itself, and the dashboard does not show its Files panel in the reduced view. The File -Search endpoints of a connector a member can see -(`/api/file-search/connectors/:id` and below) still answer as described in the -table above. +Search endpoints (`/api/file-search/connectors/:id` and below) answer 404 for +every File Search connector the member does not own, as in the table above. A restricted member who sees no connector or server gets "Nothing has been shared with you yet. Ask a workspace admin for a role." on the Connectors and @@ -6968,16 +6975,33 @@ Restricted mode hides identities and content, not every number: - **Aggregate counts.** `GET /api/license/usage` keeps returning the workspace's number of connectors, servers and users. These carry no identity. -- **A server's own activity.** For a server the member can see, - `GET /api/mcp-servers/:id/activity` returns the server's two numbers (calls - in the last 30 days, time of the last call), counted over all callers. -- **Other members' default servers.** Each invited member gets a server named - `Default ()`. In restricted mode it stays hidden unless it holds a - connector the caller can see; then the caller sees it, and with it the - member's name. To avoid this, put shared connectors on **team servers** - (for example "Sales", "Finance") instead of on members' default servers. +- **Their own servers' activity.** For a server the member owns, + `GET /api/mcp-servers/:id/activity` and the list's `usage` return the + server's two numbers (calls in the last 30 days, time of the last call), + counted over all callers. - **The member's own calls**, with their full input and output. They made - those calls. + those calls, including through a server they do not own (that server is not + named). + +## How a restricted member connects their AI client + +A restricted member never sees another member's MCP server, so team servers +(for example "Sales", "Finance") and other members' `Default ()` servers +are not listed to them and cannot be picked when they connect. They connect +in one of two ways: + +- **The workspace connection** (the shared `/mcp` endpoint, "Everything in + this workspace" on the consent page): every tool their roles allow, from + every connector, with no server to pick. When their own server is the only + one on offer, the consent page grants the workspace connection without + asking. +- **Their own server**, typically the `Default ()` server every invited + member gets. An admin can put shared connectors on it; the member then sees + those connectors on it as far as their roles reach. + +Connections made before the workspace was switched to restricted keep working: +the MCP endpoint is unchanged and roles still decide the tools. The dashboard +just no longer names a server the member does not own. ## Set it up with roles and SSO group mapping @@ -6991,10 +7015,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. @@ -7007,6 +7036,20 @@ Once any role in the workspace has a tool list, a member with **no** role gets no tools on the MCP endpoint, and so sees only the connectors they own in restricted mode. +## Route decisions (for contributors) + +Every HTTP route of the API has a written member-visibility decision in +`packages/backend/src/settings/member-visibility.routes.ts`: narrowed by +member visibility (`scoped`), refused to restricted members +(`admin-when-restricted`, enforced by `MemberVisibilityInterceptor`), +admin-only, owner-or-admin, the caller's own data, governed by its own access +model, workspace settings and aggregate counts, not reached with a member's +session (public, token or provider routes), or the MCP endpoint (roles). +`member-visibility.routes.spec.ts` reads every controller through Nest's +route metadata and fails when a route has no decision, so a new route that +returns workspace data cannot reach a restricted member unnoticed. Add the +decision when you add the route. + ## Propagation The mode is kept in memory for **30 seconds** per server process. After an @@ -7570,14 +7613,16 @@ 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`. The same MCP roles can also decide what members see in the dashboard: with [member visibility]() set to Restricted, a member who is not an admin sees only their own tool calls, the connectors -their roles reach and the MCP servers that hold one of them. Map groups to +their roles reach and the MCP servers they own. Map groups to the Viewer workspace role and to MCP roles with tool lists, then switch the mode under **Settings → Organization → Security**. @@ -8913,6 +8958,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 @@ -8931,12 +8980,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" \ @@ -8997,8 +9076,8 @@ call, so cached presence never replaces the caller's current role policy. | PUT | `/api/admin/settings/member-visibility` | Admin: set `{ "mode": "open" }` or `{ "mode": "restricted" }` | In a workspace set to `restricted`, a member who is not an admin gets only -their own calls from the audit endpoints, only the connectors and MCP servers -their roles reach, and 404 for the others. A connector they can see but do not +their own calls from the audit endpoints, only the connectors their roles +reach, only the MCP servers they own, and 404 for the others. A connector they can see but do not own comes back in a reduced view marked `memberView: true`: `id`, `name`, `type`, `icon`, `isActive`, `credentialScope`, `setupStatus`, `authStatus`, `authStatusCode`, and of each allowed tool `id`, `name`, `description` and diff --git a/package-lock.json b/package-lock.json index 847a6b3c6..fb2594d56 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "anythingmcp", - "version": "0.55.3", + "version": "0.55.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "anythingmcp", - "version": "0.55.3", + "version": "0.55.4", "license": "AGPL-3.0-only", "workspaces": [ "packages/backend", @@ -27078,7 +27078,7 @@ }, "packages/backend": { "name": "@anythingmcp/backend", - "version": "0.55.3", + "version": "0.55.4", "license": "AGPL-3.0-only", "dependencies": { "@aws-sdk/client-s3": "^3.1169.0", @@ -27354,7 +27354,7 @@ }, "packages/frontend": { "name": "@anythingmcp/frontend", - "version": "0.55.3", + "version": "0.55.4", "license": "AGPL-3.0-only", "dependencies": { "@radix-ui/react-dialog": "^1.3.1", diff --git a/package.json b/package.json index bc9b3b11b..f638f12d8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "anythingmcp", - "version": "0.55.3", + "version": "0.55.4", "description": "Turn any REST/OpenAPI, SOAP/WSDL, GraphQL, OData or SQL API into MCP tools for Claude, ChatGPT and Copilot, no code. 886 pre-built adapters for ERP, e-commerce and more (SAP S/4HANA, SAP Business One, Odoo, Xentral, JTL-Wawi, Shopware, WooCommerce, Amazon Seller). Self-hosted, open source (AGPL-3.0).", "private": true, "license": "AGPL-3.0-only", diff --git a/packages/backend/package.json b/packages/backend/package.json index da26c8ef9..897b1c53c 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -1,6 +1,6 @@ { "name": "@anythingmcp/backend", - "version": "0.55.3", + "version": "0.55.4", "description": "AnythingMCP — NestJS Backend + Dynamic MCP Server", "private": true, "license": "AGPL-3.0-only", diff --git a/packages/backend/src/settings/member-visibility.routes.ts b/packages/backend/src/settings/member-visibility.routes.ts index 9ec6015a6..7418c4ddf 100644 --- a/packages/backend/src/settings/member-visibility.routes.ts +++ b/packages/backend/src/settings/member-visibility.routes.ts @@ -453,6 +453,7 @@ export const MEMBER_VISIBILITY_ROUTES: Readonly> 'McpApiKeysController.revokeKey': own(), 'McpApiKeysController.deleteKey': own(), 'RolesController.listRoles': admin(), + 'RolesController.listMembers': admin(), 'RolesController.createRole': admin(), 'RolesController.getRole': admin(), 'RolesController.updateRole': admin(), 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/package.json b/packages/frontend/package.json index 7da09d47d..457bdc6c8 100644 --- a/packages/frontend/package.json +++ b/packages/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@anythingmcp/frontend", - "version": "0.55.3", + "version": "0.55.4", "description": "AnythingMCP — Next.js Admin UI", "private": true, "license": "AGPL-3.0-only",