- Pure WebsitePathResolver (canonieke 301's, echte 404, dotfiles geweigerd, gereserveerde prefixes) - PrerenderedSiteMiddleware, 404-fallback na de API-routes, gzip, Cache-Control, NoIndex/robots.txt - Beleid StrictSite met eigen AllowedSite*Origins; volledige headerset op alle websiteresponses - Tests: voorbeelden, FsCheck-properties en integratietests op een in-memory server Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
97 lines
5.0 KiB
C#
97 lines
5.0 KiB
C#
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)
|
|
.Concat(options.AllowedSiteScriptOrigins).Concat(options.AllowedSiteConnectOrigins).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}. " +
|
|
"Allowed site script origins: {SiteScriptOrigins}. Allowed site connect origins: {SiteConnectOrigins}.",
|
|
options.DefaultPolicy,
|
|
string.Join(", ", options.PathPolicies.Select(rule => $"{rule.PathPrefix} => {rule.Policy}")),
|
|
Describe(options.AllowedScriptOrigins),
|
|
Describe(options.AllowedConnectOrigins),
|
|
Describe(options.AllowedSiteScriptOrigins),
|
|
Describe(options.AllowedSiteConnectOrigins));
|
|
|
|
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);
|
|
}
|