Voeg WebsiteMode.PrerenderedPages toe: nginx-gelijke serving van een voorgerenderde website
- 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>
This commit is contained in:
@@ -9,7 +9,7 @@ public sealed record SecurityHeaderSet(
|
||||
string ReferrerPolicy);
|
||||
|
||||
/// <summary>
|
||||
/// The two Content-Security-Policy definitions, in code rather than in configuration.
|
||||
/// The Content-Security-Policy definitions (Strict, Relaxed, StrictSite), in code rather than in configuration.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A pure function of (policy name, origin lists) to a header set: no dependencies, no state,
|
||||
@@ -21,9 +21,17 @@ public static class CspPolicyCatalog
|
||||
public const string Strict = "Strict";
|
||||
public const string Relaxed = "Relaxed";
|
||||
|
||||
/// <summary>
|
||||
/// For a prerendered public website: strict like <see cref="Strict"/> but with the script and
|
||||
/// connect origins of the site (analytics, error reporting) taken from the dedicated
|
||||
/// <c>AllowedSite*Origins</c> lists, so the admin policies never gain them. The directive order
|
||||
/// matches the site's existing nginx header, so the value is byte-for-byte identical.
|
||||
/// </summary>
|
||||
public const string StrictSite = "StrictSite";
|
||||
|
||||
private const string ReferrerPolicyValue = "strict-origin-when-cross-origin";
|
||||
|
||||
public static IReadOnlyList<string> KnownPolicies { get; } = [Strict, Relaxed];
|
||||
public static IReadOnlyList<string> KnownPolicies { get; } = [Strict, Relaxed, StrictSite];
|
||||
|
||||
public static bool IsKnownPolicy(string? policy) =>
|
||||
policy is not null &&
|
||||
@@ -37,10 +45,31 @@ public static class CspPolicyCatalog
|
||||
public static SecurityHeaderSet Build(
|
||||
string policy,
|
||||
IEnumerable<string> allowedScriptOrigins,
|
||||
IEnumerable<string> allowedConnectOrigins)
|
||||
IEnumerable<string> allowedConnectOrigins,
|
||||
IEnumerable<string>? allowedSiteScriptOrigins = null,
|
||||
IEnumerable<string>? allowedSiteConnectOrigins = null)
|
||||
{
|
||||
var connect = Join("'self'", allowedConnectOrigins);
|
||||
|
||||
if (StrictSite.Equals(policy, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SecurityHeaderSet(
|
||||
ContentSecurityPolicy: string.Join("; ",
|
||||
"default-src 'self'",
|
||||
$"script-src {Join("'self'", allowedSiteScriptOrigins ?? [])}",
|
||||
// Same documented exception as Strict: inline style attributes only, no script.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
$"connect-src {Join("'self'", allowedSiteConnectOrigins ?? [])}",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'"),
|
||||
FrameOptions: "DENY",
|
||||
ReferrerPolicy: ReferrerPolicyValue);
|
||||
}
|
||||
|
||||
if (Strict.Equals(policy, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SecurityHeaderSet(
|
||||
|
||||
@@ -15,7 +15,7 @@ public interface ICspPolicyProvider
|
||||
/// </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
|
||||
/// files. There are three 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
|
||||
@@ -30,7 +30,12 @@ public sealed class CspPolicyProvider : ICspPolicyProvider
|
||||
_policies = CspPolicyCatalog.KnownPolicies
|
||||
.ToFrozenDictionary(
|
||||
policy => policy,
|
||||
policy => CspPolicyCatalog.Build(policy, value.AllowedScriptOrigins, value.AllowedConnectOrigins),
|
||||
policy => CspPolicyCatalog.Build(
|
||||
policy,
|
||||
value.AllowedScriptOrigins,
|
||||
value.AllowedConnectOrigins,
|
||||
value.AllowedSiteScriptOrigins,
|
||||
value.AllowedSiteConnectOrigins),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,11 +36,16 @@ public static class SecurityHeaderWriter
|
||||
/// <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>
|
||||
/// <param name="alwaysSendDocumentHeaders">
|
||||
/// True for responses of a prerendered website (every asset, redirect, 404 and robots.txt gets the
|
||||
/// full set, as nginx sends it). False keeps the HTML-only rule that API and admin responses use.
|
||||
/// </param>
|
||||
public static void Apply(
|
||||
IHeaderDictionary headers,
|
||||
string? contentType,
|
||||
SecurityHeaderSet headerSet,
|
||||
bool sendHsts)
|
||||
bool sendHsts,
|
||||
bool alwaysSendDocumentHeaders = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
ArgumentNullException.ThrowIfNull(headerSet);
|
||||
@@ -60,7 +65,7 @@ public static class SecurityHeaderWriter
|
||||
// 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))
|
||||
if (!alwaysSendDocumentHeaders && !IsHtml(contentType))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ public static class SecurityHeadersExtensions
|
||||
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),
|
||||
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
|
||||
@@ -71,11 +72,14 @@ public static class SecurityHeadersExtensions
|
||||
// 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 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.AllowedConnectOrigins),
|
||||
Describe(options.AllowedSiteScriptOrigins),
|
||||
Describe(options.AllowedSiteConnectOrigins));
|
||||
|
||||
return app.UseMiddleware<SecurityHeadersMiddleware>();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
@@ -22,6 +23,7 @@ public sealed class SecurityHeadersMiddleware
|
||||
private readonly ILogger<SecurityHeadersMiddleware> _logger;
|
||||
private readonly bool _enabled;
|
||||
private readonly bool _sendHsts;
|
||||
private readonly bool _prerenderedWebsite;
|
||||
|
||||
public SecurityHeadersMiddleware(
|
||||
RequestDelegate next,
|
||||
@@ -29,7 +31,8 @@ public sealed class SecurityHeadersMiddleware
|
||||
ICspPolicyProvider policyProvider,
|
||||
PathPolicyResolver resolver,
|
||||
IHostEnvironment environment,
|
||||
ILogger<SecurityHeadersMiddleware> logger)
|
||||
ILogger<SecurityHeadersMiddleware> logger,
|
||||
WebsiteHostingMarker? websiteHosting = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
@@ -48,6 +51,9 @@ public sealed class SecurityHeadersMiddleware
|
||||
// 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();
|
||||
|
||||
// Only a client hosting a prerendered website registers the marker (AddCmsWebsite).
|
||||
_prerenderedWebsite = websiteHosting is not null;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
@@ -67,9 +73,14 @@ public sealed class SecurityHeadersMiddleware
|
||||
// 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.
|
||||
// On a prerendered website every response outside the reserved prefixes (page, asset, 301,
|
||||
// 404, robots.txt) gets the full set, because nginx does and the site's own checks assert it.
|
||||
var documentHeadersEverywhere = _prerenderedWebsite
|
||||
&& !WebsitePathResolver.IsReservedPath(context.Request.Path.Value);
|
||||
|
||||
context.Response.OnStarting(
|
||||
WriteHeadersCallback,
|
||||
new HeaderWriteState(context.Response, headerSet, _sendHsts, _logger));
|
||||
new HeaderWriteState(context.Response, headerSet, _sendHsts, documentHeadersEverywhere, _logger));
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
@@ -80,7 +91,8 @@ public sealed class SecurityHeadersMiddleware
|
||||
|
||||
try
|
||||
{
|
||||
SecurityHeaderWriter.Apply(s.Response.Headers, s.Response.ContentType, s.HeaderSet, s.SendHsts);
|
||||
SecurityHeaderWriter.Apply(
|
||||
s.Response.Headers, s.Response.ContentType, s.HeaderSet, s.SendHsts, s.AlwaysSendDocumentHeaders);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -100,5 +112,6 @@ public sealed class SecurityHeadersMiddleware
|
||||
HttpResponse Response,
|
||||
SecurityHeaderSet HeaderSet,
|
||||
bool SendHsts,
|
||||
bool AlwaysSendDocumentHeaders,
|
||||
ILogger Logger);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,18 @@ public sealed class SecurityHeadersOptions
|
||||
/// reporting same-origin, so <c>connect-src 'self'</c> already covers it.
|
||||
/// </remarks>
|
||||
public IList<string> AllowedConnectOrigins { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Extra origins added to <c>script-src</c> under the <c>StrictSite</c> policy only (for example
|
||||
/// the analytics host of a prerendered website). Never used by the admin policies.
|
||||
/// </summary>
|
||||
public IList<string> AllowedSiteScriptOrigins { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Extra origins added to <c>connect-src</c> under the <c>StrictSite</c> policy only (for example
|
||||
/// analytics and error-reporting hosts called directly by the website).
|
||||
/// </summary>
|
||||
public IList<string> AllowedSiteConnectOrigins { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>One entry in <see cref="SecurityHeadersOptions.PathPolicies"/>.</summary>
|
||||
|
||||
Reference in New Issue
Block a user