Beschikbaarheidspoort laat publieke site-endpoints door en 429 geeft Retry-After met ProblemDetails

Nieuwe marker [PublicSiteEndpoint] (deny-by-default): alleen GET /offerings blijft bereikbaar als het CMS uit staat of in onderhoud is; alle andere acties, adminroutes inbegrepen, blijven 503. OnRejected zet Retry-After en schrijft application/problem+json met alleen type, title en status. Op master zijn de limiet-policies nog globale buckets: de contactroutes mogen pas live na de per-client-partitionering van de ASF-branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:07:18 +01:00
co-authored by Claude Sonnet 5.5
parent c3c8bcfd5e
commit a58374abeb
12 changed files with 510 additions and 10 deletions
@@ -0,0 +1,152 @@
using System.Text.Json;
using System.Threading.RateLimiting;
using FluentAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Observability;
using Xunit;
namespace SlpModularCms.Core.Tests.Hosting;
/// <summary>
/// The 429 response of every rate-limit policy: a retry hint and a machine-readable body, and
/// nothing about the limiter or the caller.
/// </summary>
public class RateLimiterOnRejectedTests
{
private sealed class TestLease(TimeSpan? retryAfter) : RateLimitLease
{
public override bool IsAcquired => false;
public override IEnumerable<string> MetadataNames =>
retryAfter is null ? [] : [MetadataName.RetryAfter.Name];
public override bool TryGetMetadata(string metadataName, out object? metadata)
{
if (retryAfter is not null && metadataName == MetadataName.RetryAfter.Name)
{
metadata = retryAfter.Value;
return true;
}
metadata = null;
return false;
}
}
private sealed class CapturingLoggerProvider : ILoggerProvider
{
public List<(EventId EventId, string Message)> Entries { get; } = [];
public ILogger CreateLogger(string categoryName) => new CapturingLogger(Entries);
public void Dispose() { }
private sealed class CapturingLogger(List<(EventId, string)> entries) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter) => entries.Add((eventId, formatter(state, exception)));
}
}
private static async Task<(HttpContext Context, string Body, CapturingLoggerProvider Logs)> RejectAsync(
TimeSpan? retryAfter, string policy = "login")
{
var logs = new CapturingLoggerProvider();
var services = new ServiceCollection();
services.AddLogging(b => b.AddProvider(logs));
services.AddCmsRateLimiting(new ConfigurationBuilder().Build());
var provider = services.BuildServiceProvider();
var options = provider.GetRequiredService<IOptions<RateLimiterOptions>>().Value;
var context = new DefaultHttpContext { RequestServices = provider };
context.Request.Path = "/api/v1/Auth/login";
context.Response.Body = new MemoryStream();
context.SetEndpoint(new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(new EnableRateLimitingAttribute(policy)),
"test"));
await options.OnRejected!(
new OnRejectedContext { HttpContext = context, Lease = new TestLease(retryAfter) },
CancellationToken.None);
context.Response.Body.Position = 0;
var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
return (context, body, logs);
}
[Fact]
public void RejectionStatusCode_Is429()
{
var provider = new ServiceCollection()
.AddLogging()
.AddCmsRateLimiting(new ConfigurationBuilder().Build())
.BuildServiceProvider();
provider.GetRequiredService<IOptions<RateLimiterOptions>>().Value.RejectionStatusCode
.Should().Be(StatusCodes.Status429TooManyRequests);
}
[Theory]
[InlineData(0.2, "1")]
[InlineData(1.0, "1")]
[InlineData(59.01, "60")]
[InlineData(61.5, "62")]
public async Task OnRejected_SetsRetryAfter_InWholeSecondsRoundedUp(double seconds, string expected)
{
var (context, _, _) = await RejectAsync(TimeSpan.FromSeconds(seconds));
context.Response.Headers.RetryAfter.ToString().Should().Be(expected);
}
[Fact]
public async Task OnRejected_FallsBackTo60Seconds_WhenTheLeaseReportsNoWait()
{
var (context, _, _) = await RejectAsync(retryAfter: null);
context.Response.Headers.RetryAfter.ToString().Should().Be("60");
}
[Fact]
public async Task OnRejected_WritesProblemJson_WithOnlyTypeTitleAndStatus()
{
var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30));
context.Response.ContentType.Should().StartWith("application/problem+json");
using var json = JsonDocument.Parse(body);
json.RootElement.EnumerateObject().Select(p => p.Name)
.Should().BeEquivalentTo(["type", "title", "status"]);
json.RootElement.GetProperty("status").GetInt32().Should().Be(429);
json.RootElement.GetProperty("title").GetString().Should().Be("Too many requests");
}
[Fact]
public async Task OnRejected_DoesNotLeakThePolicyPathOrTheLimiterInTheResponse()
{
var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "super-secret-policy");
body.Should().NotContain("super-secret-policy");
body.Should().NotContain("/api/v1/Auth/login");
body.ToLowerInvariant().Should().NotContain("permit").And.NotContain("window").And.NotContain("lease");
context.Response.Headers.Keys.Should().BeEquivalentTo(["Retry-After", "Content-Type"]);
}
[Fact]
public async Task OnRejected_StillLogsTheRateLimitSecurityEvent_ExactlyOnce()
{
// The message template is deliberately constant (see SecurityEventsTests); the policy and
// path travel as structured properties, so only the event id is asserted here.
var (_, _, logs) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "login");
logs.Entries.Count(e => e.EventId.Id == SecurityEvents.RateLimitTriggeredEventId).Should().Be(1);
}
}