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 66adfed..eb82cc6 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -363,6 +363,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 +}