-
Notifications
You must be signed in to change notification settings - Fork 734
Expand file tree
/
Copy pathMcpAuthenticationHandlerTests.cs
More file actions
203 lines (164 loc) · 9.63 KB
/
Copy pathMcpAuthenticationHandlerTests.cs
File metadata and controls
203 lines (164 loc) · 9.63 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
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.AspNetCore.Tests.Utils;
using ModelContextProtocol.Authentication;
using System.Net;
using System.Net.Http.Json;
using System.Text.Encodings.Web;
namespace ModelContextProtocol.AspNetCore.Tests.OAuth;
public class McpAuthenticationHandlerTests(ITestOutputHelper outputHelper) : KestrelInMemoryTest(outputHelper)
{
[Fact]
public async Task Challenge_WithRelativeResourceMetadataUri_SetsAbsoluteUrl()
{
const string metadataPath = "/.well-known/custom-relative";
await using var app = await StartAuthenticationServerAsync(options =>
{
options.ResourceMetadataUri = new Uri(metadataPath, UriKind.Relative);
options.ResourceMetadata!.Resource = "http://localhost:5000/challenge";
});
using var challengeResponse = await HttpClient.GetAsync(new Uri("/challenge", UriKind.Relative), HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, challengeResponse.StatusCode);
var header = Assert.Single(challengeResponse.Headers.WwwAuthenticate);
Assert.Equal("Bearer", header.Scheme);
Assert.Contains($"resource_metadata=\"http://localhost:5000{metadataPath}\"", header.Parameter);
using var metadataResponse = await HttpClient.GetAsync(new Uri(metadataPath, UriKind.Relative), TestContext.Current.CancellationToken);
metadataResponse.EnsureSuccessStatusCode();
}
[Fact]
public async Task MetadataRequest_CustomResourceMetadataUriWithoutResource_ThrowsInvalidOperationException()
{
const string metadataPath = "/.well-known/custom-metadata";
await using var app = await StartAuthenticationServerAsync(options =>
{
options.ResourceMetadataUri = new Uri(metadataPath, UriKind.Relative);
});
using var response = await HttpClient.GetAsync(new Uri(metadataPath, UriKind.Relative), TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Contains(MockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Error &&
log.Exception is InvalidOperationException &&
log.Exception.Message.Contains("ResourceMetadata.Resource could not be determined", StringComparison.Ordinal));
}
[Fact]
public async Task Challenge_WithAbsoluteResourceMetadataUri_SetsConfiguredUrl()
{
var metadataUri = new Uri("http://localhost:5000/.well-known/custom-absolute");
await using var app = await StartAuthenticationServerAsync(options =>
{
options.ResourceMetadataUri = metadataUri;
options.ResourceMetadata!.Resource = "http://localhost:5000/challenge";
});
using var challengeResponse = await HttpClient.GetAsync(new Uri("/challenge", UriKind.Relative), HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, challengeResponse.StatusCode);
var header = Assert.Single(challengeResponse.Headers.WwwAuthenticate);
Assert.Equal("Bearer", header.Scheme);
Assert.Contains($"resource_metadata=\"{metadataUri}\"", header.Parameter);
using var metadataResponse = await HttpClient.GetAsync(metadataUri, TestContext.Current.CancellationToken);
metadataResponse.EnsureSuccessStatusCode();
}
[Fact]
public async Task MetadataRequest_WithHostMismatch_LogsWarning()
{
var metadataUri = new Uri("http://expected-host:5000/.well-known/host-mismatch");
await using var app = await StartAuthenticationServerAsync(options =>
{
options.ResourceMetadataUri = metadataUri;
});
using var metadataRequest = new HttpRequestMessage(HttpMethod.Get, new Uri("http://localhost:5000/.well-known/host-mismatch"));
using var metadataResponse = await HttpClient.SendAsync(metadataRequest, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, metadataResponse.StatusCode);
Assert.Contains(MockLoggerProvider.LogMessages, log =>
log.LogLevel == LogLevel.Warning &&
log.Message.Contains("Resource metadata request host", StringComparison.OrdinalIgnoreCase) &&
log.Message.Contains("expected-host", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public async Task Challenge_WithDefaultMetadata_ComposesResourceSpecificEndpoint()
{
await using var app = await StartAuthenticationServerAsync();
using var challengeResponse = await HttpClient.GetAsync(new Uri("/resource/tools/list", UriKind.Relative), HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, challengeResponse.StatusCode);
var header = Assert.Single(challengeResponse.Headers.WwwAuthenticate);
Assert.Equal("Bearer", header.Scheme);
Assert.Contains("resource_metadata=\"http://localhost:5000/.well-known/oauth-protected-resource/resource/tools/list\"", header.Parameter);
}
[Fact]
public async Task Challenge_WithDefaultMetadata_AndPathBase_ComposesResourceSpecificEndpoint()
{
await using var app = await StartAuthenticationServerAsync(pathBase: new PathString("/api"));
using var challengeResponse = await HttpClient.GetAsync(new Uri("/api/resource/tools/list", UriKind.Relative), HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Unauthorized, challengeResponse.StatusCode);
var header = Assert.Single(challengeResponse.Headers.WwwAuthenticate);
Assert.Equal("Bearer", header.Scheme);
Assert.Contains("resource_metadata=\"http://localhost:5000/api/.well-known/oauth-protected-resource/resource/tools/list\"", header.Parameter);
}
[Fact]
public async Task MetadataRequest_DefaultEndpoint_SetsResourceFromSuffix()
{
await using var app = await StartAuthenticationServerAsync();
using var metadataResponse = await HttpClient.GetAsync(new Uri("/.well-known/oauth-protected-resource/resource/tools", UriKind.Relative), TestContext.Current.CancellationToken);
metadataResponse.EnsureSuccessStatusCode();
var metadata = await metadataResponse.Content.ReadFromJsonAsync<ProtectedResourceMetadata>(
McpJsonUtilities.DefaultOptions,
TestContext.Current.CancellationToken);
Assert.NotNull(metadata);
Assert.Equal("http://localhost:5000/resource/tools", metadata!.Resource);
}
[Fact]
public async Task MetadataRequest_DefaultEndpoint_WithPathBase_SetsResourceFromSuffix()
{
await using var app = await StartAuthenticationServerAsync(pathBase: new PathString("/api"));
using var metadataResponse = await HttpClient.GetAsync(new Uri("/api/.well-known/oauth-protected-resource/resource/tools", UriKind.Relative), TestContext.Current.CancellationToken);
metadataResponse.EnsureSuccessStatusCode();
var metadata = await metadataResponse.Content.ReadFromJsonAsync<ProtectedResourceMetadata>(
McpJsonUtilities.DefaultOptions,
TestContext.Current.CancellationToken);
Assert.NotNull(metadata);
Assert.Equal("http://localhost:5000/api/resource/tools", metadata!.Resource);
}
private async Task<WebApplication> StartAuthenticationServerAsync(Action<McpAuthenticationOptions>? configureOptions = null, PathString? pathBase = null)
{
var authenticationBuilder = Builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = McpAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = McpAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
});
authenticationBuilder.AddScheme<McpAuthenticationOptions, McpAuthenticationHandler>(McpAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ResourceMetadata = new()
{
AuthorizationServers = ["https://localhost:7029"],
ScopesSupported = ["mcp:tools"],
};
configureOptions?.Invoke(options);
});
authenticationBuilder.AddScheme<AuthenticationSchemeOptions, NoopBearerAuthenticationHandler>("Bearer", options => { });
Builder.Services.AddAuthorization();
var app = Builder.Build();
if (pathBase is PathString basePath && basePath.HasValue)
{
app.UsePathBase(basePath);
}
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/challenge", context => context.ChallengeAsync(McpAuthenticationDefaults.AuthenticationScheme));
app.MapGet("/resource/{*resourcePath}", context => context.ChallengeAsync(McpAuthenticationDefaults.AuthenticationScheme));
await app.StartAsync(TestContext.Current.CancellationToken);
return app;
}
private sealed class NoopBearerAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(AuthenticateResult.NoResult());
}
}