-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathserver-fga.test.ts
More file actions
468 lines (428 loc) · 14.3 KB
/
Copy pathserver-fga.test.ts
File metadata and controls
468 lines (428 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* @license Mastra Enterprise License - see ee/LICENSE
*/
import { FGADeniedError, MastraFGAPermissions } from '@mastra/core/auth/ee';
import { createTool } from '@mastra/core/tools';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { z } from 'zod/v3';
import { MCPServer } from '../server';
/**
* Tests for FGA authorization in MCP server tool execution.
*
* The MCP server checks FGA authorization before executing tools when an FGA
* provider is configured on the mastra instance.
*
* When no FGA provider is configured, tool execution proceeds normally
* (backward compatible). When an FGA provider is configured and no user context
* is available, authorization fails closed.
*/
function createMockMastra(fga?: any) {
return {
getServer: () => (fga ? { fga } : {}),
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
addTool: vi.fn(),
addAgent: vi.fn(),
addWorkflow: vi.fn(),
};
}
describe('MCP Server FGA checks', () => {
let mcpServer: MCPServer;
const createRequestContext = (user?: { id: string }) => {
const values = new Map<string, unknown>();
if (user) {
values.set('user', user);
}
return {
get: (key: string) => values.get(key),
set: (key: string, value: unknown) => {
values.set(key, value);
},
};
};
const testTool = createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({ input: z.string() }),
outputSchema: z.object({ output: z.string() }),
execute: async () => {
return { output: 'success' };
},
});
beforeEach(() => {
vi.clearAllMocks();
});
it('should enforce FGA in executeTool when requestContext has a user', async () => {
const execute = vi.fn().mockResolvedValue({ output: 'success' });
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({ input: z.string() }),
execute,
}),
},
});
const mockFGAProvider = {
check: vi.fn().mockResolvedValue(false),
require: vi
.fn()
.mockRejectedValue(
new FGADeniedError(
{ id: 'user-1' },
{ type: 'tool', id: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']) },
MastraFGAPermissions.TOOLS_EXECUTE,
),
),
filterAccessible: vi.fn(),
};
const mockMastra = createMockMastra(mockFGAProvider);
mcpServer.__registerMastra(mockMastra as any);
const requestContext = createRequestContext({ id: 'user-1' });
await expect(mcpServer.executeTool('test-tool', { input: 'hello' }, { requestContext })).rejects.toMatchObject({
cause: { name: 'FGADeniedError', status: 403 },
});
expect(execute).not.toHaveBeenCalled();
expect(mockFGAProvider.require).toHaveBeenCalledWith(
{ id: 'user-1' },
expect.objectContaining({
resource: { type: 'tool', id: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']) },
permission: MastraFGAPermissions.TOOLS_EXECUTE,
context: expect.objectContaining({
resourceId: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']),
requestContext,
metadata: expect.objectContaining({
mcpServerId: mcpServer.getServerInfo().id,
mcpServerName: 'test-server',
toolId: 'test-tool',
}),
}),
}),
);
});
it('should fail closed in executeTool when FGA is configured and no user is present', async () => {
const execute = vi.fn().mockResolvedValue({ output: 'success' });
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({ input: z.string() }),
execute,
}),
},
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
const mockMastra = createMockMastra(mockFGAProvider);
mcpServer.__registerMastra(mockMastra as any);
await expect(
mcpServer.executeTool('test-tool', { input: 'hello' }, { requestContext: createRequestContext() as any }),
).rejects.toMatchObject({ cause: { name: 'FGADeniedError', status: 403 } });
expect(mockFGAProvider.require).not.toHaveBeenCalled();
expect(execute).not.toHaveBeenCalled();
});
it('should filter getToolListInfo by FGA access', async () => {
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
allowed: createTool({
id: 'allowed',
description: 'Allowed tool',
inputSchema: z.object({}),
execute: vi.fn(),
}),
denied: createTool({
id: 'denied',
description: 'Denied tool',
inputSchema: z.object({}),
execute: vi.fn(),
}),
},
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(async (_user: unknown, params: { resource: { id: string } }) => {
if (params.resource.id === JSON.stringify([mcpServer.getServerInfo().id, 'denied'])) {
throw new FGADeniedError(
{ id: 'user-1' },
{ type: 'tool', id: JSON.stringify([mcpServer.getServerInfo().id, 'denied']) },
MastraFGAPermissions.TOOLS_EXECUTE,
);
}
}),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const result = await mcpServer.getToolListInfo(createRequestContext({ id: 'user-1' }) as any);
expect(result.tools.map(tool => tool.name)).toEqual(['allowed']);
expect(mockFGAProvider.require).toHaveBeenCalledTimes(2);
});
it('should expose outputSchema separately from inputSchema after FGA filtering', async () => {
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: { 'test-tool': testTool },
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const result = await mcpServer.getToolListInfo(createRequestContext({ id: 'user-1' }) as any);
expect(result.tools[0]?.inputSchema).toMatchObject({
properties: { input: expect.any(Object) },
});
expect(result.tools[0]?.outputSchema).toMatchObject({
properties: { output: expect.any(Object) },
});
});
it('should return no tools when FGA is configured and list context has no user', async () => {
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({}),
execute: vi.fn(),
}),
},
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const result = await mcpServer.getToolListInfo(createRequestContext() as any);
expect(result.tools).toEqual([]);
expect(mockFGAProvider.require).not.toHaveBeenCalled();
});
it('should map MCP authInfo to user before FGA filtering tools/list', async () => {
const authInfo = {
subject: 'user-1',
organizationMembershipId: 'org-member-1',
};
const mapAuthInfoToUser = vi.fn(({ authInfo }: { authInfo: any }) => ({
id: authInfo.subject,
organizationMembershipId: authInfo.organizationMembershipId,
}));
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({}),
execute: vi.fn(),
}),
},
mapAuthInfoToUser,
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const requestHandlers = (mcpServer.getServer() as any)._requestHandlers;
const listToolsHandler = requestHandlers.get('tools/list');
const result = await listToolsHandler(
{
jsonrpc: '2.0',
id: 'test-list',
method: 'tools/list',
},
{
authInfo,
signal: new AbortController().signal,
sendNotification: vi.fn(),
sendRequest: vi.fn(),
},
);
expect(result.tools.map((tool: { name: string }) => tool.name)).toEqual(['test-tool']);
expect(mapAuthInfoToUser).toHaveBeenCalledWith({
authInfo,
extra: expect.objectContaining({ authInfo }),
requestContext: expect.objectContaining({
get: expect.any(Function),
set: expect.any(Function),
}),
});
expect(mockFGAProvider.require).toHaveBeenCalledWith(
{ id: 'user-1', organizationMembershipId: 'org-member-1' },
expect.objectContaining({
resource: { type: 'tool', id: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']) },
permission: MastraFGAPermissions.TOOLS_EXECUTE,
}),
);
});
it('should map MCP authInfo to user before FGA enforcing tools/call', async () => {
const authInfo = {
subject: 'user-1',
organizationMembershipId: 'org-member-1',
};
const execute = vi.fn(async (_args: unknown, options: { requestContext: { get: (key: string) => any } }) => ({
output: options.requestContext.get('user').id,
}));
const mapAuthInfoToUser = vi.fn(({ authInfo }: { authInfo: any }) => ({
id: authInfo.subject,
organizationMembershipId: authInfo.organizationMembershipId,
}));
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({ input: z.string() }),
execute,
}),
},
mapAuthInfoToUser,
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const requestHandlers = (mcpServer.getServer() as any)._requestHandlers;
const callToolHandler = requestHandlers.get('tools/call');
const result = await callToolHandler(
{
jsonrpc: '2.0',
id: 'test-call',
method: 'tools/call',
params: {
name: 'test-tool',
arguments: { input: 'hello' },
},
},
{
authInfo,
signal: new AbortController().signal,
sendNotification: vi.fn(),
sendRequest: vi.fn(),
},
);
expect(result.isError).toBe(false);
expect(JSON.parse(result.content[0].text)).toEqual({ output: 'user-1' });
expect(execute).toHaveBeenCalledTimes(1);
expect(mockFGAProvider.require).toHaveBeenCalledWith(
{ id: 'user-1', organizationMembershipId: 'org-member-1' },
expect.objectContaining({
resource: { type: 'tool', id: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']) },
permission: MastraFGAPermissions.TOOLS_EXECUTE,
}),
);
});
it('should use server FGA mapping overrides when filtering tools/list', async () => {
const deriveId = vi.fn(({ user }) => user.id);
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({}),
execute: vi.fn(),
}),
},
fga: {
resourceMapping: {
tool: {
fgaResourceType: 'mcp-user',
deriveId,
},
},
permissionMapping: {
[MastraFGAPermissions.TOOLS_EXECUTE]: 'read',
},
},
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const requestContext = createRequestContext({ id: 'user-1' });
const result = await mcpServer.getToolListInfo(requestContext as any);
expect(result.tools.map(tool => tool.name)).toEqual(['test-tool']);
expect(deriveId).toHaveBeenCalledWith({
user: { id: 'user-1' },
resourceId: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']),
requestContext,
});
expect(mockFGAProvider.require).toHaveBeenCalledWith(
{ id: 'user-1' },
expect.objectContaining({
resource: { type: 'mcp-user', id: 'user-1' },
permission: 'read',
}),
);
});
it('should use server FGA mapping overrides when enforcing tools/call', async () => {
const execute = vi.fn().mockResolvedValue({ output: 'success' });
const deriveId = vi.fn(({ user }) => user.id);
mcpServer = new MCPServer({
name: 'test-server',
version: '1.0.0',
tools: {
'test-tool': createTool({
id: 'test-tool',
description: 'A test tool',
inputSchema: z.object({ input: z.string() }),
execute,
}),
},
fga: {
resourceMapping: {
tool: {
fgaResourceType: 'mcp-user',
deriveId,
},
},
permissionMapping: {
[MastraFGAPermissions.TOOLS_EXECUTE]: 'read',
},
},
});
const mockFGAProvider = {
check: vi.fn(),
require: vi.fn(),
filterAccessible: vi.fn(),
};
mcpServer.__registerMastra(createMockMastra(mockFGAProvider) as any);
const requestContext = createRequestContext({ id: 'user-1' });
await mcpServer.executeTool('test-tool', { input: 'hello' }, { requestContext: requestContext as any });
expect(execute).toHaveBeenCalledTimes(1);
expect(deriveId).toHaveBeenCalledWith({
user: { id: 'user-1' },
resourceId: JSON.stringify([mcpServer.getServerInfo().id, 'test-tool']),
requestContext,
});
expect(mockFGAProvider.require).toHaveBeenCalledWith(
{ id: 'user-1' },
expect.objectContaining({
resource: { type: 'mcp-user', id: 'user-1' },
permission: 'read',
}),
);
});
});