From 971659379dddc9c4c99f4ed596a26372d605f99f Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:45:07 +0000 Subject: [PATCH] Check the Origin header on the MCP endpoint --- .agents/skills/security-defaults/SKILL.md | 14 ++- docs/RUN.md | 4 + .../Extensions/WebApplicationExtensions.cs | 3 + src/Presentation/Security/OriginCheck.cs | 64 +++++++++++++ src/Presentation/appsettings.json | 3 + .../Security/OriginCheckTests.cs | 92 +++++++++++++++++++ .../Security/OriginCheckTests.cs | 41 +++++++++ 7 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 src/Presentation/Security/OriginCheck.cs create mode 100644 tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs create mode 100644 tests/Presentation.Tests.Unit/Security/OriginCheckTests.cs diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md index b3a4e2a..6d88898 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -1,6 +1,6 @@ --- name: security-defaults -description: What this MCP server does to be safe by default - the security response headers, and where the other protections live. Use when adding a response header, changing security middleware, or asked whether the app is safe to deploy. +description: What this MCP server does to be safe by default - the security response headers, the Origin check on /mcp, and where the other protections live. Use when adding a response header, letting a browser client in with Mcp:AllowedOrigins, changing security middleware, or asked whether the app is safe to deploy. metadata: scope: presentation --- @@ -14,6 +14,7 @@ The app ships safe by default, and each protection lives in one place in `src/Pr | Protection | Where | Default | | --- | --- | --- | | Security response headers | `SecurityHeaders` | Always on | +| `Origin` check on `/mcp` | `OriginCheck` | No `Origin` or localhost only, plus `Mcp:AllowedOrigins` | | HSTS and HTTPS redirection | Security region | HSTS outside local runs | | Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | @@ -29,6 +30,17 @@ The app ships safe by default, and each protection lives in one place in `src/Pr There's no `Content-Security-Policy` on purpose. The headers are set in `Response.OnStarting`, because the exception handler clears headers set before it runs. +## Origin check + +The MCP spec says a Streamable HTTP server must check the `Origin` header, so a web page can't reach a server on the developer's machine by DNS rebinding. `UseOriginCheck` guards `/mcp` and nothing else: + +- No `Origin` header: allowed. Desktop clients and server-side clients don't send one. +- `http` or `https` on `localhost`, `127.0.0.1` or `[::1]`, any port: allowed. That covers the MCP Inspector and the chat demo. +- An origin listed in `Mcp:AllowedOrigins`, matched exactly: allowed. +- Anything else, including `null`: 403 before authentication runs. + +To let a browser-based client on another host in, add its origin to `Mcp:AllowedOrigins` in settings. Don't widen `IsAllowed` itself, and don't set `AllowedHosts` to work around it. Unit tests for `IsAllowed` live in `tests/Presentation.Tests.Unit/Security/`, and `tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs` sends real requests. + ## Steps 1. Add a header in `SecurityHeaders`, not in an endpoint or a filter, so every response gets it. diff --git a/docs/RUN.md b/docs/RUN.md index 556ff37..e5159fe 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -90,6 +90,10 @@ Every span, metric and log carries `service.version`, so you can always tell whi The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . Outside the `local` and `Development` environments it also sends an HSTS header. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS. +## Browser origins + +Browsers send an `Origin` header, and the MCP spec asks servers to check it so a web page can't reach a local server by DNS rebinding. Requests to `/mcp` with no `Origin`, as desktop clients send them, or from `localhost` on any port go through. Anything else gets a 403. To let a browser-based client on another host call the server, add its origin to `Mcp:AllowedOrigins`, for example `Mcp__AllowedOrigins__0=https://chat.example.com`. + ## Tests ``` bash diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 33f78ea..8e7d35e 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -27,6 +27,9 @@ public static WebApplication ConfigureApplication(this WebApplication app) _ = app.UseSecurityHeaders(); + // Browsers send an Origin; the MCP spec asks servers to refuse ones they don't expect. + _ = app.UseOriginCheck("/mcp", app.Configuration); + // HSTS tells browsers to only use HTTPS from then on, so it's left off for local runs. if (!app.Environment.IsDevelopment() && !app.Environment.IsEnvironment("local")) { diff --git a/src/Presentation/Security/OriginCheck.cs b/src/Presentation/Security/OriginCheck.cs new file mode 100644 index 0000000..c20bd20 --- /dev/null +++ b/src/Presentation/Security/OriginCheck.cs @@ -0,0 +1,64 @@ +namespace CleanModelContextProtocol.Presentation.Security; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; + +/// +/// Checks the Origin header on requests to the MCP endpoint, as the MCP spec asks servers to, so a web page can't +/// reach the server through DNS rebinding. A request without an Origin, such as one from a desktop client, is let +/// through. A browser request must come from localhost or from an origin in Mcp:AllowedOrigins, or it gets a 403. +/// +public static class OriginCheck +{ + public const string SectionName = "Mcp:AllowedOrigins"; + + private static readonly string[] LoopbackHosts = ["localhost", "127.0.0.1", "[::1]"]; + + /// + /// Whether a request with this Origin may reach the MCP endpoint. + /// + /// The request's Origin header, or null when it has none. + /// The extra origins allowed, such as https://chat.example.com. + /// True when there's no origin, it's on localhost on any port, or it's one of the allowed origins. + public static bool IsAllowed(string? origin, IReadOnlyCollection allowedOrigins) + { + if (string.IsNullOrEmpty(origin)) + { + return true; + } + + if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + return false; + } + + return LoopbackHosts.Contains(uri.Host, StringComparer.OrdinalIgnoreCase) + || allowedOrigins.Any(allowed => string.Equals(allowed.TrimEnd('/'), origin.TrimEnd('/'), StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Refuses requests under whose Origin isn't allowed. + /// + /// The application to add the check to. + /// The path to guard, such as /mcp. + /// The settings to read Mcp:AllowedOrigins from. + /// The application, for chaining. + public static IApplicationBuilder UseOriginCheck(this IApplicationBuilder app, PathString path, IConfiguration configuration) + { + var allowedOrigins = configuration.GetSection(SectionName).Get() ?? []; + + return app.UseWhen( + context => context.Request.Path.StartsWithSegments(path), + branch => branch.Use(async (context, next) => + { + if (!IsAllowed(context.Request.Headers.Origin, allowedOrigins)) + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + await next(context); + })); + } +} diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index 0d22c1e..9be2434 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -31,6 +31,9 @@ }, //#endif "AllowedHosts": "*", + "Mcp": { + "AllowedOrigins": [] + }, "Database": { "SeedSampleData": false } diff --git a/tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs b/tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs new file mode 100644 index 0000000..3a8efb6 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs @@ -0,0 +1,92 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Security; + +using System.Net; +using System.Text; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class OriginCheckTests : IDisposable +{ + private readonly ModelContextProtocolApplication application = new(settings: new Dictionary + { + ["Mcp:AllowedOrigins:0"] = "https://chat.example.com" + }); + + [Theory] + [InlineData("https://evil.example.com")] + [InlineData("null")] + public async Task Mcp_WithUnknownOrigin_ShouldReturn_Forbidden(string origin) + { + // Arrange + using var client = this.application.CreateClient(); + using var request = CreateRequest(origin); + + // Act + using var response = await client.SendAsync(request); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + } + + [Theory] + [InlineData(null)] + [InlineData("http://localhost:7325")] + [InlineData("https://chat.example.com")] + public async Task Mcp_WithNoLocalOrAllowedOrigin_ShouldNotReturn_Forbidden(string? origin) + { + // Arrange + using var client = this.application.CreateClient(); + using var request = CreateRequest(origin); + + // Act + using var response = await client.SendAsync(request); + + // Assert + response.StatusCode.ShouldNotBe(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task Health_WithUnknownOrigin_ShouldReturn_Healthy() + { + // Arrange + using var client = this.application.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://localhost/health/live")); + request.Headers.Add("Origin", "https://evil.example.com"); + + // Act + using var response = await client.SendAsync(request); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } + + private static HttpRequestMessage CreateRequest(string? origin) + { + var request = new HttpRequestMessage(HttpMethod.Post, new Uri("http://localhost/mcp")) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + + if (origin is not null) + { + request.Headers.Add("Origin", origin); + } + + return request; + } +} diff --git a/tests/Presentation.Tests.Unit/Security/OriginCheckTests.cs b/tests/Presentation.Tests.Unit/Security/OriginCheckTests.cs new file mode 100644 index 0000000..7d424b2 --- /dev/null +++ b/tests/Presentation.Tests.Unit/Security/OriginCheckTests.cs @@ -0,0 +1,41 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Unit.Security; + +using Presentation.Security; +using Shouldly; +using Xunit; + +public class OriginCheckTests +{ + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("http://localhost:7325")] + [InlineData("https://localhost")] + [InlineData("http://127.0.0.1:6274")] + [InlineData("http://[::1]:7320")] + [InlineData("https://chat.example.com")] + [InlineData("https://chat.example.com/")] + public void IsAllowed_ShouldReturn_True_WhenOriginIsMissingLocalOrAllowed(string? origin) + { + // Act + var result = OriginCheck.IsAllowed(origin, ["https://chat.example.com"]); + + // Assert + result.ShouldBeTrue(); + } + + [Theory] + [InlineData("https://evil.example.com")] + [InlineData("http://chat.example.com")] + [InlineData("https://localhost.evil.example.com")] + [InlineData("null")] + [InlineData("file://localhost")] + public void IsAllowed_ShouldReturn_False_WhenOriginIsNotAllowed(string origin) + { + // Act + var result = OriginCheck.IsAllowed(origin, ["https://chat.example.com"]); + + // Assert + result.ShouldBeFalse(); + } +}