Skip to content

Commit 45e0fdf

Browse files
authored
Show restricted members only their own calls in the audit API (#1665)
1 parent 8cc1d3d commit 45e0fdf

9 files changed

Lines changed: 844 additions & 20 deletions
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
import 'reflect-metadata';
2+
import { RequestMethod } from '@nestjs/common';
3+
import { METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
4+
import { MemberVisibilityService } from '../settings/member-visibility.service';
5+
import { AuditController } from './audit.controller';
6+
7+
/**
8+
* Member visibility matrix of every GET route of AuditController:
9+
* ADMIN / EDITOR / VIEWER x open / restricted. Open workspaces and admins must
10+
* reach AuditService with exactly today's arguments; a restricted member gets
11+
* the same call plus their own user id. AuditService is mocked here; the
12+
* queries themselves are covered in audit.member-visibility.spec.ts and, on a
13+
* real database, in audit.member-visibility.integration.spec.ts.
14+
*/
15+
describe('AuditController member visibility', () => {
16+
const ORG = 'org-1';
17+
const ME = 'user-me';
18+
19+
let audit: Record<string, jest.Mock>;
20+
let orgSettings: { get: jest.Mock };
21+
let roles: { getAllowedToolIds: jest.Mock };
22+
let controller: AuditController;
23+
24+
const req = (role: string) => ({ user: { sub: ME, role, organizationId: ORG, email: '[email protected]' } });
25+
26+
/**
27+
* One entry per GET route: how to call it, the AuditService method it
28+
* reaches, and the arguments of the open path (today) and the restricted path.
29+
*/
30+
const ROUTES: Record<
31+
string,
32+
{
33+
path: string;
34+
service: string;
35+
call: (c: AuditController, role: string) => Promise<unknown>;
36+
open: unknown[];
37+
restricted: unknown[];
38+
}
39+
> = {
40+
listInvocations: {
41+
path: 'invocations',
42+
service: 'getRecentInvocations',
43+
call: (c, role) => c.listInvocations(req(role), '20', '40', 'tool-1', 'ERROR', 'crm', 'conn-1', 'srv-1'),
44+
open: [
45+
20,
46+
40,
47+
{ toolId: 'tool-1', status: 'ERROR', search: 'crm', connectorId: 'conn-1', mcpServerId: 'srv-1', organizationId: ORG },
48+
],
49+
restricted: [
50+
20,
51+
40,
52+
{
53+
toolId: 'tool-1',
54+
status: 'ERROR',
55+
search: 'crm',
56+
connectorId: 'conn-1',
57+
mcpServerId: 'srv-1',
58+
organizationId: ORG,
59+
onlyUserId: ME,
60+
},
61+
],
62+
},
63+
getStats: {
64+
path: 'stats',
65+
service: 'getStats',
66+
call: (c, role) => c.getStats(req(role)),
67+
open: [ORG],
68+
restricted: [ORG, ME],
69+
},
70+
getAnalytics: {
71+
path: 'analytics',
72+
service: 'getAnalytics',
73+
call: (c, role) => c.getAnalytics(req(role), { days: 30 }),
74+
open: [ORG, 30],
75+
restricted: [ORG, 30, ME],
76+
},
77+
getToolPerformance: {
78+
path: 'tool-performance',
79+
service: 'getToolPerformance',
80+
call: (c, role) => c.getToolPerformance(req(role), { hours: 48, connectorId: 'conn-1', mcpServerId: 'srv-1' }),
81+
open: [ORG, { hours: 48, connectorId: 'conn-1', mcpServerId: 'srv-1' }],
82+
restricted: [ORG, { hours: 48, connectorId: 'conn-1', mcpServerId: 'srv-1' }, ME],
83+
},
84+
getBreakdowns: {
85+
path: 'breakdowns',
86+
service: 'getBreakdowns',
87+
call: (c, role) => c.getBreakdowns(req(role), '14'),
88+
open: [ORG, 14],
89+
restricted: [ORG, 14, ME],
90+
},
91+
};
92+
93+
beforeEach(() => {
94+
audit = {
95+
getRecentInvocations: jest.fn().mockResolvedValue([]),
96+
getStats: jest.fn().mockResolvedValue({}),
97+
getAnalytics: jest.fn().mockResolvedValue({}),
98+
getToolPerformance: jest.fn().mockResolvedValue({ items: [], hasMore: false }),
99+
getBreakdowns: jest.fn().mockResolvedValue({}),
100+
};
101+
orgSettings = { get: jest.fn().mockResolvedValue(null) };
102+
roles = { getAllowedToolIds: jest.fn().mockResolvedValue(null) };
103+
const visibility = new MemberVisibilityService(orgSettings as any, roles as any);
104+
controller = new AuditController(audit as any, visibility);
105+
});
106+
107+
it('declares a visibility rule for every GET route of the controller', () => {
108+
const proto = AuditController.prototype as unknown as Record<string, unknown>;
109+
const getRoutes = Object.getOwnPropertyNames(proto).filter(
110+
(name) =>
111+
name !== 'constructor' &&
112+
typeof proto[name] === 'function' &&
113+
Reflect.getMetadata(METHOD_METADATA, proto[name] as object) === RequestMethod.GET,
114+
);
115+
expect(getRoutes.sort()).toEqual(Object.keys(ROUTES).sort());
116+
for (const name of getRoutes) {
117+
expect(Reflect.getMetadata(PATH_METADATA, proto[name] as object)).toBe(ROUTES[name].path);
118+
}
119+
});
120+
121+
describe.each(Object.entries(ROUTES))('%s', (_name, route) => {
122+
const expectCall = (args: unknown[]) => {
123+
const mock = audit[route.service];
124+
expect(mock).toHaveBeenCalledTimes(1);
125+
// Exact arity: the open path must not pass even an undefined extra argument.
126+
expect(mock.mock.calls[0]).toEqual(args);
127+
expect(mock.mock.calls[0]).toHaveLength(args.length);
128+
};
129+
130+
it.each(['open', 'restricted'])('ADMIN in a %s workspace: today’s call, no settings read', async (mode) => {
131+
orgSettings.get.mockResolvedValue(mode);
132+
await route.call(controller, 'ADMIN');
133+
expectCall(route.open);
134+
expect(orgSettings.get).not.toHaveBeenCalled();
135+
expect(roles.getAllowedToolIds).not.toHaveBeenCalled();
136+
});
137+
138+
it.each(['EDITOR', 'VIEWER'])('%s in an open workspace: today’s call', async (role) => {
139+
orgSettings.get.mockResolvedValue('open');
140+
await route.call(controller, role);
141+
expectCall(route.open);
142+
expect(roles.getAllowedToolIds).not.toHaveBeenCalled();
143+
});
144+
145+
it.each(['EDITOR', 'VIEWER'])('%s in a workspace that never set the mode: today’s call', async (role) => {
146+
orgSettings.get.mockResolvedValue(null);
147+
await route.call(controller, role);
148+
expectCall(route.open);
149+
});
150+
151+
it.each(['EDITOR', 'VIEWER'])('%s in a restricted workspace: own calls only', async (role) => {
152+
orgSettings.get.mockResolvedValue('restricted');
153+
await route.call(controller, role);
154+
expectCall(route.restricted);
155+
});
156+
157+
it.each([[['tool-1']], [[]]])(
158+
'a restricted member with a tool whitelist (%j) still gets own calls only',
159+
async (allowed) => {
160+
orgSettings.get.mockResolvedValue('restricted');
161+
roles.getAllowedToolIds.mockResolvedValue(allowed);
162+
await route.call(controller, 'VIEWER');
163+
expectCall(route.restricted);
164+
},
165+
);
166+
167+
it('fails closed when the role lookup throws', async () => {
168+
orgSettings.get.mockResolvedValue('restricted');
169+
roles.getAllowedToolIds.mockRejectedValue(new Error('database down'));
170+
await expect(route.call(controller, 'VIEWER')).rejects.toThrow('database down');
171+
expect(audit[route.service]).not.toHaveBeenCalled();
172+
});
173+
174+
it('fails closed when the mode lookup throws for a member', async () => {
175+
orgSettings.get.mockRejectedValue(new Error('database down'));
176+
await expect(route.call(controller, 'EDITOR')).rejects.toThrow('database down');
177+
expect(audit[route.service]).not.toHaveBeenCalled();
178+
});
179+
});
180+
181+
it.each([
182+
['toolId', [undefined, undefined, 'tool-x']],
183+
['status', [undefined, undefined, undefined, 'SUCCESS']],
184+
['search', [undefined, undefined, undefined, undefined, 'export']],
185+
['connectorId', [undefined, undefined, undefined, undefined, undefined, 'conn-x']],
186+
['mcpServerId', [undefined, undefined, undefined, undefined, undefined, undefined, 'srv-x']],
187+
] as const)('a restricted member filtering invocations by %s keeps the own-calls filter', async (_f, args) => {
188+
orgSettings.get.mockResolvedValue('restricted');
189+
await (controller.listInvocations as any)(req('VIEWER'), ...args);
190+
const filters = audit.getRecentInvocations.mock.calls[0][2];
191+
expect(filters).toMatchObject({ organizationId: ORG, onlyUserId: ME });
192+
});
193+
});

‎packages/backend/src/audit/audit.controller.ts‎

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,26 @@ import {
88
AnalyticsQueryDto,
99
} from './analytics-query.dto';
1010
import { ToolPerformanceQueryDto } from './tool-performance-query.dto';
11+
import { MemberVisibilityService } from '../settings/member-visibility.service';
12+
13+
/**
14+
* Every read route of this controller is scoped by member visibility: in a
15+
* workspace set to `restricted`, a member who is not an admin gets only the
16+
* calls they made themselves (rows without a user are hidden). Admins and open
17+
* workspaces take the unchanged workspace-wide path. The organisation filter
18+
* stays in every query; the user filter is added to it with AND, in SQL.
19+
*/
1120

1221
@ApiTags('Audit')
1322
@ApiBearerAuth()
1423
@ApiSecurity('api-key')
1524
@UseGuards(JwtOrManagementKeyGuard)
1625
@Controller('api/audit')
1726
export class AuditController {
18-
constructor(private readonly auditService: AuditService) {}
27+
constructor(
28+
private readonly auditService: AuditService,
29+
private readonly visibility: MemberVisibilityService,
30+
) {}
1931

2032
@Get('invocations')
2133
@ApiOperation({
@@ -26,7 +38,9 @@ export class AuditController {
2638
'A failure repeated within a minute is stored once with `repeatCount`. Filters combine with AND.\n\n' +
2739
'Typical uses: the last failures (`status=ERROR`), the calls of one tool or connector, or what one AI client did ' +
2840
'on one server (`mcpServerId`).\n\n' +
29-
'```bash\namcp api GET "/api/audit/invocations?status=ERROR&limit=20"\n```',
41+
'```bash\namcp api GET "/api/audit/invocations?status=ERROR&limit=20"\n```\n\n' +
42+
'In a workspace with restricted member visibility, a member who is not an admin gets only the calls they made ' +
43+
'themselves; calls without a user are hidden.',
3044
})
3145
@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Rows to return (default 100).', example: 20 })
3246
@ApiQuery({ name: 'offset', required: false, type: Number, description: 'Rows to skip, for paging.', example: 0 })
@@ -80,17 +94,35 @@ export class AuditController {
8094
@Query('connectorId') connectorId?: string,
8195
@Query('mcpServerId') mcpServerId?: string,
8296
) {
97+
const scope = await this.visibility.scopeFor(req.user);
98+
if (!scope.restricted) {
99+
return this.auditService.getRecentInvocations(
100+
limit ? parseInt(limit, 10) : 100,
101+
offset ? parseInt(offset, 10) : 0,
102+
{ toolId, status: status as any, search, connectorId, mcpServerId, organizationId: req.user.organizationId },
103+
);
104+
}
83105
return this.auditService.getRecentInvocations(
84106
limit ? parseInt(limit, 10) : 100,
85107
offset ? parseInt(offset, 10) : 0,
86-
{ toolId, status: status as any, search, connectorId, mcpServerId, organizationId: req.user.organizationId },
108+
{
109+
toolId,
110+
status: status as any,
111+
search,
112+
connectorId,
113+
mcpServerId,
114+
organizationId: req.user.organizationId,
115+
onlyUserId: scope.userId,
116+
},
87117
);
88118
}
89119

90120
@Get('stats')
91121
@ApiOperation({
92122
summary: 'Get invocation statistics',
93-
description: 'Tool-call counters for your workspace: last 24 hours, errors in the last 24 hours, last 7 days and all time.',
123+
description:
124+
'Tool-call counters for your workspace: last 24 hours, errors in the last 24 hours, last 7 days and all time.' +
125+
' In a workspace with restricted member visibility, a member who is not an admin gets only their own calls.',
94126
})
95127
@ApiResponse({
96128
status: 200,
@@ -100,7 +132,11 @@ export class AuditController {
100132
},
101133
})
102134
async getStats(@Req() req: any) {
103-
return this.auditService.getStats(req.user.organizationId);
135+
const scope = await this.visibility.scopeFor(req.user);
136+
if (!scope.restricted) {
137+
return this.auditService.getStats(req.user.organizationId);
138+
}
139+
return this.auditService.getStats(req.user.organizationId, scope.userId);
104140
}
105141

106142
@Get('analytics')
@@ -109,7 +145,8 @@ export class AuditController {
109145
description:
110146
'Returns a daily breakdown (UTC days, last `days`, default 7) of invocations by status, ' +
111147
'top 10 most-used tools, success rate, and average duration.\n\n' +
112-
'```bash\namcp api GET "/api/audit/analytics?days=30"\n```',
148+
'```bash\namcp api GET "/api/audit/analytics?days=30"\n```\n\n' +
149+
'In a workspace with restricted member visibility, a member who is not an admin gets only their own calls.',
113150
})
114151
@ApiQuery({
115152
name: 'days',
@@ -118,9 +155,17 @@ export class AuditController {
118155
description: `Window in days, 1 to ${ANALYTICS_MAX_DAYS} (default ${ANALYTICS_DEFAULT_DAYS})`,
119156
})
120157
async getAnalytics(@Req() req: any, @Query() query: AnalyticsQueryDto) {
158+
const scope = await this.visibility.scopeFor(req.user);
159+
if (!scope.restricted) {
160+
return this.auditService.getAnalytics(
161+
req.user.organizationId,
162+
query.days ?? ANALYTICS_DEFAULT_DAYS,
163+
);
164+
}
121165
return this.auditService.getAnalytics(
122166
req.user.organizationId,
123167
query.days ?? ANALYTICS_DEFAULT_DAYS,
168+
scope.userId,
124169
);
125170
}
126171

@@ -130,18 +175,23 @@ export class AuditController {
130175
description:
131176
'Groups the last hours (default 24, maximum 2160) by tool, connector and MCP server. ' +
132177
'ERROR and TIMEOUT count as failures. Latency percentiles use stored duration samples; ' +
133-
'repeated failures retain their first recorded server and duration.',
178+
'repeated failures retain their first recorded server and duration.' +
179+
' In a workspace with restricted member visibility, a member who is not an admin gets only their own calls.',
134180
})
135181
@ApiQuery({ name: 'hours', required: false, type: Number })
136182
@ApiQuery({ name: 'connectorId', required: false, type: String })
137183
@ApiQuery({ name: 'mcpServerId', required: false, type: String })
138184
@ApiQuery({ name: 'limit', required: false, type: Number })
139185
@ApiQuery({ name: 'offset', required: false, type: Number })
140186
async getToolPerformance(
141-
@Req() req: { user: { organizationId: string } },
187+
@Req() req: { user: { sub: string; role: string; organizationId: string } },
142188
@Query() query: ToolPerformanceQueryDto,
143189
) {
144-
return this.auditService.getToolPerformance(req.user.organizationId, query);
190+
const scope = await this.visibility.scopeFor(req.user);
191+
if (!scope.restricted) {
192+
return this.auditService.getToolPerformance(req.user.organizationId, query);
193+
}
194+
return this.auditService.getToolPerformance(req.user.organizationId, query, scope.userId);
145195
}
146196

147197
@Get('breakdowns')
@@ -151,7 +201,8 @@ export class AuditController {
151201
'Aggregates the last N days (default 30) of tool calls per connector, per ' +
152202
'MCP server and per user, with error counts, proxy-call metering and a ' +
153203
'volume-based cost estimate. Each list holds the top 20 by calls; `estCostMicros` is 0 unless the ' +
154-
'instance sets per-call rates.',
204+
'instance sets per-call rates.' +
205+
' In a workspace with restricted member visibility, a member who is not an admin gets only their own calls: every list and total counts only their calls, and `byUser` holds only their own row.',
155206
})
156207
@ApiQuery({ name: 'days', required: false, type: Number, description: 'Window in days, 1 to 365 (default 30).', example: 30 })
157208
@ApiResponse({
@@ -172,9 +223,17 @@ export class AuditController {
172223
},
173224
})
174225
async getBreakdowns(@Req() req: any, @Query('days') days?: string) {
226+
const scope = await this.visibility.scopeFor(req.user);
227+
if (!scope.restricted) {
228+
return this.auditService.getBreakdowns(
229+
req.user.organizationId,
230+
days ? parseInt(days, 10) : 30,
231+
);
232+
}
175233
return this.auditService.getBreakdowns(
176234
req.user.organizationId,
177235
days ? parseInt(days, 10) : 30,
236+
scope.userId,
178237
);
179238
}
180239
}

0 commit comments

Comments
 (0)