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 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 15:07:52 +01:00
co-authored by Claude Sonnet 5.5
parent ca46ce2e75
commit 612263e828
13 changed files with 408 additions and 331 deletions
+2 -2
View File
@@ -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`: 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.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.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. - `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. - `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 - `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 - `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) ### 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. 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.
-15
View File
@@ -40,8 +40,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offer
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}"
EndProject 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}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}"
EndProject 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}" 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|x64.Build.0 = Release|Any CPU
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = 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 {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.ActiveCfg = Debug|Any CPU
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = 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 {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} {43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
{BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894} {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
{759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} {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} {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
{06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894} {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
EndGlobalSection EndGlobalSection
@@ -1,104 +0,0 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
namespace SlpModularCms.Api.AndreaSlopFotografie.Tests;
/// <summary>
/// Guards the committed defaults of the Andrea Slop Fotografie host. These need no database, so they
/// run everywhere (unlike <see cref="HostPipelineTests"/>).
/// </summary>
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<bool>("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<string, string>("/admin", "Strict"))
.And.Contain(new KeyValuePair<string, string>("/api/v1", "Strict"))
.And.Contain(new KeyValuePair<string, string>("/health", "Strict"));
}
[Fact]
public void SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists()
{
var config = Load();
var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get<string[]>()!
.Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get<string[]>()!);
site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://"));
config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get<string[]>().Should().BeEmpty();
config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get<string[]>().Should().BeEmpty();
}
[Fact]
public void NoSecretsAreCommitted()
{
var config = Load();
config["JwtSettings:Secret"].Should().StartWith("<");
config["ConnectionStrings:DefaultConnection"].Should().Contain("<db-password>");
config["Identity:Setup:Token"].Should().BeNullOrEmpty();
config["Observability:SentryDsn"].Should().BeNullOrEmpty();
config.GetSection("ForwardedHeaders:KnownProxies").Get<string[]>().Should().BeNullOrEmpty();
}
[Fact]
public void Contact_IsOffByDefault_ForTheRightSite_WithNoRecipientOrCaptchaSecretCommitted()
{
var config = Load();
config.GetValue<bool>("Contact:Enabled").Should().BeFalse();
config["Contact:SiteId"].Should().Be("andreaslop");
config.GetValue<bool>("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");
}
}
@@ -1,33 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<!-- Provides WebApplicationFactory<TEntryPoint>, used to test the real, composed HTTP pipeline
rather than individual option/handler classes in isolation (NFR-CS-01). -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj" />
</ItemGroup>
</Project>
@@ -18,5 +18,3 @@ CmsHost.ConfigurePipeline(app, orchestrator, hostOptions);
app.Run(); app.Run();
// Exposed so the host regression tests can start the real application in-memory.
public partial class Program;
@@ -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 // 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 // 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 // must have exclusive access". The suite is small and fast (the pure unit tests take about a second), so the whole
@@ -0,0 +1,155 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
namespace SlpModularCms.Api.Tests;
/// <summary>
/// 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 <c>SlpModularCms.Api</c> 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.
/// </summary>
public class SiteContractTests
{
public static IEnumerable<object[]> 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<bool>("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("<db-password>");
config["Identity:Setup:Token"].Should().BeNullOrEmpty();
config["Observability:SentryDsn"].Should().BeNullOrEmpty();
config.GetSection("ForwardedHeaders:KnownProxies").Get<string[]>().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<bool>("Contact:Enabled").Should().BeFalse();
config["Contact:SiteId"].Should().Be(siteId);
config.GetValue<bool>("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<string, string>("/admin", "Strict"))
.And.Contain(new KeyValuePair<string, string>("/api/v1", "Strict"))
.And.Contain(new KeyValuePair<string, string>("/health", "Strict"));
}
[Fact]
public void AndreaSlopFotografie_SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists()
{
var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie);
var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get<string[]>()!
.Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get<string[]>()!);
site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://"));
config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get<string[]>().Should().BeEmpty();
config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get<string[]>().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");
}
}
+73
View File
@@ -0,0 +1,73 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
namespace SlpModularCms.Api.Tests;
/// <summary>
/// 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.
/// </summary>
internal static class SiteFiles
{
public const string SlpSoftware = "SlpModularCms.Api.SlpSoftware";
public const string AndreaSlopFotografie = "SlpModularCms.Api.AndreaSlopFotografie";
/// <summary>The directory that holds the project folders (<c>src</c>).</summary>
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");
/// <summary>The committed appsettings.json of a site, exactly as deployed (no environment on top).</summary>
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();
}
/// <summary>The module projects a site references, as short names (<c>Offerings</c>, <c>Identity</c>, ...).</summary>
public static IReadOnlySet<string> 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);
}
/// <summary>
/// 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.
/// </summary>
public static Dictionary<string, string?> 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);
}
}
@@ -1,71 +1,40 @@
using System.Net; using System.Net;
using System.Text.Json;
using FluentAssertions; using FluentAssertions;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Offerings.Data;
namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; namespace SlpModularCms.Api.Tests;
/// <summary>Starts the real host in-memory (Development environment).</summary> /// <summary>
public class AsfWebApplicationFactory : WebApplicationFactory<Program> /// 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.
/// </summary>
public class AsfVariantFactory : WebApplicationFactory<Program>
{ {
protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void ConfigureWebHost(IWebHostBuilder builder)
{ {
builder.UseEnvironment("Development"); 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)
/// <remarks>
/// Requires a reachable local MariaDB matching <c>appsettings.Development.json</c> of the host,
/// because <c>CmsHost.ConfigurePipeline</c> migrates the database before any endpoint answers
/// (same precondition as <c>SlpModularCms.Api.Tests</c>).
/// </remarks>
public class HostPipelineTests : IClassFixture<AsfWebApplicationFactory>
{ {
private readonly AsfWebApplicationFactory _factory; builder.UseSetting(key, value);
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] builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(settings));
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 class AsfVariantPipelineTests : IClassFixture<AsfVariantFactory>
public void OfferingsMigrations_MatchTheModel()
{ {
_ = _factory.CreateClient(); // starts the host and migrates private readonly AsfVariantFactory _factory;
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SlpModularCms.Modules.Offerings.Data.OfferingsDbContext>();
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot"); public AsfVariantPipelineTests(AsfVariantFactory factory) => _factory = factory;
}
[Fact] [Fact]
public async Task Health_IsReachable() public async Task Health_IsReachable()
@@ -85,6 +54,7 @@ public class HostPipelineTests : IClassFixture<AsfWebApplicationFactory>
[Fact] [Fact]
public async Task UnknownWebsitePath_Returns404_WithTheSiteSecurityHeaders_AndNoIndex() 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"); var response = await _factory.CreateClient().GetAsync("/some-page-that-does-not-exist");
response.StatusCode.Should().Be(HttpStatusCode.NotFound); response.StatusCode.Should().Be(HttpStatusCode.NotFound);
@@ -100,4 +70,53 @@ public class HostPipelineTests : IClassFixture<AsfWebApplicationFactory>
body.Should().Contain("Disallow: /"); body.Should().Contain("Disallow: /");
} }
[Fact]
public void TheVariantReallyUsesTheSitesSettings()
{
var config = _factory.Services.GetRequiredService<IConfiguration>();
config["Website:Mode"].Should().Be("PrerenderedPages");
config["Contact:SiteId"].Should().Be("andreaslop");
config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite");
}
}
/// <summary>Offerings behaviour that needs the real, migrated database (Offerings is part of the master host).</summary>
public class OfferingsOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
{
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<OfferingsDbContext>();
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot");
}
} }
+2 -1
View File
@@ -60,6 +60,7 @@ public static class CmsHost
builder.Services.AddCmsObservability(builder.Configuration); builder.Services.AddCmsObservability(builder.Configuration);
var websiteMode = options.ResolveWebsiteMode(builder.Configuration); var websiteMode = options.ResolveWebsiteMode(builder.Configuration);
builder.Services.AddSingleton(new WebsiteModeSelection(websiteMode));
if (websiteMode == WebsiteMode.PrerenderedPages) if (websiteMode == WebsiteMode.PrerenderedPages)
{ {
builder.Services.AddCmsWebsite(builder.Configuration); builder.Services.AddCmsWebsite(builder.Configuration);
@@ -97,7 +98,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); var websiteMode = app.Services.GetService<WebsiteModeSelection>()?.Mode ?? 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
@@ -24,6 +24,14 @@ public enum WebsiteMode
/// <see cref="CmsHost.ConfigurePipeline"/>, is how a Client project opts into different behaviour. /// <see cref="CmsHost.ConfigurePipeline"/>, is how a Client project opts into different behaviour.
/// Defaults reproduce the behaviour every existing Client project already has. /// Defaults reproduce the behaviour every existing Client project already has.
/// </remarks> /// </remarks>
/// <summary>The website mode this host started with, decided once while the services were registered.</summary>
/// <remarks>
/// 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).
/// </remarks>
public sealed record WebsiteModeSelection(WebsiteMode Mode);
public sealed class CmsHostOptions public sealed class CmsHostOptions
{ {
/// <summary> /// <summary>
@@ -24,7 +24,7 @@ public class ContactHostFactory : WebApplicationFactory<Program>, IAsyncLifetime
Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask; Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
private async Task OpenCmsSwitchAsync() public async Task OpenCmsSwitchAsync()
{ {
_ = CreateClient(); // starts the host (migrates the contact tables) _ = CreateClient(); // starts the host (migrates the contact tables)
await WithDb(async db => await WithDb(async db =>
@@ -1,58 +1,80 @@
using System.Net; using System.Net;
using System.Net.Http.Json;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions;
using FluentAssertions; using FluentAssertions;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; 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;
/// <summary> /// <summary>
/// The real Andrea Slop Fotografie host with the Contact module, against a real MariaDB/MySQL (like the other /// The contact module on the master host with the committed behaviour settings of a site on top (Andrea Slop
/// host tests: set <c>ConnectionStrings__DefaultConnection</c> to a server you may create databases on; every /// Fotografie: SiteId, security headers, mail and contact defaults). The site projects have no logic of their
/// factory uses its own throw-away database). /// own, so this is how a site's contact behaviour is tested without building the site project.
/// </summary> /// </summary>
public class AsfContactHostFactory : WebApplicationFactory<Program> internal static class AsfSettings
{ {
private readonly Dictionary<string, string?> _settings; private static readonly string[] Sections =
private readonly string _databaseName = "AsfContactHost_" + Guid.NewGuid().ToString("N")[..12]; ["Website", "SecurityHeaders", "Contact", "Email", "Identity", "ForwardedHeaders", "Cors", "App", "RateLimiting"];
public static Dictionary<string, string?> 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<string, string?> _site;
/// <summary>When set, the pipeline sees this as the TCP peer (the reverse proxy) of every request.</summary> /// <summary>When set, the pipeline sees this as the TCP peer (the reverse proxy) of every request.</summary>
public string? PeerAddress { get; init; } public string? PeerAddress { get; init; }
public AsfContactHostFactory(Dictionary<string, string?>? settings = null) => _settings = settings ?? []; public AsfContactHostFactory(Dictionary<string, string?>? overrides = null)
: this(AsfSettings.Committed(), overrides)
{
}
private static string BaseConnectionString => private AsfContactHostFactory(Dictionary<string, string?> site, Dictionary<string, string?>? overrides)
Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") : base(Merge(site, overrides))
?? throw new InvalidOperationException("Set ConnectionStrings__DefaultConnection to a MariaDB/MySQL server for the host tests."); {
_site = site;
}
private string ConnectionString => private static Dictionary<string, string?> Merge(Dictionary<string, string?> site, Dictionary<string, string?>? overrides)
Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase) {
? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase) var all = new Dictionary<string, string?>(site);
: $"{BaseConnectionString};Database={_databaseName}"; foreach (var (key, value) in overrides ?? []) all[key] = value;
return all;
}
protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void ConfigureWebHost(IWebHostBuilder builder)
{ {
builder.UseEnvironment("Development"); base.ConfigureWebHost(builder);
builder.ConfigureAppConfiguration((_, config) =>
{ // Also as host settings: those are visible while the services are registered (the website mode is read then).
var all = new Dictionary<string, string?> foreach (var (key, value) in _site) builder.UseSetting(key, value);
{
["ConnectionStrings:DefaultConnection"] = ConnectionString,
["Availability:StatusCacheSeconds"] = "0",
};
foreach (var (key, value) in _settings) all[key] = value;
config.AddInMemoryCollection(all);
});
if (PeerAddress is not null) if (PeerAddress is not null)
{ {
@@ -73,47 +95,31 @@ public class AsfContactHostFactory : WebApplicationFactory<Program>
next(app); next(app);
}; };
} }
public async Task<T> WithDb<T>(Func<ContactDbContext, Task<T>> action)
{
await using var scope = Services.CreateAsyncScope();
return await action(scope.ServiceProvider.GetRequiredService<ContactDbContext>());
} }
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<ContactDbContext>().Database.EnsureDeleted();
}
catch
{
// Best effort clean-up of the throw-away database.
}
}
base.Dispose(disposing);
}
}
/// <summary>The committed defaults, nothing overridden.</summary>
public sealed class AsfDefaultContactHostFactory() : AsfContactHostFactory(null); 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;
}
/// <summary>One form submission allowed per window: the buckets show who shares one.</summary>
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"; public const string Route = "/api/v1/contact-messages";
@@ -156,10 +162,10 @@ public class AsfContactDisabledByDefaultTests : IClassFixture<AsfDefaultContactH
using var caps = JsonDocument.Parse(await client.GetStringAsync("/api/v1/System/capabilities")); using var caps = JsonDocument.Parse(await client.GetStringAsync("/api/v1/System/capabilities"));
caps.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).Should().Contain("Contact"); caps.RootElement.GetProperty("modules").EnumerateArray().Select(e => 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); token.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await token.Content.ReadAsStringAsync()).Should().BeEmpty(); (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<AsfOpenContactHostFactory>
public AsfContactGateTests(AsfOpenContactHostFactory factory) => _factory = factory; public AsfContactGateTests(AsfOpenContactHostFactory factory) => _factory = factory;
[Fact] [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). // Switch the CMS off through the availability state of the real database (status 1 = not available).
await _factory.WithDb(db => db.Database.ExecuteSqlRawAsync( await _factory.WithDb(db => db.Database.ExecuteSqlRawAsync(
"INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'host test', NOW(), 'host test')")); "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'host test', NOW(), 'host test')"));
var client = _factory.CreateClient(); 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"); .Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed for everything not marked public");
var token = await ContactHttp.GetTokenAsync(client); var token = await AsfContactHttp.GetTokenAsync(client);
var post = await ContactHttp.PostAsync(client, token, "ASF Gate"); var post = await AsfContactHttp.PostAsync(client, token, "ASF Gate");
post.StatusCode.Should().Be(HttpStatusCode.Accepted); 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"); (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",
});
/// <summary>One form submission allowed per window: the buckets show who shares one.</summary>
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 public class AsfRateLimitBehindIisTests
{ {
[Fact] [Fact]
@@ -225,7 +205,17 @@ public class AsfRateLimitBehindIisTests
Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", "10.1.1.1"); Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", "10.1.1.1");
try 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 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] [Fact]
public async Task WithoutKnownProxies_TheWholeSiteSharesOneBucket_WhichIsWhyItIsAReleaseCondition() 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(); await factory.OpenCmsSwitchAsync();
var client = factory.CreateClient(); 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 a = await AsfContactHttp.PostAsync(client, await AsfContactHttp.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 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); a.StatusCode.Should().Be(HttpStatusCode.Accepted);
b.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "forwarded addresses are ignored without KnownProxies: everybody is the proxy"); b.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "forwarded addresses are ignored without KnownProxies: everybody is the proxy");