-
Notifications
You must be signed in to change notification settings - Fork 697
Add support for v0.1.11 client conformance tests #1178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3962a0b
Add test to make sure all client conformance tests are covered
mikekistler 84b7fb8
Fix client conformance test elicitation-sep1034-client-defaults
mikekistler 595942d
Disable auth/resource-mismatch pending fix in conformance suite
mikekistler 008d07c
Update to 0.1.11 conformance tests
stephentoub 9deb100
Update CI conformance tests from 0.1.10 to 0.1.11
stephentoub a4b9f02
Merge branch 'main' into copilot/add-support-v0111-tests
stephentoub 919ff3e
Address PR feedback: improve auth failure tracking, update DNS rebind…
Copilot f8d07f3
Delete UseMcpDnsRebindingProtection API entirely
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
src/ModelContextProtocol.AspNetCore/DnsRebindingProtectionMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Net.Http.Headers; | ||
| using System.Net; | ||
| using System.Text.Json; | ||
|
|
||
| namespace ModelContextProtocol.AspNetCore; | ||
|
|
||
| /// <summary> | ||
| /// Middleware that provides DNS rebinding protection for MCP servers by validating | ||
| /// Host and Origin headers on requests to localhost servers. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// DNS rebinding attacks can allow malicious websites to bypass browser same-origin policy | ||
| /// and make requests to localhost services. This middleware helps protect against such attacks | ||
| /// by validating that Host and Origin headers match expected localhost values. | ||
| /// </para> | ||
| /// <para> | ||
| /// Use <see cref="McpApplicationBuilderExtensions.UseMcpDnsRebindingProtection"/> to enable this middleware. | ||
| /// </para> | ||
| /// </remarks> | ||
| /// <remarks> | ||
| /// Initializes a new instance of the <see cref="DnsRebindingProtectionMiddleware"/> class. | ||
| /// </remarks> | ||
| internal sealed partial class DnsRebindingProtectionMiddleware( | ||
|
stephentoub marked this conversation as resolved.
Outdated
|
||
| RequestDelegate next, | ||
| ILogger<DnsRebindingProtectionMiddleware> logger) | ||
| { | ||
| private readonly RequestDelegate _next = next; | ||
| private readonly ILogger<DnsRebindingProtectionMiddleware> _logger = logger; | ||
|
|
||
| /// <summary> | ||
| /// Processes the HTTP request and validates Host and Origin headers for localhost servers. | ||
| /// </summary> | ||
| public async Task InvokeAsync(HttpContext context) | ||
| { | ||
| // Only apply protection to localhost servers | ||
| var localEndpoint = context.Connection.LocalIpAddress; | ||
| bool isLocalhostServer = localEndpoint is null || | ||
| IPAddress.IsLoopback(localEndpoint) || | ||
| localEndpoint.Equals(IPAddress.IPv6Loopback); | ||
|
|
||
| if (isLocalhostServer) | ||
| { | ||
| // Validate Host header | ||
| var host = context.Request.Host.Host; | ||
| if (!IsLocalhost(host)) | ||
| { | ||
| LogInvalidHostHeader(host); | ||
| await WriteJsonRpcErrorResponseAsync(context, $"Forbidden: Invalid Host header '{host}' for localhost server"); | ||
| return; | ||
| } | ||
|
|
||
| // Validate Origin header if present | ||
| if (context.Request.Headers.TryGetValue(HeaderNames.Origin, out var originValues) && | ||
| originValues.FirstOrDefault() is string origin && | ||
| Uri.TryCreate(origin, UriKind.Absolute, out var originUri) && | ||
| !IsLocalhost(originUri.Host)) | ||
| { | ||
| LogInvalidOriginHeader(origin); | ||
| await WriteJsonRpcErrorResponseAsync(context, $"Forbidden: Invalid Origin header '{origin}' for localhost server"); | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| await _next(context).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static bool IsLocalhost(string host) | ||
| { | ||
| if (!string.IsNullOrWhiteSpace(host)) | ||
| { | ||
| if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || | ||
| host.Equals("[::1]") || | ||
| host.Equals("127.0.0.1")) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (IPAddress.TryParse(host, out var ip)) | ||
| { | ||
| return IPAddress.IsLoopback(ip); | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static Task WriteJsonRpcErrorResponseAsync(HttpContext context, string message) | ||
| { | ||
| context.Response.StatusCode = StatusCodes.Status403Forbidden; | ||
| context.Response.ContentType = "application/json"; | ||
| return context.Response.WriteAsync($$""" | ||
| { | ||
| "jsonrpc": "2.0", | ||
| "error": | ||
| { | ||
| "code": -32000, | ||
| "message": "{{JsonEncodedText.Encode(message)}}" | ||
| }, | ||
| "id": null | ||
| } | ||
| """); | ||
| } | ||
|
|
||
| [LoggerMessage(Level = LogLevel.Warning, Message = "Rejected request with invalid Host header '{Host}' for localhost server. This may indicate a DNS rebinding attack.")] | ||
| private partial void LogInvalidHostHeader(string? host); | ||
|
|
||
| [LoggerMessage(Level = LogLevel.Warning, Message = "Rejected request with invalid Origin header '{Origin}' for localhost server. This may indicate a DNS rebinding attack.")] | ||
| private partial void LogInvalidOriginHeader(string origin); | ||
| } | ||
47 changes: 47 additions & 0 deletions
47
src/ModelContextProtocol.AspNetCore/McpApplicationBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| using ModelContextProtocol.AspNetCore; | ||
|
|
||
| namespace Microsoft.AspNetCore.Builder; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for adding MCP middleware to an <see cref="IApplicationBuilder"/>. | ||
| /// </summary> | ||
| public static class McpApplicationBuilderExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds DNS rebinding protection middleware for MCP servers running on localhost. | ||
| /// </summary> | ||
| /// <param name="app">The <see cref="IApplicationBuilder"/>.</param> | ||
| /// <returns>The <see cref="IApplicationBuilder"/> for chaining.</returns> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// This method provides protection against DNS rebinding attacks by validating that both | ||
| /// Host and Origin headers (when present) resolve to localhost addresses. | ||
| /// </para> | ||
| /// <para> | ||
| /// DNS rebinding attacks can allow malicious websites to bypass browser same-origin policy and make requests | ||
| /// to localhost services. This protection is recommended for any MCP server that binds to localhost. | ||
| /// </para> | ||
| /// <para> | ||
| /// For more information, see the <see href="https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-w48q-cv73-mx4w">MCP SDK security advisory</see>. | ||
| /// </para> | ||
| /// </remarks> | ||
| /// <example> | ||
| /// <code> | ||
| /// var builder = WebApplication.CreateBuilder(args); | ||
| /// builder.Services.AddMcpServer().WithHttpTransport(); | ||
| /// | ||
| /// var app = builder.Build(); | ||
| /// app.UseMcpDnsRebindingProtection(); // Add before MapMcp() | ||
| /// app.MapMcp(); | ||
| /// app.Run(); | ||
| /// </code> | ||
| /// </example> | ||
| public static IApplicationBuilder UseMcpDnsRebindingProtection(this IApplicationBuilder app) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(app); | ||
|
|
||
| app.UseMiddleware<DnsRebindingProtectionMiddleware>(); | ||
|
|
||
| return app; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should go back to testing against the latest version? I know it will be annoying when it causes random PRs to fail, but we'll definitely notice that way. And the
InvalidOperationExceptionwe'd get fromGetConformanceVersion()when they do fall out of sync should be pretty clear.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok by me.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot Also update the message in the
InvalidOperationExceptionthrown byGetConformanceVersion()to tell the developer to start pinning the version in ci-build-test.yml and file an issue to update the conformance tests if they run into it.