Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .agents/skills/security-defaults/SKILL.md
Original file line number Diff line number Diff line change
@@ -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
---
Expand All @@ -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 |

Expand All @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions docs/RUN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <http://localhost:7320> on to <https://localhost:7321>. 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
Expand Down
3 changes: 3 additions & 0 deletions src/Presentation/Extensions/WebApplicationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
{
Expand Down
64 changes: 64 additions & 0 deletions src/Presentation/Security/OriginCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
namespace CleanModelContextProtocol.Presentation.Security;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

/// <summary>
/// Checks the <c>Origin</c> 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 <c>Origin</c>, such as one from a desktop client, is let
/// through. A browser request must come from localhost or from an origin in <c>Mcp:AllowedOrigins</c>, or it gets a 403.
/// </summary>
public static class OriginCheck
{
public const string SectionName = "Mcp:AllowedOrigins";

private static readonly string[] LoopbackHosts = ["localhost", "127.0.0.1", "[::1]"];

/// <summary>
/// Whether a request with this <c>Origin</c> may reach the MCP endpoint.
/// </summary>
/// <param name="origin">The request's <c>Origin</c> header, or null when it has none.</param>
/// <param name="allowedOrigins">The extra origins allowed, such as <c>https://chat.example.com</c>.</param>
/// <returns>True when there's no origin, it's on localhost on any port, or it's one of the allowed origins.</returns>
public static bool IsAllowed(string? origin, IReadOnlyCollection<string> 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));
}

/// <summary>
/// Refuses requests under <paramref name="path"/> whose <c>Origin</c> isn't allowed.
/// </summary>
/// <param name="app">The application to add the check to.</param>
/// <param name="path">The path to guard, such as <c>/mcp</c>.</param>
/// <param name="configuration">The settings to read <c>Mcp:AllowedOrigins</c> from.</param>
/// <returns>The application, for chaining.</returns>
public static IApplicationBuilder UseOriginCheck(this IApplicationBuilder app, PathString path, IConfiguration configuration)
{
var allowedOrigins = configuration.GetSection(SectionName).Get<string[]>() ?? [];

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);
}));
}
}
3 changes: 3 additions & 0 deletions src/Presentation/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
},
//#endif
"AllowedHosts": "*",
"Mcp": {
"AllowedOrigins": []
},
"Database": {
"SeedSampleData": false
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, string?>
{
["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;
}
}
41 changes: 41 additions & 0 deletions tests/Presentation.Tests.Unit/Security/OriginCheckTests.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
Loading