-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathAuthEventTests.cs
More file actions
405 lines (340 loc) · 15 KB
/
AuthEventTests.cs
File metadata and controls
405 lines (340 loc) · 15 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
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.AspNetCore.Tests.Utils;
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
namespace ModelContextProtocol.AspNetCore.Tests;
/// <summary>
/// Tests for MCP authentication when resource metadata is provided via events rather than static configuration.
/// </summary>
public class AuthEventTests : KestrelInMemoryTest, IAsyncDisposable
{
private const string McpServerUrl = "http://localhost:5000";
private const string OAuthServerUrl = "https://localhost:7029";
private readonly CancellationTokenSource _testCts = new();
private readonly TestOAuthServer.Program _testOAuthServer;
private readonly Task _testOAuthRunTask;
public AuthEventTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
// Let the HandleAuthorizationUrlAsync take a look at the Location header
SocketsHttpHandler.AllowAutoRedirect = false;
// The dev cert may not be installed on the CI, but AddJwtBearer requires an HTTPS backchannel by default.
// The easiest workaround is to disable cert validation for testing purposes.
SocketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
_testOAuthServer = new TestOAuthServer.Program(
XunitLoggerProvider,
KestrelInMemoryTransport
);
_testOAuthRunTask = _testOAuthServer.RunServerAsync(cancellationToken: _testCts.Token);
Builder
.Services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Backchannel = HttpClient;
options.Authority = OAuthServerUrl;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = McpServerUrl,
ValidIssuer = OAuthServerUrl,
NameClaimType = "name",
RoleClaimType = "roles",
};
})
.AddMcp(options =>
{
// Note: ResourceMetadata is NOT set here - it will be provided via events
options.Events.OnResourceMetadataRequest = async context =>
{
// Dynamically provide the resource metadata
context.ResourceMetadata = new ProtectedResourceMetadata
{
Resource = new Uri(McpServerUrl),
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:tools"],
};
await Task.CompletedTask;
};
});
Builder.Services.AddAuthorization();
}
public async ValueTask DisposeAsync()
{
_testCts.Cancel();
try
{
await _testOAuthRunTask;
}
catch (OperationCanceledException) { }
finally
{
_testCts.Dispose();
}
}
[Fact]
public async Task CanAuthenticate_WithResourceMetadataFromEvent()
{
Builder.Services.AddMcpServer().WithHttpTransport();
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(
new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "demo-client",
ClientSecret = "demo-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
},
},
HttpClient,
LoggerFactory
);
await using var client = await McpClientFactory.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken
);
}
[Fact]
public async Task CanAuthenticate_WithDynamicClientRegistration_FromEvent()
{
Builder.Services.AddMcpServer().WithHttpTransport();
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
DynamicClientRegistrationResponse? dcrResponse = null;
await using var transport = new SseClientTransport(
new()
{
Endpoint = new(McpServerUrl),
OAuth = new ClientOAuthOptions()
{
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
Scopes = ["mcp:tools"],
DynamicClientRegistration = new()
{
ClientName = "Test MCP Client",
ClientUri = new Uri("https://example.com"),
ResponseDelegate = (response, cancellationToken) =>
{
dcrResponse = response;
return Task.CompletedTask;
},
},
},
},
HttpClient,
LoggerFactory
);
await using var client = await McpClientFactory.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken
);
Assert.NotNull(dcrResponse);
Assert.False(string.IsNullOrEmpty(dcrResponse.ClientId));
Assert.False(string.IsNullOrEmpty(dcrResponse.ClientSecret));
}
[Fact]
public async Task ResourceMetadataEndpoint_ReturnsCorrectMetadata_FromEvent()
{
Builder.Services.AddMcpServer().WithHttpTransport();
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var metadata = await response.Content.ReadFromJsonAsync<ProtectedResourceMetadata>(
McpJsonUtilities.DefaultOptions,
TestContext.Current.CancellationToken
);
Assert.NotNull(metadata);
Assert.Equal(new Uri(McpServerUrl), metadata.Resource);
Assert.Contains(new Uri(OAuthServerUrl), metadata.AuthorizationServers);
Assert.Contains("mcp:tools", metadata.ScopesSupported);
}
[Fact]
public async Task ResourceMetadataEndpoint_CanModifyExistingMetadata_InEvent()
{
Builder.Services.AddMcpServer().WithHttpTransport();
// Override the configuration to test modification of existing metadata
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
// Set initial metadata
options.ResourceMetadata = new ProtectedResourceMetadata
{
Resource = new Uri(McpServerUrl),
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:basic"],
};
// Override the event to modify the metadata
options.Events.OnResourceMetadataRequest = async context =>
{
// Start with the existing metadata and modify it
if (context.ResourceMetadata != null)
{
context.ResourceMetadata.ScopesSupported.Add("mcp:tools");
context.ResourceMetadata.ResourceName = "Dynamic Test Resource";
}
await Task.CompletedTask;
};
}
);
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var metadata = await response.Content.ReadFromJsonAsync<ProtectedResourceMetadata>(
McpJsonUtilities.DefaultOptions,
TestContext.Current.CancellationToken
);
Assert.NotNull(metadata);
Assert.Equal(new Uri(McpServerUrl), metadata.Resource);
Assert.Contains(new Uri(OAuthServerUrl), metadata.AuthorizationServers);
Assert.Contains("mcp:basic", metadata.ScopesSupported);
Assert.Contains("mcp:tools", metadata.ScopesSupported);
Assert.Equal("Dynamic Test Resource", metadata.ResourceName);
}
[Fact]
public async Task ResourceMetadataEndpoint_ThrowsException_WhenNoMetadataProvided()
{
Builder.Services.AddMcpServer().WithHttpTransport();
// Override the configuration to test the error case where no metadata is provided
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
// Don't set ResourceMetadata and provide an event that doesn't set it either
options.ResourceMetadata = null;
options.Events.OnResourceMetadataRequest = async context =>
{
// Intentionally don't set context.ResourceMetadata to test error handling
await Task.CompletedTask;
};
}
);
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
// Make a direct request to the resource metadata endpoint - this should fail
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// The request should fail with an internal server error due to the InvalidOperationException
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
[Fact]
public async Task ResourceMetadataEndpoint_HandlesResponse_WhenHandleResponseCalled()
{
Builder.Services.AddMcpServer().WithHttpTransport();
// Override the configuration to test HandleResponse behavior
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.ResourceMetadata = null;
options.Events.OnResourceMetadataRequest = async context =>
{
// Call HandleResponse() to discontinue processing and return to client
context.HandleResponse();
await Task.CompletedTask;
};
}
);
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// The request should be handled by the event handler without returning metadata
// Since HandleResponse() was called, the handler should have taken responsibility
// for generating the response, which in this case means an empty response
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// The response should be empty since the event handler called HandleResponse()
// but didn't write any content to the response
var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Empty(content);
}
[Fact]
public async Task ResourceMetadataEndpoint_SkipsHandler_WhenSkipHandlerCalled()
{
Builder.Services.AddMcpServer().WithHttpTransport();
// Override the configuration to test SkipHandler behavior
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.ResourceMetadata = null;
options.Events.OnResourceMetadataRequest = async context =>
{
// Call SkipHandler() to discontinue processing in the current handler
context.SkipHandler();
await Task.CompletedTask;
};
}
);
await using var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// When SkipHandler() is called, the authentication handler should skip processing
// and let other handlers in the pipeline handle the request. Since there are no
// other handlers configured for this endpoint, this should result in a 404
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
private async Task<string?> HandleAuthorizationUrlAsync(
Uri authorizationUri,
Uri redirectUri,
CancellationToken cancellationToken
)
{
using var redirectResponse = await HttpClient.GetAsync(authorizationUri, cancellationToken);
Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode);
var location = redirectResponse.Headers.Location;
if (location is not null && !string.IsNullOrEmpty(location.Query))
{
var queryParams = QueryHelpers.ParseQuery(location.Query);
return queryParams["code"];
}
return null;
}
}