Fase B1: Website:Mode via configuratie (ASF kiest in appsettings), Api = alle-modules-compositie; flaky SMTP-test gerepareerd

- CmsHostOptions.ResolveWebsiteMode: Website:Mode wint van de code, default SpaFallback, onbekende waarde stopt de host.
- ASF: Website:Mode=PrerenderedPages in appsettings.json, Program.cs zonder eigen modus.
- SlpModularCms.Api verwijst nu ook naar Offerings en Contact met generieke default-config (Website/Email/App/Contact/RateLimiting).
- SmtpFailureTests: '535' als los getal, niet als substring van een willekeurige poort.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 15:00:56 +01:00
co-authored by Claude Sonnet 5.5
parent d1f833b556
commit 24168c68a1
8 changed files with 160 additions and 10 deletions
@@ -6,8 +6,9 @@ var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true); builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
// Andrea Slop Fotografie serves a prerendered website from wwwroot/web (nginx-equivalent behaviour) // Andrea Slop Fotografie serves a prerendered website from wwwroot/web (nginx-equivalent behaviour)
// instead of the SPA-style website mount the other clients use. // instead of the SPA-style website mount the other clients use. That is chosen by Website:Mode in
var hostOptions = new CmsHostOptions { WebsiteMode = WebsiteMode.PrerenderedPages }; // appsettings.json, not here: this project is a composition (which modules, which settings) and nothing else.
var hostOptions = new CmsHostOptions();
var orchestrator = CmsHost.ConfigureServices(builder, hostOptions); var orchestrator = CmsHost.ConfigureServices(builder, hostOptions);
@@ -44,6 +44,10 @@
"KnownProxies": [] "KnownProxies": []
}, },
"Website": { "Website": {
// Andrea's site is a prerendered multi-page website (served from wwwroot/web like nginx would), not a SPA.
// Chosen here, in configuration, so the host project needs no code of its own and a test can run the same
// host in either mode. A missing value means SpaFallback.
"Mode": "PrerenderedPages",
// Secure default: every website response carries noindex and /robots.txt disallows all. A // Secure default: every website response carries noindex and /robots.txt disallows all. A
// production instance must set Website__NoIndex=false explicitly. // production instance must set Website__NoIndex=false explicitly.
"NoIndex": true "NoIndex": true
@@ -20,8 +20,10 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" /> <ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" /> <ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" /> <ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" /> <ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
</ItemGroup> </ItemGroup>
<!-- <!--
+64
View File
@@ -33,9 +33,57 @@
"FailOpenAfterMinutes": 5, "FailOpenAfterMinutes": 5,
"HttpTimeoutSeconds": 5 "HttpTimeoutSeconds": 5
}, },
"Website": {
// Secure default: every response carries noindex and /robots.txt disallows all. A site sets its own
// Website section (PublicBaseUrl, AuthoredBaseUrl, Sitemap, KnownPaths, Mode) in its appsettings.json.
"NoIndex": true
},
// Mail (invitations, password reset, notices). Mail is OFF while Email:Smtp:Host is empty and every
// flow then works as before (copy the link). Enable per environment with environment variables:
// Email__Smtp__Host, Email__Smtp__Port, Email__Smtp__EnableSsl, Email__Smtp__Username,
// Email__Smtp__Password (secrets only there, never in this file) and App__PublicBaseUrl.
// Extra sender addresses a site may choose in its settings go in Email:AllowedFromAddresses.
"Email": {
"FromAddress": "no-reply@cms.invalid",
"FromName": "SlpModularCms",
"AllowedFromAddresses": [],
"LogoUrl": "",
"BrandColor": "#ac0000",
"Smtp": {
"Host": "",
"Port": 587,
"EnableSsl": true,
"Username": "",
"Password": "",
"TimeoutSeconds": 10
}
},
"App": {
// Public https address of this site, used for links in mails, e.g. https://test.andreaslop.nl
"PublicBaseUrl": "",
"DefaultLanguage": "nl"
},
"Cors": { "Cors": {
"AllowedOrigins": [] "AllowedOrigins": []
}, },
"Contact": {
// OFF by default. The contact rate limits are per visitor (see ContactRateLimitPartition), but that only
// works with the real client address: behind a reverse proxy (IIS) set ForwardedHeaders__KnownProxies__0 to the
// proxy's address first, otherwise all visitors share ONE bucket. Release conditions, in order: that setting;
// Contact__RecipientEmail and working mail (environment only); captcha (recommended); then Contact__Enabled=true.
// The full list is in the Contact section of the Api.AndreaSlopFotografie appsettings.json.
"Enabled": false,
"SiteId": "cms",
"MinSeconds": 3,
"TokenLifetimeMinutes": 120,
"RetentionMonths": 12,
"SpamRetentionDays": 30,
"MaxSpamRowsPerDay": 200,
"MaxBodyBytes": 16384,
"Captcha": {
"Enabled": false
}
},
"RateLimiting": { "RateLimiting": {
"Login": { "Login": {
"PermitLimit": 5, "PermitLimit": 5,
@@ -48,6 +96,22 @@
"SentryTunnel": { "SentryTunnel": {
"PermitLimit": 60, "PermitLimit": 60,
"WindowSeconds": 60 "WindowSeconds": 60
},
"OfferingsPublic": {
"PermitLimit": 120,
"WindowSeconds": 60
},
"ContactForm": {
"PermitLimit": 5,
"WindowSeconds": 600
},
"ContactToken": {
"PermitLimit": 20,
"WindowSeconds": 600
},
"ContactResend": {
"PermitLimit": 5,
"WindowSeconds": 600
} }
}, },
"SecurityHeaders": { "SecurityHeaders": {
@@ -242,7 +242,9 @@ public class SmtpSenderDiagnosticsTests
result.Should().Be(MailSendResult.Fail(MailSendResult.AuthFailed)); result.Should().Be(MailSendResult.Fail(MailSendResult.AuthFailed));
var error = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error).Subject.Message; var error = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error).Subject.Message;
error.Should().Contain("code=auth_failed").And.Contain("phase=AUTH"); error.Should().Contain("code=auth_failed").And.Contain("phase=AUTH");
error.Should().NotContain("user-secret-9").And.NotContain("pw-secret-9").And.NotContain("535"); // The server's reply code must not leak into the log. Match it as a separate number: the random
// ephemeral smtp_port of the stub server can contain the digits 535 (flaky as a plain substring).
error.Should().NotContain("user-secret-9").And.NotContain("pw-secret-9").And.NotMatchRegex(@"(?<!\d)535(?!\d)");
} }
[Fact] [Fact]
@@ -0,0 +1,50 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using SlpModularCms.Core.Hosting;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting;
public class WebsiteModeTests
{
private static IConfiguration Config(string? mode)
=> new ConfigurationBuilder()
.AddInMemoryCollection(mode is null ? [] : new Dictionary<string, string?> { ["Website:Mode"] = mode })
.Build();
[Fact]
public void WithoutAConfiguredMode_TheCodeDefaultIsUsed_WhichIsSpaFallback()
{
new CmsHostOptions().ResolveWebsiteMode(Config(null)).Should().Be(WebsiteMode.SpaFallback);
new CmsHostOptions().ResolveWebsiteMode(Config(" ")).Should().Be(WebsiteMode.SpaFallback);
}
[Theory]
[InlineData("PrerenderedPages", WebsiteMode.PrerenderedPages)]
[InlineData("prerenderedpages", WebsiteMode.PrerenderedPages)]
[InlineData(" SpaFallback ", WebsiteMode.SpaFallback)]
public void TheConfiguredMode_IsUsed_CaseInsensitively(string value, WebsiteMode expected)
{
new CmsHostOptions().ResolveWebsiteMode(Config(value)).Should().Be(expected);
}
[Fact]
public void TheConfiguredMode_WinsOverTheCodeValue_AndTheCodeValueStillWorksAlone()
{
var code = new CmsHostOptions { WebsiteMode = WebsiteMode.PrerenderedPages };
code.ResolveWebsiteMode(Config(null)).Should().Be(WebsiteMode.PrerenderedPages);
code.ResolveWebsiteMode(Config("SpaFallback")).Should().Be(WebsiteMode.SpaFallback);
}
[Theory]
[InlineData("Prerendered")]
[InlineData("1")]
[InlineData("nginx")]
public void AnUnknownMode_StopsTheHost_InsteadOfServingTheSiteTheWrongWay(string value)
{
var act = () => new CmsHostOptions().ResolveWebsiteMode(Config(value));
act.Should().Throw<InvalidOperationException>().WithMessage("*Website:Mode*");
}
}
+8 -6
View File
@@ -59,7 +59,8 @@ public static class CmsHost
builder.Services.AddCmsSecurityHeaders(builder.Configuration); builder.Services.AddCmsSecurityHeaders(builder.Configuration);
builder.Services.AddCmsObservability(builder.Configuration); builder.Services.AddCmsObservability(builder.Configuration);
if (options.WebsiteMode == WebsiteMode.PrerenderedPages) var websiteMode = options.ResolveWebsiteMode(builder.Configuration);
if (websiteMode == WebsiteMode.PrerenderedPages)
{ {
builder.Services.AddCmsWebsite(builder.Configuration); builder.Services.AddCmsWebsite(builder.Configuration);
} }
@@ -96,6 +97,7 @@ public static class CmsHost
/// </summary> /// </summary>
public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options) public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options)
{ {
var websiteMode = options.ResolveWebsiteMode(app.Configuration);
// Bring the Core schema up to date before serving any traffic. Runs before the module // Bring the Core schema up to date before serving any traffic. Runs before the module
// middleware below, because the Data Protection keys table lives in this context and the // middleware below, because the Data Protection keys table lives in this context and the
// modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot // modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot
@@ -121,7 +123,7 @@ public static class CmsHost
// SpaFallback sites: X-Robots-Tag on test hosts and generated robots.txt / sitemap.xml. After the // SpaFallback sites: X-Robots-Tag on test hosts and generated robots.txt / sitemap.xml. After the
// security headers (so these answers carry them) and before the static files short-circuit. // security headers (so these answers carry them) and before the static files short-circuit.
if (options.WebsiteMode == WebsiteMode.SpaFallback) if (websiteMode == WebsiteMode.SpaFallback)
{ {
app.UseCmsSpaSeo(); app.UseCmsSpaSeo();
} }
@@ -142,12 +144,12 @@ public static class CmsHost
// wwwroot/admin/index.html + assets -> CMS admin build (see frontend/, copied in on publish) // wwwroot/admin/index.html + assets -> CMS admin build (see frontend/, copied in on publish)
// Registered before the module middleware below: static files short-circuit the pipeline, so // Registered before the module middleware below: static files short-circuit the pipeline, so
// anything that must observe them has to come first. // anything that must observe them has to come first.
app.UseCmsStaticContent(options.WebsiteMode); app.UseCmsStaticContent(websiteMode);
// WebsiteMode.PrerenderedPages: the website replaces the SPA-style website mount, at the same // WebsiteMode.PrerenderedPages: the website replaces the SPA-style website mount, at the same
// position and for the same reason (it answers before the module middleware and the API). // position and for the same reason (it answers before the module middleware and the API).
// It never handles /admin, /api/v1 or /health. // It never handles /admin, /api/v1 or /health.
if (options.WebsiteMode == WebsiteMode.PrerenderedPages) if (websiteMode == WebsiteMode.PrerenderedPages)
{ {
app.UseCmsPrerenderedSite(); app.UseCmsPrerenderedSite();
} }
@@ -177,11 +179,11 @@ public static class CmsHost
// SPA fallbacks so client-side routes (e.g. /admin/dashboard) resolve to the right index.html // SPA fallbacks so client-side routes (e.g. /admin/dashboard) resolve to the right index.html
// instead of 404ing. The "nonfile" constraint keeps genuinely missing assets (e.g. /admin/assets/x.js) as 404s. // instead of 404ing. The "nonfile" constraint keeps genuinely missing assets (e.g. /admin/assets/x.js) as 404s.
app.MapCmsSpaFallbacks(options.WebsiteMode); app.MapCmsSpaFallbacks(websiteMode);
// WebsiteMode.PrerenderedPages: lowest-priority endpoint, so unknown website paths get // WebsiteMode.PrerenderedPages: lowest-priority endpoint, so unknown website paths get
// 404.html with status 404 only AFTER every API route and the admin fallback had their turn. // 404.html with status 404 only AFTER every API route and the admin fallback had their turn.
if (options.WebsiteMode == WebsiteMode.PrerenderedPages) if (websiteMode == WebsiteMode.PrerenderedPages)
{ {
app.MapCmsWebsiteNotFound(); app.MapCmsWebsiteNotFound();
} }
@@ -26,6 +26,31 @@ public enum WebsiteMode
/// </remarks> /// </remarks>
public sealed class CmsHostOptions public sealed class CmsHostOptions
{ {
/// <summary>How the public website is served. Defaults to <see cref="WebsiteMode.SpaFallback"/>.</summary> /// <summary>
/// How the public website is served when the configuration does not say. Defaults to
/// <see cref="WebsiteMode.SpaFallback"/>. The configuration value <c>Website:Mode</c> wins over this
/// (see <see cref="ResolveWebsiteMode"/>), so a site picks its mode in its appsettings.json and a test
/// can run the same host in either mode.
/// </summary>
public WebsiteMode WebsiteMode { get; init; } = WebsiteMode.SpaFallback; public WebsiteMode WebsiteMode { get; init; } = WebsiteMode.SpaFallback;
/// <summary>
/// The mode to use: <c>Website:Mode</c> (<c>SpaFallback</c> or <c>PrerenderedPages</c>, case-insensitive)
/// when set, otherwise <see cref="WebsiteMode"/>. An unknown value stops the host at start-up instead of
/// silently serving the website the wrong way.
/// </summary>
public WebsiteMode ResolveWebsiteMode(Microsoft.Extensions.Configuration.IConfiguration configuration)
{
var value = configuration["Website:Mode"];
if (string.IsNullOrWhiteSpace(value))
return WebsiteMode;
// Names only: a bare number would also parse, and "1" is not something a person means by a mode.
var name = Enum.GetNames<WebsiteMode>().FirstOrDefault(n => string.Equals(n, value.Trim(), StringComparison.OrdinalIgnoreCase));
if (name is not null)
return Enum.Parse<WebsiteMode>(name);
throw new InvalidOperationException(
$"Website:Mode '{value}' is not valid; use '{nameof(WebsiteMode.SpaFallback)}' or '{nameof(WebsiteMode.PrerenderedPages)}'.");
}
} }