Separates website and admin roots, adds /health, hardens the availability gate
Prepares the single-host layout for deployment. The customer's public website moves from wwwroot/ to wwwroot/web/, so a CMS deploy can no longer overwrite content it does not own: with the website in its own directory, the release directory can be swapped without touching it. Each front-end gets its own file provider, and both tolerate a missing directory at startup — a fresh deployment has no website until a separate workspace deploys one, and the CMS must still serve /admin and the API. When the website's index.html is absent, an embedded placeholder is served instead of a 404, which also doubles as proof the CMS itself is running. The placeholder is embedded in the assembly rather than shipped into wwwroot/web/, because that directory is owned and overwritten by the website workspace. Adds GET /health for uptime monitoring. It reports infrastructure liveness only and is deliberately NOT the same thing as /api/v1/Availability/status or /api/v1/System/capabilities: those are CMS domain state that also serve the master/slave protocol. A healthy instance can be switched off by design, and a switched-on instance can be unhealthy, so conflating them would alert on business state and stay silent on real outages. /health is on the availability gate's bypass list for the same reason. Fixes a real defect in the gate's admin bypass. It parsed the bearer token with ReadJwtToken, which reads claims without verifying the signature, so an unauthenticated caller could forge an unsigned token carrying an Owner role claim and bypass the gate that suspends a customer's site. Protected endpoints still rejected them, so nothing leaked — but the gate itself was bypassable. The token is now fully validated against the same parameters as the bearer scheme, resolved from one shared source so the two cannot drift apart. Host wiring for these changes lands with the data-durability commit, since both units touch the same lines of Program.cs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHoJpxYXzHACSQguHrC5fw
This commit is contained in:
+23
-16
@@ -1,12 +1,9 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Modules.Availability.Middleware;
|
||||
using SlpModularCms.Modules.Availability.Services;
|
||||
|
||||
@@ -16,6 +13,7 @@ public class AvailabilityMiddlewareMasterGateTests
|
||||
{
|
||||
private readonly IAvailabilityService _localSvc;
|
||||
private readonly IMasterAvailabilityService _masterSvc;
|
||||
private readonly IAdminTokenValidator _adminTokenValidator;
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
@@ -23,8 +21,12 @@ public class AvailabilityMiddlewareMasterGateTests
|
||||
{
|
||||
_localSvc = Substitute.For<IAvailabilityService>();
|
||||
_masterSvc = Substitute.For<IMasterAvailabilityService>();
|
||||
_adminTokenValidator = Substitute.For<IAdminTokenValidator>();
|
||||
_next = Substitute.For<RequestDelegate>();
|
||||
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance);
|
||||
_middleware = new AvailabilityMiddleware(
|
||||
_next,
|
||||
NullLogger<AvailabilityMiddleware>.Instance,
|
||||
_adminTokenValidator);
|
||||
|
||||
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.Available);
|
||||
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
@@ -108,7 +110,8 @@ public class AvailabilityMiddlewareMasterGateTests
|
||||
public async Task InvokeAsync_BypassesBothGates_WhenAdminJwtPresent()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Owner")}";
|
||||
context.Request.Headers.Authorization = "Bearer owner-token";
|
||||
_adminTokenValidator.IsVerifiedAdmin("Bearer owner-token").Returns(true);
|
||||
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
|
||||
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
@@ -119,11 +122,12 @@ public class AvailabilityMiddlewareMasterGateTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_DoesNotBypass_WhenUserRoleJwtAndMasterBlocks()
|
||||
public async Task InvokeAsync_DoesNotBypass_WhenNonAdminJwtAndMasterBlocks()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Response.Body = new MemoryStream();
|
||||
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("User")}";
|
||||
context.Request.Headers.Authorization = "Bearer user-token";
|
||||
_adminTokenValidator.IsVerifiedAdmin(Arg.Any<string>()).Returns(false);
|
||||
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
|
||||
|
||||
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
|
||||
@@ -132,14 +136,17 @@ public class AvailabilityMiddlewareMasterGateTests
|
||||
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
private static string CreateJwtWithRole(string role)
|
||||
[Fact]
|
||||
public async Task InvokeAsync_BypassesBothGates_ForHealthEndpoint()
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test-signing-key-at-least-32-chars-long!"));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var token = new JwtSecurityToken(
|
||||
claims: [new Claim(ClaimTypes.Role, role)],
|
||||
expires: DateTime.UtcNow.AddHours(1),
|
||||
signingCredentials: creds);
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/health";
|
||||
_masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null));
|
||||
_localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
await _middleware.InvokeAsync(context, _localSvc, _masterSvc);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
_masterSvc.DidNotReceive().GetMasterStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Modules.Availability.Middleware;
|
||||
using SlpModularCms.Modules.Availability.Services;
|
||||
using Xunit;
|
||||
@@ -17,6 +20,7 @@ public class AvailabilityMiddlewareTests
|
||||
{
|
||||
private readonly IAvailabilityService _service;
|
||||
private readonly IMasterAvailabilityService _masterService;
|
||||
private readonly IAdminTokenValidator _adminTokenValidator;
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
@@ -24,8 +28,12 @@ public class AvailabilityMiddlewareTests
|
||||
{
|
||||
_service = Substitute.For<IAvailabilityService>();
|
||||
_masterService = Substitute.For<IMasterAvailabilityService>();
|
||||
_adminTokenValidator = Substitute.For<IAdminTokenValidator>();
|
||||
_next = Substitute.For<RequestDelegate>();
|
||||
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance);
|
||||
_middleware = new AvailabilityMiddleware(
|
||||
_next,
|
||||
NullLogger<AvailabilityMiddleware>.Instance,
|
||||
_adminTokenValidator);
|
||||
|
||||
// Master gate passes by default in these local gate tests
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
@@ -91,6 +99,34 @@ public class AvailabilityMiddlewareTests
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Infrastructure liveness must survive the CMS being switched off. A deliberately disabled
|
||||
/// instance is still perfectly healthy, and monitoring must not report it as down.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldAllowBypass_ForHealthEndpoint_WhenSystemUnavailable()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/health";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldAllowBypass_ForHealthEndpoint_WhenMasterGateClosed()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = "/health";
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(false, "Disabled by master"));
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldBlockRequest_WhenSystemInMaintenance()
|
||||
{
|
||||
@@ -105,10 +141,11 @@ public class AvailabilityMiddlewareTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldAllowAdminBypass_WhenOwnerToken()
|
||||
public async Task InvokeAsync_ShouldAllowAdminBypass_WhenValidatorAcceptsTheToken()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Owner")}";
|
||||
context.Request.Headers.Authorization = "Bearer some-token";
|
||||
_adminTokenValidator.IsVerifiedAdmin("Bearer some-token").Returns(true);
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
@@ -117,23 +154,12 @@ public class AvailabilityMiddlewareTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldAllowAdminBypass_WhenAdministratorToken()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("Administrator")}";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldNotBypass_WhenUserRoleToken()
|
||||
public async Task InvokeAsync_ShouldNotBypass_WhenValidatorRejectsTheToken()
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Response.Body = new MemoryStream();
|
||||
context.Request.Headers.Authorization = $"Bearer {CreateJwtWithRole("User")}";
|
||||
context.Request.Headers.Authorization = "Bearer some-token";
|
||||
_adminTokenValidator.IsVerifiedAdmin(Arg.Any<string>()).Returns(false);
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
@@ -147,6 +173,7 @@ public class AvailabilityMiddlewareTests
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Response.Body = new MemoryStream();
|
||||
_adminTokenValidator.IsVerifiedAdmin(Arg.Any<string>()).Returns(false);
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
@@ -154,28 +181,80 @@ public class AvailabilityMiddlewareTests
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldNotBypass_WhenInvalidJwtToken()
|
||||
/// <summary>
|
||||
/// Wires the middleware to the real validator instead of a substitute, so the two are proven
|
||||
/// to fit together. A substitute alone would keep passing even if the middleware were wired
|
||||
/// back to unvalidated token parsing.
|
||||
/// </summary>
|
||||
public class WithRealValidator
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Response.Body = new MemoryStream();
|
||||
context.Request.Headers.Authorization = "Bearer not-a-valid-jwt";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
private const string Secret = "TestSecretKeyThatIsLongEnoughForHmacSha256Signing!!";
|
||||
private const string Issuer = "SlpModularCms";
|
||||
private const string Audience = "SlpModularCmsPortal";
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
private readonly IAvailabilityService _service = Substitute.For<IAvailabilityService>();
|
||||
private readonly IMasterAvailabilityService _masterService = Substitute.For<IMasterAvailabilityService>();
|
||||
private readonly RequestDelegate _next = Substitute.For<RequestDelegate>();
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
public WithRealValidator()
|
||||
{
|
||||
var parameters = JwtTokenValidation.Create(new JwtSettings
|
||||
{
|
||||
Secret = Secret,
|
||||
Issuer = Issuer,
|
||||
Audience = Audience
|
||||
});
|
||||
|
||||
private static string CreateJwtWithRole(string role)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("test-signing-key-at-least-32-chars-long!"));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var token = new JwtSecurityToken(
|
||||
claims: [new Claim(ClaimTypes.Role, role)],
|
||||
expires: DateTime.UtcNow.AddHours(1),
|
||||
signingCredentials: creds
|
||||
);
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
_middleware = new AvailabilityMiddleware(
|
||||
_next,
|
||||
NullLogger<AvailabilityMiddleware>.Instance,
|
||||
new AdminTokenValidator(parameters));
|
||||
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldNotBypass_ForForgedUnsignedOwnerToken()
|
||||
{
|
||||
// The defect this unit fixes: an unsigned token carrying an Owner claim used to pass.
|
||||
var forged = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: Issuer,
|
||||
audience: Audience,
|
||||
claims: [new Claim(ClaimTypes.Role, "Owner")],
|
||||
expires: DateTime.UtcNow.AddHours(1)));
|
||||
|
||||
var context = new DefaultHttpContext();
|
||||
context.Response.Body = new MemoryStream();
|
||||
context.Request.Headers.Authorization = $"Bearer {forged}";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
context.Response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ShouldStillBypass_ForGenuineOwnerToken()
|
||||
{
|
||||
// Preserved behaviour: an administrator can always reach a disabled instance to
|
||||
// switch it back on.
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret));
|
||||
var genuine = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: Issuer,
|
||||
audience: Audience,
|
||||
claims: [new Claim(ClaimTypes.Role, "Owner")],
|
||||
expires: DateTime.UtcNow.AddHours(1),
|
||||
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)));
|
||||
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Headers.Authorization = $"Bearer {genuine}";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user