-
Notifications
You must be signed in to change notification settings - Fork 728
Expand file tree
/
Copy pathAuthorizeAttributeTests.cs
More file actions
537 lines (440 loc) · 22.5 KB
/
Copy pathAuthorizeAttributeTests.cs
File metadata and controls
537 lines (440 loc) · 22.5 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.AspNetCore.Tests.Utils;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.ComponentModel;
using System.Security.Claims;
namespace ModelContextProtocol.AspNetCore.Tests;
/// <summary>
/// Tests for MCP authorization functionality with [Authorize], [AllowAnonymous] and role-based authorization.
/// </summary>
public class AuthorizeAttributeTests(ITestOutputHelper testOutputHelper) : KestrelInMemoryTest(testOutputHelper)
{
private readonly MockLoggerProvider _mockLoggerProvider = new();
private async Task<McpClient> ConnectAsync()
{
await using var transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new("http://localhost:5000"),
}, HttpClient, LoggerFactory);
return await McpClient.CreateAsync(transport, cancellationToken: TestContext.Current.CancellationToken, loggerFactory: LoggerFactory);
}
[Fact]
public async Task Authorize_Tool_RequiresAuthentication()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.CallToolAsync(
"authorized_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): Access forbidden: This tool requires authorization.", exception.Message);
Assert.Equal(McpErrorCode.InvalidRequest, exception.ErrorCode);
}
[Fact]
public async Task ClassLevelAuthorize_Tool_RequiresAuthentication()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AllowAnonymousTestTools>());
var client = await ConnectAsync();
var result = await client.CallToolAsync(
"anonymous_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(result.IsError ?? false);
var content = Assert.Single(result.Content.OfType<TextContentBlock>());
Assert.Equal("Anonymous: test", content.Text);
}
[Fact]
public async Task AllowAnonymous_Tool_AllowsAnonymousAccess()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AllowAnonymousTestTools>());
var client = await ConnectAsync();
var result = await client.CallToolAsync(
"anonymous_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(result.IsError ?? false);
var content = Assert.Single(result.Content.OfType<TextContentBlock>());
Assert.Equal("Anonymous: test", content.Text);
}
[Fact]
public async Task Authorize_Tool_AllowsAuthenticatedUser()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "TestUser");
var client = await ConnectAsync();
var result = await client.CallToolAsync(
"authorized_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(result.IsError ?? false);
var content = Assert.Single(result.Content.OfType<TextContentBlock>());
Assert.Equal("Authorized: test", content.Text);
}
[Fact]
public async Task AuthorizeWithRoles_Tool_RequiresAdminRole()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "TestUser", "User");
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.CallToolAsync(
"admin_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): Access forbidden: This tool requires authorization.", exception.Message);
Assert.Equal(McpErrorCode.InvalidRequest, exception.ErrorCode);
}
[Fact]
public async Task AuthorizeWithRoles_Tool_AllowsAdminUser()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "AdminUser", "Admin");
var client = await ConnectAsync();
var result = await client.CallToolAsync(
"admin_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(result.IsError ?? false);
var content = Assert.Single(result.Content.OfType<TextContentBlock>());
Assert.Equal("Admin: test", content.Text);
}
[Fact]
public async Task ListTools_Anonymous_OnlyReturnsAnonymousTools()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>());
var client = await ConnectAsync();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Single(tools);
Assert.Equal("anonymous_tool", tools[0].Name);
}
[Fact]
public async Task ListTools_AuthenticatedUser_ReturnsAuthorizedTools()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "TestUser");
var client = await ConnectAsync();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
// Authenticated user should see anonymous and basic authorized tools, but not admin-only tools
Assert.Equal(2, tools.Count);
var toolNames = tools.Select(t => t.Name).OrderBy(n => n).ToList();
Assert.Equal(["anonymous_tool", "authorized_tool"], toolNames);
}
[Fact]
public async Task ListTools_AdminUser_ReturnsAllTools()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "AdminUser", "Admin");
var client = await ConnectAsync();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
// Admin user should see all tools
Assert.Equal(3, tools.Count);
var toolNames = tools.Select(t => t.Name).OrderBy(n => n).ToList();
Assert.Equal(["admin_tool", "anonymous_tool", "authorized_tool"], toolNames);
}
[Fact]
public async Task ListTools_UserRole_DoesNotReturnAdminTools()
{
await using var app = await StartServerWithAuth(builder => builder.WithTools<AuthorizationTestTools>(), "TestUser", "User");
var client = await ConnectAsync();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
// User with User role should not see admin-only tools
Assert.Equal(2, tools.Count);
var toolNames = tools.Select(t => t.Name).OrderBy(n => n).ToList();
Assert.Equal(["anonymous_tool", "authorized_tool"], toolNames);
}
[Fact]
public async Task Authorize_Prompt_RequiresAuthentication()
{
await using var app = await StartServerWithAuth(builder => builder.WithPrompts<AuthorizationTestPrompts>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.GetPromptAsync(
"authorized_prompt",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): Access forbidden: This prompt requires authorization.", exception.Message);
Assert.Equal(McpErrorCode.InvalidRequest, exception.ErrorCode);
}
[Fact]
public async Task Authorize_Prompt_AllowsAuthenticatedUser()
{
await using var app = await StartServerWithAuth(builder => builder.WithPrompts<AuthorizationTestPrompts>(), "TestUser");
var client = await ConnectAsync();
var result = await client.GetPromptAsync(
"authorized_prompt",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
var message = Assert.Single(result.Messages);
Assert.Equal(Role.User, message.Role);
var content = Assert.IsType<TextContentBlock>(message.Content);
Assert.Equal("Authorized prompt: test", content.Text);
}
[Fact]
public async Task ListPrompts_Anonymous_OnlyReturnsAnonymousPrompts()
{
await using var app = await StartServerWithAuth(builder => builder.WithPrompts<AuthorizationTestPrompts>());
var client = await ConnectAsync();
var prompts = await client.ListPromptsAsync(cancellationToken: TestContext.Current.CancellationToken);
// Anonymous user should only see prompts marked with [AllowAnonymous]
Assert.Single(prompts);
Assert.Equal("anonymous_prompt", prompts[0].Name);
}
[Fact]
public async Task Authorize_Resource_RequiresAuthentication()
{
await using var app = await StartServerWithAuth(builder => builder.WithResources<AuthorizationTestResources>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ReadResourceAsync(
"resource://authorized",
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): Access forbidden: This resource requires authorization.", exception.Message);
Assert.Equal(McpErrorCode.InvalidRequest, exception.ErrorCode);
}
[Fact]
public async Task Authorize_Resource_AllowsAuthenticatedUser()
{
await using var app = await StartServerWithAuth(builder => builder.WithResources<AuthorizationTestResources>(), "TestUser");
var client = await ConnectAsync();
var result = await client.ReadResourceAsync(
"resource://authorized",
cancellationToken: TestContext.Current.CancellationToken);
var content = Assert.Single(result.Contents.OfType<TextResourceContents>());
Assert.Equal("Authorized resource content", content.Text);
}
[Fact]
public async Task ListResources_Anonymous_OnlyReturnsAnonymousResources()
{
await using var app = await StartServerWithAuth(builder => builder.WithResources<AuthorizationTestResources>());
var client = await ConnectAsync();
var resources = await client.ListResourcesAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Single(resources);
Assert.Equal("resource://anonymous", resources[0].Uri);
}
[Fact]
public async Task ListTools_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithTools<AuthorizationTestTools>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for tools/list operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task CallTool_WithoutAuthFilters_ReturnsError()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithTools<AuthorizationTestTools>());
var client = await ConnectAsync();
var toolResult = await client.CallToolAsync(
"authorized_tool",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(toolResult.IsError);
var errorContent = Assert.IsType<TextContentBlock>(Assert.Single(toolResult.Content));
Assert.Equal("An error occurred invoking 'authorized_tool'.", errorContent.Text);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Error &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for tools/call operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task ListPrompts_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithPrompts<AuthorizationTestPrompts>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ListPromptsAsync(cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for prompts/list operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task GetPrompt_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithPrompts<AuthorizationTestPrompts>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.GetPromptAsync(
"authorized_prompt",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for prompts/get operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task ListResources_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithResources<AuthorizationTestResources>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ListResourcesAsync(cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for resources/list operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task ReadResource_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithResources<AuthorizationTestResources>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ReadResourceAsync(
"resource://authorized",
cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for resources/read operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
[Fact]
public async Task ListResourceTemplates_WithoutAuthFilters_ThrowsInvalidOperationException()
{
_mockLoggerProvider.LogMessages.Clear();
await using var app = await StartServerWithoutAuthFilters(builder => builder.WithResources<AuthorizationTestResources>());
var client = await ConnectAsync();
var exception = await Assert.ThrowsAsync<McpException>(async () =>
await client.ListResourceTemplatesAsync(cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal("Request failed (remote): An error occurred.", exception.Message);
Assert.Contains(_mockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("Authorization filter was not invoked for resources/templates/list operation") &&
log.Exception.Message.Contains("Ensure that AddAuthorizationFilters() is called"));
}
private async Task<WebApplication> StartServerWithAuth(Action<IMcpServerBuilder> configure, string? userName = null, params string[] roles)
{
var mcpServerBuilder = Builder.Services.AddMcpServer().WithHttpTransport().AddAuthorizationFilters();
configure(mcpServerBuilder);
Builder.Services.AddAuthorization();
Builder.Services.AddSingleton<ILoggerProvider>(_mockLoggerProvider);
var app = Builder.Build();
if (userName is not null)
{
app.Use(next =>
{
return async context =>
{
context.User = CreateUser(userName, roles);
await next(context);
};
});
}
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
return app;
}
private async Task<WebApplication> StartServerWithoutAuthFilters(Action<IMcpServerBuilder> configure)
{
var mcpServerBuilder = Builder.Services.AddMcpServer().WithHttpTransport(); // No AddAuthorizationFilters() call
configure(mcpServerBuilder);
Builder.Services.AddAuthorization();
Builder.Services.AddSingleton<ILoggerProvider>(_mockLoggerProvider);
var app = Builder.Build();
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
return app;
}
private ClaimsPrincipal CreateUser(string name, params string[] roles)
=> new ClaimsPrincipal(new ClaimsIdentity(
[new Claim("name", name), new Claim(ClaimTypes.NameIdentifier, name), .. roles.Select(role => new Claim("role", role))],
"TestAuthType", "name", "role"));
[McpServerToolType]
private class AuthorizationTestTools
{
[McpServerTool, Description("A tool that allows anonymous access.")]
public static string AnonymousTool(string message)
{
return $"Anonymous: {message}";
}
[McpServerTool, Description("A tool that requires authorization.")]
[Authorize]
public static string AuthorizedTool(string message)
{
return $"Authorized: {message}";
}
[McpServerTool, Description("A tool that requires Admin role.")]
[Authorize(Roles = "Admin")]
public static string AdminTool(string message)
{
return $"Admin: {message}";
}
}
[McpServerToolType]
[Authorize]
private class AllowAnonymousTestTools
{
[McpServerTool, Description("A tool that allows anonymous access.")]
[AllowAnonymous]
public static string AnonymousTool(string message)
{
return $"Anonymous: {message}";
}
[McpServerTool, Description("A tool that requires authorization.")]
public static string AuthorizedTool(string message)
{
return $"Authorized: {message}";
}
}
[McpServerPromptType]
private class AuthorizationTestPrompts
{
[McpServerPrompt, Description("A prompt that allows anonymous access.")]
public static string AnonymousPrompt(string message)
{
return $"Anonymous prompt: {message}";
}
[McpServerPrompt, Description("A prompt that requires authorization.")]
[Authorize]
public static string AuthorizedPrompt(string message)
{
return $"Authorized prompt: {message}";
}
}
[McpServerResourceType]
private class AuthorizationTestResources
{
[McpServerResource(UriTemplate = "resource://anonymous"), Description("A resource that allows anonymous access.")]
public static string AnonymousResource()
{
return "Anonymous resource content";
}
[McpServerResource(UriTemplate = "resource://authorized"), Description("A resource that requires authorization.")]
[Authorize]
public static string AuthorizedResource()
{
return "Authorized resource content";
}
[McpServerResource(UriTemplate = "resource://authorized/{id}"), Description("A resource template that requires authorization.")]
[Authorize]
public static string AuthorizedResourceWithTemplate(string id)
{
return "Authorized resource content";
}
}
}