From acaee6582d5f35cc0a578c3c6b5f65b6fa5d2bb5 Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:09 +0100 Subject: [PATCH 1/3] 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 a8e66abf217757693c98abad8870d8d7d8d7c7ad Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:18 +0100 Subject: [PATCH 2/3] 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 c27ec4f2ce4c2be83573a2aff260bef74d783bdb Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:08:18 +0100 Subject: [PATCH 3/3] 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 df944d7c0..8781297ef 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -489,8 +489,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 1029b832e..04e880732 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 @@ -143,6 +167,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 b6bffcc72..5521129ac 100644 --- a/docs/sso.md +++ b/docs/sso.md @@ -135,7 +135,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**.