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:
@@ -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"));
|
||||
|
||||
Reference in New Issue
Block a user