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() .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(); services.AddSingleton(); return services; } /// /// Registers the security headers middleware. /// /// /// Position matters in both directions. Call this first inside /// UseExceptionHandler(): the exception handler re-executes the pipeline from inside /// itself, so middleware registered outside it never observes the ProblemDetails response. /// And call it BEFORE UseCmsStaticContent(), 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. /// public static IApplicationBuilder UseCmsSecurityHeaders(this IApplicationBuilder app) { var options = app.ApplicationServices.GetRequiredService>().Value; var logger = app.ApplicationServices .GetRequiredService() .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(); } private static string Describe(ICollection 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); }