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:
@@ -0,0 +1,241 @@
|
||||
using System.Reflection;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Observability;
|
||||
using SlpModularCms.Modules.Availability.Controllers;
|
||||
using SlpModularCms.Modules.Availability.Middleware;
|
||||
using SlpModularCms.Modules.Availability.Services;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
using SlpModularCms.Modules.Master.Controllers;
|
||||
using SlpModularCms.Modules.Offerings.Controllers;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Availability.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The availability statuses stop the CMS only. These tests pin down which endpoints stay
|
||||
/// reachable behind a closed gate (deny-by-default, marker per action) and prove that every
|
||||
/// other endpoint, admin routes included, is still blocked.
|
||||
/// </summary>
|
||||
public class PublicSiteEndpointGateTests
|
||||
{
|
||||
private readonly IAvailabilityService _service = Substitute.For<IAvailabilityService>();
|
||||
private readonly IMasterAvailabilityService _masterService = Substitute.For<IMasterAvailabilityService>();
|
||||
private readonly IAdminTokenValidator _adminTokenValidator = Substitute.For<IAdminTokenValidator>();
|
||||
private readonly RequestDelegate _next = Substitute.For<RequestDelegate>();
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
|
||||
public PublicSiteEndpointGateTests()
|
||||
{
|
||||
_middleware = new AvailabilityMiddleware(
|
||||
_next, NullLogger<AvailabilityMiddleware>.Instance, _adminTokenValidator);
|
||||
|
||||
// No admin token on any request in these tests.
|
||||
_adminTokenValidator.Validate(Arg.Any<string>())
|
||||
.Returns(new AdminTokenResult(false, BypassRejectionReason.Absent));
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
}
|
||||
|
||||
public enum ClosedGate
|
||||
{
|
||||
CmsDisabled,
|
||||
Maintenance,
|
||||
MasterBlocks,
|
||||
}
|
||||
|
||||
private void CloseGate(ClosedGate gate)
|
||||
{
|
||||
switch (gate)
|
||||
{
|
||||
case ClosedGate.CmsDisabled:
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
break;
|
||||
case ClosedGate.Maintenance:
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
|
||||
break;
|
||||
case ClosedGate.MasterBlocks:
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Available);
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(false, "Geblokkeerd door master"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> StatusFor(Endpoint? endpoint)
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/api/v1/some-resource";
|
||||
context.Response.Body = new MemoryStream();
|
||||
if (endpoint is not null)
|
||||
{
|
||||
context.SetEndpoint(endpoint);
|
||||
}
|
||||
|
||||
_next.ClearReceivedCalls();
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
return _next.ReceivedCalls().Any() ? StatusCodes.Status200OK : context.Response.StatusCode;
|
||||
}
|
||||
|
||||
private static Endpoint EndpointWith(params object[] metadata)
|
||||
=> new(_ => Task.CompletedTask, new EndpointMetadataCollection(metadata), "test");
|
||||
|
||||
/// <summary>The metadata MVC would attach to an action: the controller's attributes, then the action's.</summary>
|
||||
private static Endpoint EndpointOf(MethodInfo action)
|
||||
{
|
||||
var metadata = action.DeclaringType!.GetCustomAttributes(inherit: true)
|
||||
.Concat(action.GetCustomAttributes(inherit: true))
|
||||
.ToArray();
|
||||
return new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(metadata), action.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ClosedGate.CmsDisabled)]
|
||||
[InlineData(ClosedGate.Maintenance)]
|
||||
[InlineData(ClosedGate.MasterBlocks)]
|
||||
public async Task AMarkedEndpoint_StaysReachable_WhateverTheClosedGate(ClosedGate gate)
|
||||
{
|
||||
CloseGate(gate);
|
||||
|
||||
(await StatusFor(EndpointWith(new PublicSiteEndpointAttribute()))).Should().Be(200);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ClosedGate.CmsDisabled)]
|
||||
[InlineData(ClosedGate.Maintenance)]
|
||||
[InlineData(ClosedGate.MasterBlocks)]
|
||||
public async Task AnUnmarkedEndpoint_IsStillBlocked(ClosedGate gate)
|
||||
{
|
||||
CloseGate(gate);
|
||||
|
||||
(await StatusFor(EndpointWith(new AuthorizeAttribute("AdminOnly")))).Should().Be(503);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARequestWithoutEndpointMetadata_IsStillBlocked()
|
||||
{
|
||||
CloseGate(ClosedGate.CmsDisabled);
|
||||
|
||||
(await StatusFor(endpoint: null)).Should().Be(503);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMarkerDoesNotBlockAnything_WhenTheCmsIsAvailable()
|
||||
{
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Available);
|
||||
|
||||
(await StatusFor(EndpointWith(new PublicSiteEndpointAttribute()))).Should().Be(200);
|
||||
(await StatusFor(endpoint: null)).Should().Be(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheAvailabilityStatusEndpoint_StaysOpen_BecauseOfItsPathBypass()
|
||||
{
|
||||
CloseGate(ClosedGate.CmsDisabled);
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/api/v1/Availability/status";
|
||||
context.Response.Body = new MemoryStream();
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
// ---- Route table: which actions of all modules carry the marker ----
|
||||
|
||||
/// <summary>
|
||||
/// The complete list of actions that stay reachable when the CMS is off. Extending it is a
|
||||
/// deliberate act: add the action here and in the code in the same change. (CMS-U3 adds the two
|
||||
/// public contact routes.)
|
||||
/// </summary>
|
||||
private static readonly string[] AllowedPublicActions =
|
||||
[
|
||||
$"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}",
|
||||
];
|
||||
|
||||
private static IReadOnlyList<MethodInfo> AllActions() =>
|
||||
new[]
|
||||
{
|
||||
typeof(AvailabilityController).Assembly,
|
||||
typeof(UsersController).Assembly,
|
||||
typeof(CmsInstanceController).Assembly,
|
||||
typeof(OfferingsController).Assembly,
|
||||
typeof(SystemController).Assembly,
|
||||
}
|
||||
.Distinct()
|
||||
.SelectMany(a => a.GetTypes())
|
||||
.Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract)
|
||||
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
|
||||
.Where(m => m.GetCustomAttributes<HttpMethodAttribute>().Any())
|
||||
.ToList();
|
||||
|
||||
private static string Name(MethodInfo m) => $"{m.DeclaringType!.Name}.{m.Name}";
|
||||
|
||||
[Fact]
|
||||
public void TheMarkerIsOnExactlyTheAllowedPublicActions()
|
||||
{
|
||||
var actions = AllActions();
|
||||
actions.Count.Should().BeGreaterThan(20, "the reflection must actually find the controllers of the modules");
|
||||
|
||||
actions.Where(m => m.GetCustomAttribute<PublicSiteEndpointAttribute>() is not null)
|
||||
.Select(Name)
|
||||
.Should().BeEquivalentTo(AllowedPublicActions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMarkedActionIsAnonymous_AndNeverAnAuthorizedOne()
|
||||
{
|
||||
foreach (var action in AllActions().Where(m => m.GetCustomAttribute<PublicSiteEndpointAttribute>() is not null))
|
||||
{
|
||||
action.GetCustomAttribute<AllowAnonymousAttribute>()
|
||||
.Should().NotBeNull($"{Name(action)} is public so it must be explicitly anonymous");
|
||||
action.GetCustomAttributes<AuthorizeAttribute>()
|
||||
.Should().BeEmpty($"{Name(action)} must not require authorization");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryOtherAction_IncludingAllAdminRoutes_IsBlockedByAClosedGate()
|
||||
{
|
||||
CloseGate(ClosedGate.CmsDisabled);
|
||||
var others = AllActions()
|
||||
.Where(m => m.GetCustomAttribute<PublicSiteEndpointAttribute>() is null)
|
||||
.ToList();
|
||||
others.Should().NotBeEmpty();
|
||||
|
||||
var reachable = new List<string>();
|
||||
foreach (var action in others)
|
||||
{
|
||||
if (await StatusFor(EndpointOf(action)) != 503)
|
||||
{
|
||||
reachable.Add(Name(action));
|
||||
}
|
||||
}
|
||||
|
||||
reachable.Should().BeEmpty("only marked actions may pass a closed gate");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMarkedActions_AreTheOnlyOnesThatPassAClosedGate()
|
||||
{
|
||||
CloseGate(ClosedGate.Maintenance);
|
||||
|
||||
var passing = new List<string>();
|
||||
foreach (var action in AllActions())
|
||||
{
|
||||
if (await StatusFor(EndpointOf(action)) == 200)
|
||||
{
|
||||
passing.Add(Name(action));
|
||||
}
|
||||
}
|
||||
|
||||
passing.Should().BeEquivalentTo(AllowedPublicActions);
|
||||
}
|
||||
}
|
||||
+8
@@ -31,4 +31,12 @@
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Only for the route-table test (PublicSiteEndpointGateTests): it inspects the controllers of
|
||||
every module a host can load to prove which endpoints stay reachable behind the gate. -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user