From ae45ac91f50ebab65227ea6c4d4861e5f4a665b6 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:33:28 +0000 Subject: [PATCH 01/12] Bind every Compose port to 127.0.0.1 --- .agents/skills/docker-and-compose/SKILL.md | 2 +- docker-compose.yml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.agents/skills/docker-and-compose/SKILL.md b/.agents/skills/docker-and-compose/SKILL.md index 9bcda42..bb3e225 100644 --- a/.agents/skills/docker-and-compose/SKILL.md +++ b/.agents/skills/docker-and-compose/SKILL.md @@ -19,7 +19,7 @@ One multi-stage `Dockerfile` does everything the pipeline needs: | `publish` | Publishes the Presentation project | | `run` | The runtime image: non-root `$APP_UID`, `WORKDIR /app`, data in `/app/data`, a `HEALTHCHECK` on `/health/live` | -`docker-compose.yml` runs the app with `DOTNET_ENVIRONMENT=docker`, the `movie-reviews-data` volume a pinned OpenTelemetry Collector that receives the app's OTLP logs, traces and metrics, configured by `otel-collector.yaml`, and a pinned Aspire dashboard the collector forwards them to (`telemetry`). The dashboard UI and the collector's OTLP ports are published on the template's own ports (below), so a `dotnet run` can send to the collector too. The dashboard runs with `ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS` and the collector's OTLP ports take anything sent to them, on purpose: the compose file is for a developer's machine, with nothing to sign in to. Keep it that way rather than adding sign-in, and don't offer the compose file for a shared or deployed environment. Images are built by CI but not pushed anywhere; the template ships the Dockerfile so users can. +`docker-compose.yml` runs the app with `DOTNET_ENVIRONMENT=docker`, the `movie-reviews-data` volume a pinned OpenTelemetry Collector that receives the app's OTLP logs, traces and metrics, configured by `otel-collector.yaml`, and a pinned Aspire dashboard the collector forwards them to (`telemetry`). The dashboard UI and the collector's OTLP ports are published on the template's own ports (below), so a `dotnet run` can send to the collector too. The dashboard runs with `ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS` and the collector's OTLP ports take anything sent to them, on purpose: the compose file is for a developer's machine, with nothing to sign in to. That's why every published port binds to `127.0.0.1`, as in `"127.0.0.1::18888"`, so nobody else on the same network can reach the app, the dashboard or the collector. Keep it that way rather than adding sign-in, and don't offer the compose file for a shared or deployed environment. Images are built by CI but not pushed anywhere; the template ships the Dockerfile so users can. The Lambda template's `run` stage is the AWS Lambda .NET base image instead. It runs as user `65534` from `/var/task`, keeps its database in `/tmp`, and has no `HEALTHCHECK`. Its compose file runs the collector and the Aspire dashboard as well. Compose maps the runtime interface emulator to 7350, so the function can be invoked with a `POST` to `/2015-03-31/functions/function/invocations`. diff --git a/docker-compose.yml b/docker-compose.yml index 36063bc..b5bfbc7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: VERSION_PREFIX: 1.0.0.0 VERSION_SUFFIX: docker ports: - - "7320:7320" + - "127.0.0.1:7320:7320" environment: DOTNET_ENVIRONMENT: docker OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317 @@ -35,8 +35,8 @@ services: volumes: - ./otel-collector.yaml:/etc/otelcol/config.yaml:ro ports: - - "7323:4317" - - "7324:4318" + - "127.0.0.1:7323:4317" + - "127.0.0.1:7324:4318" networks: - cleanmodelcontextprotocol_network depends_on: @@ -44,7 +44,7 @@ services: aspire-dashboard: image: mcr.microsoft.com/dotnet/aspire-dashboard:13.6.5 ports: - - "7322:18888" + - "127.0.0.1:7322:18888" environment: ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS: "true" networks: From 36b4937d7a7f91831a0756cc4c003e96f116df0c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:38:29 +0000 Subject: [PATCH 02/12] Read the telemetry service.version from VersionInfo --- .agents/skills/telemetry/SKILL.md | 2 +- .../WebApplicationBuilderExtensions.cs | 12 ++++++------ .../Telemetry/TelemetrySettings.cs | 8 ++++---- .../Telemetry/TelemetrySettingsTests.cs | 19 +++++++++---------- 4 files changed, 20 insertions(+), 21 deletions(-) diff --git a/.agents/skills/telemetry/SKILL.md b/.agents/skills/telemetry/SKILL.md index 1c7e7ae..7e25043 100644 --- a/.agents/skills/telemetry/SKILL.md +++ b/.agents/skills/telemetry/SKILL.md @@ -25,7 +25,7 @@ Each layer publishes under its own name, and only the presentation layer's start | --- | --- | --- | | Application | `ApplicationTelemetry.Name` activity source: a span per use case, named after the request, tagged with `application.request.name` and `application.request.outcome` | `LoggingBehaviour`, with `System.Diagnostics` only, so Application stays free of telemetry packages | | Infrastructure | `Microsoft.EntityFrameworkCore` meter: queries, saves, active contexts, compiled query cache | Built into EF Core; startup subscribes to it by name | -| Presentation | `service.name`, `service.version` and `deployment.environment.name` on everything, plus its own instrumentation | `TelemetrySettings` and the startup's Telemetry region | +| Presentation | `service.name`, `service.version` and `deployment.environment.name` on everything, plus its own instrumentation | `TelemetrySettings`, which takes `service.version` from `VersionInfo`, and the startup's Telemetry region | What each presentation layer adds: diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index c388f27..28f86d9 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -1,7 +1,6 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using Application; using Application.Common.Telemetry; using Application.Versions.Entities; @@ -38,7 +37,8 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #region Telemetry var assembly = typeof(WebApplicationBuilderExtensions).Assembly; - var telemetry = TelemetrySettings.FromConfiguration(builder.Configuration, builder.Environment.EnvironmentName, assembly); + var version = VersionInfo.FromAssembly(assembly); + var telemetry = TelemetrySettings.FromConfiguration(builder.Configuration, builder.Environment.EnvironmentName, version); var openTelemetry = builder.Services.AddOpenTelemetry() .ConfigureResource(resource => resource.AddAttributes(telemetry.ResourceAttributes)) @@ -83,10 +83,10 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat _ = loggerConfiguration.ReadFrom.Configuration(configuration) .Enrich.WithProperty( "AssemblyVersion", - assembly.GetCustomAttribute()?.Version) + version.FileVersion) .Enrich.WithProperty( "AssemblyInformationalVersion", - assembly.GetCustomAttribute()?.InformationalVersion); + version.InformationalVersion); // Logs leave over OTLP too, carrying the trace and span IDs of whatever was running when they were written. if (telemetry.Enabled) @@ -108,7 +108,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews")); _ = builder.Services.AddApplication(); - _ = builder.Services.AddSingleton(VersionInfo.FromAssembly(typeof(WebApplicationBuilderExtensions).Assembly)); + _ = builder.Services.AddSingleton(version); _ = builder.Services.AddHealthChecks().AddInfrastructureHealthChecks("ready"); #endregion Project Dependencies @@ -161,7 +161,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat Name = "clean-model-context-protocol", Title = "Clean Model Context Protocol", Description = "Movies, the authors who review them, and their star ratings, served by a Clean Architecture .NET MCP server.", - Version = assembly.GetCustomAttribute()?.InformationalVersion ?? string.Empty, + Version = version.InformationalVersion, // The docs site and a pinned brand release, not this repository: dotnet new renames the // template's name wherever it appears, so repository links break in a new solution. WebsiteUrl = "https://leanmeanclean.dev/mcp/", diff --git a/src/Presentation/Telemetry/TelemetrySettings.cs b/src/Presentation/Telemetry/TelemetrySettings.cs index f72f91c..1d84a01 100644 --- a/src/Presentation/Telemetry/TelemetrySettings.cs +++ b/src/Presentation/Telemetry/TelemetrySettings.cs @@ -1,6 +1,6 @@ namespace CleanModelContextProtocol.Presentation.Telemetry; -using System.Reflection; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; /// @@ -16,7 +16,7 @@ public class TelemetrySettings /// The service.name on everything this app sends. public required string ServiceName { get; init; } - /// The service.version: the informational version of the presentation assembly. + /// The service.version: the informational version from , the same one the version endpoint returns. public required string ServiceVersion { get; init; } /// The deployment.environment.name, such as local or docker. @@ -35,14 +35,14 @@ public class TelemetrySettings ["deployment.environment.name"] = this.EnvironmentName }; - public static TelemetrySettings FromConfiguration(IConfiguration configuration, string environmentName, Assembly assembly) + public static TelemetrySettings FromConfiguration(IConfiguration configuration, string environmentName, VersionInfo version) { var serviceName = configuration["OTEL_SERVICE_NAME"]; return new TelemetrySettings { ServiceName = string.IsNullOrWhiteSpace(serviceName) ? DefaultServiceName : serviceName, - ServiceVersion = assembly.GetCustomAttribute()?.InformationalVersion ?? "unknown", + ServiceVersion = string.IsNullOrWhiteSpace(version.InformationalVersion) ? "unknown" : version.InformationalVersion, EnvironmentName = environmentName, OtlpEndpoint = configuration["OTEL_EXPORTER_OTLP_ENDPOINT"] }; diff --git a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs index dd82466..8bd80d6 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -1,7 +1,6 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Telemetry; -using System.Reflection; -using System.Reflection.Emit; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; using Presentation.Telemetry; using Shouldly; @@ -14,15 +13,15 @@ public void FromConfiguration_ShouldReturn_DisabledDefaults_WhenNothingIsSet() { // Arrange var configuration = new ConfigurationBuilder().Build(); - var assembly = typeof(TelemetrySettingsTests).Assembly; + var version = new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3+e30eba8" }; // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "local", version); // Assert result.Enabled.ShouldBeFalse(); result.ServiceName.ShouldBe(TelemetrySettings.DefaultServiceName); - result.ServiceVersion.ShouldBe(assembly.GetCustomAttribute()!.InformationalVersion); + result.ServiceVersion.ShouldBe("1.2.3+e30eba8"); result.EnvironmentName.ShouldBe("local"); } @@ -39,25 +38,25 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenEndpointIsSet() .Build(); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "docker", typeof(TelemetrySettingsTests).Assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "docker", new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3" }); // Assert result.Enabled.ShouldBeTrue(); result.OtlpEndpoint.ShouldBe("http://aspire-dashboard:18889"); result.ResourceAttributes["service.name"].ShouldBe("movie-reviews"); - result.ResourceAttributes["service.version"].ShouldBe(result.ServiceVersion); + result.ResourceAttributes["service.version"].ShouldBe("1.2.3"); result.ResourceAttributes["deployment.environment.name"].ShouldBe("docker"); } [Fact] - public void FromConfiguration_ShouldReturn_UnknownVersion_WhenAssemblyHasNone() + public void FromConfiguration_ShouldReturn_UnknownVersion_WhenVersionIsEmpty() { // Arrange var configuration = new ConfigurationBuilder().Build(); - var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("NoVersion"), AssemblyBuilderAccess.Run); + var version = VersionInfo.FromAssembly(null); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "local", version); // Assert result.ServiceVersion.ShouldBe("unknown"); From 81b8e980dc18dc8e6f1d43a2a27f3d642f0a972d Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:43:18 +0000 Subject: [PATCH 03/12] Send security headers on every response --- .agents/skills/security-defaults/SKILL.md | 41 +++++++++++++++++++ AGENTS.md | 1 + .../Extensions/WebApplicationExtensions.cs | 3 ++ src/Presentation/Security/SecurityHeaders.cs | 34 +++++++++++++++ .../Security/SecurityHeadersTests.cs | 41 +++++++++++++++++++ 5 files changed, 120 insertions(+) create mode 100644 .agents/skills/security-defaults/SKILL.md create mode 100644 src/Presentation/Security/SecurityHeaders.cs create mode 100644 tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md new file mode 100644 index 0000000..b3a4e2a --- /dev/null +++ b/.agents/skills/security-defaults/SKILL.md @@ -0,0 +1,41 @@ +--- +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. +metadata: + scope: presentation +--- + +# Security defaults (MCP server) + +## The rule + +The app ships safe by default, and each protection lives in one place in `src/Presentation/Security/`, switched on in the Security region of `WebApplicationExtensions.ConfigureApplication`. Keep that shape: a new protection gets its own small class there and a line in that region, never a check scattered across endpoints. + +| Protection | Where | Default | +| --- | --- | --- | +| Security response headers | `SecurityHeaders` | Always on | +| HSTS and HTTPS redirection | Security region | HSTS outside local runs | +| Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | + +## Security headers + +`UseSecurityHeaders` adds three headers to every response, errors and health checks included: + +| Header | Value | Why | +| --- | --- | --- | +| `X-Content-Type-Options` | `nosniff` | Browsers use the declared content type instead of guessing | +| `X-Frame-Options` | `DENY` | No other site can show the app in a frame | +| `Referrer-Policy` | `no-referrer` | Links out of the app don't leak its URLs | + +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. + +## Steps + +1. Add a header in `SecurityHeaders`, not in an endpoint or a filter, so every response gets it. +2. Add it to the theory in `tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs`, which checks a healthy response and a 404. +3. Check it by hand: `curl -sI http://localhost:7320/health/live`. + +## Check + +- [ ] The header is set in `SecurityHeaders` and tested for a success and an error response. +- [ ] No `Content-Security-Policy` unless the browser tools have been checked with it. diff --git a/AGENTS.md b/AGENTS.md index 4900190..807ca07 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,6 +130,7 @@ These are for this MCP server's presentation layer. The other templates have the | `api-conventions` | Name a tool, set its annotations, shape a result or change an error message | | `json-serialization` | Add a result model or change how JSON looks | | `presentation-integration-tests` | Write a test that talks to the server through an MCP client | +| `security-defaults` | Add a response header or other protection, or check what the app does to stay safe | | `mcp-inspector` | Try the server by hand as a client sees it | diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 5db854b..33f78ea 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -9,6 +9,7 @@ namespace CleanModelContextProtocol.Presentation.Extensions; #if includeAuth using Presentation.Authentication; #endif +using Presentation.Security; using Serilog; [ExcludeFromCodeCoverage] @@ -24,6 +25,8 @@ public static WebApplication ConfigureApplication(this WebApplication app) #region Security + _ = app.UseSecurityHeaders(); + // 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/SecurityHeaders.cs b/src/Presentation/Security/SecurityHeaders.cs new file mode 100644 index 0000000..9a9e663 --- /dev/null +++ b/src/Presentation/Security/SecurityHeaders.cs @@ -0,0 +1,34 @@ +namespace CleanModelContextProtocol.Presentation.Security; + +using Microsoft.AspNetCore.Builder; + +/// +/// The response headers every response carries, errors included. No Content-Security-Policy, so the browser tools keep +/// working. +/// +public static class SecurityHeaders +{ + /// + /// Adds X-Content-Type-Options: nosniff, X-Frame-Options: DENY and Referrer-Policy: no-referrer + /// to every response. + /// + /// The application to add the headers to. + /// The application, for chaining. + public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) + { + return app.Use(async (context, next) => + { + // Set as the response starts, because the exception handler clears headers set earlier. + context.Response.OnStarting(() => + { + var headers = context.Response.Headers; + headers.XContentTypeOptions = "nosniff"; + headers.XFrameOptions = "DENY"; + headers["Referrer-Policy"] = "no-referrer"; + return Task.CompletedTask; + }); + + await next(context); + }); + } +} diff --git a/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs new file mode 100644 index 0000000..257e226 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs @@ -0,0 +1,41 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Security; + +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class SecurityHeadersTests : IDisposable +{ + private readonly ModelContextProtocolApplication application = new(); + + [Theory] + [InlineData("/health/live")] + [InlineData("/not-a-real-path")] + public async Task Response_ShouldCarry_SecurityHeaders(string path) + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync(path); + + // Assert + response.Headers.GetValues("X-Content-Type-Options").ShouldBe(["nosniff"]); + response.Headers.GetValues("X-Frame-Options").ShouldBe(["DENY"]); + response.Headers.GetValues("Referrer-Policy").ShouldBe(["no-referrer"]); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } +} 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 04/12] 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(); + } +} From cda82b03770c75609c9e7df883719721273ce1e1 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:01:27 +0000 Subject: [PATCH 05/12] Run dotnet run in the Development environment --- .agents/skills/configuration-and-environments/SKILL.md | 6 +++--- .agents/skills/presentation-integration-tests/SKILL.md | 2 +- .agents/skills/sample-data/SKILL.md | 2 +- .agents/skills/serilog/SKILL.md | 4 ++-- docs/RUN.md | 6 +++--- src/Presentation/Extensions/WebApplicationExtensions.cs | 4 ++-- src/Presentation/Properties/launchSettings.json | 2 +- src/Presentation/Telemetry/TelemetrySettings.cs | 2 +- ...{appsettings.local.json => appsettings.Development.json} | 2 +- .../ModelContextProtocolApplication.cs | 2 +- .../Telemetry/TelemetrySettingsTests.cs | 6 +++--- 11 files changed, 19 insertions(+), 19 deletions(-) rename src/Presentation/{appsettings.local.json => appsettings.Development.json} (84%) diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index 9bd1fae..f9bf0e4 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -1,6 +1,6 @@ --- name: configuration-and-environments -description: How settings are layered with appsettings files and environment variables, what the local and docker environments are, and how to add a new setting. Use when adding configuration, a connection string or environment-specific behaviour. +description: How settings are layered with appsettings files and environment variables, what the Development and docker environments are, and how to add a new setting. Use when adding configuration, a connection string or environment-specific behaviour. metadata: scope: shared --- @@ -15,7 +15,7 @@ The Lambda template has no appsettings files or environments. Its startup builds | Environment | Set by | Used for | | --- | --- | --- | -| `local` | `launchSettings.json` (`DOTNET_ENVIRONMENT=local`) | `dotnet run` on a developer machine: console logs, sample data on | +| `Development` | `launchSettings.json` (`DOTNET_ENVIRONMENT=Development`) | `dotnet run` on a developer machine: console logs, sample data on | | `docker` | `docker-compose.yml` and the Dockerfile | `docker compose up`: telemetry over OTLP through the collector to the Aspire dashboard, database in `/app/data`, sample data on | | anything else | the host | Real deployments: base settings only, sample data off, HSTS on | @@ -39,7 +39,7 @@ Settings that exist today: ## Don't - Put secrets, passwords or tokens in any `appsettings*.json` file. Use environment variables or user secrets. -- Check `IsEnvironment("local")` for behaviour that should be a setting. Add a setting instead. +- Check `IsDevelopment()` or `IsEnvironment("docker")` for behaviour that should be a setting. Add a setting instead. - Read `Environment.GetEnvironmentVariable` directly. Go through `IConfiguration`. ## Check diff --git a/.agents/skills/presentation-integration-tests/SKILL.md b/.agents/skills/presentation-integration-tests/SKILL.md index c29cea9..3203352 100644 --- a/.agents/skills/presentation-integration-tests/SKILL.md +++ b/.agents/skills/presentation-integration-tests/SKILL.md @@ -9,7 +9,7 @@ metadata: ## The rule -`tests/Presentation.Tests.Integration` talks to the whole server the way a real client does. `ModelContextProtocolApplication` (a `WebApplicationFactory`) starts the server with the `local` environment, its own shared-cache in-memory SQLite database and the sample data on. `BaseToolTests` connects an `McpClient` to it over the streamable HTTP transport before each test and disposes both after. +`tests/Presentation.Tests.Integration` talks to the whole server the way a real client does. `ModelContextProtocolApplication` (a `WebApplicationFactory`) starts the server with the `Development` environment, its own shared-cache in-memory SQLite database and the sample data on. `BaseToolTests` connects an `McpClient` to it over the streamable HTTP transport before each test and disposes both after. | Helper | Use it to | | --- | --- | diff --git a/.agents/skills/sample-data/SKILL.md b/.agents/skills/sample-data/SKILL.md index 614c449..bbba8e9 100644 --- a/.agents/skills/sample-data/SKILL.md +++ b/.agents/skills/sample-data/SKILL.md @@ -16,7 +16,7 @@ There are two kinds of data, and they never mix. | Sample data | `src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs` (`AddData`) | Local runs, Docker and the presentation integration tests | 15 authors, 50 movies, 150 reviews from Bogus with a fixed seed | | Test data | `tests/Infrastructure.Tests.Integration/Databases/MovieReviews/Extensions/MovieReviewsCollectionData.cs` (`AddTestData`) | Repository tests | A handful of hand-written rows named "One", "Two", "Three" so assertions can find them | -Sample data is only added when `Database:SeedSampleData` is `true` (on in `appsettings.local.json` and `appsettings.docker.json`, off in `appsettings.json`; Lambda turns it on only in `docker-compose.yml`) and the database is empty. A deployed copy never starts with fake data. +Sample data is only added when `Database:SeedSampleData` is `true` (on in `appsettings.Development.json` and `appsettings.docker.json`, off in `appsettings.json`; Lambda turns it on only in `docker-compose.yml`) and the database is empty. A deployed copy never starts with fake data. ## Steps diff --git a/.agents/skills/serilog/SKILL.md b/.agents/skills/serilog/SKILL.md index 2c4c22e..a35637d 100644 --- a/.agents/skills/serilog/SKILL.md +++ b/.agents/skills/serilog/SKILL.md @@ -13,7 +13,7 @@ Serilog is the logger. Application and Infrastructure code log through `Microsof | Environment | Sink | Where to look | | --- | --- | --- | -| `local` | Console, with the output template in `appsettings.local.json` | The terminal | +| `Development` | Console, with the output template in `appsettings.Development.json` | The terminal | | `docker` | Console, and OTLP through the collector to the Aspire dashboard | The Aspire dashboard, on the port `docs/RUN.md` lists, or `docker compose logs` | | Lambda, anywhere | Console, as compact JSON, and OTLP when the endpoint is set | CloudWatch Logs, or `docker compose logs` for the emulator, and the Aspire dashboard in Docker Compose | | Any, when `OTEL_EXPORTER_OTLP_ENDPOINT` is set | Also OTLP, through `Serilog.Sinks.OpenTelemetry` | Whatever receives the OTLP (`telemetry`) | @@ -29,7 +29,7 @@ Every event carries these properties: | `AssemblyVersion`, `AssemblyInformationalVersion` | Added in code at startup | | Anything pushed with `LogContext` | `FromLogContext` | -Levels are set in configuration, never in code: `Information` by default and `Debug` in `local`, with `Information` for `Microsoft`, `Warning` for `Microsoft.AspNetCore` and `Microsoft.EntityFrameworkCore.Database.Command` (a line per SQL statement buries everything else, and EF Core's meter already counts them), and `Error` for `System`. The built-in `Logging` section is set to `None` so nothing is written twice. +Levels are set in configuration, never in code: `Information` by default and `Debug` in `Development`, with `Information` for `Microsoft`, `Warning` for `Microsoft.AspNetCore` and `Microsoft.EntityFrameworkCore.Database.Command` (a line per SQL statement buries everything else, and EF Core's meter already counts them), and `Error` for `System`. The built-in `Logging` section is set to `None` so nothing is written twice. Three things log a request, and each says something the others don't: diff --git a/docs/RUN.md b/docs/RUN.md index e5159fe..3ce8593 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -1,10 +1,10 @@ # Running Clean Model Context Protocol -There are two pre-configured environments, `local` and `docker`. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you. +There are two pre-configured environments, `Development` and `docker`. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you. ## Database -The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.local.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory. +The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.Development.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory. To add a migration after changing the data model: @@ -88,7 +88,7 @@ Every span, metric and log carries `service.version`, so you can always tell whi ## HTTPS -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. +The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . Outside the `Development` environment 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 diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 8e7d35e..7ffc3d7 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -30,8 +30,8 @@ public static WebApplication ConfigureApplication(this WebApplication app) // 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")) + // HSTS tells browsers to only use HTTPS from then on, so it's left off in Development. + if (!app.Environment.IsDevelopment()) { _ = app.UseHsts(); } diff --git a/src/Presentation/Properties/launchSettings.json b/src/Presentation/Properties/launchSettings.json index 02dc77b..85e0297 100644 --- a/src/Presentation/Properties/launchSettings.json +++ b/src/Presentation/Properties/launchSettings.json @@ -7,7 +7,7 @@ "launchBrowser": false, "applicationUrl": "https://localhost:7321;http://localhost:7320", "environmentVariables": { - "DOTNET_ENVIRONMENT": "local" + "DOTNET_ENVIRONMENT": "Development" } } } diff --git a/src/Presentation/Telemetry/TelemetrySettings.cs b/src/Presentation/Telemetry/TelemetrySettings.cs index 1d84a01..5364c10 100644 --- a/src/Presentation/Telemetry/TelemetrySettings.cs +++ b/src/Presentation/Telemetry/TelemetrySettings.cs @@ -19,7 +19,7 @@ public class TelemetrySettings /// The service.version: the informational version from , the same one the version endpoint returns. public required string ServiceVersion { get; init; } - /// The deployment.environment.name, such as local or docker. + /// The deployment.environment.name, such as Development or docker. public required string EnvironmentName { get; init; } /// Where the OTLP exporters send everything. Empty means nothing is exported. diff --git a/src/Presentation/appsettings.local.json b/src/Presentation/appsettings.Development.json similarity index 84% rename from src/Presentation/appsettings.local.json rename to src/Presentation/appsettings.Development.json index 7f4709f..648ca5a 100644 --- a/src/Presentation/appsettings.local.json +++ b/src/Presentation/appsettings.Development.json @@ -12,7 +12,7 @@ } ], "Properties": { - "ApplicationName": "CleanModelContextProtocol-Local" + "ApplicationName": "CleanModelContextProtocol-Development" } }, "Database": { diff --git a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs index 4bd78db..0ffa49f 100644 --- a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs +++ b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs @@ -6,7 +6,7 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration; using Microsoft.Extensions.Hosting; internal sealed class ModelContextProtocolApplication( - string environment = "local", + string environment = "Development", Dictionary? settings = null, Action? configureServices = null) : WebApplicationFactory { diff --git a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs index 8bd80d6..2171a3a 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -16,13 +16,13 @@ public void FromConfiguration_ShouldReturn_DisabledDefaults_WhenNothingIsSet() var version = new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3+e30eba8" }; // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", version); + var result = TelemetrySettings.FromConfiguration(configuration, "Development", version); // Assert result.Enabled.ShouldBeFalse(); result.ServiceName.ShouldBe(TelemetrySettings.DefaultServiceName); result.ServiceVersion.ShouldBe("1.2.3+e30eba8"); - result.EnvironmentName.ShouldBe("local"); + result.EnvironmentName.ShouldBe("Development"); } [Fact] @@ -56,7 +56,7 @@ public void FromConfiguration_ShouldReturn_UnknownVersion_WhenVersionIsEmpty() var version = VersionInfo.FromAssembly(null); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", version); + var result = TelemetrySettings.FromConfiguration(configuration, "Development", version); // Assert result.ServiceVersion.ShouldBe("unknown"); From 7397c53bdea8c53c4a28653e35de832d85c3c045 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:07:12 +0000 Subject: [PATCH 06/12] Refuse to start a deployed copy with auth off --- .../configuration-and-environments/SKILL.md | 5 +- .agents/skills/optional-token-auth/SKILL.md | 2 + .agents/skills/security-defaults/SKILL.md | 12 ++- .github/workflows/build-pipeline.yml | 1 + Dockerfile | 2 +- docs/RUN.md | 2 +- .../WebApplicationBuilderExtensions.cs | 4 + src/Presentation/Security/DeploymentGuard.cs | 67 ++++++++++++++ src/Presentation/appsettings.json | 7 +- .../Security/DeploymentGuardTests.cs | 90 +++++++++++++++++++ 10 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 src/Presentation/Security/DeploymentGuard.cs create mode 100644 tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index f9bf0e4..3f9b296 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -16,8 +16,8 @@ The Lambda template has no appsettings files or environments. Its startup builds | Environment | Set by | Used for | | --- | --- | --- | | `Development` | `launchSettings.json` (`DOTNET_ENVIRONMENT=Development`) | `dotnet run` on a developer machine: console logs, sample data on | -| `docker` | `docker-compose.yml` and the Dockerfile | `docker compose up`: telemetry over OTLP through the collector to the Aspire dashboard, database in `/app/data`, sample data on | -| anything else | the host | Real deployments: base settings only, sample data off, HSTS on | +| `docker` | `docker-compose.yml` | `docker compose up`: telemetry over OTLP through the collector to the Aspire dashboard, database in `/app/data`, sample data on | +| anything else | the host, or `Production`, the image's default | Real deployments: base settings only, sample data off, HSTS on. The web templates refuse to start here without authentication unless `Authentication:AllowAnonymous` is true (`security-defaults`) | Settings that exist today: @@ -26,6 +26,7 @@ Settings that exist today: | `ConnectionStrings:MovieReviews` | SQLite connection string. `Data Source=Name;Mode=Memory;Cache=Shared` keeps everything in memory. | | `Database:SeedSampleData` | Seed sample data into an empty database (`sample-data`). | | `Authentication:Authority`, `Authentication:Audience` | Only in a solution created with `--include-auth`: turn on token authentication (`optional-token-auth`). MCP also has `Authentication:Scopes`, published in its protected resource metadata. | +| `Authentication:AllowAnonymous` | Web templates only: let a deployed environment run without authentication on purpose (`security-defaults`). Off by default. | | `Serilog:*` | Logging (`serilog`). | ## Steps diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index b8741ef..a750d70 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -15,6 +15,8 @@ With `--include-auth`, endpoints always ask for authorization. An empty `Authent Settings are read through `AuthenticationSettings.FromConfiguration` (`Enabled` is true when the authority isn't empty). +Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`). + ## Steps 1. In a solution with authentication, a new endpoint or group gets `.RequireAuthorization()` (or the presentation layer's equivalent). That's the default; don't skip it. Without it there's nothing to call. diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md index 6d88898..5253b60 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, 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. +description: What this MCP server does to be safe by default - the startup guard for deployed environments, 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 --- @@ -13,11 +13,21 @@ The app ships safe by default, and each protection lives in one place in `src/Pr | Protection | Where | Default | | --- | --- | --- | +| Refuse to start deployed and open | `DeploymentGuard` | On; `Authentication:AllowAnonymous` opts out | | 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 | +## Deployment guard + +`DeploymentGuard.EnsureSafeToStart` runs first in the startup, before any service is added. `Development` (`dotnet run`) and `docker` (Docker Compose) are a developer's machine. Every other environment name, including `Production` (the image's default), `uat` or anything a team invents, counts as deployed, so a new name fails closed. + +- A deployed environment without authentication throws at startup, unless `Authentication:AllowAnonymous` is `true`. The message names the setting. +- In a solution with authentication, a set `Authentication:Authority` must be an absolute `https` URL, in every environment. An empty `Authentication:Audience` already fails closed, because every token is rejected. + +Don't add environment names to `IsLocal` to get a deployment past the guard; set `Authentication:AllowAnonymous` there instead, so the choice is visible in that environment's settings. `tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs` starts the app in each kind of environment. + ## Security headers `UseSecurityHeaders` adds three headers to every response, errors and health checks included: diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index 1fbd596..523f1e9 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -359,6 +359,7 @@ jobs: # The database goes in /app/data, the only folder the non-root user can write to, as it does # in docker-compose.yml. Logs stay on the console so a failure shows up below. docker run --detach --name api --publish 7320:7320 \ + --env DOTNET_ENVIRONMENT=docker \ --env ConnectionStrings__MovieReviews="Data Source=/app/data/movie-reviews.db" \ --env Database__SeedSampleData=true "$IMAGE" for attempt in $(seq 1 30); do diff --git a/Dockerfile b/Dockerfile index 3ae85c2..89e4494 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,7 @@ FROM ${BASE_IMAGE_REPO}/${BASE_IMAGE_BUILD}:${BASE_IMAGE_BUILD_TAG} AS build # Build, Test and Publish ARGS ARG VERSION_PREFIX=1.0.0.0 ARG VERSION_SUFFIX -ARG ENVIRONMENT=docker +ARG ENVIRONMENT=Production # Build, Test and Publish ENVS ENV DOTNET_ENVIRONMENT=${ENVIRONMENT} diff --git a/docs/RUN.md b/docs/RUN.md index 3ce8593..f3cb09b 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -1,6 +1,6 @@ # Running Clean Model Context Protocol -There are two pre-configured environments, `Development` and `docker`. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you. +There are two pre-configured environments: `Development` for `dotnet run` and `docker` for Docker Compose. Every other environment name counts as deployed, including `Production`, which is what the image runs as unless you say otherwise. A deployed copy with no authentication refuses to start, so nobody ships an open API by accident; set `Authentication:AllowAnonymous` to `true` (`Authentication__AllowAnonymous=true`) if open is what you want. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you. ## Database diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index 28f86d9..1766469 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -24,6 +24,7 @@ namespace CleanModelContextProtocol.Presentation.Extensions; #endif using Presentation.Completions; using Presentation.Errors; +using Presentation.Security; using Presentation.Serialization; using Presentation.Telemetry; using Presentation.Tools; @@ -34,6 +35,9 @@ public static class WebApplicationBuilderExtensions { public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicationBuilder builder) { + // Before anything else, so a deployed copy with no authentication never gets as far as listening. + DeploymentGuard.EnsureSafeToStart(builder.Environment, builder.Configuration); + #region Telemetry var assembly = typeof(WebApplicationBuilderExtensions).Assembly; diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs new file mode 100644 index 0000000..a6cc66b --- /dev/null +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -0,0 +1,67 @@ +namespace CleanModelContextProtocol.Presentation.Security; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +#if includeAuth +using Presentation.Authentication; +#endif + +/// +/// Stops a deployed copy starting wide open by accident. Development (dotnet run) and docker +/// (Docker Compose) are a developer's machine; every other environment name counts as deployed. +/// +public static class DeploymentGuard +{ + /// The setting that lets a deployed copy run without authentication on purpose. + public const string AllowAnonymousKey = "Authentication:AllowAnonymous"; + + /// + /// Whether the environment is a developer's machine rather than a deployment. + /// + /// The host's environment. + /// True for Development and docker. + public static bool IsLocal(IHostEnvironment environment) + { + return environment.IsDevelopment() || environment.IsEnvironment("docker"); + } + + /// + /// Throws when the app shouldn't start: a deployed environment without authentication, unless + /// Authentication:AllowAnonymous is true. + /// + /// The host's environment. + /// The settings to check. + /// The settings aren't safe to start with. + public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguration configuration) + { +#if includeAuth + var authentication = AuthenticationSettings.FromConfiguration(configuration); + + if (authentication.Enabled) + { + if (!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps) + { + throw new InvalidOperationException( + $"Authentication:Authority must be an absolute https URL, such as https://login.example.com, not '{authentication.Authority}'."); + } + + return; + } + +#endif + if (IsLocal(environment) || configuration.GetValue(AllowAnonymousKey)) + { + return; + } + +#if includeAuth + throw new InvalidOperationException( + $"The '{environment.EnvironmentName}' environment has no authentication, so anyone could call it. Set Authentication:Authority, " + + $"or set {AllowAnonymousKey} to true to run it open on purpose."); +#else + throw new InvalidOperationException( + $"The '{environment.EnvironmentName}' environment has no authentication, so anyone could call it. " + + $"Set {AllowAnonymousKey} to true to run it open on purpose."); +#endif + } +} diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index 9be2434..00baf7a 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -23,13 +23,14 @@ "ConnectionStrings": { "MovieReviews": "Data Source=movie-reviews.db" }, - //#if (includeAuth) "Authentication": { + //#if (includeAuth) "Authority": "", "Audience": "", - "Scopes": [] + "Scopes": [], + //#endif + "AllowAnonymous": false }, - //#endif "AllowedHosts": "*", "Mcp": { "AllowedOrigins": [] diff --git a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs new file mode 100644 index 0000000..9a335e3 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs @@ -0,0 +1,90 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Security; + +using System.Net; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class DeploymentGuardTests +{ + [Theory] + [InlineData("Production")] + [InlineData("uat")] + public void DeployedEnvironment_WithoutAuthentication_ShouldNotStart(string environment) + { + // Arrange + using var application = new ModelContextProtocolApplication(environment); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain($"'{environment}' environment has no authentication"); + exception.Message.ShouldContain("Authentication:AllowAnonymous"); + } + + [Theory] + [InlineData("Development")] + [InlineData("docker")] + public async Task LocalEnvironment_WithoutAuthentication_ShouldStart(string environment) + { + // Arrange + using var application = new ModelContextProtocolApplication(environment); + using var client = application.CreateClient(); + + // Act + using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task DeployedEnvironment_WithAllowAnonymous_ShouldStart() + { + // Arrange + using var application = new ModelContextProtocolApplication("Production", new Dictionary { ["Authentication:AllowAnonymous"] = "true" }); + using var client = application.CreateClient(); + + // Act + using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } +#if includeAuth + + [Fact] + public async Task DeployedEnvironment_WithAuthority_ShouldStart() + { + // Arrange + using var application = new ModelContextProtocolApplication("Production", new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Audience"] = "https://api.example.com" + }); + using var client = application.CreateClient(); + + // Act + using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Theory] + [InlineData("http://login.example.com")] + [InlineData("login.example.com")] + public void AnyEnvironment_WithAuthorityThatIsNotHttps_ShouldNotStart(string authority) + { + // Arrange + using var application = new ModelContextProtocolApplication(settings: new Dictionary { ["Authentication:Authority"] = authority }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("Authentication:Authority must be an absolute https URL"); + } +#endif +} From fb35718057c7dff79b7a3921b883bdff248c6c1c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:21:59 +0000 Subject: [PATCH 07/12] Accept dotnet user-jwts tokens in Development --- .agents/skills/mcp-inspector/SKILL.md | 2 +- .agents/skills/optional-token-auth/SKILL.md | 4 +- docs/RUN.md | 14 +++ .../Authentication/AuthenticationSettings.cs | 23 ++++- .../WebApplicationBuilderExtensions.cs | 21 +++-- src/Presentation/Security/DeploymentGuard.cs | 3 +- .../Authentication/DevelopmentTokenTests.cs | 85 +++++++++++++++++++ .../AuthenticationSettingsTests.cs | 22 +++++ 8 files changed, 164 insertions(+), 10 deletions(-) create mode 100644 tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs diff --git a/.agents/skills/mcp-inspector/SKILL.md b/.agents/skills/mcp-inspector/SKILL.md index 064e825..e0d9ddc 100644 --- a/.agents/skills/mcp-inspector/SKILL.md +++ b/.agents/skills/mcp-inspector/SKILL.md @@ -24,7 +24,7 @@ metadata: 3. After changing a tool, check its description and every argument's description read well, the annotations are right, and a call returns the result model you expect. 4. Try the failure paths too: an unknown id, a star rating of 6. The model should get a message it can act on. 5. Find the tool call in the Aspire dashboard if something looks wrong: its trace shows the tool, the use case and each SQL command, and its logs sit beside it (`telemetry`). -6. With authentication on, the Inspector needs a token from your authority. Leave `Authentication:Authority` empty for local checks. +6. With authentication on, the Inspector needs a token. For local checks, run `dotnet user-jwts create --project src/Presentation` and paste the token under **Authentication**, **Bearer Token** (`optional-token-auth`), or leave `Authentication:Authority` empty. ## Chat demo diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index a750d70..93a43d5 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -13,7 +13,9 @@ Authentication is a choice made when the solution is created. With `--include-au With `--include-auth`, endpoints always ask for authorization. An empty `Authentication:Authority` still runs everything open, because the default policy then lets every request through, which is how the tests run unless they set an authority. Only health checks and the API reference (where a template has them) are anonymous. The version endpoint is protected like everything else; telemetry carries `service.version` for anyone who needs to know what's deployed. The Lambda template has no token authentication; API Gateway or the caller's IAM role does that job. -Settings are read through `AuthenticationSettings.FromConfiguration` (`Enabled` is true when the authority isn't empty). +Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` is true when the authority isn't empty or `dotnet user-jwts` is set up. + +For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`). diff --git a/docs/RUN.md b/docs/RUN.md index f3cb09b..1bb68c1 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -86,6 +86,20 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7323 dotnet run --project ./src/Pre Every span, metric and log carries `service.version`, so you can always tell which build sent it. + +## Trying it with a token + +With an authority set, every call needs a token from it. To try the app on your machine without one, let .NET make you a development token: + +```bash +dotnet user-jwts create --project src/Presentation +``` + +It prints a token, adds a `UserSecretsId` to the project, keeps the signing key in your user secrets and writes the issuer and audiences into `appsettings.Development.json`. From then on a `dotnet run` accepts its tokens instead of your authority's. Nothing changes anywhere else, because user secrets and that file only load in `Development`. + +In the MCP Inspector, put the token in **Authentication**, under **Bearer Token**, before you connect. Run `dotnet user-jwts create` again for a fresh token, and `dotnet user-jwts clear --project src/Presentation` and delete the `Authentication` block from `appsettings.Development.json` to go back to your authority. + + ## HTTPS The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . Outside the `Development` environment 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. diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs index 426fdb6..30617aa 100644 --- a/src/Presentation/Authentication/AuthenticationSettings.cs +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -18,10 +18,29 @@ public class AuthenticationSettings /// The scopes clients should ask for, published in the protected resource metadata. public List Scopes { get; init; } = []; - public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority); + /// + /// The issuer dotnet user-jwts writes to appsettings.Development.json, read from + /// Authentication:Schemes:Bearer:ValidIssuer. When it's set, the app accepts the tokens that tool creates. + /// + public string? DevelopmentTokenIssuer { get; private set; } + + /// Whether requests need a token: true when an authority or dotnet user-jwts is set up. + public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority) || this.UsesDevelopmentTokens; + + /// + /// Whether the tokens come from dotnet user-jwts. They win over the authority, so running the tool switches + /// a dotnet run to them and clearing it switches back. + /// + public bool UsesDevelopmentTokens => !string.IsNullOrWhiteSpace(this.DevelopmentTokenIssuer); + + /// Whether a real authorization server issues the tokens. + public bool HasAuthority => !string.IsNullOrWhiteSpace(this.Authority) && !this.UsesDevelopmentTokens; public static AuthenticationSettings FromConfiguration(IConfiguration configuration) { - return configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + var settings = configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + settings.DevelopmentTokenIssuer = configuration[$"{SectionName}:Schemes:Bearer:ValidIssuer"]; + + return settings; } } diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index 1766469..fa9ca68 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -124,25 +124,36 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat if (authentication.Enabled) { - _ = builder.Services + var authenticationBuilder = builder.Services .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme; + + // With an authority, a 401 tells the client where to sign in. Development tokens have nowhere to send it. + options.DefaultChallengeScheme = authentication.HasAuthority + ? McpAuthenticationDefaults.AuthenticationScheme + : JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { - options.Authority = authentication.Authority; + // With dotnet user-jwts set up, there's no authority to ask: the tool has put the issuer, audiences + // and signing key in the settings, and the handler reads them from Authentication:Schemes:Bearer. + options.Authority = authentication.HasAuthority ? authentication.Authority : null; options.Audience = authentication.Audience; options.MapInboundClaims = false; - }) - .AddMcp(options => options.ResourceMetadata = new() + }); + + if (authentication.HasAuthority) + { + _ = authenticationBuilder.AddMcp(options => options.ResourceMetadata = new() { Resource = authentication.Audience, AuthorizationServers = [authentication.Authority!], ScopesSupported = authentication.Scopes, ResourceName = "Clean Model Context Protocol" }); + } + _ = builder.Services.AddAuthorization(); } else diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index a6cc66b..fbfb4dd 100644 --- a/src/Presentation/Security/DeploymentGuard.cs +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -39,7 +39,8 @@ public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguratio if (authentication.Enabled) { - if (!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps) + if (!string.IsNullOrWhiteSpace(authentication.Authority) && + (!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps)) { throw new InvalidOperationException( $"Authentication:Authority must be an absolute https URL, such as https://login.example.com, not '{authentication.Authority}'."); diff --git a/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs new file mode 100644 index 0000000..6f3910d --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs @@ -0,0 +1,85 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Authentication; + +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using Shouldly; +using Xunit; + +public class DevelopmentTokenTests : IDisposable +{ + private const string Issuer = "dotnet-user-jwts"; + private const string Audience = "http://localhost"; + + private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes("a-development-signing-key-for-the-tests-1234"); + + // What dotnet user-jwts writes: the issuer and audiences in appsettings.Development.json, the key in user secrets. + private readonly ModelContextProtocolApplication application = new(settings: new Dictionary + { + ["Authentication:Schemes:Bearer:ValidIssuer"] = Issuer, + ["Authentication:Schemes:Bearer:ValidAudiences:0"] = Audience, + ["Authentication:Schemes:Bearer:SigningKeys:0:Id"] = "test", + ["Authentication:Schemes:Bearer:SigningKeys:0:Issuer"] = Issuer, + ["Authentication:Schemes:Bearer:SigningKeys:0:Value"] = Convert.ToBase64String(KeyBytes), + ["Authentication:Schemes:Bearer:SigningKeys:0:Length"] = "32" + }); + + [Fact] + public async Task Mcp_WithoutToken_ShouldReturn_Unauthorized() + { + // Arrange + using var client = this.application.CreateClient(); + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + + // Act + using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Mcp_WithDevelopmentToken_ShouldNotReturn_Unauthorized() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(KeyBytes)); + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + + // Act + using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content); + + // Assert + response.StatusCode.ShouldNotBe(HttpStatusCode.Unauthorized); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } + + private static string CreateToken(byte[] key) + { + return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor + { + Issuer = Issuer, + Audience = Audience, + Subject = new ClaimsIdentity([new Claim("sub", "developer")]), + Expires = DateTime.UtcNow.AddMinutes(5), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) + }); + } +} diff --git a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs index 04a09c8..8eed69c 100644 --- a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -43,4 +43,26 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet() result.Audience.ShouldBe("https://localhost:5001"); result.Scopes.ShouldBe(["movies.read"]); } + + [Fact] + public void FromConfiguration_ShouldReturn_EnabledSettings_WhenDevelopmentTokensAreSetUp_EvenWithAnAuthority() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Schemes:Bearer:ValidIssuer"] = "dotnet-user-jwts" + }) + .Build(); + + // Act + var result = AuthenticationSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeTrue(); + result.UsesDevelopmentTokens.ShouldBeTrue(); + result.HasAuthority.ShouldBeFalse(); + result.DevelopmentTokenIssuer.ShouldBe("dotnet-user-jwts"); + } } From ea7912ddc011fb9e7b2cde3f3f5c0ab65d05c9f1 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:46:49 +0000 Subject: [PATCH 08/12] Add optional rate limiting --- .../configuration-and-environments/SKILL.md | 1 + .agents/skills/security-defaults/SKILL.md | 21 +++++- .agents/skills/template-authoring/SKILL.md | 3 +- .github/workflows/build-pipeline.yml | 15 +++- .template.config/dotnetcli.host.json | 4 + .template.config/ide.host.json | 10 +++ .template.config/template.json | 15 ++++ NUGET.md | 1 + README.md | 1 + docs/RUN.md | 6 ++ .../WebApplicationBuilderExtensions.cs | 11 +++ .../Extensions/WebApplicationExtensions.cs | 13 ++++ src/Presentation/Presentation.csproj | 4 +- .../RateLimiting/RateLimitingExtensions.cs | 62 ++++++++++++++++ .../RateLimiting/RateLimitingSettings.cs | 25 +++++++ src/Presentation/appsettings.json | 6 ++ .../Presentation.Tests.Integration.csproj | 4 +- .../RateLimiting/RateLimitingTests.cs | 73 +++++++++++++++++++ .../RateLimiting/RateLimitingSettingsTests.cs | 63 ++++++++++++++++ 19 files changed, 329 insertions(+), 9 deletions(-) create mode 100644 src/Presentation/RateLimiting/RateLimitingExtensions.cs create mode 100644 src/Presentation/RateLimiting/RateLimitingSettings.cs create mode 100644 tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs create mode 100644 tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index 3f9b296..c1572e5 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -27,6 +27,7 @@ Settings that exist today: | `Database:SeedSampleData` | Seed sample data into an empty database (`sample-data`). | | `Authentication:Authority`, `Authentication:Audience` | Only in a solution created with `--include-auth`: turn on token authentication (`optional-token-auth`). MCP also has `Authentication:Scopes`, published in its protected resource metadata. | | `Authentication:AllowAnonymous` | Web templates only: let a deployed environment run without authentication on purpose (`security-defaults`). Off by default. | +| `RateLimiting:PermitLimit`, `RateLimiting:Window` | Web templates, only in a solution created with `--include-rate-limiting`: requests each client IP address may make in each window. `0`, the default, leaves the limiter off (`security-defaults`). | | `Serilog:*` | Logging (`serilog`). | ## Steps diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md index 5253b60..db59067 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 startup guard for deployed environments, 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. +description: What this MCP server does to be safe by default - the startup guard for deployed environments, the security response headers, the Origin check on /mcp, optional rate limiting and where the other protections live. Use when adding a response header, turning on or tuning rate limiting, letting a browser client in with Mcp:AllowedOrigins, changing security middleware, or asked whether the app is safe to deploy. metadata: scope: presentation --- @@ -16,6 +16,7 @@ The app ships safe by default, and each protection lives in one place in `src/Pr | Refuse to start deployed and open | `DeploymentGuard` | On; `Authentication:AllowAnonymous` opts out | | Security response headers | `SecurityHeaders` | Always on | | `Origin` check on `/mcp` | `OriginCheck` | No `Origin` or localhost only, plus `Mcp:AllowedOrigins` | +| Rate limiting per client IP address | `RateLimiting/` | Only with `--include-rate-limiting`, and off until `RateLimiting:PermitLimit` is set | | HSTS and HTTPS redirection | Security region | HSTS outside local runs | | Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | @@ -51,6 +52,24 @@ The MCP spec says a Streamable HTTP server must check the `Origin` header, so a 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. +## Rate limiting + +A solution created with `--include-rate-limiting` has a fixed window limiter in `src/Presentation/RateLimiting/`, wired in by `WebApplicationBuilderExtensions` and `WebApplicationExtensions`. It's the one protection outside `Security/`, because the whole folder is left out without the toggle. It stays off until `RateLimiting:PermitLimit` is above `0`: + +``` json +"RateLimiting": { + "PermitLimit": 100, + "Window": "00:01:00" +} +``` + +- Every request, so each MCP message a client posts to `/mcp`, counts against the caller's IP address. Past the limit the app answers `429 Too Many Requests` with a `Retry-After` header. +- `/health` is never limited, so a busy client can't make the app look down to its host. +- The limiter runs before authentication, so a flood of calls without a token is limited too. +- Behind a reverse proxy or load balancer every request comes from the proxy's address, so all clients share one window. Set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` there, which makes the app read the client's address from the proxy's `X-Forwarded-For` header before any of its own middleware runs, or limit at the proxy instead. + +`tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs` checks the 429, the health exemption and that nothing is limited by default. To try it by hand, set a `PermitLimit` of `2` and make three calls inside a minute: the third gets the 429. + ## Steps 1. Add a header in `SecurityHeaders`, not in an endpoint or a filter, so every response gets it. diff --git a/.agents/skills/template-authoring/SKILL.md b/.agents/skills/template-authoring/SKILL.md index d7d7df2..8e153c5 100644 --- a/.agents/skills/template-authoring/SKILL.md +++ b/.agents/skills/template-authoring/SKILL.md @@ -15,6 +15,7 @@ The repository is both a working solution and a `dotnet new` template. `.templat | --- | --- | --- | | `authorName` | `--authorName`
`-an` | `Stephen Walsh` (`--author` is reserved by `dotnet new`) | | `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and `authority` becomes required through `isRequired` (web templates) | +| `includeRateLimiting` | `--include-rate-limiting` | Nothing. A toggle, off by default. Off, the `RateLimiting` folders and every line that wires them in are left out; on, the limiter is still off until `RateLimiting:PermitLimit` is set (web templates) | | `authority` | `--authority`
`-iss` | The empty `Authentication:Authority` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `audience` | `--audience`
`-aud` | The empty `Authentication:Audience` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `skipRestore` | `--no-restore` | Nothing; it turns the restore post action off | @@ -95,4 +96,4 @@ The README and `NUGET.md` name the aliases under the install commands, and the d ## Check -The Test job's Verify Template step installs the packed template, generates a solution and checks that nothing of the template leaked into it (no `includeAuth` markers, no trace of the template's own name, no `icon.png`) and that it has `README.md` and `.github/workflows/ci.yml`, then checks its format and runs its tests. Where the template has `--include-auth` it does it again with the toggle on, and checks that `--include-auth` without `--authority` is refused with exit code 102. +The Test job's Verify Template step installs the packed template, generates a solution and checks that nothing of the template leaked into it (no toggle markers such as `includeAuth`, no trace of the template's own name, no `icon.png`) and that it has `README.md` and `.github/workflows/ci.yml`, then checks its format and runs its tests. Where the template has `--include-auth` it does it again with every toggle on, and checks that `--include-auth` without `--authority` is refused with exit code 102. Where it has `--include-rate-limiting` it also verifies a solution with only that toggle on. diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index 523f1e9..63aeec7 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -235,6 +235,7 @@ jobs: verify() { dotnet new "$SHORT_NAME" --name "$1" --output "$1" "${@:2}" clean "$1" includeAuth + clean "$1" includeRateLimiting clean "$1" "$SOURCE_NAME" test ! -e "$1/icon.png" test -f "$1/README.md" @@ -246,16 +247,24 @@ jobs: verify Template.Verification VARIANTS="the generated solution carries nothing of the template, passes its format check, builds and passes its tests" - # Templates with an auth option are verified a second time with it on, and --include-auth without + # Templates with a rate limiting option are verified with only that toggle on. + ALL_ON=() + if jq -e '.symbols.includeRateLimiting' .template.config/template.json > /dev/null; then + verify Template.RateLimiting --include-rate-limiting + ALL_ON+=(--include-rate-limiting) + VARIANTS="$VARIANTS, with --include-rate-limiting on its own" + fi + + # Templates with an auth option are verified again with every toggle on, and --include-auth without # --authority has to stop before anything is written (exit code 102, a missing mandatory option). if jq -e '.symbols.includeAuth' .template.config/template.json > /dev/null; then - verify Template.Authentication --include-auth --authority https://login.example.com --audience https://api.example.com + verify Template.Authentication --include-auth --authority https://login.example.com --audience https://api.example.com "${ALL_ON[@]}" set +e dotnet new "$SHORT_NAME" --name Template.NoAuthority --output Template.NoAuthority --include-auth NO_AUTHORITY=$? set -e test "$NO_AUTHORITY" -eq 102 || { echo "::error::--include-auth without --authority exited $NO_AUTHORITY, not 102"; exit 1; } - VARIANTS="$VARIANTS with and without --include-auth, and --include-auth without --authority is refused" + VARIANTS="$VARIANTS, with every toggle on, and --include-auth without --authority is refused" fi echo "### Template" >> "$GITHUB_STEP_SUMMARY" diff --git a/.template.config/dotnetcli.host.json b/.template.config/dotnetcli.host.json index f65268e..d238cfc 100644 --- a/.template.config/dotnetcli.host.json +++ b/.template.config/dotnetcli.host.json @@ -9,6 +9,10 @@ "longName": "include-auth", "shortName": "" }, + "includeRateLimiting": { + "longName": "include-rate-limiting", + "shortName": "" + }, "authority": { "longName": "authority", "shortName": "iss" diff --git a/.template.config/ide.host.json b/.template.config/ide.host.json index 5ea2193..6a5f1f9 100644 --- a/.template.config/ide.host.json +++ b/.template.config/ide.host.json @@ -41,6 +41,16 @@ }, "isVisible": true }, + { + "id": "includeRateLimiting", + "name": { + "text": "Include rate limiting" + }, + "description": { + "text": "Add the built-in rate limiter, a fixed window per client IP address, off until RateLimiting:PermitLimit is set. Default: off." + }, + "isVisible": true + }, { "id": "authority", "name": { diff --git a/.template.config/template.json b/.template.config/template.json index 1eb20f6..4a89e7a 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -53,6 +53,14 @@ "tests/Presentation.Tests.Unit/Authentication/**", "tests/Presentation.Tests.Integration/Authentication/**" ] + }, + { + "condition": "(!includeRateLimiting)", + "exclude": [ + "src/Presentation/RateLimiting/**", + "tests/Presentation.Tests.Unit/RateLimiting/**", + "tests/Presentation.Tests.Integration/RateLimiting/**" + ] } ] } @@ -73,6 +81,13 @@ "description": "Add OAuth for MCP clients. Leave it off and the server has no auth code at all, which is fine on your machine and brave anywhere else.", "defaultValue": "false" }, + "includeRateLimiting": { + "type": "parameter", + "datatype": "bool", + "displayName": "Include rate limiting", + "description": "Add ASP.NET Core's rate limiter, a fixed window per client IP address, switched on by setting RateLimiting:PermitLimit. For when there's no gateway doing it for you.", + "defaultValue": "false" + }, "authority": { "type": "parameter", "datatype": "string", diff --git a/NUGET.md b/NUGET.md index c2f3093..68757b7 100644 --- a/NUGET.md +++ b/NUGET.md @@ -32,6 +32,7 @@ cd WorksOnMyMachine.Movies | `--name` | `-n` | The folder's name | Names the solution and its root namespace | | `--authorName` | `-an` | `Stephen Walsh` | Puts your name on the assembly instead of ours | | `--include-auth` | | Off | Adds OAuth for MCP clients. Leave it out and the server has no auth code at all | +| `--include-rate-limiting` | | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority` | `-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | | `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Only used with `--include-auth` | | `--no-restore` | | Off | Skips the package restore that normally runs once the solution is created | diff --git a/README.md b/README.md index 4765241..c1513b5 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ cd WorksOnMyMachine.Movies | `--name`
`-n` | The folder's name | Names the solution and its root namespace | | `--authorName`
`-an` | `Stephen Walsh` | Puts your name on the assembly instead of ours | | `--include-auth` | Off | Adds OAuth for MCP clients. Leave it out and the server has no auth code at all | +| `--include-rate-limiting` | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority`
`-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | | `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Only used with `--include-auth` | | `--no-restore` | Off | Skips the package restore that normally runs once the solution is created | diff --git a/docs/RUN.md b/docs/RUN.md index 1bb68c1..dab789a 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -108,6 +108,12 @@ The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dot 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`. + +## Rate limiting + +The rate limiter is in the code but off. Turn it on by setting how many requests each client IP address may make in each window, in `appsettings.json` or as environment variables (`RateLimiting__PermitLimit=100`, `RateLimiting__Window=00:01:00`). Past the limit, calls get `429 Too Many Requests` with a `Retry-After` header. Health checks are never limited. Behind a reverse proxy every call looks like it comes from the proxy, so set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` (as in HTTPS above) and the app reads the client's address from the proxy's `X-Forwarded-For` header, or limit at the proxy instead. + + ## Tests ``` bash diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index fa9ca68..2c6b074 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -24,6 +24,9 @@ namespace CleanModelContextProtocol.Presentation.Extensions; #endif using Presentation.Completions; using Presentation.Errors; +#if includeRateLimiting +using Presentation.RateLimiting; +#endif using Presentation.Security; using Presentation.Serialization; using Presentation.Telemetry; @@ -107,6 +110,14 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #endregion Logging +#if includeRateLimiting + #region Rate Limiting + + _ = builder.Services.AddRateLimiting(builder.Configuration); + + #endregion Rate Limiting + +#endif #region Project Dependencies _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 7ffc3d7..07a19da 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -9,6 +9,9 @@ namespace CleanModelContextProtocol.Presentation.Extensions; #if includeAuth using Presentation.Authentication; #endif +#if includeRateLimiting +using Presentation.RateLimiting; +#endif using Presentation.Security; using Serilog; @@ -46,6 +49,16 @@ public static WebApplication ConfigureApplication(this WebApplication app) #endregion Logging +#if includeRateLimiting + #region Rate Limiting + + // After the error handlers, so a 429 gets the same body as any other error, and before authentication, so a + // client over its limit is turned away before its token is checked. + _ = app.UseRateLimiting(app.Configuration); + + #endregion Rate Limiting + +#endif #if includeAuth #region Authentication diff --git a/src/Presentation/Presentation.csproj b/src/Presentation/Presentation.csproj index 221efdd..be964e0 100644 --- a/src/Presentation/Presentation.csproj +++ b/src/Presentation/Presentation.csproj @@ -10,8 +10,8 @@ Linux $(NoWarn);1573 - - $(DefineConstants);includeAuth + + $(DefineConstants);includeAuth;includeRateLimiting diff --git a/src/Presentation/RateLimiting/RateLimitingExtensions.cs b/src/Presentation/RateLimiting/RateLimitingExtensions.cs new file mode 100644 index 0000000..e898a54 --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingExtensions.cs @@ -0,0 +1,62 @@ +namespace CleanModelContextProtocol.Presentation.RateLimiting; + +using System.Globalization; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +/// +/// Adds ASP.NET Core's built-in rate limiter when RateLimiting:PermitLimit is set. Each client IP address gets +/// its own fixed window; a client over its limit gets a 429 with a Retry-After header. Health checks are never +/// limited, so probes keep working when a client is being turned away. +/// +public static class RateLimitingExtensions +{ + /// + /// Registers the limiter, if it's switched on. + /// + /// The services to add the limiter to. + /// The settings to read RateLimiting from. + /// The services, for chaining. + public static IServiceCollection AddRateLimiting(this IServiceCollection services, IConfiguration configuration) + { + var settings = RateLimitingSettings.FromConfiguration(configuration); + + if (!settings.Enabled) + { + return services; + } + + return services.AddRateLimiter(options => + { + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.GlobalLimiter = PartitionedRateLimiter.Create(context => + context.Request.Path.StartsWithSegments("/health") + ? RateLimitPartition.GetNoLimiter("health") + : RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions { PermitLimit = settings.PermitLimit, Window = settings.Window })); + options.OnRejected = (context, _) => + { + if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter)) + { + context.HttpContext.Response.Headers.RetryAfter = ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture); + } + + return ValueTask.CompletedTask; + }; + }); + } + + /// + /// Puts the limiter in the pipeline, if it's switched on. + /// + /// The application to add the limiter to. + /// The settings to read RateLimiting from. + /// The application, for chaining. + public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder app, IConfiguration configuration) + { + return RateLimitingSettings.FromConfiguration(configuration).Enabled ? app.UseRateLimiter() : app; + } +} diff --git a/src/Presentation/RateLimiting/RateLimitingSettings.cs b/src/Presentation/RateLimiting/RateLimitingSettings.cs new file mode 100644 index 0000000..3be7628 --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingSettings.cs @@ -0,0 +1,25 @@ +namespace CleanModelContextProtocol.Presentation.RateLimiting; + +using Microsoft.Extensions.Configuration; + +/// +/// The built-in rate limiter's settings: a fixed window per client IP address. Leave at 0 to +/// switch it off, which is the default. +/// +public class RateLimitingSettings +{ + public const string SectionName = "RateLimiting"; + + /// How many requests one client IP address may make in each window. 0 switches the limiter off. + public int PermitLimit { get; init; } + + /// How long each window lasts. One minute unless set. + public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1); + + public bool Enabled => this.PermitLimit > 0 && this.Window > TimeSpan.Zero; + + public static RateLimitingSettings FromConfiguration(IConfiguration configuration) + { + return configuration.GetSection(SectionName).Get() ?? new RateLimitingSettings(); + } +} diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index 00baf7a..a6461b6 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -32,6 +32,12 @@ "AllowAnonymous": false }, "AllowedHosts": "*", + //#if (includeRateLimiting) + "RateLimiting": { + "PermitLimit": 0, + "Window": "00:01:00" + }, + //#endif "Mcp": { "AllowedOrigins": [] }, diff --git a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj index 0d8c5e6..5bd7acd 100644 --- a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj +++ b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj @@ -4,8 +4,8 @@ false true - - $(DefineConstants);includeAuth + + $(DefineConstants);includeAuth;includeRateLimiting diff --git a/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs b/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs new file mode 100644 index 0000000..411b731 --- /dev/null +++ b/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs @@ -0,0 +1,73 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.RateLimiting; + +using System.Net; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class RateLimitingTests +{ + private static readonly Dictionary TwoPerMinute = new() + { + ["RateLimiting:PermitLimit"] = "2", + ["RateLimiting:Window"] = "00:01:00" + }; + + [Fact] + public async Task Request_OverTheLimit_ShouldReturn_TooManyRequestsWithRetryAfter() + { + // Arrange + using var application = new ModelContextProtocolApplication(settings: TwoPerMinute); + using var client = application.CreateClient(); + var path = new Uri("/not-a-real-path", UriKind.Relative); + + // Act + using var first = await client.GetAsync(path); + using var second = await client.GetAsync(path); + using var third = await client.GetAsync(path); + + // Assert + first.StatusCode.ShouldNotBe(HttpStatusCode.TooManyRequests); + second.StatusCode.ShouldNotBe(HttpStatusCode.TooManyRequests); + third.StatusCode.ShouldBe(HttpStatusCode.TooManyRequests); + third.Headers.RetryAfter.ShouldNotBeNull(); + } + + [Fact] + public async Task Health_OverTheLimit_ShouldReturn_Healthy() + { + // Arrange + using var application = new ModelContextProtocolApplication(settings: TwoPerMinute); + using var client = application.CreateClient(); + + for (var i = 0; i < 3; i++) + { + using var _ = await client.GetAsync(new Uri("/not-a-real-path", UriKind.Relative)); + } + + // Act + using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task Request_WithoutALimit_ShouldNotReturn_TooManyRequests() + { + // Arrange + using var application = new ModelContextProtocolApplication(); + using var client = application.CreateClient(); + var statusCodes = new List(); + + // Act + for (var i = 0; i < 5; i++) + { + using var response = await client.GetAsync(new Uri("/not-a-real-path", UriKind.Relative)); + statusCodes.Add(response.StatusCode); + } + + // Assert + statusCodes.ShouldNotContain(HttpStatusCode.TooManyRequests); + } +} diff --git a/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs b/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs new file mode 100644 index 0000000..77c201b --- /dev/null +++ b/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs @@ -0,0 +1,63 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Unit.RateLimiting; + +using Microsoft.Extensions.Configuration; +using Presentation.RateLimiting; +using Shouldly; +using Xunit; + +public class RateLimitingSettingsTests +{ + [Fact] + public void FromConfiguration_ShouldReturn_DisabledSettings_WhenSectionIsMissing() + { + // Arrange + var configuration = new ConfigurationBuilder().Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeFalse(); + result.Window.ShouldBe(TimeSpan.FromMinutes(1)); + } + + [Fact] + public void FromConfiguration_ShouldReturn_EnabledSettings_WhenPermitLimitIsSet() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["RateLimiting:PermitLimit"] = "100", + ["RateLimiting:Window"] = "00:00:10" + }) + .Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeTrue(); + result.PermitLimit.ShouldBe(100); + result.Window.ShouldBe(TimeSpan.FromSeconds(10)); + } + + [Fact] + public void FromConfiguration_ShouldReturn_DisabledSettings_WhenWindowIsZero() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["RateLimiting:PermitLimit"] = "100", + ["RateLimiting:Window"] = "00:00:00" + }) + .Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeFalse(); + } +} From 1ba670a3195fc0c1232bb4a83c7e06873e4c7035 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:29:14 +0000 Subject: [PATCH 09/12] Log a refused Origin --- src/Presentation/Security/OriginCheck.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Presentation/Security/OriginCheck.cs b/src/Presentation/Security/OriginCheck.cs index c20bd20..9dc7471 100644 --- a/src/Presentation/Security/OriginCheck.cs +++ b/src/Presentation/Security/OriginCheck.cs @@ -3,13 +3,15 @@ namespace CleanModelContextProtocol.Presentation.Security; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; /// /// 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 static partial class OriginCheck { public const string SectionName = "Mcp:AllowedOrigins"; @@ -52,8 +54,12 @@ public static IApplicationBuilder UseOriginCheck(this IApplicationBuilder app, P context => context.Request.Path.StartsWithSegments(path), branch => branch.Use(async (context, next) => { - if (!IsAllowed(context.Request.Headers.Origin, allowedOrigins)) + string? origin = context.Request.Headers.Origin; + + if (!IsAllowed(origin, allowedOrigins)) { + // This runs before request logging, so without it a refused browser client leaves no trace. + LogRefused(context.RequestServices.GetRequiredService().CreateLogger(typeof(OriginCheck)), origin); context.Response.StatusCode = StatusCodes.Status403Forbidden; return; } @@ -61,4 +67,7 @@ public static IApplicationBuilder UseOriginCheck(this IApplicationBuilder app, P await next(context); })); } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Refused a request to the MCP endpoint from origin {Origin}, which isn't localhost or in Mcp:AllowedOrigins")] + private static partial void LogRefused(ILogger logger, string? origin); } From 42abad5f6e3a202ba4eb9f69bc47ec8fd4eedfac Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:29:15 +0000 Subject: [PATCH 10/12] Keep development tokens to the Development environment --- .agents/skills/optional-token-auth/SKILL.md | 2 +- .agents/skills/security-defaults/SKILL.md | 3 ++- .agents/skills/time-provider/SKILL.md | 2 +- docs/RUN.md | 4 ++-- .../Extensions/WebApplicationExtensions.cs | 3 +-- src/Presentation/Security/DeploymentGuard.cs | 8 ++++++++ .../Security/DeploymentGuardTests.cs | 20 +++++++++++++++++++ 7 files changed, 35 insertions(+), 7 deletions(-) diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index 93a43d5..72af74a 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -15,7 +15,7 @@ With `--include-auth`, endpoints always ask for authorization. An empty `Authent Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` is true when the authority isn't empty or `dotnet user-jwts` is set up. -For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. +For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, and `DeploymentGuard` refuses to start with that issuer set in any other environment, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`). diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md index db59067..c7917e0 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -26,6 +26,7 @@ The app ships safe by default, and each protection lives in one place in `src/Pr - A deployed environment without authentication throws at startup, unless `Authentication:AllowAnonymous` is `true`. The message names the setting. - In a solution with authentication, a set `Authentication:Authority` must be an absolute `https` URL, in every environment. An empty `Authentication:Audience` already fails closed, because every token is rejected. +- In a solution with authentication, `dotnet user-jwts` development tokens (`Authentication:Schemes:Bearer:ValidIssuer`) set up outside `Development` throw at startup, because they replace the authority. Don't add environment names to `IsLocal` to get a deployment past the guard; set `Authentication:AllowAnonymous` there instead, so the choice is visible in that environment's settings. `tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs` starts the app in each kind of environment. @@ -50,7 +51,7 @@ The MCP spec says a Streamable HTTP server must check the `Origin` header, so a - 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. +To let a web page on another host in, add its origin to `Mcp:AllowedOrigins` in settings; a page on a different origin from the server also needs a CORS policy, which isn't here. A refused origin is logged as a warning, because the check runs before request logging. 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. ## Rate limiting diff --git a/.agents/skills/time-provider/SKILL.md b/.agents/skills/time-provider/SKILL.md index e5f270c..f45016e 100644 --- a/.agents/skills/time-provider/SKILL.md +++ b/.agents/skills/time-provider/SKILL.md @@ -54,7 +54,7 @@ updatedReview.DateModified.ShouldBe(this.database.TimeProvider.GetUtcNow().UtcDa - Store local times. - Assert a date with a tolerance ("within a second of now"). Fix the clock and assert the exact value. -The one exception, in a solution with authentication, is the test that creates a token for the real JWT handler, which checks expiry against the system clock (`tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs`, in the templates that have token authentication). +The one exception, in a solution with authentication, is the tests that create a token for the real JWT handler, which checks expiry against the system clock (`AuthenticationTests.cs` and `DevelopmentTokenTests.cs` in `tests/Presentation.Tests.Integration/Authentication`, in the templates that have token authentication). ## Check diff --git a/docs/RUN.md b/docs/RUN.md index dab789a..18202c9 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -95,7 +95,7 @@ With an authority set, every call needs a token from it. To try the app on your dotnet user-jwts create --project src/Presentation ``` -It prints a token, adds a `UserSecretsId` to the project, keeps the signing key in your user secrets and writes the issuer and audiences into `appsettings.Development.json`. From then on a `dotnet run` accepts its tokens instead of your authority's. Nothing changes anywhere else, because user secrets and that file only load in `Development`. +It prints a token, adds a `UserSecretsId` to the project, keeps the signing key in your user secrets and writes the issuer and audiences into `appsettings.Development.json`. From then on a `dotnet run` accepts its tokens instead of your authority's. Nothing changes anywhere else: user secrets and that file only load in `Development`, and the app refuses to start with development tokens set up in any other environment. If you commit the file, everyone's `dotnet run` switches to development tokens, and each person makes their own with the same command. In the MCP Inspector, put the token in **Authentication**, under **Bearer Token**, before you connect. Run `dotnet user-jwts create` again for a fresh token, and `dotnet user-jwts clear --project src/Presentation` and delete the `Authentication` block from `appsettings.Development.json` to go back to your authority. @@ -106,7 +106,7 @@ The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dot ## 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`. +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 web page on another host call the server, add its origin to `Mcp:AllowedOrigins`, for example `Mcp__AllowedOrigins__0=https://chat.example.com`. A page on a different origin from the server also needs a CORS policy, which the template leaves to you. A refused origin is logged as a warning, so it's easy to see which one to add. ## Rate limiting diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 07a19da..4220e13 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -52,8 +52,7 @@ public static WebApplication ConfigureApplication(this WebApplication app) #if includeRateLimiting #region Rate Limiting - // After the error handlers, so a 429 gets the same body as any other error, and before authentication, so a - // client over its limit is turned away before its token is checked. + // Before authentication, so a client over its limit is turned away before its token is checked. _ = app.UseRateLimiting(app.Configuration); #endregion Rate Limiting diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index fbfb4dd..7d859b9 100644 --- a/src/Presentation/Security/DeploymentGuard.cs +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -37,6 +37,14 @@ public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguratio #if includeAuth var authentication = AuthenticationSettings.FromConfiguration(configuration); + // dotnet user-jwts tokens replace the authority, so they're kept to the one environment they're made for. + if (authentication.UsesDevelopmentTokens && !environment.IsDevelopment()) + { + throw new InvalidOperationException( + "Authentication:Schemes:Bearer:ValidIssuer is set, which switches the app to dotnet user-jwts development tokens. " + + $"They're only for the Development environment, so remove it from the '{environment.EnvironmentName}' environment's settings."); + } + if (authentication.Enabled) { if (!string.IsNullOrWhiteSpace(authentication.Authority) && diff --git a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs index 9a335e3..a8fc227 100644 --- a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs +++ b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs @@ -72,6 +72,26 @@ public async Task DeployedEnvironment_WithAuthority_ShouldStart() response.StatusCode.ShouldBe(HttpStatusCode.OK); } + [Theory] + [InlineData("Production")] + [InlineData("docker")] + public void EnvironmentOtherThanDevelopment_WithDevelopmentTokens_ShouldNotStart(string environment) + { + // Arrange + using var application = new ModelContextProtocolApplication(environment, new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Schemes:Bearer:ValidIssuer"] = "dotnet-user-jwts" + }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("development tokens"); + exception.Message.ShouldContain($"'{environment}' environment"); + } + [Theory] [InlineData("http://login.example.com")] [InlineData("login.example.com")] From db0d951fe4a17b56030aa3d195d327bbf60d48ff Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:30:14 +0000 Subject: [PATCH 11/12] Say what a deployed copy does without authentication --- .template.config/template.json | 2 +- NUGET.md | 2 +- README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.template.config/template.json b/.template.config/template.json index 4a89e7a..7810156 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -78,7 +78,7 @@ "type": "parameter", "datatype": "bool", "displayName": "Include authentication", - "description": "Add OAuth for MCP clients. Leave it off and the server has no auth code at all, which is fine on your machine and brave anywhere else.", + "description": "Add OAuth for MCP clients. Leave it off and the server has no auth code at all, which is fine on your machine. Anywhere else it won't start until you say open is what you want.", "defaultValue": "false" }, "includeRateLimiting": { diff --git a/NUGET.md b/NUGET.md index 68757b7..e1fd272 100644 --- a/NUGET.md +++ b/NUGET.md @@ -51,7 +51,7 @@ dotnet test Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at . It's already pointed at the server at , so flip the switch to connect and open **Tools**. -The server is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then `/mcp` asks for a bearer token and publishes protected resource metadata so clients can sign in. Leave `--include-auth` out and there's no auth code at all. +On your machine the server is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then `/mcp` asks for a bearer token and publishes protected resource metadata so clients can sign in. Leave `--include-auth` out and there's no auth code at all, and a deployed copy refuses to start until you set `Authentication:AllowAnonymous`. ## What's inside diff --git a/README.md b/README.md index 6b8b7db..d0353d3 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ There are six tools shaped around jobs rather than tables: `movies_search`, `mov No Docker? `dotnet run --project src/Presentation` works too. Every other way to run it, from plain `docker run` to stamping a version into the image, is in [docs/RUN.md](docs/RUN.md). -The server is open unless you ask for authentication. Create the solution with `--include-auth --authority https://login.example.com --audience https://mcp.example.com` and `/mcp` asks for a bearer token, and the server publishes [protected resource metadata](https://modelcontextprotocol.io/specification/latest/basic/authorization) so MCP clients can find your authorization server and sign in by themselves. Leave `--include-auth` out and there's no authentication code in the solution at all, so there's nothing to leave switched off by accident. [Securing the server](https://leanmeanclean.dev/mcp/guides/secure-the-server/) has the details, including how to add it later. +On your machine the server is open unless you ask for authentication. Deployed anywhere else without it, the server refuses to start until you set `Authentication:AllowAnonymous`, so nobody ships an open server by accident. Create the solution with `--include-auth --authority https://login.example.com --audience https://mcp.example.com` and `/mcp` asks for a bearer token, and the server publishes [protected resource metadata](https://modelcontextprotocol.io/specification/latest/basic/authorization) so MCP clients can find your authorization server and sign in by themselves. Leave `--include-auth` out and there's no authentication code in the solution at all, so there's nothing to leave switched off by accident. [Securing the server](https://leanmeanclean.dev/mcp/guides/secure-the-server/) has the details, including how to add it later. ## What's inside From 10722793ee7278070b84f98786d19d482c452c82 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sun, 6 Dec 2026 02:57:37 +0000 Subject: [PATCH 12/12] Refuse to start when an authority has no audience An authority without an audience used to reject every token without saying why. The deployment guard now stops at startup and names the setting, and --audience is required with --include-auth. --- .agents/skills/optional-token-auth/SKILL.md | 4 ++-- .agents/skills/security-defaults/SKILL.md | 2 +- .agents/skills/template-authoring/SKILL.md | 4 ++-- .github/workflows/build-pipeline.yml | 9 ++++++--- .template.config/ide.host.json | 4 ++-- .template.config/template.json | 7 ++++--- NUGET.md | 4 ++-- README.md | 2 +- src/Presentation/Security/DeploymentGuard.cs | 8 ++++++++ .../Security/DeploymentGuardTests.cs | 19 +++++++++++++++++++ 10 files changed, 47 insertions(+), 16 deletions(-) diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index 72af74a..65d4b1e 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -9,7 +9,7 @@ metadata: ## The rule -Authentication is a choice made when the solution is created. With `--include-auth`, `--authority` and usually `--audience`, every request needs a valid JWT bearer token from that authority (an OAuth access token in the MCP server), and those options fill in `Authentication:Authority` and `Authentication:Audience`. Without `--include-auth` there's no authentication code at all: no settings, no package, no policy and nothing asking for authorization. If `AuthenticationSettings` isn't in the solution, it was created without `--include-auth`; see "Adding it later". +Authentication is a choice made when the solution is created. With `--include-auth`, `--authority` and `--audience`, every request needs a valid JWT bearer token from that authority (an OAuth access token in the MCP server), and those options fill in `Authentication:Authority` and `Authentication:Audience`. Without `--include-auth` there's no authentication code at all: no settings, no package, no policy and nothing asking for authorization. If `AuthenticationSettings` isn't in the solution, it was created without `--include-auth`; see "Adding it later". With `--include-auth`, endpoints always ask for authorization. An empty `Authentication:Authority` still runs everything open, because the default policy then lets every request through, which is how the tests run unless they set an authority. Only health checks and the API reference (where a template has them) are anonymous. The version endpoint is protected like everything else; telemetry carries `service.version` for anyone who needs to know what's deployed. The Lambda template has no token authentication; API Gateway or the caller's IAM role does that job. @@ -17,7 +17,7 @@ Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, and `DeploymentGuard` refuses to start with that issuer set in any other environment, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. -Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`). +Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL and comes with an audience (`security-defaults`). ## Steps diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md index c7917e0..0d27e73 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -25,7 +25,7 @@ The app ships safe by default, and each protection lives in one place in `src/Pr `DeploymentGuard.EnsureSafeToStart` runs first in the startup, before any service is added. `Development` (`dotnet run`) and `docker` (Docker Compose) are a developer's machine. Every other environment name, including `Production` (the image's default), `uat` or anything a team invents, counts as deployed, so a new name fails closed. - A deployed environment without authentication throws at startup, unless `Authentication:AllowAnonymous` is `true`. The message names the setting. -- In a solution with authentication, a set `Authentication:Authority` must be an absolute `https` URL, in every environment. An empty `Authentication:Audience` already fails closed, because every token is rejected. +- In a solution with authentication, a set `Authentication:Authority` must be an absolute `https` URL and come with an `Authentication:Audience`, in every environment. Without an audience every token would be rejected, so the app stops at startup and says so. - In a solution with authentication, `dotnet user-jwts` development tokens (`Authentication:Schemes:Bearer:ValidIssuer`) set up outside `Development` throw at startup, because they replace the authority. Don't add environment names to `IsLocal` to get a deployment past the guard; set `Authentication:AllowAnonymous` there instead, so the choice is visible in that environment's settings. `tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs` starts the app in each kind of environment. diff --git a/.agents/skills/template-authoring/SKILL.md b/.agents/skills/template-authoring/SKILL.md index 7ca5234..32dbdc3 100644 --- a/.agents/skills/template-authoring/SKILL.md +++ b/.agents/skills/template-authoring/SKILL.md @@ -14,7 +14,7 @@ The repository is both a working solution and a `dotnet new` template. `.templat | Symbol | Option | Replaces | | --- | --- | --- | | `authorName` | `--authorName`
`-an` | `Stephen Walsh` (`--author` is reserved by `dotnet new`) | -| `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and `authority` becomes required through `isRequired` (web templates) | +| `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and both become required through `isRequired` (web templates) | | `includeRateLimiting` | `--include-rate-limiting` | Nothing. A toggle, off by default. Off, the `RateLimiting` folders and every line that wires them in are left out; on, the limiter is still off until `RateLimiting:PermitLimit` is set (web templates) | | `authority` | `--authority`
`-iss` | The empty `Authentication:Authority` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `audience` | `--audience`
`-aud` | The empty `Authentication:Audience` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | @@ -74,7 +74,7 @@ The README and `NUGET.md` name the aliases under the install commands, and the d dotnet new uninstall ./ ``` - With `--include-auth`, also create one with `--include-auth --authority https://login.example.com --output ../Secured` and test that. Leave the authority out and `dotnet new` should stop with exit code 102. + With `--include-auth`, also create one with `--include-auth --authority https://login.example.com --audience https://api.example.com --output ../Secured` and test that. Leave the authority or the audience out and `dotnet new` should stop with exit code 102. `--help` shows the short flags and descriptions. Creating the solution should end with `Restoring .../Sample.slnx` and `Restore succeeded`, which is the post action at work; `--no-restore` should skip it. diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index 0b51ed3..ba047af 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -326,16 +326,19 @@ jobs: fi # Templates with an auth option are verified again with every toggle on, and --include-auth without - # --authority has to stop before anything is written (exit code 102, a missing mandatory option). + # --authority or --audience has to stop before anything is written (exit code 102, a missing mandatory option). if jq -e '.symbols.includeAuth' .template.config/template.json > /dev/null; then verify Template.Authentication --include-auth --authority https://login.example.com --audience https://api.example.com "${ALL_ON[@]}" jq -e '.options.authentication.Authority == "https://login.example.com"' Template.Authentication/.lmca.json set +e - dotnet new "$SHORT_NAME" --name Template.NoAuthority --output Template.NoAuthority --include-auth + dotnet new "$SHORT_NAME" --name Template.NoAuthority --output Template.NoAuthority --include-auth --audience https://api.example.com NO_AUTHORITY=$? + dotnet new "$SHORT_NAME" --name Template.NoAudience --output Template.NoAudience --include-auth --authority https://login.example.com + NO_AUDIENCE=$? set -e test "$NO_AUTHORITY" -eq 102 || { echo "::error::--include-auth without --authority exited $NO_AUTHORITY, not 102"; exit 1; } - VARIANTS="$VARIANTS, with every toggle on, and --include-auth without --authority is refused" + test "$NO_AUDIENCE" -eq 102 || { echo "::error::--include-auth without --audience exited $NO_AUDIENCE, not 102"; exit 1; } + VARIANTS="$VARIANTS, with every toggle on, and --include-auth without --authority or --audience is refused" fi echo "### Template" >> "$GITHUB_STEP_SUMMARY" diff --git a/.template.config/ide.host.json b/.template.config/ide.host.json index 6a5f1f9..011624b 100644 --- a/.template.config/ide.host.json +++ b/.template.config/ide.host.json @@ -64,10 +64,10 @@ { "id": "audience", "name": { - "text": "Authentication audience (optional)" + "text": "Authentication audience" }, "description": { - "text": "Who the tokens are for, usually the server's own URL. Only used when Include authentication is ticked." + "text": "Who the tokens are for, usually the server's own URL. Only used when Include authentication is ticked, and needed then." }, "isVisible": true } diff --git a/.template.config/template.json b/.template.config/template.json index 7810156..3b4e4ff 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -100,10 +100,11 @@ "audience": { "type": "parameter", "datatype": "string", - "displayName": "Authentication audience (optional)", - "description": "The audience access tokens must be issued for, usually the server's own URL. Not the people in the room, who are lovely but don't carry tokens.", + "displayName": "Authentication audience", + "description": "The audience access tokens must be issued for, usually the server's own URL. Not the people in the room, who are lovely but don't carry tokens. Required with --include-auth.", "defaultValue": "", - "isEnabled": "includeAuth" + "isEnabled": "includeAuth", + "isRequired": "includeAuth" }, "skipRestore": { "type": "parameter", diff --git a/NUGET.md b/NUGET.md index e1fd272..b628ce2 100644 --- a/NUGET.md +++ b/NUGET.md @@ -34,7 +34,7 @@ cd WorksOnMyMachine.Movies | `--include-auth` | | Off | Adds OAuth for MCP clients. Leave it out and the server has no auth code at all | | `--include-rate-limiting` | | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority` | `-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | -| `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Only used with `--include-auth` | +| `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Required with `--include-auth` | | `--no-restore` | | Off | Skips the package restore that normally runs once the solution is created | Rather click than type? Visual Studio and Rider show the same options in their new project dialogs. They always show the authority and audience fields, but only use them when **Include authentication** is ticked. In the terminal, `dotnet new cleanmodelcontextprotocol --help` lists them all. @@ -51,7 +51,7 @@ dotnet test Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at . It's already pointed at the server at , so flip the switch to connect and open **Tools**. -On your machine the server is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then `/mcp` asks for a bearer token and publishes protected resource metadata so clients can sign in. Leave `--include-auth` out and there's no auth code at all, and a deployed copy refuses to start until you set `Authentication:AllowAnonymous`. +On your machine the server is open unless you create it with `--include-auth`, `--authority` and `--audience`, and then `/mcp` asks for a bearer token and publishes protected resource metadata so clients can sign in. Leave `--include-auth` out and there's no auth code at all, and a deployed copy refuses to start until you set `Authentication:AllowAnonymous`. ## What's inside diff --git a/README.md b/README.md index d0353d3..d580ddc 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ cd WorksOnMyMachine.Movies | `--include-auth` | Off | Adds OAuth for MCP clients. Leave it out and the server has no auth code at all | | `--include-rate-limiting` | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority`
`-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | -| `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Only used with `--include-auth` | +| `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the server's own URL. Required with `--include-auth` | | `--no-restore` | Off | Skips the package restore that normally runs once the solution is created | Rather click than type? Visual Studio and Rider show the same options in their new project dialogs. They always show the authority and audience fields, but only use them when **Include authentication** is ticked. In the terminal, `dotnet new cleanmodelcontextprotocol --help` lists them all. diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index 7d859b9..9f0dafd 100644 --- a/src/Presentation/Security/DeploymentGuard.cs +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -54,6 +54,14 @@ public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguratio $"Authentication:Authority must be an absolute https URL, such as https://login.example.com, not '{authentication.Authority}'."); } + // An authority's tokens are checked against the audience, so without one every token would be rejected. + if (authentication.HasAuthority && string.IsNullOrWhiteSpace(authentication.Audience)) + { + throw new InvalidOperationException( + "Authentication:Authority is set without Authentication:Audience, so every token would be rejected. " + + "Set Authentication:Audience to the audience your tokens are issued for, usually this app's own URL."); + } + return; } diff --git a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs index a8fc227..50e6232 100644 --- a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs +++ b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs @@ -72,6 +72,25 @@ public async Task DeployedEnvironment_WithAuthority_ShouldStart() response.StatusCode.ShouldBe(HttpStatusCode.OK); } + [Theory] + [InlineData("Development")] + [InlineData("Production")] + public void AnyEnvironment_WithAuthorityButNoAudience_ShouldNotStart(string environment) + { + // Arrange + using var application = new ModelContextProtocolApplication(environment, new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Audience"] = string.Empty + }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("Authentication:Authority is set without Authentication:Audience"); + } + [Theory] [InlineData("Production")] [InlineData("docker")]