PUT /availability/status vervangt POST /availability/admin/status; de poort sluit alleen het lezen van de status vrij
De status is één resource: de publieke GET en de PUT van de beheerder delen het pad; de PUT geeft de bijgewerkte resource terug. De vrijstelling van de poort geldt nu alleen voor GET en HEAD, zodat de PUT als beheerroute gewoon achter de poort blijft. De oude route verdwijnt zonder alias, dus API en admin-app moeten als één release uit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -39,6 +39,7 @@ public class AvailabilityGateScopeTests
|
||||
var middleware = new AvailabilityMiddleware(next, NullLogger<AvailabilityMiddleware>.Instance, validator);
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = path;
|
||||
context.Request.Method = HttpMethods.Get; // reading: the status path is open for GET only
|
||||
context.Response.Body = new MemoryStream();
|
||||
|
||||
await middleware.InvokeAsync(context, localSvc, masterSvc);
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
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.Security;
|
||||
using SlpModularCms.Core.Observability;
|
||||
using SlpModularCms.Modules.Availability.Controllers;
|
||||
using SlpModularCms.Modules.Availability.Middleware;
|
||||
using SlpModularCms.Modules.Availability.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Availability.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The availability status is one resource: the public GET and the administrator's PUT share the
|
||||
/// path. There is no separate admin route, and the gate must not exempt the PUT.
|
||||
/// </summary>
|
||||
public class AvailabilityStatusRouteTests
|
||||
{
|
||||
private readonly IAvailabilityService _service = Substitute.For<IAvailabilityService>();
|
||||
private readonly IMasterAvailabilityService _master = Substitute.For<IMasterAvailabilityService>();
|
||||
private readonly IAdminTokenValidator _validator = Substitute.For<IAdminTokenValidator>();
|
||||
private readonly RequestDelegate _next = Substitute.For<RequestDelegate>();
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
|
||||
public AvailabilityStatusRouteTests()
|
||||
{
|
||||
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance, _validator);
|
||||
_master.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent));
|
||||
}
|
||||
|
||||
private async Task<DefaultHttpContext> Call(string method, string path = "/api/v1/Availability/status")
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Method = method;
|
||||
context.Request.Path = path;
|
||||
context.Response.Body = new MemoryStream();
|
||||
_next.ClearReceivedCalls();
|
||||
await _middleware.InvokeAsync(context, _service, _master);
|
||||
return context;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET")]
|
||||
[InlineData("HEAD")]
|
||||
public async Task ReadingTheStatus_StaysOpen_WhateverTheState(string method)
|
||||
{
|
||||
await Call(method);
|
||||
|
||||
await _next.Received(1).Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("PUT")]
|
||||
[InlineData("POST")]
|
||||
[InlineData("DELETE")]
|
||||
[InlineData("PATCH")]
|
||||
public async Task ChangingTheStatus_IsNotExempted_ItMeetsTheGateLikeEveryAdminRoute(string method)
|
||||
{
|
||||
var context = await Call(method);
|
||||
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
context.Response.StatusCode.Should().Be(503);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AVerifiedAdministrator_CanStillChangeTheStatus_WhileTheCmsIsDisabled()
|
||||
{
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(true, default));
|
||||
|
||||
await Call("PUT");
|
||||
|
||||
await _next.Received(1).Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnExpiredAdministratorToken_OnThePut_Gets401_SoTheAppRefreshesItsSession()
|
||||
{
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(false, BypassRejectionReason.Expired));
|
||||
|
||||
var context = await Call("PUT");
|
||||
|
||||
context.Response.StatusCode.Should().Be(401);
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePathMatchIsCaseInsensitive_ForReadingToo()
|
||||
{
|
||||
await Call("GET", "/api/v1/availability/STATUS");
|
||||
|
||||
await _next.Received(1).Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
// ---- route table of the controller ----
|
||||
|
||||
private static IEnumerable<(MethodInfo Action, HttpMethodAttribute Http)> Actions() =>
|
||||
typeof(AvailabilityController)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
|
||||
.Select(m => (Action: m, Http: m.GetCustomAttributes<HttpMethodAttribute>().SingleOrDefault()))
|
||||
.Where(x => x.Http is not null)
|
||||
.Select(x => (x.Action, x.Http!));
|
||||
|
||||
[Fact]
|
||||
public void RouteTable_StatusIsOneResource_GetIsPublic_PutIsAdminOnly_AndNoRouteHasAnAdminSegment()
|
||||
{
|
||||
Actions().Select(a => $"{a.Http.HttpMethods.Single()} {a.Http.Template}")
|
||||
.Should().BeEquivalentTo(["GET status", "PUT status"]);
|
||||
|
||||
var get = Actions().Single(a => a.Http.HttpMethods.Single() == "GET").Action;
|
||||
var put = Actions().Single(a => a.Http.HttpMethods.Single() == "PUT").Action;
|
||||
|
||||
get.GetCustomAttribute<AllowAnonymousAttribute>().Should().NotBeNull();
|
||||
put.GetCustomAttribute<AllowAnonymousAttribute>().Should().BeNull();
|
||||
put.GetCustomAttribute<AuthorizeAttribute>()!.Policy.Should().Be("AdminOnly");
|
||||
put.GetCustomAttribute<PublicSiteEndpointAttribute>().Should().BeNull("changing the status must stay behind the gate");
|
||||
|
||||
foreach (var (_, http) in Actions())
|
||||
{
|
||||
(http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOldAdminRoute_IsGone_AndAnswersLikeAnyUnknownRoute()
|
||||
{
|
||||
// Not exempted by the gate and not a route of the controller.
|
||||
var context = await Call("POST", "/api/v1/Availability/admin/status");
|
||||
|
||||
context.Response.StatusCode.Should().Be(503, "an unknown admin-looking path is gated like every other non-exempted path");
|
||||
Actions().Should().NotContain(a => (a.Http.Template ?? "").Contains("admin"));
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -95,7 +95,12 @@ public class AvailabilityControllerTests
|
||||
var result = await controller.UpdateStatus(
|
||||
new UpdateStatusRequest(AvailabilityStatus.Maintenance, "Test maintenance"));
|
||||
|
||||
result.Should().BeOfType<OkResult>();
|
||||
// The answer is the updated resource, in the same shape as GET /Availability/status.
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value!.GetType().GetProperty("Status")!.GetValue(ok.Value).Should().Be("Maintenance");
|
||||
ok.Value.GetType().GetProperty("Message")!.GetValue(ok.Value).Should().Be("Test maintenance");
|
||||
ok.Value.GetType().GetProperties().Select(p => p.Name)
|
||||
.Should().BeEquivalentTo(["Status", "CheckedAt", "Message", "IsMasterControlled"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -142,6 +142,7 @@ public class PublicSiteEndpointGateTests
|
||||
CloseGate(ClosedGate.CmsDisabled);
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/api/v1/Availability/status";
|
||||
context.Request.Method = HttpMethods.Get;
|
||||
context.Response.Body = new MemoryStream();
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
@@ -9,6 +9,7 @@ internal static class TestContexts
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = path;
|
||||
context.Request.Method = HttpMethods.Get; // a real request always has a method; the status path is open for reads only
|
||||
return context;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,18 +20,21 @@ public class AvailabilityController : ControllerBase
|
||||
[HttpGet("status")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> GetStatus()
|
||||
{
|
||||
var details = await _availabilityService.GetStatusDetailsAsync();
|
||||
return Ok(new
|
||||
{
|
||||
Status = details.Status.ToString(),
|
||||
CheckedAt = DateTimeOffset.UtcNow,
|
||||
Message = details.Message ?? string.Empty,
|
||||
details.IsMasterControlled,
|
||||
});
|
||||
}
|
||||
=> Ok(ToResponse(await _availabilityService.GetStatusDetailsAsync()));
|
||||
|
||||
[HttpPost("admin/status")]
|
||||
private static object ToResponse(AvailabilityStatusDetails details) => new
|
||||
{
|
||||
Status = details.Status.ToString(),
|
||||
CheckedAt = DateTimeOffset.UtcNow,
|
||||
Message = details.Message ?? string.Empty,
|
||||
details.IsMasterControlled,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Changes the status. Same resource as the public GET (no separate admin route); the answer is the
|
||||
/// updated resource, in the same shape as the GET.
|
||||
/// </summary>
|
||||
[HttpPut("status")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public async Task<IActionResult> UpdateStatus([FromBody] UpdateStatusRequest request)
|
||||
{
|
||||
@@ -47,7 +50,7 @@ public class AvailabilityController : ControllerBase
|
||||
request.Reason,
|
||||
User.Identity?.Name);
|
||||
|
||||
return Ok();
|
||||
return Ok(ToResponse(await _availabilityService.GetStatusDetailsAsync()));
|
||||
}
|
||||
catch (MasterControlledAvailabilityException ex)
|
||||
{
|
||||
|
||||
@@ -40,9 +40,12 @@ public class AvailabilityMiddleware
|
||||
// on the bypass list, which only went unnoticed while another server (nginx) served the website and the SPA.
|
||||
private const string GatedPrefix = "/api/";
|
||||
|
||||
// Reading the status stays open for everyone (GET/HEAD only). Changing it (PUT, same path) is an admin route and
|
||||
// is NOT exempted: it follows the normal gate (a verified Owner/Administrator passes).
|
||||
private const string StatusPath = "/api/v1/Availability/status";
|
||||
|
||||
private static readonly string[] _bypassPrefixes =
|
||||
[
|
||||
"/api/v1/Availability/status",
|
||||
"/api/v1/Auth/",
|
||||
"/api/v1/Setup/status",
|
||||
"/api/v1/master/",
|
||||
@@ -63,7 +66,9 @@ public class AvailabilityMiddleware
|
||||
return;
|
||||
}
|
||||
|
||||
if (_bypassPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
||||
var readsStatus = path.StartsWith(StatusPath, StringComparison.OrdinalIgnoreCase)
|
||||
&& (HttpMethods.IsGet(context.Request.Method) || HttpMethods.IsHead(context.Request.Method));
|
||||
if (readsStatus || _bypassPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>The availability status as one RESTful resource, on the real composed host.</summary>
|
||||
public class AvailabilityStatusPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture<ClosedCmsSwitchContactHostFactory>
|
||||
{
|
||||
private const string Status = "/api/v1/Availability/status";
|
||||
|
||||
private static async Task<JsonElement> Read(HttpResponseMessage response)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
return doc.RootElement.Clone();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheWholeStory_PutMaintenance_VisitorsAreBlocked_PutAvailableAgain()
|
||||
{
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
var visitor = factory.CreateClient();
|
||||
|
||||
// Anonymous change: meets authentication while the CMS is available.
|
||||
(await visitor.PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"x"}""")))
|
||||
.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
// A regular user is refused.
|
||||
(await Jwt.ClientWithRole(factory, "User").PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"x"}""")))
|
||||
.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
|
||||
// The administrator changes it; the answer is the updated resource, same shape as the GET.
|
||||
var put = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"Gepland onderhoud"}"""));
|
||||
put.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
var body = await Read(put);
|
||||
body.GetProperty("status").GetString().Should().Be("Maintenance");
|
||||
body.GetProperty("message").GetString().Should().Be("Gepland onderhoud");
|
||||
body.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["status", "checkedAt", "message", "isMasterControlled"]);
|
||||
|
||||
// Reading stays open for everyone and shows the new state.
|
||||
var read = await visitor.GetAsync(Status);
|
||||
read.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await Read(read)).GetProperty("status").GetString().Should().Be("Maintenance");
|
||||
|
||||
// Visitors meet the gate on a CMS route, and ALSO on the PUT itself (it is not exempted).
|
||||
(await visitor.GetAsync("/api/v1/offerings/categories")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
|
||||
(await visitor.PutAsync(Status, Jwt.Json("""{"newStatus":"Available","reason":null}"""))).StatusCode
|
||||
.Should().Be(HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
// The administrator can always switch it back on.
|
||||
var back = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Available","reason":null}"""));
|
||||
back.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await Read(back)).GetProperty("status").GetString().Should().Be("Available");
|
||||
(await visitor.GetAsync("/api/v1/offerings/categories")).StatusCode.Should().NotBe(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOldAdminRoute_IsGone()
|
||||
{
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
|
||||
// The host answers a path that no controller owns with the site's fallback page, so the proof is
|
||||
// behavioural: the old route behaves exactly like a route that never existed, and it changes nothing.
|
||||
var old = await admin.PostAsync("/api/v1/Availability/admin/status", Jwt.Json("""{"newStatus":"Maintenance","reason":"old route"}"""));
|
||||
var neverExisted = await admin.PostAsync("/api/v1/Availability/no-such-route", Jwt.Json("""{"newStatus":"Maintenance","reason":"old route"}"""));
|
||||
|
||||
old.StatusCode.Should().Be(neverExisted.StatusCode);
|
||||
old.Content.Headers.ContentType?.MediaType.Should().Be(neverExisted.Content.Headers.ContentType?.MediaType);
|
||||
old.Content.Headers.ContentType?.MediaType.Should().NotBe("application/json");
|
||||
(await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("status").GetString().Should().Be("Available");
|
||||
(await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("message").GetString().Should().NotContain("old route");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnInvalidStatus_IsRejected_AndTheStateDoesNotChange()
|
||||
{
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
|
||||
var response = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Exploded","reason":null}"""));
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
(await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("status").GetString().Should().Be("Available");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user