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,113 @@
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The three HTML-only header values belonging to one policy.
|
||||
/// </summary>
|
||||
public sealed record SecurityHeaderSet(
|
||||
string ContentSecurityPolicy,
|
||||
string FrameOptions,
|
||||
string ReferrerPolicy);
|
||||
|
||||
/// <summary>
|
||||
/// The two Content-Security-Policy definitions, in code rather than in configuration.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A pure function of (policy name, origin lists) to a header set: no dependencies, no state,
|
||||
/// directly unit-testable. Configuration can misroute a path to the wrong policy — visible and
|
||||
/// recoverable — but cannot invent a policy that is subtly permissive.
|
||||
/// </remarks>
|
||||
public static class CspPolicyCatalog
|
||||
{
|
||||
public const string Strict = "Strict";
|
||||
public const string Relaxed = "Relaxed";
|
||||
|
||||
private const string ReferrerPolicyValue = "strict-origin-when-cross-origin";
|
||||
|
||||
public static IReadOnlyList<string> KnownPolicies { get; } = [Strict, Relaxed];
|
||||
|
||||
public static bool IsKnownPolicy(string? policy) =>
|
||||
policy is not null &&
|
||||
KnownPolicies.Any(known => known.Equals(policy, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>
|
||||
/// Builds the header set for <paramref name="policy"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The policy name is not known. Callers reach this only
|
||||
/// past startup validation, so it indicates a code defect rather than a configuration one.</exception>
|
||||
public static SecurityHeaderSet Build(
|
||||
string policy,
|
||||
IEnumerable<string> allowedScriptOrigins,
|
||||
IEnumerable<string> allowedConnectOrigins)
|
||||
{
|
||||
var connect = Join("'self'", allowedConnectOrigins);
|
||||
|
||||
if (Strict.Equals(policy, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SecurityHeaderSet(
|
||||
ContentSecurityPolicy: string.Join("; ",
|
||||
"default-src 'self'",
|
||||
// The directive that matters. No 'unsafe-inline' and no 'unsafe-eval':
|
||||
// relax this and the value of the whole policy collapses.
|
||||
"script-src 'self'",
|
||||
// The one exception, and it is unavoidable. Radix UI positions dropdowns,
|
||||
// dialogs and selects with inline style ATTRIBUTES whose values are
|
||||
// recomputed per click, viewport and scroll position. CSP nonces apply only
|
||||
// to <style> and <script> ELEMENTS; inline style attributes are outside
|
||||
// their scope entirely. The alternatives are 'unsafe-inline' or
|
||||
// 'unsafe-hashes' with a hash per exact value — and the values are dynamic,
|
||||
// so no finite set exists. Bounded to style-src: injected CSS can restyle a
|
||||
// page but cannot execute, because script-src 'self' still holds.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
$"connect-src {connect}",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"object-src 'none'"),
|
||||
FrameOptions: "DENY",
|
||||
ReferrerPolicy: ReferrerPolicyValue);
|
||||
}
|
||||
|
||||
if (Relaxed.Equals(policy, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SecurityHeaderSet(
|
||||
ContentSecurityPolicy: string.Join("; ",
|
||||
"default-src 'self'",
|
||||
// The public website is authored elsewhere, by someone who has never seen
|
||||
// this policy. Inline script and style are permitted so a normal marketing
|
||||
// page is not broken by a policy its author never chose. External script
|
||||
// ORIGINS are still blocked — a third-party script requires adding its
|
||||
// origin to configuration, which keeps this from being a rubber stamp.
|
||||
//
|
||||
// Note: when a source list contains 'unsafe-inline', browsers honour it AND
|
||||
// the listed origins, so adding an origin does not disable inline scripts.
|
||||
$"script-src {Join("'self' 'unsafe-inline'", allowedScriptOrigins)}",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: https:",
|
||||
"font-src 'self' data: https:",
|
||||
$"connect-src {connect}",
|
||||
"frame-src 'self' https:",
|
||||
"frame-ancestors 'self'",
|
||||
"base-uri 'self'",
|
||||
"object-src 'none'"),
|
||||
// A customer embedding one of their own pages in an iframe on their own site is
|
||||
// not broken by a policy they never chose. The admin UI keeps DENY.
|
||||
FrameOptions: "SAMEORIGIN",
|
||||
ReferrerPolicy: ReferrerPolicyValue);
|
||||
}
|
||||
|
||||
throw new ArgumentException($"Unknown security policy '{policy}'.", nameof(policy));
|
||||
}
|
||||
|
||||
private static string Join(string baseSources, IEnumerable<string> extraOrigins)
|
||||
{
|
||||
var extras = extraOrigins
|
||||
.Where(origin => !string.IsNullOrWhiteSpace(origin))
|
||||
.Select(origin => origin.Trim().TrimEnd('/'))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
return extras.Length == 0 ? baseSources : $"{baseSources} {string.Join(' ', extras)}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Collections.Frozen;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>Supplies the precomposed header set for a policy name.</summary>
|
||||
public interface ICspPolicyProvider
|
||||
{
|
||||
/// <summary>Returns the header set for <paramref name="policyName"/>.</summary>
|
||||
SecurityHeaderSet Get(string policyName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Composes every known policy once, at startup, and serves them from a frozen dictionary.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Composing a CSP string per response would be wasteful on a workload that is mostly static
|
||||
/// files. There are two policies and they are read on every HTML response, which is exactly
|
||||
/// what <see cref="FrozenDictionary{TKey,TValue}"/> exists for.
|
||||
/// </remarks>
|
||||
public sealed class CspPolicyProvider : ICspPolicyProvider
|
||||
{
|
||||
private readonly FrozenDictionary<string, SecurityHeaderSet> _policies;
|
||||
|
||||
public CspPolicyProvider(IOptions<SecurityHeadersOptions> options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var value = options.Value;
|
||||
|
||||
_policies = CspPolicyCatalog.KnownPolicies
|
||||
.ToFrozenDictionary(
|
||||
policy => policy,
|
||||
policy => CspPolicyCatalog.Build(policy, value.AllowedScriptOrigins, value.AllowedConnectOrigins),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public SecurityHeaderSet Get(string policyName) =>
|
||||
_policies.TryGetValue(policyName, out var set)
|
||||
? set
|
||||
// Unreachable past startup validation, which rejects unknown names before the host
|
||||
// starts. Throwing rather than falling back keeps that guarantee honest: a silent
|
||||
// fallback here would be either wrong or permissive, and would hide the fact that
|
||||
// validation had been bypassed.
|
||||
: throw new ArgumentException($"Unknown security policy '{policyName}'.", nameof(policyName));
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Maps a request path to a policy name using the configured, ordered prefix rules.
|
||||
/// </summary>
|
||||
public sealed class PathPolicyResolver
|
||||
{
|
||||
private readonly (PathString Prefix, string Policy)[] _rules;
|
||||
private readonly string _defaultPolicy;
|
||||
|
||||
public PathPolicyResolver(IOptions<SecurityHeadersOptions> options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var value = options.Value;
|
||||
|
||||
_rules = value.PathPolicies
|
||||
.Where(rule => !string.IsNullOrWhiteSpace(rule.PathPrefix))
|
||||
.Select(rule => (Normalize(rule.PathPrefix), rule.Policy))
|
||||
.ToArray();
|
||||
|
||||
_defaultPolicy = value.DefaultPolicy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the policy name for <paramref name="path"/>. First matching rule wins.
|
||||
/// </summary>
|
||||
public string Resolve(PathString path)
|
||||
{
|
||||
foreach (var (prefix, policy) in _rules)
|
||||
{
|
||||
// StartsWithSegments, never string.StartsWith: "/administrator".StartsWith("/admin")
|
||||
// is true, so a future route named /admin-tools or a public page at /administration
|
||||
// would silently inherit the strict policy and lose its inline scripts — a failure
|
||||
// that shows up as a broken page with a browser console error and no server-side
|
||||
// trace at all. StartsWithSegments compares whole path segments and does not match.
|
||||
if (path.StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return policy;
|
||||
}
|
||||
}
|
||||
|
||||
return _defaultPolicy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts "admin", "/admin" and "/admin/" alike. <see cref="PathString"/> requires a
|
||||
/// leading slash and treats a trailing slash inconsistently across overloads, so the shape
|
||||
/// is fixed once here rather than depended on per rule.
|
||||
/// </summary>
|
||||
private static PathString Normalize(string prefix)
|
||||
{
|
||||
var trimmed = prefix.Trim().TrimEnd('/');
|
||||
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
return PathString.Empty;
|
||||
}
|
||||
|
||||
return new PathString(trimmed.StartsWith('/') ? trimmed : "/" + trimmed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Decides which security headers apply to a response and writes them.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// All of U3's decision logic lives here, in a static function over an
|
||||
/// <see cref="IHeaderDictionary"/>, deliberately: <c>DefaultHttpContext.Response.OnStarting</c>
|
||||
/// is a no-op — there is no response feature to trigger it — so a unit test that drives the
|
||||
/// middleware through a <c>DefaultHttpContext</c> finds no headers and looks like a bug. Worse,
|
||||
/// a test asserting that nothing was set passes for the wrong reason and keeps passing after
|
||||
/// the middleware is deleted. Testing this function directly against a bare
|
||||
/// <c>HeaderDictionary</c> avoids both, and leaves the middleware as glue whose only real risk
|
||||
/// is registration order.
|
||||
/// </remarks>
|
||||
public static class SecurityHeaderWriter
|
||||
{
|
||||
public const string ContentTypeOptionsHeader = "X-Content-Type-Options";
|
||||
public const string StrictTransportSecurityHeader = "Strict-Transport-Security";
|
||||
public const string ContentSecurityPolicyHeader = "Content-Security-Policy";
|
||||
public const string FrameOptionsHeader = "X-Frame-Options";
|
||||
public const string ReferrerPolicyHeader = "Referrer-Policy";
|
||||
|
||||
/// <summary>One year, with subdomains — the value SECURITY-04 asks for.</summary>
|
||||
public const string HstsValue = "max-age=31536000; includeSubDomains";
|
||||
|
||||
private const string HtmlMediaType = "text/html";
|
||||
|
||||
/// <summary>
|
||||
/// Applies the headers appropriate to this response.
|
||||
/// </summary>
|
||||
/// <param name="headers">Response headers, mutated in place.</param>
|
||||
/// <param name="contentType">Raw <c>Content-Type</c>; null for bodyless responses.</param>
|
||||
/// <param name="headerSet">The resolved policy's HTML-only header values.</param>
|
||||
/// <param name="sendHsts">False in Development only; see <see cref="SecurityHeadersMiddleware"/>.</param>
|
||||
public static void Apply(
|
||||
IHeaderDictionary headers,
|
||||
string? contentType,
|
||||
SecurityHeaderSet headerSet,
|
||||
bool sendHsts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
ArgumentNullException.ThrowIfNull(headerSet);
|
||||
|
||||
// nosniff exists to stop a browser guessing the type of a NON-HTML resource — an
|
||||
// uploaded .txt or .svg interpreted as HTML or JavaScript is the attack it prevents.
|
||||
// Restricting it to HTML would remove it precisely where it does its job.
|
||||
headers.TryAdd(ContentTypeOptionsHeader, "nosniff");
|
||||
|
||||
// A host-level transport directive rather than a page directive: a visitor whose first
|
||||
// request is an asset would otherwise never receive it.
|
||||
if (sendHsts)
|
||||
{
|
||||
headers.TryAdd(StrictTransportSecurityHeader, HstsValue);
|
||||
}
|
||||
|
||||
// The remaining three govern documents and are meaningless on an image or a script
|
||||
// file. A null content type — 304, redirect, empty body — is not HTML, which is what
|
||||
// makes those cases fall out here instead of needing branches of their own.
|
||||
if (!IsHtml(contentType))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
headers.TryAdd(ContentSecurityPolicyHeader, headerSet.ContentSecurityPolicy);
|
||||
headers.TryAdd(FrameOptionsHeader, headerSet.FrameOptions);
|
||||
headers.TryAdd(ReferrerPolicyHeader, headerSet.ReferrerPolicy);
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// TryAdd, never the indexer: <c>headers["X-Frame-Options"] = value</c> overwrites, and a
|
||||
/// component that deliberately set a header knows something this writer does not.
|
||||
/// TryAdd is a no-op when the key exists, which is exactly the rule, and it states the
|
||||
/// intent in the call rather than in a surrounding if.
|
||||
/// </remarks>
|
||||
private static bool IsHtml(string? contentType)
|
||||
{
|
||||
if (string.IsNullOrEmpty(contentType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Parsed rather than matched with Contains("text/html"): the real header is
|
||||
// "text/html; charset=utf-8", so a substring check happens to work — until something
|
||||
// serves application/xhtml+xml or a type whose PARAMETER contains the string.
|
||||
return MediaTypeHeaderValue.TryParse(contentType, out var parsed)
|
||||
&& parsed.MediaType.Equals(HtmlMediaType, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Emits the HTTP security headers that a reverse proxy would normally supply.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// NFR-01 forbids depending on server configuration, so the application must send these itself.
|
||||
/// That changes the failure mode: a bad nginx config fails loudly at reload, whereas a
|
||||
/// middleware that never runs sends nothing and says nothing — which is why registration order
|
||||
/// is asserted by an integration test rather than trusted to the comment at the call site.
|
||||
/// </remarks>
|
||||
public sealed class SecurityHeadersMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ICspPolicyProvider _policyProvider;
|
||||
private readonly PathPolicyResolver _resolver;
|
||||
private readonly ILogger<SecurityHeadersMiddleware> _logger;
|
||||
private readonly bool _enabled;
|
||||
private readonly bool _sendHsts;
|
||||
|
||||
public SecurityHeadersMiddleware(
|
||||
RequestDelegate next,
|
||||
IOptions<SecurityHeadersOptions> options,
|
||||
ICspPolicyProvider policyProvider,
|
||||
PathPolicyResolver resolver,
|
||||
IHostEnvironment environment,
|
||||
ILogger<SecurityHeadersMiddleware> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
|
||||
_next = next;
|
||||
_policyProvider = policyProvider;
|
||||
_resolver = resolver;
|
||||
_logger = logger;
|
||||
_enabled = options.Value.Enabled;
|
||||
|
||||
// Browsers remember HSTS per host for a long time, and localhost is shared with every
|
||||
// other local project — sending it during development would affect unrelated work and
|
||||
// is awkward to undo. Every OTHER header does apply in Development, so a CSP violation
|
||||
// surfaces while developing rather than in production.
|
||||
//
|
||||
// Resolved once here rather than per response: EnvironmentName cannot change while the
|
||||
// process runs, and this middleware sees every static asset the website serves.
|
||||
_sendHsts = !environment.IsDevelopment();
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (!_enabled)
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// The policy is resolved on the way in, from the path; the headers are written at
|
||||
// response start, because the content type — which decides whether the HTML-only
|
||||
// headers apply — is not known any earlier. Doing both at response start would repeat
|
||||
// path matching on every static asset.
|
||||
var headerSet = _policyProvider.Get(_resolver.Resolve(context.Request.Path));
|
||||
|
||||
// The (callback, state) overload with a cached static delegate. The lambda overload
|
||||
// allocates a closure and a delegate on every response, including every static asset of
|
||||
// the public website — the bulk of the traffic in this hosting model.
|
||||
context.Response.OnStarting(
|
||||
WriteHeadersCallback,
|
||||
new HeaderWriteState(context.Response, headerSet, _sendHsts, _logger));
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
|
||||
private static readonly Func<object, Task> WriteHeadersCallback = static state =>
|
||||
{
|
||||
var s = (HeaderWriteState)state;
|
||||
|
||||
try
|
||||
{
|
||||
SecurityHeaderWriter.Apply(s.Response.Headers, s.Response.ContentType, s.HeaderSet, s.SendHsts);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Deliberately the one place in this unit that swallows. An exception thrown from an
|
||||
// OnStarting callback surfaces after the response has begun — too late for the
|
||||
// exception handler — and produces a truncated or malformed response instead of a
|
||||
// diagnosable error. Startup validation is what keeps this catch honest: by the time
|
||||
// a request arrives the configuration is already known good, so anything reaching
|
||||
// here is a code defect and belongs in the log.
|
||||
s.Logger.LogError(ex, "Failed to apply security headers to the response.");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
private sealed record HeaderWriteState(
|
||||
HttpResponse Response,
|
||||
SecurityHeaderSet HeaderSet,
|
||||
bool SendHsts,
|
||||
ILogger Logger);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration for the HTTP security headers emitted by <see cref="SecurityHeadersMiddleware"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The split between this class and <see cref="CspPolicyCatalog"/> is deliberate: configuration
|
||||
/// decides WHERE a policy applies and WHICH external origins are permitted, while code decides
|
||||
/// WHAT a policy means. A misconfiguration can therefore misroute a path or omit an origin —
|
||||
/// both recoverable and both visible — but cannot produce a policy that is subtly wrong.
|
||||
///
|
||||
/// The defaults below are the production values. An environment that supplies no
|
||||
/// <c>SecurityHeaders</c> section at all still gets the strict policy on /admin, /api/v1 and
|
||||
/// /health and the relaxed policy elsewhere: omission cannot produce an unprotected host.
|
||||
///
|
||||
/// No secret belongs in this section — origins are public hostnames — so it is committed with
|
||||
/// real values per environment rather than supplied through environment variables (contrast
|
||||
/// D-16, which governs credentials).
|
||||
/// </remarks>
|
||||
public sealed class SecurityHeadersOptions
|
||||
{
|
||||
public const string SectionName = "SecurityHeaders";
|
||||
|
||||
/// <summary>
|
||||
/// Diagnostic escape hatch. Disabling is logged as a warning at startup, because silently
|
||||
/// disabled security headers are worse than none at all.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Policy applied when no <see cref="PathPolicies"/> prefix matches — the public website.
|
||||
/// </summary>
|
||||
public string DefaultPolicy { get; set; } = CspPolicyCatalog.Relaxed;
|
||||
|
||||
/// <summary>
|
||||
/// Ordered path-prefix to policy mapping. <b>First match wins</b>, not longest prefix, so
|
||||
/// the order in configuration is meaningful.
|
||||
/// </summary>
|
||||
public IList<PathPolicyRule> PathPolicies { get; set; } =
|
||||
[
|
||||
new() { PathPrefix = "/admin", Policy = CspPolicyCatalog.Strict },
|
||||
new() { PathPrefix = "/api/v1", Policy = CspPolicyCatalog.Strict },
|
||||
new() { PathPrefix = "/health", Policy = CspPolicyCatalog.Strict }
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Extra origins added to <c>script-src</c> under the relaxed policy — in practice the
|
||||
/// Umami script host. Never added to the strict policy: the admin SPA must not load script
|
||||
/// from anywhere but itself.
|
||||
/// </summary>
|
||||
public IList<string> AllowedScriptOrigins { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Extra origins added to <c>connect-src</c> under both policies.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// No Sentry ingest origin is expected here: the Sentry tunnel keeps browser error
|
||||
/// reporting same-origin, so <c>connect-src 'self'</c> already covers it.
|
||||
/// </remarks>
|
||||
public IList<string> AllowedConnectOrigins { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>One entry in <see cref="SecurityHeadersOptions.PathPolicies"/>.</summary>
|
||||
public sealed class PathPolicyRule
|
||||
{
|
||||
/// <summary>Matched case-insensitively against whole leading path segments.</summary>
|
||||
public string PathPrefix { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Must name a policy known to <see cref="CspPolicyCatalog"/>, or startup fails.</summary>
|
||||
public string Policy { get; set; } = string.Empty;
|
||||
}
|
||||
Reference in New Issue
Block a user