Voeg Api.AndreaSlopFotografie toe met setup-token, proxy-bewuste limiters en ASF-admin-thema
- Core: opt-in ForwardedHeaders:KnownProxies en rate limiters per clientadres (zonder configuratie ongewijzigd gedrag) - Identity: optioneel setup-token (X-Setup-Token), beide setup-endpoints onder de login-limiter, beveiligingsgebeurtenis setup_token_rejected (5007) - Nieuw client-project SlpModularCms.Api.AndreaSlopFotografie (Identity + Availability) met bijbehorende tests - Frontend: thema asf (VITE_THEME), VITE_DEFAULT_LANGUAGE, tokenveld op de setup-pagina - CI: jobs publish/deploy-asf-test achter ASF_TEST_DEPLOY_ENABLED - Fix U1: 301-Location wordt nu percent-encoded (gevonden door de property-test) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
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 Host_DoesNotReferenceMasterOrOfferingsModules()
|
||||
{
|
||||
var referenced = typeof(Program).Assembly.GetReferencedAssemblies().Select(a => a.Name);
|
||||
|
||||
referenced.Should().NotContain("SlpModularCms.Modules.Offerings")
|
||||
.And.NotContain("SlpModularCms.Modules.Master");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
|
||||
namespace SlpModularCms.Api.AndreaSlopFotografie.Tests;
|
||||
|
||||
/// <summary>Starts the real host in-memory (Development environment).</summary>
|
||||
public class AsfWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
public HostPipelineTests(AsfWebApplicationFactory factory) => _factory = factory;
|
||||
|
||||
[Fact]
|
||||
public async Task Capabilities_ListIdentityAndAvailability_ButNotOfferingsOrMaster()
|
||||
{
|
||||
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");
|
||||
modules.Should().NotContain("Offerings").And.NotContain("Master");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Health_IsReachable()
|
||||
{
|
||||
(await _factory.CreateClient().GetAsync("/health")).IsSuccessStatusCode.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetupStatus_ReportsNoTokenRequired_WhenNoneConfigured()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/Setup/status");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await response.Content.ReadAsStringAsync()).Should().Contain("\"tokenRequired\":false");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnknownWebsitePath_Returns404_WithTheSiteSecurityHeaders_AndNoIndex()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/some-page-that-does-not-exist");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
response.Headers.GetValues("Content-Security-Policy").Single()
|
||||
.Should().Contain("https://analytics.slpsoftware.nl");
|
||||
response.Headers.GetValues("X-Robots-Tag").Single().Should().Be("noindex, nofollow");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RobotsTxt_DisallowsEverything_OnTheDefaultNoIndexConfiguration()
|
||||
{
|
||||
var body = await _factory.CreateClient().GetStringAsync("/robots.txt");
|
||||
|
||||
body.Should().Contain("Disallow: /");
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
<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>
|
||||
@@ -0,0 +1,21 @@
|
||||
using SlpModularCms.Core.Hosting;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Load local developer overrides
|
||||
builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
|
||||
|
||||
// Andrea Slop Fotografie serves a prerendered website from wwwroot/web (nginx-equivalent behaviour)
|
||||
// instead of the SPA-style website mount the other clients use.
|
||||
var hostOptions = new CmsHostOptions { WebsiteMode = WebsiteMode.PrerenderedPages };
|
||||
|
||||
var orchestrator = CmsHost.ConfigureServices(builder, hostOptions);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
CmsHost.ConfigurePipeline(app, orchestrator, hostOptions);
|
||||
|
||||
app.Run();
|
||||
|
||||
// Exposed so the host regression tests can start the real application in-memory.
|
||||
public partial class Program;
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5200",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"launchUrl": "scalar"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:7200;http://localhost:5200",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"launchUrl": "scalar"
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Asp.Versioning.Mvc" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Deliberately Identity + Availability only: this client serves one prerendered website and its
|
||||
admin. No Master (it is not a master/slave setup) and no Offerings (a SlpSoftware-specific
|
||||
feature), so /api/v1/System/capabilities does not list them. Availability is kept because the
|
||||
admin SPA reads the availability status.
|
||||
-->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
The admin SPA (frontend/) is served at /admin from wwwroot/admin and the prerendered website
|
||||
at / from wwwroot/web. Neither is built by an MSBuild target here — see
|
||||
SlpModularCms.Api.csproj for why; the CI workflow builds the admin as its own step and the
|
||||
website is delivered by its own repository.
|
||||
-->
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
// Own, isolated local dev database, separate from the other clients' local databases.
|
||||
"DefaultConnection": "Server=127.0.0.1;Port=3306;Database=AndreaSlopFotografieDev;Uid=root;Pwd=<your-local-mariadb-password>"
|
||||
},
|
||||
"JwtSettings": {
|
||||
"Secret": "SuperSecretKeyForDevelopmentOnly_MustBeLongerThan32Bytes!",
|
||||
"Issuer": "SlpModularCms",
|
||||
"Audience": "SlpModularCmsPortal",
|
||||
"ExpiryMinutes": 60,
|
||||
"RefreshTokenExpiryDays": 7,
|
||||
"CookieSameSite": "None"
|
||||
},
|
||||
"Cors": {
|
||||
// The admin dev server (`pnpm dev:asf`, see frontend/.env.example).
|
||||
"AllowedOrigins": [ "http://localhost:5176", "https://localhost:5176" ]
|
||||
},
|
||||
"RateLimiting": {
|
||||
"Login": {
|
||||
"PermitLimit": 500,
|
||||
"WindowSeconds": 60
|
||||
},
|
||||
"Refresh": {
|
||||
"PermitLimit": 500,
|
||||
"WindowSeconds": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Information",
|
||||
// Pinned at Warning deliberately. At Information, EF prints every SQL statement INCLUDING
|
||||
// parameter values, and the login path passes a normalised email address through it.
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
// Secrets and per-environment values are NEVER committed here; the deployed host receives them as
|
||||
// environment variables (ConnectionStrings__DefaultConnection, JwtSettings__Secret, ...).
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=<db-host>;Port=3306;Database=AndreaSlopFotografie<Env>;Uid=<db-user>;Pwd=<db-password>"
|
||||
},
|
||||
"JwtSettings": {
|
||||
"Secret": "<secure-long-random-secret-key-from-env>",
|
||||
"Issuer": "SlpModularCms",
|
||||
"Audience": "SlpModularCmsPortal",
|
||||
"ExpiryMinutes": 60,
|
||||
"RefreshTokenExpiryDays": 7
|
||||
},
|
||||
"Availability": {
|
||||
"CircuitBreakerSeconds": 30,
|
||||
"StatusCacheSeconds": 1
|
||||
},
|
||||
"MasterPolling": {
|
||||
"PollIntervalSeconds": 30,
|
||||
"FailOpenAfterMinutes": 5,
|
||||
"HttpTimeoutSeconds": 5
|
||||
},
|
||||
"Identity": {
|
||||
"Setup": {
|
||||
// Optional protection of the first-administrator setup. Supplied per environment as
|
||||
// Identity__Setup__Token (at least 32 random characters) and removed once the first
|
||||
// administrator exists. Empty = setup is not token-protected.
|
||||
"Token": ""
|
||||
}
|
||||
},
|
||||
// Opt-in trust in the reverse proxy in front of this host. Supplied per environment as
|
||||
// ForwardedHeaders__KnownProxies__0 (the proxy IP address). Empty = forwarded headers are ignored.
|
||||
"ForwardedHeaders": {
|
||||
"KnownProxies": []
|
||||
},
|
||||
"Website": {
|
||||
// Secure default: every website response carries noindex and /robots.txt disallows all. A
|
||||
// production instance must set Website__NoIndex=false explicitly.
|
||||
"NoIndex": true
|
||||
},
|
||||
"Cors": {
|
||||
"AllowedOrigins": []
|
||||
},
|
||||
"RateLimiting": {
|
||||
"Login": {
|
||||
"PermitLimit": 5,
|
||||
"WindowSeconds": 60
|
||||
},
|
||||
"Refresh": {
|
||||
"PermitLimit": 20,
|
||||
"WindowSeconds": 60
|
||||
},
|
||||
"SentryTunnel": {
|
||||
"PermitLimit": 60,
|
||||
"WindowSeconds": 60
|
||||
},
|
||||
"OfferingsPublic": {
|
||||
"PermitLimit": 120,
|
||||
"WindowSeconds": 60
|
||||
}
|
||||
},
|
||||
"SecurityHeaders": {
|
||||
"Enabled": true,
|
||||
// The public website is the default; the CMS admin and API keep the strict policy.
|
||||
"DefaultPolicy": "StrictSite",
|
||||
"PathPolicies": [
|
||||
{ "PathPrefix": "/admin", "Policy": "Strict" },
|
||||
{ "PathPrefix": "/api/v1", "Policy": "Strict" },
|
||||
{ "PathPrefix": "/health", "Policy": "Strict" }
|
||||
],
|
||||
"AllowedScriptOrigins": [],
|
||||
"AllowedConnectOrigins": [],
|
||||
// Origins the website itself calls (analytics script + beacon, Sentry error reporting). Only
|
||||
// the StrictSite policy gets them; the admin policies are not widened. The host and admin set
|
||||
// up no Umami: the admin reports errors through the same-origin /sentry-tunnel.
|
||||
"AllowedSiteScriptOrigins": [ "https://analytics.slpsoftware.nl" ],
|
||||
"AllowedSiteConnectOrigins": [
|
||||
"https://analytics.slpsoftware.nl",
|
||||
"https://o4511795618185216.ingest.de.sentry.io"
|
||||
]
|
||||
},
|
||||
"Observability": {
|
||||
// Supplied per environment as Observability__SentryDsn. Empty means Sentry is skipped
|
||||
// entirely and console logging continues — a normal, supported state, not an error.
|
||||
"SentryDsn": "",
|
||||
// Falls back to ASPNETCORE_ENVIRONMENT when empty.
|
||||
"Environment": "",
|
||||
"TracesSampleRate": 0.1,
|
||||
"TunnelMaxPayloadBytes": 204800
|
||||
}
|
||||
}
|
||||
@@ -80,8 +80,9 @@ public class SecurityEventsTests
|
||||
SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.InvalidSignature);
|
||||
SecurityEvents.RateLimitTriggered(logger, "login", "/e");
|
||||
SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 5);
|
||||
SecurityEvents.SetupTokenRejected(logger, "/Setup/owner");
|
||||
|
||||
logger.Entries.Should().HaveCount(6);
|
||||
logger.Entries.Should().HaveCount(7);
|
||||
logger.Entries.Should().OnlyContain(e => e.Level >= LogLevel.Warning);
|
||||
}
|
||||
|
||||
@@ -96,10 +97,23 @@ public class SecurityEventsTests
|
||||
SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.Expired);
|
||||
SecurityEvents.RateLimitTriggered(logger, "login", "/e");
|
||||
SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 1);
|
||||
SecurityEvents.SetupTokenRejected(logger, "/Setup/owner");
|
||||
|
||||
logger.Entries.Select(e => e.EventId.Id).Should().OnlyHaveUniqueItems();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetupTokenRejected_ShouldCarryTheEventNameAndId()
|
||||
{
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
SecurityEvents.SetupTokenRejected(logger, "/Setup/owner");
|
||||
|
||||
var entry = logger.Entries.Single();
|
||||
entry.Message.Should().Contain(SecurityEventNames.SetupTokenRejected);
|
||||
entry.EventId.Id.Should().Be(5007);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MigrationFailure_ShouldBeCritical()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
using System.Net;
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Hosting.Proxy;
|
||||
|
||||
public class ForwardedHeadersSettingsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parse_ValidAddresses_AreReturned()
|
||||
{
|
||||
var result = ForwardedHeadersSettings.ParseKnownProxies(["192.168.1.102", " ::1 "]);
|
||||
|
||||
result.Should().Equal(IPAddress.Parse("192.168.1.102"), IPAddress.IPv6Loopback);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_NullOrEmpty_MeansNoProxies()
|
||||
{
|
||||
ForwardedHeadersSettings.ParseKnownProxies(null).Should().BeEmpty();
|
||||
ForwardedHeadersSettings.ParseKnownProxies([]).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-an-ip")]
|
||||
[InlineData("")]
|
||||
[InlineData("192.168.1.0/24")]
|
||||
[InlineData("0.0.0.0")]
|
||||
[InlineData("::")]
|
||||
public void Parse_InvalidOrWildcard_Throws(string entry)
|
||||
{
|
||||
var act = () => ForwardedHeadersSettings.ParseKnownProxies([entry]);
|
||||
|
||||
act.Should().Throw<InvalidOperationException>();
|
||||
}
|
||||
|
||||
// PBT: every concrete (non-wildcard) IPv4 address round-trips through the parser.
|
||||
[Fact]
|
||||
public void Parse_AnyConcreteIPv4_RoundTrips()
|
||||
{
|
||||
var arb = Gen.Choose(0, 255).ArrayOf(4)
|
||||
.Where(o => o.Any(x => x != 0))
|
||||
.Select(o => string.Join('.', o))
|
||||
.ToArbitrary();
|
||||
|
||||
Prop.ForAll(arb, text =>
|
||||
ForwardedHeadersSettings.ParseKnownProxies([text]).Single().ToString() == text)
|
||||
.QuickCheckThrowOnFailure();
|
||||
}
|
||||
}
|
||||
|
||||
public class ClientPartitionKeyTests
|
||||
{
|
||||
private static HttpContext ContextFor(IPAddress? address)
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Connection.RemoteIpAddress = address;
|
||||
return context;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownAddress_UsesFallbackKey()
|
||||
{
|
||||
ClientPartitionKey.For(ContextFor(null)).Should().Be(ClientPartitionKey.Unknown);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MappedIPv4_EqualsPlainIPv4()
|
||||
{
|
||||
var plain = ClientPartitionKey.For(ContextFor(IPAddress.Parse("203.0.113.9")));
|
||||
var mapped = ClientPartitionKey.For(ContextFor(IPAddress.Parse("::ffff:203.0.113.9")));
|
||||
|
||||
mapped.Should().Be(plain);
|
||||
}
|
||||
|
||||
// PBT: same address -> same key; different addresses -> different keys.
|
||||
[Fact]
|
||||
public void Key_IsInjectiveOverAddresses()
|
||||
{
|
||||
var addr = Gen.Choose(0, 255).ArrayOf(4)
|
||||
.Select(o => new IPAddress(o.Select(x => (byte)x).ToArray()));
|
||||
var arb = Gen.Two(addr).ToArbitrary();
|
||||
|
||||
Prop.ForAll(arb, pair =>
|
||||
{
|
||||
var (a, b) = pair;
|
||||
var ka = ClientPartitionKey.For(ContextFor(a));
|
||||
var kb = ClientPartitionKey.For(ContextFor(b));
|
||||
return a.Equals(b) == (ka == kb);
|
||||
}).QuickCheckThrowOnFailure();
|
||||
}
|
||||
}
|
||||
|
||||
public class ForwardedHeadersPipelineTests : IAsyncDisposable
|
||||
{
|
||||
private readonly List<WebApplication> _apps = [];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var app in _apps)
|
||||
{
|
||||
await app.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// A tiny host composing the real extensions: peer address is faked from a test header,
|
||||
// then forwarded headers (opt-in), then the real limiter policy "login" (limit 2 per window).
|
||||
private async Task<HttpClient> StartAsync(string? knownProxy)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseTestServer();
|
||||
var config = new Dictionary<string, string?> { ["RateLimiting:Login:PermitLimit"] = "2" };
|
||||
if (knownProxy is not null)
|
||||
{
|
||||
config["ForwardedHeaders:KnownProxies:0"] = knownProxy;
|
||||
}
|
||||
|
||||
builder.Configuration.AddInMemoryCollection(config);
|
||||
builder.Services.AddCmsForwardedHeaders(builder.Configuration);
|
||||
builder.Services.AddCmsRateLimiting(builder.Configuration);
|
||||
|
||||
var app = builder.Build();
|
||||
app.Use((context, next) =>
|
||||
{
|
||||
if (context.Request.Headers.TryGetValue("X-Test-Peer", out var peer))
|
||||
{
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse(peer.ToString());
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
app.UseCmsForwardedHeaders();
|
||||
app.UseRateLimiter();
|
||||
app.MapGet("/who", (HttpContext c) => $"{c.Connection.RemoteIpAddress}|{c.Request.Scheme}")
|
||||
.RequireRateLimiting("login");
|
||||
|
||||
await app.StartAsync();
|
||||
_apps.Add(app);
|
||||
return app.GetTestClient();
|
||||
}
|
||||
|
||||
private static HttpRequestMessage Request(string peer, string? xff = null, string? proto = null)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, "/who");
|
||||
request.Headers.Add("X-Test-Peer", peer);
|
||||
if (xff is not null) request.Headers.Add("X-Forwarded-For", xff);
|
||||
if (proto is not null) request.Headers.Add("X-Forwarded-Proto", proto);
|
||||
return request;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoProxyConfigured_ForwardedHeadersAreIgnored_AndCallersShareTheProxyBucket()
|
||||
{
|
||||
var client = await StartAsync(knownProxy: null);
|
||||
|
||||
var first = await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1", proto: "https"));
|
||||
(await first.Content.ReadAsStringAsync()).Should().Be("10.0.0.1|http");
|
||||
|
||||
(await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
// Third request from a "different visitor" behind the same peer: shared bucket, as before.
|
||||
(await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.3"))).StatusCode
|
||||
.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TrustedProxy_RealClientAddressAndSchemeAreUsed_AndBucketsAreSeparate()
|
||||
{
|
||||
var client = await StartAsync(knownProxy: "10.0.0.1");
|
||||
|
||||
var first = await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1", proto: "https"));
|
||||
(await first.Content.ReadAsStringAsync()).Should().Be("198.51.100.1|https");
|
||||
|
||||
(await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1"))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1"))).StatusCode
|
||||
.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
|
||||
// A different visitor behind the same proxy is not throttled by the first one.
|
||||
(await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UntrustedPeer_CannotSpoofItsAddress()
|
||||
{
|
||||
var client = await StartAsync(knownProxy: "10.0.0.1");
|
||||
|
||||
var response = await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.1", proto: "https"));
|
||||
|
||||
(await response.Content.ReadAsStringAsync()).Should().Be("203.0.113.50|http");
|
||||
// Rotating the spoofed header does not buy fresh buckets.
|
||||
(await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.3"))).StatusCode
|
||||
.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WildcardProxy_FailsAtStartup()
|
||||
{
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { ["ForwardedHeaders:KnownProxies:0"] = "0.0.0.0" })
|
||||
.Build();
|
||||
|
||||
var act = () => new ServiceCollection().AddCmsForwardedHeaders(config);
|
||||
|
||||
act.Should().Throw<InvalidOperationException>();
|
||||
}
|
||||
}
|
||||
@@ -116,8 +116,10 @@ public class WebsitePathResolverPropertyTests(ITestOutputHelper output)
|
||||
return true;
|
||||
}
|
||||
|
||||
// A browser follows the Location as a URL: split path and query there, and the server
|
||||
// sees the path decoded again.
|
||||
var split = first.Location.IndexOf('?');
|
||||
var targetPath = split < 0 ? first.Location : first.Location[..split];
|
||||
var targetPath = Uri.UnescapeDataString(split < 0 ? first.Location : first.Location[..split]);
|
||||
var targetQuery = split < 0 ? null : first.Location[split..];
|
||||
|
||||
return WebsitePathResolver.Resolve(targetPath, targetQuery, Exists) is not WebsiteResolution.Redirect;
|
||||
|
||||
@@ -92,6 +92,18 @@ public class WebsitePathResolverTests
|
||||
public void TrailingSlash_RedirectsToStrippedPath_EvenWhenTargetDoesNotExist(string path, string target) =>
|
||||
Resolve(path).Should().Be(Redirect(target));
|
||||
|
||||
// Regression (found by the property test): the Location is built from the DECODED path and must
|
||||
// be re-encoded, or /a%3Fb/ would redirect to /a?b (another resource), '#' would start a
|
||||
// fragment and non-ASCII would end up raw in a header value.
|
||||
[Theory]
|
||||
[InlineData("/a?b/", "/a%3Fb")]
|
||||
[InlineData("/a#b/", "/a%23b")]
|
||||
[InlineData("/café/", "/caf%C3%A9")]
|
||||
[InlineData("/50%/", "/50%25")]
|
||||
[InlineData("/blog/", "/blog")]
|
||||
public void Redirect_Location_IsPercentEncoded(string decodedPath, string expectedLocation) =>
|
||||
Resolve(decodedPath).Should().Be(Redirect(expectedLocation));
|
||||
|
||||
[Fact]
|
||||
public void TrailingSlash_KeepsQueryString() =>
|
||||
Resolve("/onbekend/", "?a=1").Should().Be(Redirect("/onbekend?a=1"));
|
||||
|
||||
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Hosting.Health;
|
||||
using SlpModularCms.Core.Hosting.Observability;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using Scalar.AspNetCore;
|
||||
@@ -52,6 +53,7 @@ public static class CmsHost
|
||||
// 2. Add Core Infrastructure
|
||||
builder.Services.AddCoreInfrastructure(builder.Configuration);
|
||||
builder.Services.AddCmsCors(builder.Configuration);
|
||||
builder.Services.AddCmsForwardedHeaders(builder.Configuration);
|
||||
builder.Services.AddCmsRateLimiting(builder.Configuration);
|
||||
builder.Services.AddCmsHealthChecks();
|
||||
builder.Services.AddCmsSecurityHeaders(builder.Configuration);
|
||||
@@ -97,6 +99,12 @@ public static class CmsHost
|
||||
// what makes a liveness-only health check trustworthy.
|
||||
app.MigrateCoreDatabase();
|
||||
|
||||
// Opt-in (ForwardedHeaders:KnownProxies): makes the real visitor address and scheme visible to
|
||||
// everything below (rate limiter partitions, HTTPS redirection, logging). Not added at all when
|
||||
// no proxy is configured. First in the pipeline so the exception handler and all later
|
||||
// middleware already see the corrected values.
|
||||
app.UseCmsForwardedHeaders();
|
||||
|
||||
// 5. Global Exception Handling
|
||||
app.UseExceptionHandler();
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@ public sealed class SecurityEventProcessor : ISentryEventProcessor
|
||||
SecurityEventNames.MasterApiKeyRejected,
|
||||
SecurityEventNames.AdminBypassRejected,
|
||||
SecurityEventNames.RateLimitTriggered,
|
||||
SecurityEventNames.MigrationFailure
|
||||
SecurityEventNames.MigrationFailure,
|
||||
SecurityEventNames.SetupTokenRejected
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
/// <summary>
|
||||
/// The key that separates rate-limit buckets per client. It is the remote address as seen by the
|
||||
/// pipeline (the real visitor once forwarded headers are trusted, otherwise the direct peer).
|
||||
/// </summary>
|
||||
public static class ClientPartitionKey
|
||||
{
|
||||
public const string Unknown = "(unknown)";
|
||||
|
||||
public static string For(HttpContext context)
|
||||
{
|
||||
var address = context.Connection.RemoteIpAddress;
|
||||
if (address is null)
|
||||
{
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
return (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
public static class ForwardedHeadersExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the <c>ForwardedHeaders</c> section and configures the framework middleware to
|
||||
/// trust only the listed proxies (default trust of loopback is cleared, one hop only).
|
||||
/// Nothing is observable until <see cref="UseCmsForwardedHeaders"/> finds a proxy configured.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddCmsForwardedHeaders(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var settings = configuration.GetSection(ForwardedHeadersSettings.SectionName).Get<ForwardedHeadersSettings>()
|
||||
?? new ForwardedHeadersSettings();
|
||||
var proxies = ForwardedHeadersSettings.ParseKnownProxies(settings.KnownProxies);
|
||||
|
||||
services.AddSingleton(new ForwardedHeadersState(proxies.Count > 0));
|
||||
services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
options.ForwardLimit = 1;
|
||||
options.KnownProxies.Clear();
|
||||
options.KnownIPNetworks.Clear();
|
||||
foreach (var proxy in proxies)
|
||||
{
|
||||
options.KnownProxies.Add(proxy);
|
||||
}
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>Adds the forwarded-headers middleware only when at least one proxy is configured.</summary>
|
||||
public static IApplicationBuilder UseCmsForwardedHeaders(this IApplicationBuilder app)
|
||||
{
|
||||
var state = app.ApplicationServices.GetService<ForwardedHeadersState>();
|
||||
return state is { Enabled: true } ? app.UseForwardedHeaders() : app;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record ForwardedHeadersState(bool Enabled);
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Net;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in trust in a reverse proxy (section <c>ForwardedHeaders</c>). With no known proxy
|
||||
/// configured the host ignores <c>X-Forwarded-*</c> headers completely, exactly as before.
|
||||
/// </summary>
|
||||
public sealed class ForwardedHeadersSettings
|
||||
{
|
||||
public const string SectionName = "ForwardedHeaders";
|
||||
|
||||
/// <summary>IP addresses of the reverse proxies whose <c>X-Forwarded-For</c>/<c>-Proto</c> are trusted.</summary>
|
||||
public string[] KnownProxies { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Parses and validates the configured proxy addresses.
|
||||
/// Throws <see cref="InvalidOperationException"/> for an unparsable entry or a wildcard
|
||||
/// (any-address) entry: trusting every sender would let any client spoof its address.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<IPAddress> ParseKnownProxies(IEnumerable<string>? entries)
|
||||
{
|
||||
var result = new List<IPAddress>();
|
||||
foreach (var entry in entries ?? [])
|
||||
{
|
||||
if (!IPAddress.TryParse(entry?.Trim(), out var address))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{SectionName}:KnownProxies contains an entry that is not an IP address.");
|
||||
}
|
||||
|
||||
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{SectionName}:KnownProxies must not contain an any-address entry (0.0.0.0 or ::).");
|
||||
}
|
||||
|
||||
result.Add(address);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Exceptions;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
@@ -157,43 +158,58 @@ public static class ServiceCollectionExtensions
|
||||
return ValueTask.CompletedTask;
|
||||
};
|
||||
|
||||
options.AddFixedWindowLimiter("login", opt =>
|
||||
// Every named policy is partitioned per client address (ClientPartitionKey). Behind a
|
||||
// reverse proxy that is only meaningful once ForwardedHeaders:KnownProxies is set;
|
||||
// without it all callers share the proxy address, i.e. one bucket, as before.
|
||||
options.AddPolicy("login", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:Login");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 5);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 5),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
options.AddSlidingWindowLimiter("refresh", opt =>
|
||||
options.AddPolicy("refresh", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:Refresh");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 20);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.SegmentsPerWindow = 4;
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetSlidingWindowLimiter(ClientPartitionKey.For(context), _ => new SlidingWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 20),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
SegmentsPerWindow = 4,
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
// Guards the anonymous Sentry tunnel. Generous, because a burst of browser errors is
|
||||
// exactly when reporting matters most, but bounded, because the endpoint makes an
|
||||
// outbound HTTPS request per call.
|
||||
options.AddFixedWindowLimiter(SentryTunnelExtensions.RateLimiterName, opt =>
|
||||
options.AddPolicy(SentryTunnelExtensions.RateLimiterName, context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:SentryTunnel");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 60);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 60),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
// Guards the anonymous public offerings listing (NFR-OFF-01) against scraping.
|
||||
// Only the public GET carries this policy — admin mutation endpoints are already
|
||||
// behind AdminOnly authentication (Offerings NFR Requirements Q1 = A).
|
||||
options.AddFixedWindowLimiter("offerings-public", opt =>
|
||||
options.AddPolicy("offerings-public", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:OfferingsPublic");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 120);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 120),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Website;
|
||||
|
||||
/// <summary>
|
||||
@@ -138,13 +140,13 @@ public static class WebsitePathResolver
|
||||
{
|
||||
return !hasTrailingSlash && name == pageName
|
||||
? new WebsiteResolution.ServeFile(pageName + ".html")
|
||||
: new WebsiteResolution.Redirect("/" + pageName + query);
|
||||
: new WebsiteResolution.Redirect(EncodePath("/" + pageName) + query);
|
||||
}
|
||||
|
||||
// R11 - trailing slashes are stripped by a 301, whether or not the target exists.
|
||||
if (hasTrailingSlash)
|
||||
{
|
||||
return new WebsiteResolution.Redirect(stripped + query);
|
||||
return new WebsiteResolution.Redirect(EncodePath(stripped) + query);
|
||||
}
|
||||
|
||||
// R8 - paths that look like files are served as they are (never lower-cased) or not found.
|
||||
@@ -158,6 +160,13 @@ public static class WebsitePathResolver
|
||||
return fileExists(directoryIndex) ? new WebsiteResolution.ServeFile(directoryIndex) : notFound;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The input path is decoded, but a Location header must be a valid URL reference: without this a
|
||||
/// request for <c>/a%3Fb/</c> would redirect to <c>/a?b</c> (a different resource), a '#' would
|
||||
/// start a fragment, and non-ASCII characters would end up raw in a header value.
|
||||
/// </summary>
|
||||
private static string EncodePath(string decodedPath) => new PathString(decodedPath).ToUriComponent();
|
||||
|
||||
private static bool HasForbiddenCharacters(string path)
|
||||
{
|
||||
foreach (var c in path)
|
||||
|
||||
@@ -11,10 +11,11 @@ public static class SecurityEventNames
|
||||
public const string AdminBypassRejected = "admin_bypass_rejected";
|
||||
public const string RateLimitTriggered = "rate_limit_triggered";
|
||||
public const string MigrationFailure = "migration_failure";
|
||||
public const string SetupTokenRejected = "setup_token_rejected";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The six security events that alert rules are built on.
|
||||
/// The seven security events that alert rules are built on.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Why source-generated <see cref="LoggerMessageAttribute"/> rather than plain log calls:</b>
|
||||
@@ -32,7 +33,7 @@ public static class SecurityEventNames
|
||||
/// would break the day someone improves the wording — silently, because a rule that matches
|
||||
/// nothing looks exactly like a rule with nothing to match.
|
||||
///
|
||||
/// All six sit at <c>Warning</c> or above by construction, so they cross the Sentry event
|
||||
/// All seven sit at <c>Warning</c> or above by construction, so they cross the Sentry event
|
||||
/// threshold rather than depending on a coincidence of configuration.
|
||||
/// </remarks>
|
||||
public static partial class SecurityEvents
|
||||
@@ -43,6 +44,7 @@ public static partial class SecurityEvents
|
||||
public const int AdminBypassRejectedEventId = 5004;
|
||||
public const int RateLimitTriggeredEventId = 5005;
|
||||
public const int MigrationFailureEventId = 5006;
|
||||
public const int SetupTokenRejectedEventId = 5007;
|
||||
|
||||
/// <summary>
|
||||
/// Repeated occurrences suggest an attack or a forgotten password. Carries whether the
|
||||
@@ -82,6 +84,19 @@ public static partial class SecurityEvents
|
||||
public static void MigrationFailure(ILogger logger, Exception exception, int attempts) =>
|
||||
MigrationFailureCore(logger, exception, SecurityEventNames.MigrationFailure, attempts);
|
||||
|
||||
/// <summary>
|
||||
/// Someone tried to create the first administrator without the right setup token. Never carries
|
||||
/// the presented token.
|
||||
/// </summary>
|
||||
public static void SetupTokenRejected(ILogger logger, string endpoint) =>
|
||||
SetupTokenRejectedCore(logger, SecurityEventNames.SetupTokenRejected, endpoint);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = SetupTokenRejectedEventId,
|
||||
Level = LogLevel.Warning,
|
||||
Message = "Security event {SecurityEvent}: setup token rejected on {Endpoint}")]
|
||||
private static partial void SetupTokenRejectedCore(ILogger logger, string securityEvent, string endpoint);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = FailedLoginEventId,
|
||||
Level = LogLevel.Warning,
|
||||
|
||||
@@ -1,44 +1,70 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Core.Observability;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
using SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
|
||||
|
||||
public class SetupControllerTests
|
||||
{
|
||||
private readonly ISetupService _setupService = Substitute.For<ISetupService>();
|
||||
private readonly ISetupTokenValidator _validator = Substitute.For<ISetupTokenValidator>();
|
||||
private readonly ILogger<SetupController> _logger = Substitute.For<ILogger<SetupController>>();
|
||||
|
||||
public SetupControllerTests()
|
||||
{
|
||||
_validator.IsAuthorized(Arg.Any<string?>()).Returns(true);
|
||||
_logger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
}
|
||||
|
||||
private SetupController NewController(string? tokenHeader = null)
|
||||
{
|
||||
var controller = new SetupController(_setupService, _validator, _logger)
|
||||
{
|
||||
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
|
||||
};
|
||||
if (tokenHeader is not null)
|
||||
{
|
||||
controller.HttpContext.Request.Headers[SetupController.TokenHeader] = tokenHeader;
|
||||
}
|
||||
|
||||
return controller;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStatus_ReturnsOk_WithInitializedTrue_WhenSystemIsSetUp()
|
||||
{
|
||||
_setupService.IsSystemInitializedAsync().Returns(true);
|
||||
var controller = new SetupController(_setupService);
|
||||
var controller = NewController();
|
||||
|
||||
var result = await controller.GetStatus();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = true });
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = true, TokenRequired = false });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStatus_ReturnsOk_WithInitializedFalse_WhenSystemIsNotSetUp()
|
||||
{
|
||||
_setupService.IsSystemInitializedAsync().Returns(false);
|
||||
var controller = new SetupController(_setupService);
|
||||
var controller = NewController();
|
||||
|
||||
var result = await controller.GetStatus();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = false });
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = false, TokenRequired = false });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_ReturnsOk_WithSuccessMessage()
|
||||
{
|
||||
var controller = new SetupController(_setupService);
|
||||
var controller = NewController();
|
||||
|
||||
var result = await controller.CreateOwner(new CreateOwnerRequest("Owner", "owner@test.com", "Password1!"));
|
||||
|
||||
@@ -46,4 +72,65 @@ public class SetupControllerTests
|
||||
ok.Value.Should().BeEquivalentTo(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." });
|
||||
await _setupService.Received(1).CreateInitialOwnerAsync("Owner", "owner@test.com", "Password1!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStatus_ReportsTokenRequired_WhenConfigured()
|
||||
{
|
||||
_setupService.IsSystemInitializedAsync().Returns(false);
|
||||
_validator.TokenRequired.Returns(true);
|
||||
|
||||
var result = await NewController().GetStatus();
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>().Which.Value
|
||||
.Should().BeEquivalentTo(new { Initialized = false, TokenRequired = true });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_WithRejectedToken_Returns401_AndNeverCreatesTheOwner()
|
||||
{
|
||||
_validator.IsAuthorized("wrong").Returns(false);
|
||||
|
||||
var result = await NewController("wrong").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!"));
|
||||
|
||||
result.Should().BeOfType<ObjectResult>().Which.StatusCode.Should().Be(StatusCodes.Status401Unauthorized);
|
||||
await _setupService.DidNotReceiveWithAnyArgs().CreateInitialOwnerAsync(default!, default!, default!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_MissingAndWrongToken_GiveIdenticalResponses()
|
||||
{
|
||||
_validator.IsAuthorized(Arg.Any<string?>()).Returns(false);
|
||||
var request = new CreateOwnerRequest("O", "o@test.com", "Password1!");
|
||||
|
||||
var missing = (ObjectResult)await NewController().CreateOwner(request);
|
||||
var wrong = (ObjectResult)await NewController("guess").CreateOwner(request);
|
||||
|
||||
missing.StatusCode.Should().Be(wrong.StatusCode);
|
||||
missing.Value.Should().BeEquivalentTo(wrong.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_WithRejectedToken_LogsSecurityEvent_WithoutTheToken()
|
||||
{
|
||||
_validator.IsAuthorized("super-secret-guess").Returns(false);
|
||||
|
||||
await NewController("super-secret-guess").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!"));
|
||||
|
||||
var logged = _logger.ReceivedCalls()
|
||||
.Where(c => c.GetMethodInfo().Name == nameof(ILogger.Log))
|
||||
.ToList();
|
||||
logged.Should().NotBeEmpty();
|
||||
logged.Select(c => c.GetArguments()[2]!.ToString()!)
|
||||
.Should().OnlyContain(m => !m.Contains("super-secret-guess"));
|
||||
logged.Select(c => c.GetArguments()[2]!.ToString()!)
|
||||
.Should().Contain(m => m.Contains(SecurityEventNames.SetupTokenRejected));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_PassesTheHeaderValueToTheValidator()
|
||||
{
|
||||
await NewController("abc").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!"));
|
||||
|
||||
_validator.Received(1).IsAuthorized("abc");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Setup;
|
||||
|
||||
public class SetupTokenValidatorTests
|
||||
{
|
||||
private static SetupTokenValidator With(string? token) =>
|
||||
new(Options.Create(new SetupOptions { Token = token }));
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void NoTokenConfigured_NothingRequired_EverythingAuthorized(string? configured)
|
||||
{
|
||||
var validator = With(configured);
|
||||
|
||||
validator.TokenRequired.Should().BeFalse();
|
||||
validator.IsAuthorized(null).Should().BeTrue();
|
||||
validator.IsAuthorized("anything").Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExactToken_IsAuthorized()
|
||||
{
|
||||
var validator = With("correct-horse-battery-staple-0123456789");
|
||||
|
||||
validator.TokenRequired.Should().BeTrue();
|
||||
validator.IsAuthorized("correct-horse-battery-staple-0123456789").Should().BeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("correct-horse-battery-staple-0123456789 ")]
|
||||
[InlineData("CORRECT-HORSE-BATTERY-STAPLE-0123456789")]
|
||||
[InlineData("correct")]
|
||||
public void MissingOrDifferentToken_IsRejected(string? provided)
|
||||
{
|
||||
With("correct-horse-battery-staple-0123456789").IsAuthorized(provided).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(" ")]
|
||||
[InlineData(" \t")]
|
||||
public void WhitespaceOnlyToken_FailsOptionsValidation(string token)
|
||||
{
|
||||
SetupOptions.IsValid(new SetupOptions { Token = token }).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("abc")]
|
||||
public void NullEmptyOrRealToken_PassesOptionsValidation(string? token)
|
||||
{
|
||||
SetupOptions.IsValid(new SetupOptions { Token = token }).Should().BeTrue();
|
||||
}
|
||||
|
||||
// PBT: only the exact configured token passes; any other string fails; never throws.
|
||||
[Fact]
|
||||
public void Property_OnlyTheExactTokenIsAccepted()
|
||||
{
|
||||
var tokens = ArbMap.Default.ArbFor<NonEmptyString>().Generator
|
||||
.Select(s => s.Get)
|
||||
.Where(s => !string.IsNullOrWhiteSpace(s));
|
||||
var arb = Gen.Two(tokens).ToArbitrary();
|
||||
|
||||
Prop.ForAll(arb, pair =>
|
||||
{
|
||||
var (configured, provided) = pair;
|
||||
var validator = With(configured);
|
||||
return validator.IsAuthorized(configured)
|
||||
&& validator.IsAuthorized(provided) == (provided == configured);
|
||||
}).QuickCheckThrowOnFailure();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Property_NeverThrows_ForArbitraryInput()
|
||||
{
|
||||
var validator = With("configured-token");
|
||||
|
||||
Prop.ForAll(ArbMap.Default.ArbFor<string>(), input =>
|
||||
{
|
||||
validator.IsAuthorized(input);
|
||||
return true;
|
||||
}).QuickCheckThrowOnFailure();
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="FsCheck.Xunit" Version="3.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Core.Observability;
|
||||
using SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Controllers;
|
||||
|
||||
@@ -8,23 +13,42 @@ namespace SlpModularCms.Modules.Identity.Controllers;
|
||||
[Route("[controller]")]
|
||||
public class SetupController : ControllerBase
|
||||
{
|
||||
private readonly ISetupService _setupService;
|
||||
public const string TokenHeader = "X-Setup-Token";
|
||||
|
||||
public SetupController(ISetupService setupService)
|
||||
private readonly ISetupService _setupService;
|
||||
private readonly ISetupTokenValidator _tokenValidator;
|
||||
private readonly ILogger<SetupController> _logger;
|
||||
|
||||
public SetupController(
|
||||
ISetupService setupService,
|
||||
ISetupTokenValidator tokenValidator,
|
||||
ILogger<SetupController> logger)
|
||||
{
|
||||
_setupService = setupService;
|
||||
_tokenValidator = tokenValidator;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet("status")]
|
||||
[EnableRateLimiting("login")]
|
||||
public async Task<IActionResult> GetStatus()
|
||||
{
|
||||
var initialized = await _setupService.IsSystemInitializedAsync();
|
||||
return Ok(new { Initialized = initialized });
|
||||
return Ok(new { Initialized = initialized, TokenRequired = _tokenValidator.TokenRequired });
|
||||
}
|
||||
|
||||
[HttpPost("owner")]
|
||||
[EnableRateLimiting("login")]
|
||||
public async Task<IActionResult> CreateOwner([FromBody] CreateOwnerRequest request)
|
||||
{
|
||||
// Missing and wrong tokens give the identical response, so the endpoint reveals nothing about
|
||||
// whether a token exists or how close a guess was. The token itself is never logged.
|
||||
if (!_tokenValidator.IsAuthorized(Request.Headers[TokenHeader].ToString()))
|
||||
{
|
||||
SecurityEvents.SetupTokenRejected(_logger, Request.Path);
|
||||
return Problem(title: "Setup token ontbreekt of is onjuist.", statusCode: StatusCodes.Status401Unauthorized);
|
||||
}
|
||||
|
||||
await _setupService.CreateInitialOwnerAsync(request.Name, request.Email, request.Password);
|
||||
return Ok(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Modules;
|
||||
using SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity;
|
||||
|
||||
@@ -13,7 +15,11 @@ public class IdentityModule : IModule
|
||||
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
// Specifieke services voor deze module (indien niet al in Core)
|
||||
services.AddOptions<SetupOptions>()
|
||||
.BindConfiguration(SetupOptions.SectionName)
|
||||
.Validate(SetupOptions.IsValid, "Identity:Setup:Token must not consist only of whitespace.")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<ISetupTokenValidator, SetupTokenValidator>();
|
||||
}
|
||||
|
||||
public void UseModule(IApplicationBuilder app)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Optional protection of the first-administrator setup (section <c>Identity:Setup</c>).
|
||||
/// With no token configured the setup endpoints behave exactly as before.
|
||||
/// </summary>
|
||||
public sealed class SetupOptions
|
||||
{
|
||||
public const string SectionName = "Identity:Setup";
|
||||
|
||||
/// <summary>The secret the person creating the first administrator must present. Empty = not required.</summary>
|
||||
public string? Token { get; set; }
|
||||
|
||||
/// <summary>True when a token is configured and therefore required.</summary>
|
||||
public bool TokenRequired => !string.IsNullOrEmpty(Token);
|
||||
|
||||
/// <summary>
|
||||
/// A token that is set but consists only of whitespace is a configuration mistake (it would look
|
||||
/// protected but could be guessed trivially), so it is rejected at startup. Null or empty means
|
||||
/// "no token".
|
||||
/// </summary>
|
||||
public static bool IsValid(SetupOptions options) =>
|
||||
string.IsNullOrEmpty(options.Token) || !string.IsNullOrWhiteSpace(options.Token);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Setup;
|
||||
|
||||
/// <summary>Decides whether a request may create the first administrator.</summary>
|
||||
public interface ISetupTokenValidator
|
||||
{
|
||||
/// <summary>True when a setup token is configured.</summary>
|
||||
bool TokenRequired { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True when no token is required, or when <paramref name="provided"/> equals the configured one.
|
||||
/// Never throws for any input.
|
||||
/// </summary>
|
||||
bool IsAuthorized(string? provided);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares SHA-256 digests with a fixed-time comparison, so neither the length nor the content of
|
||||
/// the configured token leaks through response timing.
|
||||
/// </summary>
|
||||
public sealed class SetupTokenValidator : ISetupTokenValidator
|
||||
{
|
||||
private readonly byte[]? _expectedDigest;
|
||||
|
||||
public SetupTokenValidator(IOptions<SetupOptions> options)
|
||||
{
|
||||
var token = options.Value.Token;
|
||||
_expectedDigest = string.IsNullOrEmpty(token) ? null : Hash(token);
|
||||
}
|
||||
|
||||
public bool TokenRequired => _expectedDigest is not null;
|
||||
|
||||
public bool IsAuthorized(string? provided)
|
||||
{
|
||||
if (_expectedDigest is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(provided))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CryptographicOperations.FixedTimeEquals(_expectedDigest, Hash(provided));
|
||||
}
|
||||
|
||||
private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
|
||||
}
|
||||
Reference in New Issue
Block a user