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
@@ -24,7 +24,7 @@ public class ContactHostFactory : WebApplicationFactory<Program>, 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 =>
@@ -0,0 +1,239 @@
using System.Net;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>
/// 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.
/// </summary>
internal static class AsfSettings
{
private static readonly string[] Sections =
["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>
public string? PeerAddress { get; init; }
public AsfContactHostFactory(Dictionary<string, string?>? overrides = null)
: this(AsfSettings.Committed(), overrides)
{
}
private AsfContactHostFactory(Dictionary<string, string?> site, Dictionary<string, string?>? overrides)
: base(Merge(site, overrides))
{
_site = site;
}
private static Dictionary<string, string?> Merge(Dictionary<string, string?> site, Dictionary<string, string?>? overrides)
{
var all = new Dictionary<string, string?>(site);
foreach (var (key, value) in overrides ?? []) all[key] = value;
return all;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
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)
{
// Stands in for the reverse proxy: the TCP peer of every request. Runs before the forwarded-headers step.
builder.ConfigureServices(services => services.AddTransient<IStartupFilter>(_ => new PeerFilter(PeerAddress)));
}
}
private sealed class PeerFilter(string address) : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
{
app.Use((context, nextMiddleware) =>
{
context.Connection.RemoteIpAddress = IPAddress.Parse(address);
return nextMiddleware();
});
next(app);
};
}
}
public sealed class AsfDefaultContactHostFactory() : AsfContactHostFactory(null);
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 static async Task<string> GetTokenAsync(HttpClient client, string? forwardedFor = null)
{
var request = new HttpRequestMessage(HttpMethod.Get, $"{Route}/token");
if (forwardedFor is not null) request.Headers.Add("X-Forwarded-For", forwardedFor);
var response = await client.SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return json.RootElement.GetProperty("token").GetString()!;
}
public static Task<HttpResponseMessage> PostAsync(HttpClient client, string token, string name, string? forwardedFor = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, Route)
{
Content = new StringContent(JsonSerializer.Serialize(new
{
name, email = "jan@example.nl", subject = "Portretfotografie", message = "Hallo", hpCheck = "", token,
}), Encoding.UTF8, "application/json"),
};
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
if (forwardedFor is not null) request.Headers.Add("X-Forwarded-For", forwardedFor);
return client.SendAsync(request);
}
}
public class AsfContactDisabledByDefaultTests : IClassFixture<AsfDefaultContactHostFactory>
{
private readonly AsfDefaultContactHostFactory _factory;
public AsfContactDisabledByDefaultTests(AsfDefaultContactHostFactory factory) => _factory = factory;
[Fact]
public async Task TheCommittedDefaults_KeepTheContactModuleLoadedButClosed()
{
var client = _factory.CreateClient();
using var caps = JsonDocument.Parse(await client.GetStringAsync("/api/v1/System/capabilities"));
caps.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).Should().Contain("Contact");
var token = await client.GetAsync($"{AsfContactHttp.Route}/token");
token.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await token.Content.ReadAsStringAsync()).Should().BeEmpty();
(await client.PostAsync(AsfContactHttp.Route, null)).StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
public class AsfContactGateTests : IClassFixture<AsfOpenContactHostFactory>
{
private readonly AsfOpenContactHostFactory _factory;
public AsfContactGateTests(AsfOpenContactHostFactory factory) => _factory = factory;
[Fact]
public async Task ThePublicContactRoutes_StayReachable_WhileTheCmsIsNotAvailable_AndTheMessageGetsTheSitesId()
{
_ = _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($"{AsfContactHttp.Route}?pageSize=1")).StatusCode
.Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed for everything not marked public");
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.SingleAsync(m => m.Name == "ASF Gate"))).SiteId.Should().Be("andreaslop");
}
}
public class AsfRateLimitBehindIisTests
{
[Fact]
public async Task WithTheProxyKnown_EachVisitorAddressHasItsOwnBucket()
{
// The proxy list is read while the host is being composed, before test configuration is applied, so (like in
// production) it comes from the environment: ForwardedHeaders__KnownProxies__0.
Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", "10.1.1.1");
try
{
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
{
Environment.SetEnvironmentVariable("ForwardedHeaders__KnownProxies__0", null);
}
}
[Fact]
public async Task WithoutKnownProxies_TheWholeSiteSharesOneBucket_WhichIsWhyItIsAReleaseCondition()
{
using var factory = new AsfOneSubmissionContactHostFactory { PeerAddress = "10.1.1.1" };
await factory.OpenCmsSwitchAsync();
var client = factory.CreateClient();
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");
}
}