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:
2026-11-06 15:52:04 +01:00
co-authored by Claude Sonnet 5.5
parent d9cc539481
commit 7d21d9024a
25 changed files with 1859 additions and 23 deletions
@@ -0,0 +1,56 @@
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using SlpModularCms.Core.Hosting.Security;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting.Security;
/// <summary>The <c>alwaysSendDocumentHeaders</c> flag used for prerendered-website responses (Q1 = A).</summary>
public class SecurityHeaderWriterDocumentHeadersTests
{
private static readonly SecurityHeaderSet Set = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], []);
[Theory]
[InlineData(null)]
[InlineData("image/png")]
[InlineData("application/javascript")]
[InlineData("text/plain; charset=utf-8")]
public void WithTheFlag_DocumentHeadersAreSentOnNonHtmlResponses(string? contentType)
{
var headers = new HeaderDictionary();
SecurityHeaderWriter.Apply(headers, contentType, Set, sendHsts: true, alwaysSendDocumentHeaders: true);
headers.ContainsKey("Content-Security-Policy").Should().BeTrue();
headers["X-Frame-Options"].ToString().Should().Be("DENY");
headers["Referrer-Policy"].ToString().Should().Be("strict-origin-when-cross-origin");
headers["X-Content-Type-Options"].ToString().Should().Be("nosniff");
headers.ContainsKey("Strict-Transport-Security").Should().BeTrue();
}
[Theory]
[InlineData(null)]
[InlineData("image/png")]
public void WithoutTheFlag_TheHtmlOnlyRuleIsUnchanged(string? contentType)
{
var headers = new HeaderDictionary();
SecurityHeaderWriter.Apply(headers, contentType, Set, sendHsts: true);
headers.ContainsKey("Content-Security-Policy").Should().BeFalse();
headers.ContainsKey("X-Frame-Options").Should().BeFalse();
headers.ContainsKey("Referrer-Policy").Should().BeFalse();
headers["X-Content-Type-Options"].ToString().Should().Be("nosniff");
}
[Fact]
public void WithTheFlag_AnExistingHeaderIsNotOverwritten()
{
var headers = new HeaderDictionary { ["X-Frame-Options"] = "SAMEORIGIN" };
SecurityHeaderWriter.Apply(headers, null, Set, sendHsts: false, alwaysSendDocumentHeaders: true);
headers["X-Frame-Options"].ToString().Should().Be("SAMEORIGIN");
headers.ContainsKey("Strict-Transport-Security").Should().BeFalse();
}
}
@@ -0,0 +1,138 @@
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting.Security;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting.Security;
/// <summary>Guards the StrictSite policy: byte-for-byte the CSP the prerendered site sends today.</summary>
public class StrictSitePolicyTests
{
private const string Umami = "https://analytics.slpsoftware.nl";
private const string Sentry = "https://o4511795618185216.ingest.de.sentry.io";
/// <summary>The exact nginx value of the website (security headers, test and production).</summary>
private const string ExpectedSiteCsp =
"default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; " +
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
"connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; " +
"object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
[Fact]
public void StrictSite_WithTheSiteOrigins_MatchesTheNginxHeaderByteForByte()
{
var set = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], [], [Umami], [Umami, Sentry]);
set.ContentSecurityPolicy.Should().Be(ExpectedSiteCsp);
set.FrameOptions.Should().Be("DENY");
set.ReferrerPolicy.Should().Be("strict-origin-when-cross-origin");
}
[Fact]
public void StrictSite_WithoutOrigins_AllowsOnlySelf()
{
var set = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], []);
set.ContentSecurityPolicy.Should().Contain("script-src 'self';").And.Contain("connect-src 'self';");
set.ContentSecurityPolicy.Should().NotContain("script-src 'self' 'unsafe-inline'").And.NotContain("'unsafe-eval'");
}
[Fact]
public void SiteOrigins_AreUsedByStrictSiteOnly()
{
var strict = CspPolicyCatalog.Build(CspPolicyCatalog.Strict, [], [], [Umami], [Sentry]);
var relaxed = CspPolicyCatalog.Build(CspPolicyCatalog.Relaxed, [], [], [Umami], [Sentry]);
strict.ContentSecurityPolicy.Should().NotContain(Umami).And.NotContain(Sentry);
relaxed.ContentSecurityPolicy.Should().NotContain(Umami).And.NotContain(Sentry);
}
[Fact]
public void AdminOrigins_AreNotUsedByStrictSite()
{
var set = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [Umami], [Sentry]);
set.ContentSecurityPolicy.Should().NotContain(Umami).And.NotContain(Sentry);
}
[Fact]
public void StrictAndRelaxed_AreUnchangedByTheNewParameters()
{
foreach (var policy in new[] { CspPolicyCatalog.Strict, CspPolicyCatalog.Relaxed })
{
var before = CspPolicyCatalog.Build(policy, [Umami], [Sentry]);
var after = CspPolicyCatalog.Build(policy, [Umami], [Sentry], [Umami], [Sentry]);
after.Should().Be(before);
}
}
[Fact]
public void StrictSite_IsAKnownPolicy_AndUnknownNamesStillFail()
{
CspPolicyCatalog.IsKnownPolicy("StrictSite").Should().BeTrue();
CspPolicyCatalog.IsKnownPolicy("strictsite").Should().BeTrue();
CspPolicyCatalog.IsKnownPolicy("StrictSyte").Should().BeFalse();
}
[Fact]
public void Configuration_CanSelectStrictSite_AndBindsTheSiteOrigins()
{
var provider = BuildProvider(new Dictionary<string, string?>
{
["SecurityHeaders:DefaultPolicy"] = "StrictSite",
["SecurityHeaders:AllowedSiteScriptOrigins:0"] = Umami,
["SecurityHeaders:AllowedSiteConnectOrigins:0"] = Umami,
["SecurityHeaders:AllowedSiteConnectOrigins:1"] = Sentry
});
provider.GetRequiredService<IOptions<SecurityHeadersOptions>>().Value.DefaultPolicy.Should().Be("StrictSite");
provider.GetRequiredService<ICspPolicyProvider>().Get("StrictSite").ContentSecurityPolicy
.Should().Be(ExpectedSiteCsp);
}
[Theory]
[InlineData("AllowedSiteScriptOrigins", "analytics.example.com")]
[InlineData("AllowedSiteConnectOrigins", "https://example.com/path")]
[InlineData("AllowedSiteConnectOrigins", "htp://example.com")]
public void SiteOriginLists_AreValidatedLikeTheExistingOnes(string key, string origin)
{
var provider = BuildProvider(new Dictionary<string, string?> { [$"SecurityHeaders:{key}:0"] = origin });
var act = () => provider.GetRequiredService<IOptions<SecurityHeadersOptions>>().Value;
act.Should().Throw<OptionsValidationException>().WithMessage("*origins must be absolute scheme-and-host*");
}
/// <summary>PBT-02: every configured origin appears in the right directive and nowhere else.</summary>
[Fact]
public void Property_ConfiguredSiteOrigins_AppearInTheirDirectiveOnly()
{
var hosts = Gen.Elements("a", "b", "cdn", "stats", "x1").Select(h => $"https://{h}.example.com");
var lists = Gen.ListOf(hosts).Select(l => l.Distinct().ToArray());
Prop.ForAll(lists.ToArbitrary(), lists.ToArbitrary(), (script, connect) =>
{
var csp = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], [], script, connect).ContentSecurityPolicy;
var directives = csp.Split("; ").ToDictionary(d => d.Split(' ')[0], d => d.Split(' ').Skip(1).ToArray());
return directives["script-src"].Skip(1).OrderBy(x => x).SequenceEqual(script.OrderBy(x => x))
&& directives["connect-src"].Skip(1).OrderBy(x => x).SequenceEqual(connect.OrderBy(x => x))
&& directives["default-src"].SequenceEqual(["'self'"]);
})
.Check(Config.QuickThrowOnFailure.WithMaxTest(300));
}
private static ServiceProvider BuildProvider(Dictionary<string, string?> values)
{
var configuration = new ConfigurationBuilder().AddInMemoryCollection(values).Build();
var services = new ServiceCollection();
services.AddLogging();
services.AddCmsSecurityHeaders(configuration);
return services.BuildServiceProvider();
}
}
@@ -0,0 +1,464 @@
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Hosting.Security;
using SlpModularCms.Core.Hosting.Website;
using Xunit;
using Xunit.Abstractions;
namespace SlpModularCms.Core.Tests.Hosting.Website;
/// <summary>
/// End-to-end tests of the prerendered website on an in-memory server (no database needed):
/// the real security-header, static-content and website extensions over a temporary
/// <c>wwwroot/web</c>, with a stand-in API route for the reserved prefix.
/// </summary>
public sealed class PrerenderedSiteIntegrationTests : IDisposable
{
private const string Umami = "https://analytics.slpsoftware.nl";
private const string Sentry = "https://o4511795618185216.ingest.de.sentry.io";
private readonly string _root = Path.Combine(Path.GetTempPath(), "slp-site-" + Guid.NewGuid().ToString("N"));
private readonly ITestOutputHelper _output;
private readonly List<WebApplication> _apps = [];
public PrerenderedSiteIntegrationTests(ITestOutputHelper output)
{
_output = output;
Write("index.html", "<!doctype html><title>Home</title>");
Write("over-mij.html", "<!doctype html><title>Over mij</title>");
Write("404.html", "<!doctype html><title>Niet gevonden</title>");
Write("assets/app.abc123.js", "console.log('x');" + new string(' ', 2000));
Write("assets/logo.png", "PNG");
Write("blog/index.html", "<!doctype html><title>Blog</title>");
Write(".well-known/security.txt", "Contact: mailto:a@example.com");
Write(".env", "SECRET=1");
}
public void Dispose()
{
foreach (var app in _apps)
{
app.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
private void Write(string relative, string content)
{
var path = Path.Combine(_root, "wwwroot", "web", relative);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, content);
}
private async Task<HttpClient> StartAsync(bool noIndex = false, bool prerendered = true, Dictionary<string, string?>? extra = null)
{
Directory.CreateDirectory(Path.Combine(_root, "wwwroot"));
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
EnvironmentName = Environments.Production,
ContentRootPath = _root,
WebRootPath = Path.Combine(_root, "wwwroot")
});
builder.WebHost.UseTestServer();
builder.Logging.ClearProviders();
var settings = new Dictionary<string, string?>
{
["SecurityHeaders:DefaultPolicy"] = "StrictSite",
["SecurityHeaders:AllowedSiteScriptOrigins:0"] = Umami,
["SecurityHeaders:AllowedSiteConnectOrigins:0"] = Umami,
["SecurityHeaders:AllowedSiteConnectOrigins:1"] = Sentry,
["Website:NoIndex"] = noIndex ? "true" : "false"
};
foreach (var (key, value) in extra ?? [])
{
settings[key] = value;
}
builder.Configuration.AddInMemoryCollection(settings);
builder.Services.AddCmsSecurityHeaders(builder.Configuration);
if (prerendered)
{
builder.Services.AddCmsWebsite(builder.Configuration);
}
var app = builder.Build();
var mode = prerendered ? WebsiteMode.PrerenderedPages : WebsiteMode.SpaFallback;
app.UseCmsSecurityHeaders();
app.UseCmsStaticContent(mode);
if (prerendered)
{
app.UseCmsPrerenderedSite();
}
app.MapGet("/api/v1/ping", () => Results.Text("pong"));
app.MapPost("/sentry-stand-in", () => Results.Ok("tunnel"));
app.MapCmsSpaFallbacks(mode);
if (prerendered)
{
app.MapCmsWebsiteNotFound();
}
await app.StartAsync();
_apps.Add(app);
var client = app.GetTestClient();
return client;
}
private static string[] Header(HttpResponseMessage response, string name) =>
response.Headers.TryGetValues(name, out var values) ? values.ToArray()
: response.Content.Headers.TryGetValues(name, out var cvalues) ? cvalues.ToArray()
: [];
// The full header set Q1 = A requires on every website response.
private static void AssertFullHeaderSet(HttpResponseMessage response, string because)
{
Header(response, "Content-Security-Policy").Should().ContainSingle(because)
.Which.Should().StartWith("default-src 'self'; script-src 'self' " + Umami);
Header(response, "Strict-Transport-Security").Should().Equal(["max-age=31536000; includeSubDomains"], because);
Header(response, "X-Content-Type-Options").Should().Equal(["nosniff"], because);
Header(response, "X-Frame-Options").Should().Equal(["DENY"], because);
Header(response, "Referrer-Policy").Should().Equal(["strict-origin-when-cross-origin"], because);
}
private static HttpClient NoRedirect(HttpClient client) => client;
[Fact]
public async Task Root_ServesIndex_NoCache_WithFullHeaders()
{
var client = await StartAsync();
var response = await client.GetAsync("/");
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Contain("<title>Home</title>");
response.Content.Headers.ContentType!.ToString().Should().Be("text/html; charset=utf-8");
Header(response, "Cache-Control").Should().Equal(["no-cache"]);
AssertFullHeaderSet(response, "page");
}
[Fact]
public async Task Page_IsServedFromExtensionlessUrl()
{
var client = await StartAsync();
var response = await client.GetAsync("/over-mij");
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Contain("Over mij");
}
[Theory]
[InlineData("/Over-Mij?x=1", "/over-mij?x=1")]
[InlineData("/over-mij.html", "/over-mij")]
[InlineData("/over-mij/", "/over-mij")]
[InlineData("/index", "/")]
[InlineData("/index.html", "/")]
[InlineData("/onbekend/", "/onbekend")]
public async Task NonCanonicalUrl_Gets_One301_WithRelativeLocation_AndFullHeaders(string path, string location)
{
var client = await StartAsync();
var response = await client.GetAsync(path);
response.StatusCode.Should().Be(HttpStatusCode.MovedPermanently);
response.Headers.Location!.OriginalString.Should().Be(location);
AssertFullHeaderSet(response, "301");
}
[Fact]
public async Task Asset_IsImmutable_AndCarriesTheFullHeaderSet()
{
var client = await StartAsync();
var response = await client.GetAsync("/assets/logo.png");
response.StatusCode.Should().Be(HttpStatusCode.OK);
Header(response, "Cache-Control").Should().Equal(["public, max-age=31536000, immutable"]);
AssertFullHeaderSet(response, "asset");
}
[Fact]
public async Task UnknownPath_Gets404Page_WithStatus404_AndFullHeaders()
{
var client = await StartAsync();
var response = await client.GetAsync("/onbekend");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await response.Content.ReadAsStringAsync()).Should().Contain("Niet gevonden");
response.Content.Headers.ContentType!.ToString().Should().Be("text/html; charset=utf-8");
AssertFullHeaderSet(response, "404");
}
[Theory]
[InlineData("/404")]
[InlineData("/404.html")]
[InlineData("/assets/missing.js")]
[InlineData("/assets")]
public async Task ForbiddenOrMissing_Is404WithThe404Page(string path)
{
var client = await StartAsync();
var response = await client.GetAsync(path);
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await response.Content.ReadAsStringAsync()).Should().Contain("Niet gevonden");
}
[Fact]
public async Task Missing404Html_GivesAPlain404()
{
File.Delete(Path.Combine(_root, "wwwroot", "web", "404.html"));
var client = await StartAsync();
var response = await client.GetAsync("/onbekend");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await response.Content.ReadAsStringAsync()).Should().BeEmpty();
}
[Theory]
[InlineData("/.env")]
[InlineData("/.git/config")]
[InlineData("/assets/.hidden")]
public async Task Dotfiles_Are404_AndNeverServed(string path)
{
var client = await StartAsync();
var response = await client.GetAsync(path);
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await response.Content.ReadAsStringAsync()).Should().NotContain("SECRET");
}
[Fact]
public async Task WellKnown_IsServed()
{
var client = await StartAsync();
var response = await client.GetAsync("/.well-known/security.txt");
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Contain("Contact:");
}
[Theory]
[InlineData("/../secret")]
[InlineData("/%2e%2e/secret")]
[InlineData("/assets/..%2f..%2fsecret")]
public async Task Traversal_Is404(string path)
{
var client = await StartAsync();
var response = await client.GetAsync(path);
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task ReservedApiPath_IsHandledByTheApi_AndUnknownApiPathStaysA404WithoutTheWebsitePage()
{
var client = await StartAsync();
var known = await client.GetAsync("/api/v1/ping");
var unknown = await client.GetAsync("/api/v1/does-not-exist");
known.StatusCode.Should().Be(HttpStatusCode.OK);
(await known.Content.ReadAsStringAsync()).Should().Be("pong");
unknown.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await unknown.Content.ReadAsStringAsync()).Should().BeEmpty();
}
[Fact]
public async Task NonReservedPostIsLeftToEndpoints()
{
var client = await StartAsync();
var tunnel = await client.PostAsync("/sentry-stand-in", new StringContent("x"));
var other = await client.PostAsync("/over-mij", new StringContent("x"));
tunnel.StatusCode.Should().Be(HttpStatusCode.OK);
other.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);
other.Content.Headers.Allow.Should().BeEquivalentTo(["GET", "HEAD"]);
}
[Fact]
public async Task Head_BehavesLikeGetWithoutBody()
{
var client = await StartAsync();
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "/over-mij"));
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().BeEmpty();
Header(response, "Content-Length").Should().NotBeEmpty();
}
[Fact]
public async Task NoIndex_AddsRobotsHeaderEverywhere_AndServesDisallowAll()
{
var client = await StartAsync(noIndex: true);
var page = await client.GetAsync("/over-mij");
var asset = await client.GetAsync("/assets/logo.png");
var redirect = await client.GetAsync("/Over-Mij");
var notFound = await client.GetAsync("/onbekend");
var robots = await client.GetAsync("/robots.txt");
foreach (var response in new[] { page, asset, redirect, notFound, robots })
{
Header(response, "X-Robots-Tag").Should().Equal(["noindex, nofollow"]);
}
robots.StatusCode.Should().Be(HttpStatusCode.OK);
(await robots.Content.ReadAsStringAsync()).Should().Be("User-agent: *\nDisallow: /\n");
AssertFullHeaderSet(robots, "robots.txt");
}
[Fact]
public async Task WithoutNoIndex_NoRobotsHeader_AndMissingRobotsTxtIs404()
{
var client = await StartAsync();
var page = await client.GetAsync("/over-mij");
var robots = await client.GetAsync("/robots.txt");
Header(page, "X-Robots-Tag").Should().BeEmpty();
robots.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task Gzip_IsUsedForTextTypes_AndBrotliIsNot()
{
var client = await StartAsync();
var request = new HttpRequestMessage(HttpMethod.Get, "/assets/app.abc123.js");
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
var js = await client.SendAsync(request);
var imageRequest = new HttpRequestMessage(HttpMethod.Get, "/assets/logo.png");
imageRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
var png = await client.SendAsync(imageRequest);
Header(js, "Content-Encoding").Should().Equal(["gzip"]);
Header(js, "Vary").Should().Contain("Accept-Encoding");
Header(png, "Content-Encoding").Should().BeEmpty();
}
[Fact]
public async Task ApiResponses_AreNotCompressed()
{
var client = await StartAsync();
var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/ping");
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
var response = await client.SendAsync(request);
Header(response, "Content-Encoding").Should().BeEmpty();
}
[Fact]
public async Task ApiResponses_KeepTheHtmlOnlyHeaderRule()
{
var client = await StartAsync();
var response = await client.GetAsync("/api/v1/ping");
// text/plain from the stand-in route: nosniff and HSTS yes, document headers no.
Header(response, "X-Content-Type-Options").Should().Equal(["nosniff"]);
Header(response, "Content-Security-Policy").Should().BeEmpty();
}
[Fact]
public async Task MissingWebsiteDirectory_KeepsTheHostAlive_AndAnswers404()
{
Directory.Delete(Path.Combine(_root, "wwwroot", "web"), recursive: true);
var client = await StartAsync();
var page = await client.GetAsync("/over-mij");
var api = await client.GetAsync("/api/v1/ping");
page.StatusCode.Should().Be(HttpStatusCode.NotFound);
api.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task WebsiteDeliveredAfterStartup_IsServedWithoutRestart()
{
var client = await StartAsync();
(await client.GetAsync("/nieuw")).StatusCode.Should().Be(HttpStatusCode.NotFound);
Write("nieuw.html", "<!doctype html><title>Nieuw</title>");
(await client.GetAsync("/nieuw")).StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task PlainHttp_NeverRedirectsToHttps_AndLocationsAreRelative()
{
var client = await StartAsync();
var response = await client.GetAsync("/Over-Mij");
response.Headers.Location!.IsAbsoluteUri.Should().BeFalse();
}
[Fact]
public async Task SpaFallbackMode_StaysUntouched_UnknownPathsAreNotTheWebsite404()
{
var client = await StartAsync(prerendered: false);
var response = await client.GetAsync("/Over-Mij");
// Old behaviour: no canonical redirect, SPA-style handling (index.html fallback).
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Contain("<title>Home</title>");
Header(response, "Content-Security-Policy").Should().NotBeEmpty();
}
[Fact]
public async Task LocalTimingCheck_PageServing_IsFast()
{
var client = await StartAsync();
await client.GetAsync("/over-mij");
const int iterations = 500;
var watch = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
(await client.GetAsync("/over-mij")).EnsureSuccessStatusCode();
}
watch.Stop();
var perRequest = watch.Elapsed.TotalMilliseconds / iterations;
// Recorded in the hand-back note (NFR-PF-02); the bound only catches pathological regressions.
_output.WriteLine($"TIMING: {iterations} GET /over-mij via in-memory server = {perRequest:F3} ms/request");
perRequest.Should().BeLessThan(20);
}
}
@@ -0,0 +1,145 @@
using FsCheck;
using FsCheck.Fluent;
using SlpModularCms.Core.Hosting.Website;
using Xunit;
using Xunit.Abstractions;
namespace SlpModularCms.Core.Tests.Hosting.Website;
/// <summary>
/// Property-based tests for the pure resolver (PBT-03 invariants, idempotence).
/// </summary>
/// <remarks>
/// A failing run prints FsCheck's replay seed in the failure message (PBT-08); once a shrunk
/// counterexample is understood it is added to <see cref="WebsitePathResolverTests"/> as a plain
/// example test so the regression stays pinned.
/// </remarks>
public class WebsitePathResolverPropertyTests(ITestOutputHelper output)
{
private static readonly string[] KnownFiles =
[
"index.html", "over-mij.html", "contact.html", "404.html", "robots.txt",
"assets/app.abc123.js", "blog/index.html", ".well-known/security.txt"
];
private static bool Exists(string candidate) => KnownFiles.Contains(candidate);
// PBT-07 generators: path-ish strings that stress slashes, dots, case, encoding and control characters.
private static readonly string[] Fragments =
[
"/", "/", "//", "\\", ".", "..", "...", ".git", ".well-known", "%2e", "%2E", "%2f", "%5c", "%",
"over-mij", "Over-Mij", "contact", "index", "Index", ".html", ".HTML", "404", "assets", "app.abc123.js",
"blog", "admin", "api", "v1", "health", "a", "é", "ß", "İ", "\0", "\n", " ", "?", "#", "~", "x"
];
private static Arbitrary<string> PathArb()
{
var gen = Gen.Elements(Fragments)
.ArrayOf()
.Select(parts => string.Concat(parts))
.Select(tail => "/" + tail);
// Also exercise inputs that do not start with a slash and the empty string.
return Gen.OneOf(gen, Gen.Elements("", "x", "..", "\\x").Select(s => s))
.ToArbitrary();
}
private static Arbitrary<string?> QueryArb() =>
Gen.Elements(null, "", "?", "?a=1", "?a=1&b=%2e%2e", "a=1", "?x\r\ny")
.ToArbitrary();
private void Check(Func<string, string?, bool> property)
{
var config = Config.QuickThrowOnFailure.WithMaxTest(2000);
Prop.ForAll(PathArb(), QueryArb(), (path, query) => property(path, query))
.Check(config);
output.WriteLine("Property held for 2000 generated inputs.");
}
[Fact]
public void Resolve_NeverThrows() =>
Check((path, query) =>
{
WebsitePathResolver.Resolve(path, query, Exists);
return true;
});
[Fact]
public void ServeFile_IsAlwaysASafeExistingRelativePath() =>
Check((path, query) =>
{
if (WebsitePathResolver.Resolve(path, query, Exists) is not WebsiteResolution.ServeFile serve)
{
return true;
}
var p = serve.RelativePath;
var segments = p.Split('/');
return Exists(p)
&& p.Length > 0
&& !p.StartsWith('/')
&& !p.Contains('\\')
&& !p.Contains('\0')
&& segments.All(s => s.Length > 0 && s != "." && s != "..")
&& segments.Skip(1).All(s => !s.StartsWith('.'))
&& (!segments[0].StartsWith('.') || segments[0] == ".well-known");
});
[Fact]
public void Redirect_LocationIsRelativeAndNeverAnOpenRedirect() =>
Check((path, query) =>
{
if (WebsitePathResolver.Resolve(path, query, Exists) is not WebsiteResolution.Redirect redirect)
{
return true;
}
var location = redirect.Location;
var pathPart = location.Split('?')[0];
return location.StartsWith('/')
&& !location.StartsWith("//", StringComparison.Ordinal)
&& !location.StartsWith("/\\", StringComparison.Ordinal)
&& !location.Any(c => c < 0x20 || c == 0x7f || c == '\\')
&& (pathPart == "/" || !pathPart.EndsWith('/'));
});
[Fact]
public void Redirect_TargetNeverRedirectsAgain() =>
Check((path, query) =>
{
if (WebsitePathResolver.Resolve(path, query, Exists) is not WebsiteResolution.Redirect first)
{
return true;
}
var split = first.Location.IndexOf('?');
var targetPath = split < 0 ? first.Location : first.Location[..split];
var targetQuery = split < 0 ? null : first.Location[split..];
return WebsitePathResolver.Resolve(targetPath, targetQuery, Exists) is not WebsiteResolution.Redirect;
});
[Fact]
public void ReservedPaths_AreNeverResolved() =>
Check((path, query) =>
!WebsitePathResolver.IsReservedPath(path)
|| WebsitePathResolver.Resolve(path, query, Exists) is WebsiteResolution.NotFound);
[Fact]
public void Resolve_DoesAtMostTwoFileChecks() =>
Check((path, query) =>
{
var calls = 0;
WebsitePathResolver.Resolve(path, query, c =>
{
calls++;
return Exists(c);
});
return calls <= 2;
});
}
@@ -0,0 +1,224 @@
using FluentAssertions;
using SlpModularCms.Core.Hosting.Website;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting.Website;
/// <summary>Example-based tests for the nginx-parity rules R1-R14 of the pure path resolver.</summary>
public class WebsitePathResolverTests
{
private static readonly string[] Files =
[
"index.html", "over-mij.html", "404.html", "robots.txt",
"assets/app.abc123.js", "blog/index.html", ".well-known/security.txt", ".env"
];
private static bool Exists(string candidate) => Files.Contains(candidate);
private static WebsiteResolution Resolve(string? path, string? query = null) =>
WebsitePathResolver.Resolve(path, query, Exists);
private static WebsiteResolution.ServeFile Serve(string file) => new(file);
private static WebsiteResolution.Redirect Redirect(string location) => new(location);
// R5
[Fact]
public void Root_ServesIndex() => Resolve("/").Should().Be(Serve("index.html"));
[Fact]
public void Root_WithoutIndexFile_IsNotFound() =>
WebsitePathResolver.Resolve("/", null, _ => false).Should().BeOfType<WebsiteResolution.NotFound>();
// R9
[Fact]
public void Page_ServesHtmlFile() => Resolve("/over-mij").Should().Be(Serve("over-mij.html"));
[Fact]
public void Directory_ServesItsIndexPage() => Resolve("/blog").Should().Be(Serve("blog/index.html"));
// R10
[Theory]
[InlineData("/Over-Mij")]
[InlineData("/OVER-MIJ")]
[InlineData("/over-mij.html")]
[InlineData("/Over-Mij.HTML")]
[InlineData("/over-mij/")]
[InlineData("/over-mij///")]
public void NonCanonicalPage_RedirectsOnceToLowercaseNoHtml(string path) =>
Resolve(path).Should().Be(Redirect("/over-mij"));
[Fact]
public void Redirect_PreservesQueryString() =>
Resolve("/Over-Mij", "?x=1&y=2").Should().Be(Redirect("/over-mij?x=1&y=2"));
// R6
[Theory]
[InlineData("/index")]
[InlineData("/index.html")]
[InlineData("/Index")]
[InlineData("/index/")]
public void IndexVariants_RedirectToRoot(string path) => Resolve(path).Should().Be(Redirect("/"));
// R7
[Theory]
[InlineData("/404")]
[InlineData("/404.html")]
[InlineData("/404/")]
public void NotFoundPage_IsNeverServedDirectly(string path) =>
Resolve(path).Should().BeOfType<WebsiteResolution.NotFound>();
// R8
[Fact]
public void Asset_IsServedAsIs() =>
Resolve("/assets/app.abc123.js").Should().Be(Serve("assets/app.abc123.js"));
[Fact]
public void Asset_IsNeverLowerCasedOrRedirected() =>
Resolve("/assets/APP.abc123.js").Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void MissingFile_IsNotFound_AndNeverFallsBackToAPage() =>
Resolve("/assets/missing.js").Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void RootFile_IsServed() => Resolve("/robots.txt").Should().Be(Serve("robots.txt"));
// R11
[Theory]
[InlineData("/onbekend/", "/onbekend")]
[InlineData("/a/b/c//", "/a/b/c")]
[InlineData("/assets/", "/assets")]
public void TrailingSlash_RedirectsToStrippedPath_EvenWhenTargetDoesNotExist(string path, string target) =>
Resolve(path).Should().Be(Redirect(target));
[Fact]
public void TrailingSlash_KeepsQueryString() =>
Resolve("/onbekend/", "?a=1").Should().Be(Redirect("/onbekend?a=1"));
[Fact]
public void RedirectTarget_NeverEndsInSlashExceptRoot()
{
foreach (var path in new[] { "/x/", "/over-mij/", "/index/", "/a//" })
{
if (Resolve(path) is WebsiteResolution.Redirect r)
{
(r.Location == "/" || !r.Location.TrimEnd('?').EndsWith('/')).Should().BeTrue(path);
}
}
}
// R12
[Theory]
[InlineData("//evil.example/")]
[InlineData("//evil.example")]
[InlineData("/\\evil.example")]
[InlineData("/a\\b")]
[InlineData("/a//b")]
public void OpenRedirectShapes_AreNotFound(string path) =>
Resolve(path).Should().BeOfType<WebsiteResolution.NotFound>();
// R2
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("over-mij")]
[InlineData("/a\0b")]
[InlineData("/a\nb")]
[InlineData("/../etc/passwd")]
[InlineData("/assets/../../secret")]
[InlineData("/%2e%2e/secret")]
[InlineData("/%2E%2E%2Fsecret")]
[InlineData("/a%5cb")]
public void InvalidOrTraversalInput_IsNotFound(string? path) =>
Resolve(path).Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void OverlongPath_IsNotFound() =>
Resolve("/" + new string('a', 3000)).Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void QueryWithControlCharacters_IsNotFound() =>
Resolve("/Over-Mij", "?a=\r\nSet-Cookie: x=1").Should().BeOfType<WebsiteResolution.NotFound>();
// R3
[Theory]
[InlineData("/.env")]
[InlineData("/.git/config")]
[InlineData("/assets/.hidden")]
[InlineData("/.well-known/.hidden")]
[InlineData("/./over-mij")]
public void DotSegments_AreNotFound(string path) =>
Resolve(path).Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void WellKnown_IsServed() =>
Resolve("/.well-known/security.txt").Should().Be(Serve(".well-known/security.txt"));
// R1
[Theory]
[InlineData("/admin", true)]
[InlineData("/Admin/dashboard", true)]
[InlineData("/api/v1", true)]
[InlineData("/API/V1/offerings", true)]
[InlineData("/health", true)]
[InlineData("/administrator", false)]
[InlineData("/api", false)]
[InlineData("/api/v2/x", false)]
[InlineData("/over-mij", false)]
[InlineData("/", false)]
[InlineData(null, false)]
public void IsReservedPath_MatchesWholeSegmentsOnly(string? path, bool expected) =>
WebsitePathResolver.IsReservedPath(path).Should().Be(expected);
[Theory]
[InlineData("/admin")]
[InlineData("/api/v1/x")]
[InlineData("/health")]
public void ReservedPaths_AreNeverResolved(string path) =>
Resolve(path).Should().BeOfType<WebsiteResolution.NotFound>();
// R13
[Fact]
public void DirectoryWithoutIndexPage_IsNotFound() =>
Resolve("/assets").Should().BeOfType<WebsiteResolution.NotFound>();
// R14 / unknown
[Fact]
public void UnknownPage_IsNotFound() => Resolve("/onbekend").Should().BeOfType<WebsiteResolution.NotFound>();
// NFR-PF-01
[Theory]
[InlineData("/")]
[InlineData("/over-mij")]
[InlineData("/Over-Mij/")]
[InlineData("/assets/app.abc123.js")]
[InlineData("/onbekend")]
[InlineData("/blog")]
[InlineData("/onbekend/")]
public void Resolve_DoesAtMostTwoFileChecks(string path)
{
var calls = 0;
WebsitePathResolver.Resolve(path, null, candidate =>
{
calls++;
return Exists(candidate);
});
calls.Should().BeLessThanOrEqualTo(2);
}
[Fact]
public void PredicateFailure_IsNotFound_NeverAnException() =>
WebsitePathResolver.Resolve("/over-mij", null, _ => throw new IOException("disk"))
.Should().BeOfType<WebsiteResolution.NotFound>();
[Fact]
public void ServedPath_AfterRedirect_IsServedWithoutSecondRedirect()
{
var first = (WebsiteResolution.Redirect)Resolve("/Over-Mij/");
Resolve(first.Location).Should().Be(Serve("over-mij.html"));
}
}
@@ -15,6 +15,8 @@
<PackageReference Include="AutoFixture" Version="4.18.1" />
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="FsCheck.Xunit" Version="3.4.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />