Sends the security headers from the application instead of the proxy
U3. These headers normally come from nginx, but the deployment target does
not allow server configuration, so the application emits them itself. That
changes the failure mode: a bad nginx config fails loudly at reload, while a
middleware that never runs sends nothing and says nothing.
Two policies, defined in code. Strict for /admin, /api/v1 and /health;
relaxed for the public website, which is authored elsewhere by someone who
has never seen this policy. Configuration decides where a policy applies and
which external origins are permitted; it cannot invent a policy that is
subtly permissive.
script-src 'self' under Strict has no 'unsafe-inline' and no 'unsafe-eval',
asserted by a test so that loosening it means deleting a test that says why.
style-src does carry 'unsafe-inline' and cannot not: Radix positions its
overlays with inline style attributes, which nonces cannot reach at all.
Two traps handled explicitly. StartsWithSegments rather than string
StartsWith, because "/administrator".StartsWith("/admin") is true and a
public page would silently lose its inline scripts with no server-side trace.
And all decision logic sits in a static writer rather than in the middleware,
because DefaultHttpContext.Response.OnStarting is a no-op — the obvious
middleware test observes nothing and an assertion that nothing was written
passes for entirely the wrong reason.
An unknown policy name fails ValidateOnStart, so the process exits rather
than quietly serving /admin under the relaxed policy. Origin format is
validated too, beyond what the design asked: a CSP source list silently
ignores a malformed source, so a URL with a path would look configured and
block the script anyway.
BR-U3-22's Umami startup warning is withdrawn (REF-U3-01) — the backend
never sees VITE_UMAMI_WEBSITE_ID. It becomes a blocking CI gate in U5.
Build 0 errors; 315 tests pass, up from 253.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHoJpxYXzHACSQguHrC5fw
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class SecurityHeadersExtensions
|
||||
{
|
||||
public static IServiceCollection AddCmsSecurityHeaders(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<SecurityHeadersOptions>()
|
||||
.Bind(configuration.GetSection(SecurityHeadersOptions.SectionName))
|
||||
.Validate(
|
||||
options => options.PathPolicies.All(rule => CspPolicyCatalog.IsKnownPolicy(rule.Policy)),
|
||||
$"SecurityHeaders:PathPolicies contains an unknown policy name. Known policies: {string.Join(", ", CspPolicyCatalog.KnownPolicies)}.")
|
||||
.Validate(
|
||||
options => CspPolicyCatalog.IsKnownPolicy(options.DefaultPolicy),
|
||||
$"SecurityHeaders:DefaultPolicy is not a known policy. Known policies: {string.Join(", ", CspPolicyCatalog.KnownPolicies)}.")
|
||||
.Validate(
|
||||
options => options.AllowedScriptOrigins.Concat(options.AllowedConnectOrigins).All(IsOrigin),
|
||||
"SecurityHeaders origins must be absolute scheme-and-host values without a path, e.g. https://analytics.example.com.")
|
||||
// ValidateOnStart, not a constructor check: options resolve lazily, so without this
|
||||
// a typo in PathPolicies is discovered when the first request arrives — by which
|
||||
// time the deployment has been reported successful and /health is green. This
|
||||
// registers a startup validator, so the process exits non-zero instead and the
|
||||
// release switch is visibly broken. Fail closed (SECURITY-15): any fallback would
|
||||
// be either wrong or silently permissive.
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddSingleton<ICspPolicyProvider, CspPolicyProvider>();
|
||||
services.AddSingleton<PathPolicyResolver>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the security headers middleware.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Position matters in both directions.</b> Call this first inside
|
||||
/// <c>UseExceptionHandler()</c>: the exception handler re-executes the pipeline from inside
|
||||
/// itself, so middleware registered outside it never observes the ProblemDetails response.
|
||||
/// And call it BEFORE <c>UseCmsStaticContent()</c>, because static-file middleware
|
||||
/// terminates the request — anything after it is invisible to the public website, which is
|
||||
/// almost all of the HTML this host serves.
|
||||
/// </remarks>
|
||||
public static IApplicationBuilder UseCmsSecurityHeaders(this IApplicationBuilder app)
|
||||
{
|
||||
var options = app.ApplicationServices.GetRequiredService<IOptions<SecurityHeadersOptions>>().Value;
|
||||
var logger = app.ApplicationServices
|
||||
.GetRequiredService<ILoggerFactory>()
|
||||
.CreateLogger(typeof(SecurityHeadersExtensions).FullName!);
|
||||
|
||||
if (!options.Enabled)
|
||||
{
|
||||
// A diagnostic escape hatch is worth having, but silently disabled security headers
|
||||
// are worse than none at all, so switching them off announces itself.
|
||||
logger.LogWarning(
|
||||
"HTTP security headers are DISABLED by configuration (SecurityHeaders:Enabled = false). " +
|
||||
"No CSP, HSTS, nosniff, frame or referrer headers will be sent.");
|
||||
return app;
|
||||
}
|
||||
|
||||
// Records what was actually permitted, so the log answers the question later rather
|
||||
// than requiring someone to reconstruct it from the deployed appsettings.
|
||||
logger.LogInformation(
|
||||
"HTTP security headers enabled. Default policy: {DefaultPolicy}. Path policies: {PathPolicies}. " +
|
||||
"Allowed script origins: {ScriptOrigins}. Allowed connect origins: {ConnectOrigins}.",
|
||||
options.DefaultPolicy,
|
||||
string.Join(", ", options.PathPolicies.Select(rule => $"{rule.PathPrefix} => {rule.Policy}")),
|
||||
Describe(options.AllowedScriptOrigins),
|
||||
Describe(options.AllowedConnectOrigins));
|
||||
|
||||
return app.UseMiddleware<SecurityHeadersMiddleware>();
|
||||
}
|
||||
|
||||
private static string Describe(ICollection<string> origins) =>
|
||||
origins.Count == 0 ? "(none)" : string.Join(", ", origins);
|
||||
|
||||
private static bool IsOrigin(string origin) =>
|
||||
!string.IsNullOrWhiteSpace(origin)
|
||||
&& Uri.TryCreate(origin.TrimEnd('/'), UriKind.Absolute, out var uri)
|
||||
&& (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp)
|
||||
&& uri.AbsolutePath == "/"
|
||||
&& string.IsNullOrEmpty(uri.Query);
|
||||
}
|
||||
Reference in New Issue
Block a user