From a8641c9b0cc0c9ccd8d06c8fc06b10aa05b31387 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/10] 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 6d3b523..b2b54e5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: VERSION_PREFIX: 1.0.0.0 VERSION_SUFFIX: docker ports: - - "7340:7340" + - "127.0.0.1:7340:7340" environment: DOTNET_ENVIRONMENT: docker OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317 @@ -23,8 +23,8 @@ services: volumes: - ./otel-collector.yaml:/etc/otelcol/config.yaml:ro ports: - - "7343:4317" - - "7344:4318" + - "127.0.0.1:7343:4317" + - "127.0.0.1:7344:4318" networks: - cleanwebapi_network depends_on: @@ -32,7 +32,7 @@ services: aspire-dashboard: image: mcr.microsoft.com/dotnet/aspire-dashboard:13.6.5 ports: - - "7342:18888" + - "127.0.0.1:7342:18888" environment: ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS: "true" networks: From 75821897ce71ee210467303e18f248a82bc556f4 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:38:32 +0000 Subject: [PATCH 02/10] Read the telemetry service.version from VersionInfo --- .agents/skills/telemetry/SKILL.md | 2 +- .../Extensions/ProgramExtensions.cs | 10 +++++----- .../Telemetry/TelemetrySettings.cs | 8 ++++---- .../Telemetry/TelemetrySettingsTests.cs | 19 +++++++++---------- 4 files changed, 19 insertions(+), 20 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/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 93a624c..30ab5bd 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -1,7 +1,6 @@ namespace CleanWebApi.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using Application; using Application.Common.Telemetry; using Application.Versions.Entities; @@ -44,7 +43,8 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder #region Telemetry var assembly = typeof(ProgramExtensions).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)) @@ -88,10 +88,10 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder _ = 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) @@ -173,7 +173,7 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews")); _ = builder.Services.AddApplication(); - _ = builder.Services.AddSingleton(VersionInfo.FromAssembly(typeof(ProgramExtensions).Assembly)); + _ = builder.Services.AddSingleton(version); _ = builder.Services.AddHealthChecks().AddInfrastructureHealthChecks("ready"); #endregion Project Dependencies diff --git a/src/Presentation/Telemetry/TelemetrySettings.cs b/src/Presentation/Telemetry/TelemetrySettings.cs index 7616bed..a1f6b08 100644 --- a/src/Presentation/Telemetry/TelemetrySettings.cs +++ b/src/Presentation/Telemetry/TelemetrySettings.cs @@ -1,6 +1,6 @@ namespace CleanWebApi.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 68b681b..13e9e89 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -1,7 +1,6 @@ namespace CleanWebApi.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 ffff1f97d19928e6b4a006c8a910a30dd068019a Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:43:22 +0000 Subject: [PATCH 03/10] Send security headers on every response --- .agents/skills/security-defaults/SKILL.md | 41 +++++++++++++++++++ AGENTS.md | 1 + .../Extensions/ProgramExtensions.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..52137dd --- /dev/null +++ b/.agents/skills/security-defaults/SKILL.md @@ -0,0 +1,41 @@ +--- +name: security-defaults +description: What this Web API 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 (Web API) + +## 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 `ProgramExtensions`. 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. Scalar is served from the same app and needs scripts, styles and frames of its own, so a strict policy would break it. 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:7340/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 c36d74f..52299be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,7 @@ These are for this Web API's presentation layer. The other templates have their | `json-serialization` | Add a request or response type, or change how JSON looks | | `openapi-and-scalar` | Change the API description, security scheme or Scalar | | `presentation-integration-tests` | Write a test that makes a real HTTP request | +| `security-defaults` | Add a response header or other protection, or check what the app does to stay safe | These are for working on the template repository itself, and they aren't included in solutions created with `dotnet new`: diff --git a/src/Presentation/Extensions/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 30ab5bd..6a59bbb 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -25,6 +25,7 @@ namespace CleanWebApi.Presentation.Extensions; using OpenTelemetry.Resources; using OpenTelemetry.Trace; using Scalar.AspNetCore; +using Security; using Serialization; using Serilog; using Telemetry; @@ -191,6 +192,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..d01fb1e --- /dev/null +++ b/src/Presentation/Security/SecurityHeaders.cs @@ -0,0 +1,34 @@ +namespace CleanWebApi.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..16410b6 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs @@ -0,0 +1,41 @@ +namespace CleanWebApi.Presentation.Tests.Integration.Security; + +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class SecurityHeadersTests : IDisposable +{ + private readonly WebApiApplication 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 975fc162cc9be8267135b8f8e9130b498d49700c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:01:30 +0000 Subject: [PATCH 04/10] 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/ProgramExtensions.cs | 4 ++-- src/Presentation/Presentation.http | 2 +- src/Presentation/Properties/launchSettings.json | 2 +- src/Presentation/Telemetry/TelemetrySettings.cs | 2 +- ...{appsettings.local.json => appsettings.Development.json} | 2 +- tests/Presentation.Tests.Integration/WebApiApplication.cs | 2 +- .../Telemetry/TelemetrySettingsTests.cs | 6 +++--- 12 files changed, 20 insertions(+), 20 deletions(-) rename src/Presentation/{appsettings.local.json => appsettings.Development.json} (87%) 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 be7ac5c..c750177 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` makes real HTTP requests to the whole application in memory. `WebApiApplication` (a `WebApplicationFactory`) starts the app with the `local` environment, its own shared-cache in-memory SQLite database and the sample data on, so tests never touch a file or each other. +`tests/Presentation.Tests.Integration` makes real HTTP requests to the whole application in memory. `WebApiApplication` (a `WebApplicationFactory`) starts the app with the `Development` environment, its own shared-cache in-memory SQLite database and the sample data on, so tests never touch a file or each other. Each test class creates one `WebApiApplication` in its constructor and disposes it. The constructor takes three optional arguments: 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 b383ba2..3f72924 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 9d72ea0..d890193 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -1,10 +1,10 @@ # Running Clean Web API -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: @@ -75,7 +75,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. ## Tests diff --git a/src/Presentation/Extensions/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 6a59bbb..24a5901 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -194,8 +194,8 @@ public static WebApplication ConfigureApplication(this WebApplication app) _ = 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")) + // 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/Presentation.http b/src/Presentation/Presentation.http index d2ed997..501180f 100644 --- a/src/Presentation/Presentation.http +++ b/src/Presentation/Presentation.http @@ -2,7 +2,7 @@ @host = https://localhost:7341 # @host = http://localhost:7340 -# Sample data ids from the fixed local and docker seed. +# Sample data ids from the fixed Development and docker seed. @movieId = cb188ef6-14e7-f85f-2f78-924c2ab26b28 @authorId = 01fa8b58-05d2-abd4-e55c-2633222dd0a5 @reviewId = 45911e6f-a366-417b-1453-f34097338ee2 diff --git a/src/Presentation/Properties/launchSettings.json b/src/Presentation/Properties/launchSettings.json index 2e5ef63..8b411b1 100644 --- a/src/Presentation/Properties/launchSettings.json +++ b/src/Presentation/Properties/launchSettings.json @@ -8,7 +8,7 @@ "launchUrl": "scalar", "applicationUrl": "https://localhost:7341;http://localhost:7340", "environmentVariables": { - "DOTNET_ENVIRONMENT": "local" + "DOTNET_ENVIRONMENT": "Development" } } } diff --git a/src/Presentation/Telemetry/TelemetrySettings.cs b/src/Presentation/Telemetry/TelemetrySettings.cs index a1f6b08..7c23bcb 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 87% rename from src/Presentation/appsettings.local.json rename to src/Presentation/appsettings.Development.json index 725216e..64287f9 100644 --- a/src/Presentation/appsettings.local.json +++ b/src/Presentation/appsettings.Development.json @@ -12,7 +12,7 @@ } ], "Properties": { - "ApplicationName": "CleanWebApi-Local" + "ApplicationName": "CleanWebApi-Development" } }, "Database": { diff --git a/tests/Presentation.Tests.Integration/WebApiApplication.cs b/tests/Presentation.Tests.Integration/WebApiApplication.cs index 19f49af..8723654 100644 --- a/tests/Presentation.Tests.Integration/WebApiApplication.cs +++ b/tests/Presentation.Tests.Integration/WebApiApplication.cs @@ -6,7 +6,7 @@ namespace CleanWebApi.Presentation.Tests.Integration; using Microsoft.Extensions.Hosting; internal sealed class WebApiApplication( - 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 13e9e89..c84dde5 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 d3f02039e296bc96ab3f96d330177db82c2fa7ba Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:07:56 +0000 Subject: [PATCH 05/10] 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 +- .../Extensions/ProgramExtensions.cs | 3 + src/Presentation/Security/DeploymentGuard.cs | 67 ++++++++++++++ src/Presentation/appsettings.json | 7 +- .../Security/DeploymentGuardTests.cs | 90 +++++++++++++++++++ 10 files changed, 183 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 52137dd..20d1b9f 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 Web API 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 Web API does to be safe by default - the startup guard for deployed environments, 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 --- @@ -13,10 +13,20 @@ 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 | | 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 8359fa2..3799f56 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 7340:7340 \ + --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 f503234..f7566be 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 d890193..1593daf 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -1,6 +1,6 @@ # Running Clean Web API -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/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 24a5901..201e9a6 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -35,6 +35,9 @@ public static class ProgramExtensions { public static WebApplicationBuilder ConfigureBuilder(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 Controllers _ = builder.Services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.UseApiDefaults()); diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs new file mode 100644 index 0000000..f34f82d --- /dev/null +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -0,0 +1,67 @@ +namespace CleanWebApi.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 3a03d2c..02b26e0 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -23,12 +23,13 @@ "ConnectionStrings": { "MovieReviews": "Data Source=movie-reviews.db" }, - //#if (includeAuth) "Authentication": { + //#if (includeAuth) "Authority": "", - "Audience": "" + "Audience": "", + //#endif + "AllowAnonymous": false }, - //#endif "AllowedHosts": "*", "Database": { "SeedSampleData": false diff --git a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs new file mode 100644 index 0000000..ef07694 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs @@ -0,0 +1,90 @@ +namespace CleanWebApi.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 WebApiApplication(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 WebApiApplication(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 WebApiApplication("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 WebApiApplication("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 WebApiApplication(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 c40cdad564d6aec01c6ee4549ec4a64719d3c131 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:22:02 +0000 Subject: [PATCH 06/10] Accept dotnet user-jwts tokens in Development --- .agents/skills/openapi-and-scalar/SKILL.md | 2 +- .agents/skills/optional-token-auth/SKILL.md | 4 +- docs/RUN.md | 14 +++ .../Authentication/AuthenticationSettings.cs | 23 ++++- .../Extensions/ProgramExtensions.cs | 4 +- src/Presentation/Security/DeploymentGuard.cs | 3 +- .../Authentication/DevelopmentTokenTests.cs | 97 +++++++++++++++++++ .../AuthenticationSettingsTests.cs | 22 +++++ 8 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs diff --git a/.agents/skills/openapi-and-scalar/SKILL.md b/.agents/skills/openapi-and-scalar/SKILL.md index b352695..893eeb2 100644 --- a/.agents/skills/openapi-and-scalar/SKILL.md +++ b/.agents/skills/openapi-and-scalar/SKILL.md @@ -14,7 +14,7 @@ The OpenAPI document is generated at runtime by `Microsoft.AspNetCore.OpenApi` a | Transformer | Adds | | --- | --- | | `DocumentInfoTransformer` | Title (with the environment name), description, contact, licence, external docs and the tag descriptions | -| `BearerSecurityTransformer` | Only in a solution with authentication, and only when `Authentication:Authority` is set: the `Bearer` security scheme, a security requirement and a `401` response on every operation that needs a token | +| `BearerSecurityTransformer` | Only in a solution with authentication, and only when `Authentication:Authority` or `dotnet user-jwts` is set up: the `Bearer` security scheme, a security requirement and a `401` response on every operation that needs a token | Scalar is set up in `ProgramExtensions.ConfigureApplication` with the title, C# `HttpClient` as the default code sample, and its developer tools, agent, MCP and telemetry features turned off. 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 1593daf..8a85c9b 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -73,6 +73,20 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7343 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 Scalar at , open **Authentication**, choose the `Bearer` scheme and paste the token. In `Presentation.http`, set `@token` and uncomment the `Authorization` lines. 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 953f412..caad9e8 100644 --- a/src/Presentation/Authentication/AuthenticationSettings.cs +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -15,10 +15,29 @@ public class AuthenticationSettings /// The audience access tokens must be issued for. This is usually the API's own URL. public string? Audience { 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/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 201e9a6..72de9e2 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -149,7 +149,9 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder .AddAuthentication(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; }); diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index f34f82d..89e3834 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..0fda0ff --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs @@ -0,0 +1,97 @@ +namespace CleanWebApi.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 WebApiApplication 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 Request_WithoutToken_ShouldReturn_Unauthorized() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Request_WithDevelopmentToken_ShouldReturn_Ok() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(KeyBytes)); + + // Act + using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task Request_WithTokenSignedByAnotherKey_ShouldReturn_Unauthorized() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(Encoding.UTF8.GetBytes("someone-elses-signing-key-that-is-long-enough"))); + + // Act + using var response = await client.GetAsync(new Uri("/api/movies", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(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 c5674f2..5def158 100644 --- a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -40,4 +40,26 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet() result.Authority.ShouldBe("https://login.example.com"); result.Audience.ShouldBe("https://api.example.com"); } + + [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 a4bbb46bc839bde1c9fa7362a89f9f6cb14d1fb5 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:46:52 +0000 Subject: [PATCH 07/10] 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 ++ .../Extensions/ProgramExtensions.cs | 21 ++++++ 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 ++++++++++++++++ 18 files changed, 326 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 20d1b9f..87a53b4 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 Web API does to be safe by default - the startup guard for deployed environments, 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 Web API does to be safe by default - the startup guard for deployed environments, the security response headers, optional rate limiting and where the other protections live. Use when adding a response header, turning on or tuning rate limiting, changing security middleware, or asked whether the app is safe to deploy. metadata: scope: presentation --- @@ -15,6 +15,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 | +| 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 | @@ -39,6 +40,24 @@ Don't add environment names to `IsLocal` to get a deployment past the guard; set There's no `Content-Security-Policy` on purpose. Scalar is served from the same app and needs scripts, styles and frames of its own, so a strict policy would break it. The headers are set in `Response.OnStarting`, because the exception handler clears headers set before it runs. +## Rate limiting + +A solution created with `--include-rate-limiting` has a fixed window limiter in `src/Presentation/RateLimiting/`, wired in by `ProgramExtensions`. 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 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 3799f56..0da8254 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 625d2ca..e6f9d78 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 7662fcd..20f7d90 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -56,6 +56,14 @@ "tests/Presentation.Tests.Unit/OpenApi/BearerSecurityTransformerTests.cs", "tests/Presentation.Tests.Integration/Authentication/**" ] + }, + { + "condition": "(!includeRateLimiting)", + "exclude": [ + "src/Presentation/RateLimiting/**", + "tests/Presentation.Tests.Unit/RateLimiting/**", + "tests/Presentation.Tests.Integration/RateLimiting/**" + ] } ] } @@ -102,6 +110,13 @@ "description": "Add JWT bearer token authentication. Leave it off and the API 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 c0635ab..f4f0e9a 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 JWT bearer token authentication. Leave it out and the API 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 API'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 105fb01..25f9dad 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 JWT bearer token authentication. Leave it out and the API 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 API'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 8a85c9b..eee58e9 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -91,6 +91,12 @@ In Scalar at , open **Authentication**, choose th 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. + +## 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/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index 72de9e2..da40376 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -24,6 +24,9 @@ namespace CleanWebApi.Presentation.Extensions; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using OpenTelemetry.Trace; +#if includeRateLimiting +using RateLimiting; +#endif using Scalar.AspNetCore; using Security; using Serialization; @@ -174,6 +177,14 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder #endregion Errors +#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); @@ -223,6 +234,16 @@ public static WebApplication ConfigureApplication(this WebApplication app) #endregion Errors +#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 0d11787..5431ec0 100644 --- a/src/Presentation/Presentation.csproj +++ b/src/Presentation/Presentation.csproj @@ -11,8 +11,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..8bac0ed --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingExtensions.cs @@ -0,0 +1,62 @@ +namespace CleanWebApi.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..a315495 --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingSettings.cs @@ -0,0 +1,25 @@ +namespace CleanWebApi.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 02b26e0..4d99c0f 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -31,6 +31,12 @@ "AllowAnonymous": false }, "AllowedHosts": "*", + //#if (includeRateLimiting) + "RateLimiting": { + "PermitLimit": 0, + "Window": "00:01:00" + }, + //#endif "Database": { "SeedSampleData": false } 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..0e285a3 --- /dev/null +++ b/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs @@ -0,0 +1,73 @@ +namespace CleanWebApi.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 WebApiApplication(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 WebApiApplication(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 WebApiApplication(); + 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..3b09404 --- /dev/null +++ b/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs @@ -0,0 +1,63 @@ +namespace CleanWebApi.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 2720055673a536b7f064dec94170502e39831ee5 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 08/10] Keep development tokens to the Development environment --- .agents/skills/optional-token-auth/SKILL.md | 2 +- .agents/skills/security-defaults/SKILL.md | 1 + .agents/skills/time-provider/SKILL.md | 2 +- docs/RUN.md | 2 +- src/Presentation/Security/DeploymentGuard.cs | 8 ++++++++ .../Security/DeploymentGuardTests.cs | 20 +++++++++++++++++++ 6 files changed, 32 insertions(+), 3 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 87a53b4..f6343aa 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -25,6 +25,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. 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 eee58e9..001997d 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -82,7 +82,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 Scalar at , open **Authentication**, choose the `Bearer` scheme and paste the token. In `Presentation.http`, set `@token` and uncomment the `Authorization` lines. 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. diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index 89e3834..89a477d 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 ef07694..1387400 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 WebApiApplication(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 727a48c43a9f1db91d6e67ceaef81c02229eeb51 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:30:18 +0000 Subject: [PATCH 09/10] 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 20f7d90..4e261df 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -107,7 +107,7 @@ "type": "parameter", "datatype": "bool", "displayName": "Include authentication", - "description": "Add JWT bearer token authentication. Leave it off and the API has no auth code at all, which is fine on your machine and brave anywhere else.", + "description": "Add JWT bearer token authentication. Leave it off and the API 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 f4f0e9a..ac8edbe 100644 --- a/NUGET.md +++ b/NUGET.md @@ -54,7 +54,7 @@ dotnet test Then open [Scalar](https://github.com/scalar/scalar) at to browse and try every endpoint. -The API is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then it asks for a JWT bearer token. Leave `--include-auth` out and there's no auth code at all. +On your machine the API is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then it asks for a JWT bearer token. 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 4efd2b5..4bd43dd 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ Open [Scalar](https://github.com/scalar/scalar) at Date: Sun, 6 Dec 2026 02:57:42 +0000 Subject: [PATCH 10/10] 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 f6343aa..5e28db0 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -24,7 +24,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 5a2d875..bbe0ad1 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 e6f9d78..5eab83f 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 API's own URL. Only used when Include authentication is ticked." + "text": "Who the tokens are for, usually the API'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 4e261df..2feb297 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -129,10 +129,11 @@ "audience": { "type": "parameter", "datatype": "string", - "displayName": "Authentication audience (optional)", - "description": "The audience access tokens must be issued for, usually the API'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 API'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 ac8edbe..c23771f 100644 --- a/NUGET.md +++ b/NUGET.md @@ -34,7 +34,7 @@ cd WorksOnMyMachine.Movies | `--include-auth` | | Off | Adds JWT bearer token authentication. Leave it out and the API 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 API's own URL. Only used with `--include-auth` | +| `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the API'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 cleanwebapi --help` lists them all. @@ -54,7 +54,7 @@ dotnet test Then open [Scalar](https://github.com/scalar/scalar) at to browse and try every endpoint. -On your machine the API is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then it asks for a JWT bearer token. 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 API is open unless you create it with `--include-auth`, `--authority` and `--audience`, and then it asks for a JWT bearer token. 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 4bd43dd..f60f467 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ cd WorksOnMyMachine.Movies | `--include-auth` | Off | Adds JWT bearer token authentication. Leave it out and the API 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 API's own URL. Only used with `--include-auth` | +| `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the API'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 cleanwebapi --help` lists them all. diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs index 89a477d..fe618f0 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 1387400..dedc755 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 WebApiApplication(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")]