From 612263e82809b0d5f3fc079f4bf6856355e8668d Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Sun, 15 Nov 2026 15:07:52 +0100 Subject: [PATCH] Fase B2: ASF-testproject opgeheven; tests verhuisd naar de master-Api (geen testverlies, 18 -> 18) Tellijst Api.AndreaSlopFotografie.Tests (18): - HostConfigurationTests (7) -> Api.Tests/SiteContractTests: NoIndex (beide sites), StrictSite+padbeleid, https-only site-origins, geen geheimen (beide), Contact uit + SiteId (beide), 'ASF zonder Master' (nu exacte modulelijst per csproj), mail uit (beide) + logo-urls. - HostPipelineTests (7) -> Api.Tests: AsfVariantPipelineTests (health, setup/status, 404+CSP+noindex, robots; master-host met de gedragsinstellingen van ASF) en OfferingsOnTheMasterHostTests (capabilities, banner 204, migraties == model). - ContactHostTests (4) -> Contact.Tests/Pipeline/SiteVariantContactTests (defaults dicht, poort + SiteId andreaslop, proxy bekend/onbekend). Nieuw: sitecontract per site (modules, Website:Mode, Program.cs dun), WebsiteModeSelection (modus eenmalig bepaald), Api.Tests serieel (MySql.Data). Co-Authored-By: Claude Sonnet 5.5 --- README.md | 4 +- SlpModularCms.sln | 15 -- .../HostConfigurationTests.cs | 104 --------- ...rCms.Api.AndreaSlopFotografie.Tests.csproj | 33 --- .../Program.cs | 2 - .../AssemblyBehavior.cs | 2 +- .../SiteContractTests.cs | 155 +++++++++++++ src/SlpModularCms.Api.Tests/SiteFiles.cs | 73 ++++++ .../SiteVariantPipelineTests.cs} | 121 ++++++---- src/SlpModularCms.Core/Hosting/CmsHost.cs | 3 +- .../Hosting/CmsHostOptions.cs | 8 + .../Pipeline/ContactHostFactory.cs | 2 +- .../Pipeline/SiteVariantContactTests.cs} | 217 ++++++++---------- 13 files changed, 408 insertions(+), 331 deletions(-) delete mode 100644 src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs delete mode 100644 src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj rename src/{SlpModularCms.Api.AndreaSlopFotografie.Tests => SlpModularCms.Api.Tests}/AssemblyBehavior.cs (82%) create mode 100644 src/SlpModularCms.Api.Tests/SiteContractTests.cs create mode 100644 src/SlpModularCms.Api.Tests/SiteFiles.cs rename src/{SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs => SlpModularCms.Api.Tests/SiteVariantPipelineTests.cs} (52%) rename src/{SlpModularCms.Api.AndreaSlopFotografie.Tests/ContactHostTests.cs => SlpModularCms.Modules.Contact.Tests/Pipeline/SiteVariantContactTests.cs} (53%) diff --git a/README.md b/README.md index 79b5c5e..f6f8165 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Een modulaire monolith CMS gebouwd met .NET 10. - `src/SlpModularCms.Api`: De host applicatie en API shell (lokale ontwikkeling / dev-host). - `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`- en `Contact`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project. -- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host de modules `Identity`, `Availability`, `Offerings` en `Contact` (geen `Master`) en serveert de voorgerenderde website uit `wwwroot/web/` (`WebsiteMode.PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Bijbehorende tests: `SlpModularCms.Api.AndreaSlopFotografie.Tests` (de pipelinetests daarin hebben net als `Api.Tests` een bereikbare MariaDB nodig). +- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host de modules `Identity`, `Availability`, `Offerings` en `Contact` (geen `Master`) en serveert de voorgerenderde website uit `wwwroot/web/` (`Website:Mode=PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Geen eigen testproject: het gedrag zit in Core en de modules en wordt getest op de master-`SlpModularCms.Api` (alle modules); de samenstelling en standaardwaarden van deze site worden getest in `SlpModularCms.Api.Tests` (`SiteContractTests`, `AsfVariantPipelineTests`) en `SlpModularCms.Modules.Contact.Tests` (`SiteVariantContactTests`). `Website:Mode=PrerenderedPages` staat in de eigen `appsettings.json`. - `src/SlpModularCms.Core`: Kern functionaliteiten, data modellen en interfaces. Bevat ook `Core/Hosting/CmsHost.cs` — de gedeelde service- en pipeline-compositie die elk Client-project (`Api`, `Api.SlpSoftware`) vanuit zijn eigen dunne `Program.cs` aanroept, zodat beide projecten niet uit elkaar kunnen groeien. - `src/SlpModularCms.Modules.*`: Onafhankelijke functionele modules. - `frontend/`: De CMS admin web-UI (Vite + React + TypeScript). Bewust buiten `src/` gehouden om de .NET solution schoon te houden. @@ -376,7 +376,7 @@ In productie moeten gevoelige instellingen worden doorgegeven via Environment Va - `Observability__SentryDsn` — leeg is een normale, ondersteunde staat: Sentry wordt dan overgeslagen en alleen console-logging blijft actief - `SecurityHeaders__AllowedScriptOrigins__0`, `SecurityHeaders__AllowedConnectOrigins__0`, ... — externe origins die de CSP van `/admin` en `/api/v1` mag toestaan (bijv. de Umami-scripthost en Sentry's ingest-endpoint). Zie `appsettings.json → SecurityHeaders` voor de volledige optiesvorm; een onbekende `PathPolicies`-policy-naam laat de applicatie bij **opstarten** falen, niet pas bij de eerste request -- **Voorgerenderde website (`WebsiteMode.PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md). +- **Voorgerenderde website (`Website:Mode=PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md). ### 2a. Data Protection key ring (Master CMS Module) De API keys van geregistreerde slaves worden versleuteld opgeslagen met ASP.NET Core Data Protection. De key ring wordt **automatisch** persistent opgeslagen in de database (`PersistKeysToDbContext`, met een expliciete, stabiele applicatie-discriminator) — dit hoeft niet meer apart geconfigureerd te worden. Dit is bewust zo gebouwd omdat de atomische release-switch (zie hierboven) bij elke deploy een nieuwe content-root-map gebruikt: zonder een database-backed key ring zou dat elke keer de key ring weggooien en alle opgeslagen slave-API-keys onleesbaar maken. diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 8ca0860..6576ff6 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -40,8 +40,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offer EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}" @@ -236,18 +234,6 @@ Global {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.Build.0 = Release|Any CPU {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = Release|Any CPU {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.Build.0 = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.ActiveCfg = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.Build.0 = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.ActiveCfg = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.Build.0 = Debug|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.Build.0 = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.ActiveCfg = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = Debug|Any CPU {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -294,7 +280,6 @@ Global {43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894} {759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} - {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894} EndGlobalSection diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs deleted file mode 100644 index 8c8cee1..0000000 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -using FluentAssertions; -using Microsoft.Extensions.Configuration; - -namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; - -/// -/// Guards the committed defaults of the Andrea Slop Fotografie host. These need no database, so they -/// run everywhere (unlike ). -/// -public class HostConfigurationTests -{ - private static IConfigurationRoot Load() - { - var dir = new DirectoryInfo(AppContext.BaseDirectory); - while (dir is not null && - !File.Exists(Path.Combine(dir.FullName, "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"))) - { - dir = dir.Parent; - } - - dir.Should().NotBeNull("the host project must be found next to this test project"); - var path = Path.Combine(dir!.FullName, "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"); - return new ConfigurationBuilder().AddJsonFile(path, optional: false).Build(); - } - - [Fact] - public void WebsiteIsNoIndex_ByDefault() - { - Load().GetValue("Website:NoIndex").Should().BeTrue(); - } - - [Fact] - public void DefaultPolicyIsStrictSite_AndAdminApiHealthStayStrict() - { - var config = Load(); - - config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite"); - var rules = config.GetSection("SecurityHeaders:PathPolicies").GetChildren() - .ToDictionary(c => c["PathPrefix"]!, c => c["Policy"]!); - rules.Should().Contain(new KeyValuePair("/admin", "Strict")) - .And.Contain(new KeyValuePair("/api/v1", "Strict")) - .And.Contain(new KeyValuePair("/health", "Strict")); - } - - [Fact] - public void SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists() - { - var config = Load(); - var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get()! - .Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get()!); - - site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://")); - config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get().Should().BeEmpty(); - config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get().Should().BeEmpty(); - } - - [Fact] - public void NoSecretsAreCommitted() - { - var config = Load(); - - config["JwtSettings:Secret"].Should().StartWith("<"); - config["ConnectionStrings:DefaultConnection"].Should().Contain(""); - config["Identity:Setup:Token"].Should().BeNullOrEmpty(); - config["Observability:SentryDsn"].Should().BeNullOrEmpty(); - config.GetSection("ForwardedHeaders:KnownProxies").Get().Should().BeNullOrEmpty(); - } - - [Fact] - public void Contact_IsOffByDefault_ForTheRightSite_WithNoRecipientOrCaptchaSecretCommitted() - { - var config = Load(); - - config.GetValue("Contact:Enabled").Should().BeFalse(); - config["Contact:SiteId"].Should().Be("andreaslop"); - config.GetValue("Contact:Captcha:Enabled").Should().BeFalse(); - config["Contact:RecipientEmail"].Should().BeNullOrEmpty("the address comes from the environment only"); - config["Contact:Captcha:Secret"].Should().BeNullOrEmpty(); - config["Contact:Captcha:SiteKey"].Should().BeNullOrEmpty(); - } - - [Fact] - public void Host_DoesNotReferenceTheMasterModule() - { - // Offerings has no compile-time reference from the host (modules are discovered at runtime), so its - // presence is asserted through /System/capabilities in HostPipelineTests instead. - var referenced = typeof(Program).Assembly.GetReferencedAssemblies().Select(a => a.Name); - - referenced.Should().NotContain("SlpModularCms.Modules.Master"); - } - - [Fact] - public void Mail_IsOffByDefault_AndNoCredentialIsCommitted() - { - var config = Load(); - - config["Email:Smtp:Host"].Should().BeNullOrEmpty("mail is switched on per environment"); - config["Email:Smtp:Username"].Should().BeNullOrEmpty(); - config["Email:Smtp:Password"].Should().BeNullOrEmpty(); - config["Email:FromAddress"].Should().NotBeNullOrEmpty(); - config["Email:LogoUrl"].Should().Be("/admin/brand-logo-mail.png"); - config["Email:LogoDarkUrl"].Should().Be("/admin/brand-logo-on-dark.png"); - } -} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj deleted file mode 100644 index 3952e39..0000000 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - net10.0 - enable - enable - false - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs index 8ca4362..01fd3db 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs @@ -18,5 +18,3 @@ CmsHost.ConfigurePipeline(app, orchestrator, hostOptions); app.Run(); -// Exposed so the host regression tests can start the real application in-memory. -public partial class Program; diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/AssemblyBehavior.cs b/src/SlpModularCms.Api.Tests/AssemblyBehavior.cs similarity index 82% rename from src/SlpModularCms.Api.AndreaSlopFotografie.Tests/AssemblyBehavior.cs rename to src/SlpModularCms.Api.Tests/AssemblyBehavior.cs index dce25e9..688f14b 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/AssemblyBehavior.cs +++ b/src/SlpModularCms.Api.Tests/AssemblyBehavior.cs @@ -1,4 +1,4 @@ -// The host tests start several real hosts against MariaDB/MySQL. The MySql.Data driver keeps a static, +// The pipeline tests start several real hosts against MariaDB/MySQL. The MySql.Data driver keeps a static, // non-thread-safe dictionary that is touched while a connection is opened (MySql.Data.Common.Ssl.StartSSL), so opening // connections from several hosts at the same time can fail with "Operations that change non-concurrent collections // must have exclusive access". The suite is small and fast (the pure unit tests take about a second), so the whole diff --git a/src/SlpModularCms.Api.Tests/SiteContractTests.cs b/src/SlpModularCms.Api.Tests/SiteContractTests.cs new file mode 100644 index 0000000..3a6a6fe --- /dev/null +++ b/src/SlpModularCms.Api.Tests/SiteContractTests.cs @@ -0,0 +1,155 @@ +using FluentAssertions; +using Microsoft.Extensions.Configuration; + +namespace SlpModularCms.Api.Tests; + +/// +/// What every site (client project) must look like, checked from its files alone: the modules it references and +/// the defaults it commits. The sites carry no logic of their own (all behaviour lives in Core and the modules and +/// is tested against the master SlpModularCms.Api host), so a site can only go wrong in its composition: +/// a module reference that is missing or too much, or an unsafe default. These tests need no database. +/// +public class SiteContractTests +{ + public static IEnumerable Sites() => + [ + [SiteFiles.SlpSoftware], + [SiteFiles.AndreaSlopFotografie], + ]; + + [Fact] + public void TheMasterCms_ReferencesEveryModule() + { + SiteFiles.Modules("SlpModularCms.Api").Should().BeEquivalentTo( + ["Availability", "Contact", "Identity", "Master", "Offerings"], + "the master Api is the all-modules composition the CI builds and tests"); + } + + [Fact] + public void SlpSoftware_IsTheFullComposition() + { + SiteFiles.Modules(SiteFiles.SlpSoftware).Should().BeEquivalentTo( + ["Availability", "Contact", "Identity", "Master", "Offerings"]); + } + + [Fact] + public void AndreaSlopFotografie_HasEverythingExceptTheMasterModule() + { + // Not a master/slave setup: no Master module, so /System/capabilities does not list it. + SiteFiles.Modules(SiteFiles.AndreaSlopFotografie).Should().BeEquivalentTo( + ["Availability", "Contact", "Identity", "Offerings"]); + } + + [Theory] + [MemberData(nameof(Sites))] + public void NoSiteReferencesAModuleTheMasterDoesNot(string site) + { + SiteFiles.Modules(site).Should().BeSubsetOf(SiteFiles.Modules("SlpModularCms.Api"), + "a module that the CI does not build and test must not ship in a site"); + } + + [Theory] + [InlineData(SiteFiles.SlpSoftware, "SpaFallback")] + [InlineData(SiteFiles.AndreaSlopFotografie, "PrerenderedPages")] + public void EachSite_ServesItsWebsiteTheRightWay(string site, string mode) + { + // Missing means SpaFallback (the host's default); Andrea's prerendered site must say so explicitly, + // otherwise it would start as an SPA and answer 200 for every unknown path. + var configured = SiteFiles.Committed(site)["Website:Mode"]; + (configured ?? "SpaFallback").Should().Be(mode); + } + + [Theory] + [MemberData(nameof(Sites))] + public void WebsiteIsNoIndex_ByDefault(string site) + { + SiteFiles.Committed(site).GetValue("Website:NoIndex").Should().BeTrue( + "indexing is switched on per environment, never by the committed defaults"); + } + + [Theory] + [MemberData(nameof(Sites))] + public void NoSecretsAreCommitted(string site) + { + var config = SiteFiles.Committed(site); + + config["JwtSettings:Secret"].Should().StartWith("<"); + config["ConnectionStrings:DefaultConnection"].Should().Contain(""); + config["Identity:Setup:Token"].Should().BeNullOrEmpty(); + config["Observability:SentryDsn"].Should().BeNullOrEmpty(); + config.GetSection("ForwardedHeaders:KnownProxies").Get().Should().BeNullOrEmpty( + "the proxy address is environment configuration"); + } + + [Theory] + [InlineData(SiteFiles.SlpSoftware, "slpsoftware")] + [InlineData(SiteFiles.AndreaSlopFotografie, "andreaslop")] + public void Contact_IsOffByDefault_ForTheRightSite_WithNoRecipientOrCaptchaSecretCommitted(string site, string siteId) + { + var config = SiteFiles.Committed(site); + + config.GetValue("Contact:Enabled").Should().BeFalse(); + config["Contact:SiteId"].Should().Be(siteId); + config.GetValue("Contact:Captcha:Enabled").Should().BeFalse(); + config["Contact:RecipientEmail"].Should().BeNullOrEmpty("the address comes from the environment only"); + config["Contact:Captcha:Secret"].Should().BeNullOrEmpty(); + config["Contact:Captcha:SiteKey"].Should().BeNullOrEmpty(); + } + + [Theory] + [MemberData(nameof(Sites))] + public void Mail_IsOffByDefault_AndNoCredentialIsCommitted(string site) + { + var config = SiteFiles.Committed(site); + + config["Email:Smtp:Host"].Should().BeNullOrEmpty("mail is switched on per environment"); + config["Email:Smtp:Username"].Should().BeNullOrEmpty(); + config["Email:Smtp:Password"].Should().BeNullOrEmpty(); + config["Email:FromAddress"].Should().NotBeNullOrEmpty(); + } + + [Fact] + public void AndreaSlopFotografie_DefaultPolicyIsStrictSite_AndAdminApiHealthStayStrict() + { + var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie); + + config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite"); + var rules = config.GetSection("SecurityHeaders:PathPolicies").GetChildren() + .ToDictionary(c => c["PathPrefix"]!, c => c["Policy"]!); + rules.Should().Contain(new KeyValuePair("/admin", "Strict")) + .And.Contain(new KeyValuePair("/api/v1", "Strict")) + .And.Contain(new KeyValuePair("/health", "Strict")); + } + + [Fact] + public void AndreaSlopFotografie_SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists() + { + var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie); + var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get()! + .Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get()!); + + site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://")); + config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get().Should().BeEmpty(); + config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get().Should().BeEmpty(); + } + + [Fact] + public void AndreaSlopFotografie_MailBrandingPointsAtTheAdminAssets() + { + var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie); + + config["Email:LogoUrl"].Should().Be("/admin/brand-logo-mail.png"); + config["Email:LogoDarkUrl"].Should().Be("/admin/brand-logo-on-dark.png"); + } + + [Theory] + [MemberData(nameof(Sites))] + public void EachSiteProgram_IsAThinComposition(string site) + { + // The site's Program.cs may only compose: no mode, module or option decisions in code. + var program = File.ReadAllText(Path.Combine(SiteFiles.SourceRoot(), site, "Program.cs")); + + program.Should().Contain("CmsHost.ConfigureServices").And.Contain("CmsHost.ConfigurePipeline"); + program.Should().NotContain("WebsiteMode.", "the mode is chosen with Website:Mode in appsettings.json"); + } +} diff --git a/src/SlpModularCms.Api.Tests/SiteFiles.cs b/src/SlpModularCms.Api.Tests/SiteFiles.cs new file mode 100644 index 0000000..e8b9292 --- /dev/null +++ b/src/SlpModularCms.Api.Tests/SiteFiles.cs @@ -0,0 +1,73 @@ +using FluentAssertions; +using Microsoft.Extensions.Configuration; + +namespace SlpModularCms.Api.Tests; + +/// +/// Finds the site (client) projects in the repository without referencing or building them. The sites are thin +/// compositions (a Program.cs, a list of modules and an appsettings.json); what these tests check about them is +/// read from those files. +/// +internal static class SiteFiles +{ + public const string SlpSoftware = "SlpModularCms.Api.SlpSoftware"; + public const string AndreaSlopFotografie = "SlpModularCms.Api.AndreaSlopFotografie"; + + /// The directory that holds the project folders (src). + public static string SourceRoot() + { + // Walks up from the test output and from the working directory, so it also works when the build output + // is redirected elsewhere in the repository (for example with --artifacts-path). + foreach (var start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) + { + for (var dir = new DirectoryInfo(start); dir is not null; dir = dir.Parent) + { + if (File.Exists(Path.Combine(dir.FullName, "SlpModularCms.Api", "appsettings.json"))) + return dir.FullName; + if (File.Exists(Path.Combine(dir.FullName, "src", "SlpModularCms.Api", "appsettings.json"))) + return Path.Combine(dir.FullName, "src"); + } + } + + throw new InvalidOperationException("The src folder with the SlpModularCms.* projects was not found above the test output."); + } + + public static string AppSettingsPath(string site) => Path.Combine(SourceRoot(), site, "appsettings.json"); + + public static string CsprojPath(string site) => Path.Combine(SourceRoot(), site, site + ".csproj"); + + /// The committed appsettings.json of a site, exactly as deployed (no environment on top). + public static IConfigurationRoot Committed(string site) + { + File.Exists(AppSettingsPath(site)).Should().BeTrue($"{site} must have an appsettings.json"); + return new ConfigurationBuilder().AddJsonFile(AppSettingsPath(site), optional: false).Build(); + } + + /// The module projects a site references, as short names (Offerings, Identity, ...). + public static IReadOnlySet Modules(string site) + { + var doc = System.Xml.Linq.XDocument.Load(CsprojPath(site)); + return doc.Descendants("ProjectReference") + .Select(e => (string?)e.Attribute("Include") ?? string.Empty) + .Select(include => Path.GetFileNameWithoutExtension(include.Replace('\\', '/'))) + .Where(name => name.StartsWith("SlpModularCms.Modules.", StringComparison.Ordinal)) + .Select(name => name["SlpModularCms.Modules.".Length..]) + .ToHashSet(StringComparer.Ordinal); + } + + /// + /// The site's own settings that shape behaviour (never connection strings or secrets), as in-memory key/values + /// to put on top of the master host's configuration. That is how a test runs the master composition "as" a site. + /// + public static Dictionary BehaviourSettings(string site) + { + string[] sections = + [ + "Website", "SecurityHeaders", "Contact", "Email", "Identity", "ForwardedHeaders", "Cors", "App", "RateLimiting", + ]; + var committed = Committed(site); + return committed.AsEnumerable() + .Where(kv => kv.Value is not null && sections.Any(s => kv.Key.StartsWith(s + ":", StringComparison.Ordinal))) + .ToDictionary(kv => kv.Key, kv => kv.Value); + } +} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs b/src/SlpModularCms.Api.Tests/SiteVariantPipelineTests.cs similarity index 52% rename from src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs rename to src/SlpModularCms.Api.Tests/SiteVariantPipelineTests.cs index 997725f..29cbe30 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs +++ b/src/SlpModularCms.Api.Tests/SiteVariantPipelineTests.cs @@ -1,71 +1,40 @@ using System.Net; -using System.Text.Json; using FluentAssertions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Modules.Offerings.Data; -namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; +namespace SlpModularCms.Api.Tests; -/// Starts the real host in-memory (Development environment). -public class AsfWebApplicationFactory : WebApplicationFactory +/// +/// The master host with the behaviour settings of Andrea Slop Fotografie on top (website mode, security headers, +/// contact and mail defaults). The sites have no logic of their own, so this is how a site's behaviour is tested +/// without building the site project: same code, the site's committed configuration. +/// +public class AsfVariantFactory : WebApplicationFactory { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Development"); + // Each setting both as a host setting (visible while the services are registered) and as configuration. + var settings = SiteFiles.BehaviourSettings(SiteFiles.AndreaSlopFotografie); + foreach (var (key, value) in settings) + { + builder.UseSetting(key, value); + } + + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(settings)); } } -/// -/// Requires a reachable local MariaDB matching appsettings.Development.json of the host, -/// because CmsHost.ConfigurePipeline migrates the database before any endpoint answers -/// (same precondition as SlpModularCms.Api.Tests). -/// -public class HostPipelineTests : IClassFixture +public class AsfVariantPipelineTests : IClassFixture { - private readonly AsfWebApplicationFactory _factory; + private readonly AsfVariantFactory _factory; - public HostPipelineTests(AsfWebApplicationFactory factory) => _factory = factory; - - [Fact] - public async Task Capabilities_ListIdentityAvailabilityAndOfferings_ButNotMaster() - { - var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities"); - - response.StatusCode.Should().Be(HttpStatusCode.OK); - using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - var modules = doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).ToList(); - modules.Should().Contain("Identity").And.Contain("Availability").And.Contain("Offerings"); - modules.Should().NotContain("Master"); - } - - [Fact] - public async Task OfferingBanner_Is204_WhenNoneIsActive_AndOfferingsAreListed_OnAMigratedDatabase() - { - var client = _factory.CreateClient(); - - var banner = await client.GetAsync("/api/v1/offerings/banner"); - banner.StatusCode.Should().Be(HttpStatusCode.NoContent); - - // Position: top works the same, no parameter means bottom, anything else is rejected. - (await client.GetAsync("/api/v1/offerings/banner?position=top")).StatusCode.Should().Be(HttpStatusCode.NoContent); - (await client.GetAsync("/api/v1/offerings/banner?position=bottom")).StatusCode.Should().Be(HttpStatusCode.NoContent); - (await client.GetAsync("/api/v1/offerings/banner?position=left")).StatusCode.Should().Be(HttpStatusCode.BadRequest); - - (await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK); - (await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); - } - - [Fact] - public void OfferingsMigrations_MatchTheModel() - { - _ = _factory.CreateClient(); // starts the host and migrates - using var scope = _factory.Services.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot"); - } + public AsfVariantPipelineTests(AsfVariantFactory factory) => _factory = factory; [Fact] public async Task Health_IsReachable() @@ -85,6 +54,7 @@ public class HostPipelineTests : IClassFixture [Fact] public async Task UnknownWebsitePath_Returns404_WithTheSiteSecurityHeaders_AndNoIndex() { + // Website:Mode=PrerenderedPages comes from the site's settings: an SPA would answer 200 here. var response = await _factory.CreateClient().GetAsync("/some-page-that-does-not-exist"); response.StatusCode.Should().Be(HttpStatusCode.NotFound); @@ -100,4 +70,53 @@ public class HostPipelineTests : IClassFixture body.Should().Contain("Disallow: /"); } + + [Fact] + public void TheVariantReallyUsesTheSitesSettings() + { + var config = _factory.Services.GetRequiredService(); + + config["Website:Mode"].Should().Be("PrerenderedPages"); + config["Contact:SiteId"].Should().Be("andreaslop"); + config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite"); + } +} + +/// Offerings behaviour that needs the real, migrated database (Offerings is part of the master host). +public class OfferingsOnTheMasterHostTests : IClassFixture +{ + private readonly ApiWebApplicationFactory _factory; + + public OfferingsOnTheMasterHostTests(ApiWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task Capabilities_ListEveryModule() + { + var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var doc = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var modules = doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).ToList(); + modules.Should().Contain(["Identity", "Availability", "Offerings", "Contact", "Master"]); + } + + [Fact] + public async Task OfferingBanner_Is204_WhenNoneIsActive_AndOfferingsAreListed_OnAMigratedDatabase() + { + var client = _factory.CreateClient(); + + (await client.GetAsync("/api/v1/offerings/banner")).StatusCode.Should().Be(HttpStatusCode.NoContent); + (await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public void OfferingsMigrations_MatchTheModel() + { + _ = _factory.CreateClient(); // starts the host and migrates + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot"); + } } diff --git a/src/SlpModularCms.Core/Hosting/CmsHost.cs b/src/SlpModularCms.Core/Hosting/CmsHost.cs index 961a426..7322ef9 100644 --- a/src/SlpModularCms.Core/Hosting/CmsHost.cs +++ b/src/SlpModularCms.Core/Hosting/CmsHost.cs @@ -60,6 +60,7 @@ public static class CmsHost builder.Services.AddCmsObservability(builder.Configuration); var websiteMode = options.ResolveWebsiteMode(builder.Configuration); + builder.Services.AddSingleton(new WebsiteModeSelection(websiteMode)); if (websiteMode == WebsiteMode.PrerenderedPages) { builder.Services.AddCmsWebsite(builder.Configuration); @@ -97,7 +98,7 @@ public static class CmsHost /// public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options) { - var websiteMode = options.ResolveWebsiteMode(app.Configuration); + var websiteMode = app.Services.GetService()?.Mode ?? options.ResolveWebsiteMode(app.Configuration); // 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 // modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot diff --git a/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs b/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs index 503615e..796aabf 100644 --- a/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs +++ b/src/SlpModularCms.Core/Hosting/CmsHostOptions.cs @@ -24,6 +24,14 @@ public enum WebsiteMode /// , is how a Client project opts into different behaviour. /// Defaults reproduce the behaviour every existing Client project already has. /// +/// The website mode this host started with, decided once while the services were registered. +/// +/// The pipeline reads this instead of resolving the mode a second time, so the registered services and the +/// pipeline can never disagree about the mode (a half-configured host that registers SPA services but runs the +/// prerendered pipeline would fail on its first request). +/// +public sealed record WebsiteModeSelection(WebsiteMode Mode); + public sealed class CmsHostOptions { /// diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs index 599ad43..4dc7c28 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs @@ -24,7 +24,7 @@ public class ContactHostFactory : WebApplicationFactory, IAsyncLifetime Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask; - private async Task OpenCmsSwitchAsync() + public async Task OpenCmsSwitchAsync() { _ = CreateClient(); // starts the host (migrates the contact tables) await WithDb(async db => diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/ContactHostTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/SiteVariantContactTests.cs similarity index 53% rename from src/SlpModularCms.Api.AndreaSlopFotografie.Tests/ContactHostTests.cs rename to src/SlpModularCms.Modules.Contact.Tests/Pipeline/SiteVariantContactTests.cs index 3d5af63..66c182b 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/ContactHostTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/SiteVariantContactTests.cs @@ -1,58 +1,80 @@ using System.Net; -using System.Net.Http.Json; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; using FluentAssertions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using SlpModularCms.Modules.Contact.Data; -using SlpModularCms.Modules.Contact.Data.Entities; -namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; /// -/// The real Andrea Slop Fotografie host with the Contact module, against a real MariaDB/MySQL (like the other -/// host tests: set ConnectionStrings__DefaultConnection to a server you may create databases on; every -/// factory uses its own throw-away database). +/// The contact module on the master host with the committed behaviour settings of a site on top (Andrea Slop +/// Fotografie: SiteId, security headers, mail and contact defaults). The site projects have no logic of their +/// own, so this is how a site's contact behaviour is tested without building the site project. /// -public class AsfContactHostFactory : WebApplicationFactory +internal static class AsfSettings { - private readonly Dictionary _settings; - private readonly string _databaseName = "AsfContactHost_" + Guid.NewGuid().ToString("N")[..12]; + private static readonly string[] Sections = + ["Website", "SecurityHeaders", "Contact", "Email", "Identity", "ForwardedHeaders", "Cors", "App", "RateLimiting"]; + + public static Dictionary Committed() + { + string? path = null; + foreach (var start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) + { + for (var dir = new DirectoryInfo(start); dir is not null && path is null; dir = dir.Parent) + { + var candidates = new[] + { + Path.Combine(dir.FullName, "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"), + Path.Combine(dir.FullName, "src", "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"), + }; + path = candidates.FirstOrDefault(File.Exists); + } + } + + path.Should().NotBeNull("the committed settings of the Andrea Slop Fotografie site must be found in the repository"); + var config = new ConfigurationBuilder().AddJsonFile(path!, optional: false).Build(); + return config.AsEnumerable() + .Where(kv => kv.Value is not null && Sections.Any(s => kv.Key.StartsWith(s + ":", StringComparison.Ordinal))) + .ToDictionary(kv => kv.Key, kv => kv.Value); + } +} + +public class AsfContactHostFactory : ContactHostFactory +{ + private readonly Dictionary _site; /// When set, the pipeline sees this as the TCP peer (the reverse proxy) of every request. public string? PeerAddress { get; init; } - public AsfContactHostFactory(Dictionary? settings = null) => _settings = settings ?? []; + public AsfContactHostFactory(Dictionary? overrides = null) + : this(AsfSettings.Committed(), overrides) + { + } - private static string BaseConnectionString => - Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") - ?? throw new InvalidOperationException("Set ConnectionStrings__DefaultConnection to a MariaDB/MySQL server for the host tests."); + private AsfContactHostFactory(Dictionary site, Dictionary? overrides) + : base(Merge(site, overrides)) + { + _site = site; + } - private string ConnectionString => - Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase) - ? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase) - : $"{BaseConnectionString};Database={_databaseName}"; + private static Dictionary Merge(Dictionary site, Dictionary? overrides) + { + var all = new Dictionary(site); + foreach (var (key, value) in overrides ?? []) all[key] = value; + return all; + } protected override void ConfigureWebHost(IWebHostBuilder builder) { - builder.UseEnvironment("Development"); - builder.ConfigureAppConfiguration((_, config) => - { - var all = new Dictionary - { - ["ConnectionStrings:DefaultConnection"] = ConnectionString, - ["Availability:StatusCacheSeconds"] = "0", - }; - foreach (var (key, value) in _settings) all[key] = value; - config.AddInMemoryCollection(all); - }); + base.ConfigureWebHost(builder); + + // Also as host settings: those are visible while the services are registered (the website mode is read then). + foreach (var (key, value) in _site) builder.UseSetting(key, value); if (PeerAddress is not null) { @@ -73,47 +95,31 @@ public class AsfContactHostFactory : WebApplicationFactory next(app); }; } - - public async Task WithDb(Func> action) - { - await using var scope = Services.CreateAsyncScope(); - return await action(scope.ServiceProvider.GetRequiredService()); - } - - public async Task OpenCmsSwitchAsync() - { - _ = CreateClient(); // starts the host (migrates the contact tables) - await WithDb(async db => - { - db.ContactSettings.Add(new ContactSettings { Enabled = true, UpdatedAt = DateTimeOffset.UtcNow, UpdatedByUserId = Guid.NewGuid() }); - await db.SaveChangesAsync(); - return 0; - }); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - try - { - using var scope = Services.CreateScope(); - scope.ServiceProvider.GetRequiredService().Database.EnsureDeleted(); - } - catch - { - // Best effort clean-up of the throw-away database. - } - } - - base.Dispose(disposing); - } } -/// The committed defaults, nothing overridden. public sealed class AsfDefaultContactHostFactory() : AsfContactHostFactory(null); -internal static class ContactHttp +public sealed class AsfOpenContactHostFactory() : AsfContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}) +{ + protected override bool OpenCmsSwitch => true; +} + +/// One form submission allowed per window: the buckets show who shares one. +public sealed class AsfOneSubmissionContactHostFactory() : AsfContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}); + +internal static class AsfContactHttp { public const string Route = "/api/v1/contact-messages"; @@ -156,10 +162,10 @@ public class AsfContactDisabledByDefaultTests : IClassFixture e.GetString()).Should().Contain("Contact"); - var token = await client.GetAsync($"{ContactHttp.Route}/token"); + var token = await client.GetAsync($"{AsfContactHttp.Route}/token"); token.StatusCode.Should().Be(HttpStatusCode.NotFound); (await token.Content.ReadAsStringAsync()).Should().BeEmpty(); - (await client.PostAsync(ContactHttp.Route, null)).StatusCode.Should().Be(HttpStatusCode.NotFound); + (await client.PostAsync(AsfContactHttp.Route, null)).StatusCode.Should().Be(HttpStatusCode.NotFound); } } @@ -170,51 +176,25 @@ public class AsfContactGateTests : IClassFixture public AsfContactGateTests(AsfOpenContactHostFactory factory) => _factory = factory; [Fact] - public async Task ThePublicContactRoutes_StayReachable_WhileTheCmsIsNotAvailable_ButTheManagementRoutesAreGated() + public async Task ThePublicContactRoutes_StayReachable_WhileTheCmsIsNotAvailable_AndTheMessageGetsTheSitesId() { - await _factory.OpenCmsSwitchAsync(); + _ = _factory.CreateClient(); // Switch the CMS off through the availability state of the real database (status 1 = not available). await _factory.WithDb(db => db.Database.ExecuteSqlRawAsync( "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'host test', NOW(), 'host test')")); var client = _factory.CreateClient(); - (await client.GetAsync($"{ContactHttp.Route}?pageSize=1")).StatusCode + (await client.GetAsync($"{AsfContactHttp.Route}?pageSize=1")).StatusCode .Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed for everything not marked public"); - var token = await ContactHttp.GetTokenAsync(client); - var post = await ContactHttp.PostAsync(client, token, "ASF Gate"); + var token = await AsfContactHttp.GetTokenAsync(client); + var post = await AsfContactHttp.PostAsync(client, token, "ASF Gate"); post.StatusCode.Should().Be(HttpStatusCode.Accepted); - (await _factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "ASF Gate"))).Should().Be(1); (await _factory.WithDb(db => db.ContactMessages.SingleAsync(m => m.Name == "ASF Gate"))).SiteId.Should().Be("andreaslop"); } } -public sealed class AsfOpenContactHostFactory() : AsfContactHostFactory(new() -{ - ["Contact:Enabled"] = "true", - ["Contact:MinSeconds"] = "0", - ["RateLimiting:ContactForm:PermitLimit"] = "1000", - ["RateLimiting:ContactToken:PermitLimit"] = "1000", -}); - -/// One form submission allowed per window: the buckets show who shares one. -public sealed class AsfBehindProxyWithKnownProxyFactory() : AsfContactHostFactory(new() -{ - ["Contact:Enabled"] = "true", - ["Contact:MinSeconds"] = "0", - ["RateLimiting:ContactForm:PermitLimit"] = "1", - ["RateLimiting:ContactToken:PermitLimit"] = "1000", -}); - -public sealed class AsfBehindProxyWithoutKnownProxyFactory() : AsfContactHostFactory(new() -{ - ["Contact:Enabled"] = "true", - ["Contact:MinSeconds"] = "0", - ["RateLimiting:ContactForm:PermitLimit"] = "1", - ["RateLimiting:ContactToken:PermitLimit"] = "1000", -}); - public class AsfRateLimitBehindIisTests { [Fact] @@ -225,7 +205,17 @@ public class AsfRateLimitBehindIisTests Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", "10.1.1.1"); try { - await RunWithKnownProxyAsync(); + using var factory = new AsfOneSubmissionContactHostFactory { PeerAddress = "10.1.1.1" }; + await factory.OpenCmsSwitchAsync(); + var client = factory.CreateClient(); + + var a1 = await AsfContactHttp.PostAsync(client, await AsfContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A1", "203.0.113.10"); + var a2 = await AsfContactHttp.PostAsync(client, await AsfContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A2", "203.0.113.10"); + var b1 = await AsfContactHttp.PostAsync(client, await AsfContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF B1", "203.0.113.20"); + + a1.StatusCode.Should().Be(HttpStatusCode.Accepted); + a2.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "the same visitor is limited"); + b1.StatusCode.Should().Be(HttpStatusCode.Accepted, "another visitor has a bucket of their own"); } finally { @@ -233,30 +223,15 @@ public class AsfRateLimitBehindIisTests } } - private static async Task RunWithKnownProxyAsync() - { - using var factory = new AsfBehindProxyWithKnownProxyFactory { PeerAddress = "10.1.1.1" }; - await factory.OpenCmsSwitchAsync(); - var client = factory.CreateClient(); - - var a1 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A1", "203.0.113.10"); - var a2 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF A2", "203.0.113.10"); - var b1 = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF B1", "203.0.113.20"); - - a1.StatusCode.Should().Be(HttpStatusCode.Accepted); - a2.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "the same visitor is limited"); - b1.StatusCode.Should().Be(HttpStatusCode.Accepted, "another visitor has a bucket of their own"); - } - [Fact] public async Task WithoutKnownProxies_TheWholeSiteSharesOneBucket_WhichIsWhyItIsAReleaseCondition() { - using var factory = new AsfBehindProxyWithoutKnownProxyFactory { PeerAddress = "10.1.1.1" }; + using var factory = new AsfOneSubmissionContactHostFactory { PeerAddress = "10.1.1.1" }; await factory.OpenCmsSwitchAsync(); var client = factory.CreateClient(); - var a = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF Shared A", "203.0.113.10"); - var b = await ContactHttp.PostAsync(client, await ContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF Shared B", "203.0.113.20"); + var a = await AsfContactHttp.PostAsync(client, await AsfContactHttp.GetTokenAsync(client, "203.0.113.10"), "ASF Shared A", "203.0.113.10"); + var b = await AsfContactHttp.PostAsync(client, await AsfContactHttp.GetTokenAsync(client, "203.0.113.20"), "ASF Shared B", "203.0.113.20"); a.StatusCode.Should().Be(HttpStatusCode.Accepted); b.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "forwarded addresses are ignored without KnownProxies: everybody is the proxy");