From ff796527b43cb36dfb9e67e4600624221c38f77f Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:43:16 +0000 Subject: [PATCH] Send security headers on every response --- .agents/skills/security-defaults/SKILL.md | 41 +++++++++++++++++++ AGENTS.md | 1 + .../Extensions/WebApplicationExtensions.cs | 3 ++ src/Presentation/Security/SecurityHeaders.cs | 34 +++++++++++++++ .../Security/SecurityHeadersTests.cs | 41 +++++++++++++++++++ 5 files changed, 120 insertions(+) create mode 100644 .agents/skills/security-defaults/SKILL.md create mode 100644 src/Presentation/Security/SecurityHeaders.cs create mode 100644 tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md new file mode 100644 index 00000000..0248efe8 --- /dev/null +++ b/.agents/skills/security-defaults/SKILL.md @@ -0,0 +1,41 @@ +--- +name: security-defaults +description: What this Minimal 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 (Minimal 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 `WebApplicationExtensions.ConfigureApplication`. Keep that shape: a new protection gets its own small class there and a line in that region, never a check scattered across endpoints. + +| Protection | Where | Default | +| --- | --- | --- | +| Security response headers | `SecurityHeaders` | Always on | +| HSTS and HTTPS redirection | Security region | HSTS outside local runs | +| Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | + +## Security headers + +`UseSecurityHeaders` adds three headers to every response, errors and health checks included: + +| Header | Value | Why | +| --- | --- | --- | +| `X-Content-Type-Options` | `nosniff` | Browsers use the declared content type instead of guessing | +| `X-Frame-Options` | `DENY` | No other site can show the app in a frame | +| `Referrer-Policy` | `no-referrer` | Links out of the app don't leak its URLs | + +There's no `Content-Security-Policy` on purpose. 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:7310/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 35e05481..227fc44d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,7 @@ These are for this Minimal API's presentation layer. The other templates have th | `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/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index c9614ebe..19203f46 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -10,6 +10,7 @@ namespace CleanMinimalApi.Presentation.Extensions; using Presentation.Authentication; #endif using Presentation.Endpoints; +using Presentation.Security; using Scalar.AspNetCore; using Serilog; @@ -26,6 +27,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 00000000..fb50887d --- /dev/null +++ b/src/Presentation/Security/SecurityHeaders.cs @@ -0,0 +1,34 @@ +namespace CleanMinimalApi.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 00000000..883c0332 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs @@ -0,0 +1,41 @@ +namespace CleanMinimalApi.Presentation.Tests.Integration.Security; + +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class SecurityHeadersTests : IDisposable +{ + private readonly MinimalApiApplication 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(); + } + } +}