From 701091f179e52d8a6eb60b8c624bf1ca5a26d9bf Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 01:35:11 +0100 Subject: [PATCH] Beschikbaarheidspoort blokkeert alleen de API, niet de website en de admin Een uitgeschakeld CMS gaf een kale 503 op de publieke website en op /admin, omdat de poort elk pad stopte dat niet op de bypass-lijst stond. Sinds de host website en admin zelf serveert, viel dat verkeer eronder en kon de admin-app de status niet lezen om de uitgeschakeld-kaart te tonen. Nu worden alleen paden onder /api/ beoordeeld; alle andere paden gaan door. Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/active-features.md | 1 + .../bug-fix.md | 43 ++++ .../AvailabilityGateScopeTests.cs | 224 ++++++++++++++++++ .../AvailabilityMiddlewareMasterGateTests.cs | 20 +- .../AvailabilityMiddlewareTests.cs | 28 +-- .../TestContexts.cs | 14 ++ .../Middleware/AvailabilityMiddleware.cs | 14 ++ 7 files changed, 320 insertions(+), 24 deletions(-) create mode 100644 aidlc-docs/bugs/availability-gate-blocks-website-and-admin/bug-fix.md create mode 100644 src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs create mode 100644 src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index e4f5881..914b1e6 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -14,3 +14,4 @@ | Bug | [invitation-delete-and-lifetime](bugs/invitation-delete-and-lifetime/bug-fix.md) | ✅ Complete (wacht op goedkeuring ASF test) | feature/andreaslop-site-hosting | Core (invitations), Identity, Frontend | 2026-11-08 | | Feature | Identity e-mail notifications (identity-email-notifications) | 🔵 Inception (wacht op antwoorden) | feature/identity-email-notifications | Core (IEmailSender), Identity, Frontend | 2026-11-08 | | Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (wacht op ASF test deploy) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 | +| Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (wacht op deploy) | feature/identity-email-notifications | Availability (middleware) | 2026-11-09 | diff --git a/aidlc-docs/bugs/availability-gate-blocks-website-and-admin/bug-fix.md b/aidlc-docs/bugs/availability-gate-blocks-website-and-admin/bug-fix.md new file mode 100644 index 0000000..888a1ea --- /dev/null +++ b/aidlc-docs/bugs/availability-gate-blocks-website-and-admin/bug-fix.md @@ -0,0 +1,43 @@ +# Bug Fix: a disabled CMS answers a bare 503 on the website and on /admin + +- **Slug**: availability-gate-blocks-website-and-admin +- **Status**: Complete (pending deploy) +- **Issue**: None (reported by Bryan via "CMS & API", 2026-11-09) +- **Branch**: feature/identity-email-notifications +- **Started**: 2026-11-09 +- **Documentation Language**: English +- **Conversation Language**: Dutch (user language) + +## Report + +**Reproduction**: on ASF test, the master switches the CMS to "not available". Then `test.andreaslop.nl` (the public website) and `/admin` answer a bare 503 (JSON / browser error page). + +**Expected** (Bryan): the public website keeps working; `/admin` loads and shows the dashboard with the "CMS disabled" card, as on SlpSoftware. **Actual**: 503 for everything that is not on the gate's bypass list. + +**Environment**: ASF test (website in PrerenderedPages mode, admin files served by the host itself). + +## Root Cause + +`AvailabilityMiddleware` applied the gate to EVERY path except a short bypass list (`/api/v1/Availability/status`, `/api/v1/Auth/`, `/api/v1/Setup/status`, `/api/v1/master/`, `/api/v1/SlaveStatus`, `/health`). It runs before the static content and the website, so once the host served the website pages and the admin files itself (PrerenderedPages mode), those requests were stopped as well, and the SPA never loaded to read the open status endpoint. On SlpSoftware nginx serves the SPA and only `/api` reaches the host, so only API calls were blocked and the SPA could show its card: the flaw was hidden, not absent. (The same holds on any host that serves `/admin` itself.) + +**Confirmed with user**: relayed by "CMS & API" (Bryan decided: website keeps working, `/admin` loads). + +## The Fix + +`AvailabilityMiddleware` gates only paths under `/api/` (the prefix every controller gets). Everything else (the website, `/admin` files and SPA fallback, the 404 page, `/health`, `/sentry-tunnel`) passes straight through, and a request outside the API is no longer even checked for a bearer token (so the `admin_bypass_rejected ... Expired` noise for asset requests disappears too). The bypass list under `/api/` is unchanged (status, auth, setup status, master, slave status), and an admin with a valid token still passes the gate for the rest of the API. + +Behaviour change for other hosts: on hosts that serve only the API behind nginx nothing changes (their non-API paths never reach the host); on hosts that serve `/admin` or the website themselves the website and admin now stay reachable while the CMS is disabled. `/sentry-tunnel` also stays reachable (it was blocked before). + +## Verification + +**Path used**: Automated test framework (`AvailabilityGateScopeTests`, `AvailabilityGateOnTheRealPipelineTests`, existing middleware tests adapted to API paths). + +**Before the fix**: with the old gate 16 of the new tests fail (website, admin files, `/robots.txt`, `/sentry-tunnel`, 404 page, master gate all answered 503). + +**After the fix**: Availability.Tests 109 pass. Real pipeline (prerendered website + admin files + stand-in API + the real gate), CMS not available or in maintenance: `/`, `/over-mij`, `/admin/`, `/admin/index.html`, `/admin/assets/...`, an `/admin/...` client route, `/health` all 200, an unknown path the website 404 page, `/api/v1/Availability/status` 200 (the admin app reads it), `/api/v1/Users` 503; with the CMS available `/api/v1/Users` is 200; master switching the CMS off behaves the same. Unit level: every non-API path passes through for local not-available, maintenance and the master gate; `/api/v1/Users`, `/api/v1/Offerings/...`, `/api/v1/System/capabilities` (also `/API/V1/...`) stay 503; the open API endpoints stay open; no token validation outside the API. + +## Result + +- **PR(s)**: None +- **Commit(s)**: see branch history +- **Completed**: 2026-11-09 diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs new file mode 100644 index 0000000..75fb60a --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs @@ -0,0 +1,224 @@ +using System.Net; +using FluentAssertions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Security; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Availability.Middleware; +using SlpModularCms.Modules.Availability.Services; + +namespace SlpModularCms.Modules.Availability.Tests; + +/// +/// The availability gate protects the API, nothing else. A disabled CMS must still serve its public website and +/// let the admin app load (so the app can read the open status endpoint and show its "CMS disabled" card): +/// a bare 503 on those is the defect this guards. Unit tests of the middleware first, then the real thing on an +/// in-memory server with the prerendered website and the admin files. +/// +public class AvailabilityGateScopeTests +{ + private static async Task<(int Status, bool Passed)> RunAsync( + string path, AvailabilityStatus local = AvailabilityStatus.NotAvailable, bool masterAvailable = true) + { + var next = Substitute.For(); + var localSvc = Substitute.For(); + localSvc.IsAvailableAsync().Returns(local); + var masterSvc = Substitute.For(); + masterSvc.GetMasterStatus().Returns(new MasterGateStatus(masterAvailable, masterAvailable ? null : "Down")); + var validator = Substitute.For(); + var middleware = new AvailabilityMiddleware(next, NullLogger.Instance, validator); + var context = new DefaultHttpContext(); + context.Request.Path = path; + context.Response.Body = new MemoryStream(); + + await middleware.InvokeAsync(context, localSvc, masterSvc); + + return (context.Response.StatusCode, next.ReceivedCalls().Any()); + } + + [Theory] + [InlineData("/")] + [InlineData("/over-mij")] + [InlineData("/blog/een-bericht")] + [InlineData("/robots.txt")] + [InlineData("/favicon.png")] + [InlineData("/admin")] + [InlineData("/admin/")] + [InlineData("/admin/index.html")] + [InlineData("/admin/assets/index-abc123.js")] + [InlineData("/admin/users")] + [InlineData("/sentry-tunnel")] + [InlineData("/health")] + [InlineData("/does-not-exist")] + public async Task EverythingOutsideTheApi_PassesThroughAdisabledCms_LocalOrMaster(string path) + { + foreach (var status in new[] { AvailabilityStatus.NotAvailable, AvailabilityStatus.Maintenance }) + { + var (code, passed) = await RunAsync(path, status); + passed.Should().BeTrue($"{path} is not an API call ({status})"); + code.Should().NotBe(StatusCodes.Status503ServiceUnavailable); + } + + var (masterCode, masterPassed) = await RunAsync(path, AvailabilityStatus.Available, masterAvailable: false); + masterPassed.Should().BeTrue($"{path} is not an API call (master gate)"); + masterCode.Should().NotBe(StatusCodes.Status503ServiceUnavailable); + } + + [Theory] + [InlineData("/api/v1/Users")] + [InlineData("/api/v1/Offerings/abc")] + [InlineData("/api/v1/System/capabilities")] + [InlineData("/API/V1/users")] + public async Task ApiCalls_AreStillBlocked_WhenTheCmsIsDisabled(string path) + { + var (localCode, localPassed) = await RunAsync(path, AvailabilityStatus.NotAvailable); + localPassed.Should().BeFalse(); + localCode.Should().Be(StatusCodes.Status503ServiceUnavailable); + + var (maintenanceCode, _) = await RunAsync(path, AvailabilityStatus.Maintenance); + maintenanceCode.Should().Be(StatusCodes.Status503ServiceUnavailable); + + var (masterCode, masterPassed) = await RunAsync(path, AvailabilityStatus.Available, masterAvailable: false); + masterPassed.Should().BeFalse(); + masterCode.Should().Be(StatusCodes.Status503ServiceUnavailable); + } + + [Theory] + [InlineData("/api/v1/Availability/status")] + [InlineData("/api/v1/Auth/login")] + [InlineData("/api/v1/Setup/status")] + [InlineData("/api/v1/master/status")] + [InlineData("/api/v1/SlaveStatus")] + public async Task TheOpenApiEndpoints_StayOpen(string path) + { + var (_, passed) = await RunAsync(path, AvailabilityStatus.NotAvailable); + + passed.Should().BeTrue(); + } + + [Fact] + public async Task ARequestOutsideTheApi_IsNotEvenCheckedForABearerToken() + { + // Static files and website pages are requested constantly; looking at their (often expired) token would only + // produce noise in the security log. + var validator = Substitute.For(); + var middleware = new AvailabilityMiddleware(Substitute.For(), NullLogger.Instance, validator); + var context = new DefaultHttpContext(); + context.Request.Path = "/admin/assets/index-abc123.js"; + context.Request.Headers.Authorization = "Bearer an-expired-token"; + + await middleware.InvokeAsync(context, Substitute.For(), Substitute.For()); + + validator.DidNotReceiveWithAnyArgs().Validate(default); + } +} + +/// The same on a real pipeline: prerendered website, admin files, a stand-in API and the real gate. +public sealed class AvailabilityGateOnTheRealPipelineTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "slp-gate-" + Guid.NewGuid().ToString("N")); + private readonly List _apps = []; + + public void Dispose() + { + foreach (var app in _apps) app.DisposeAsync().AsTask().GetAwaiter().GetResult(); + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + + private void Write(string area, string relative, string content) + { + var path = Path.Combine(_root, "wwwroot", area, relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } + + private async Task StartAsync(AvailabilityStatus local, bool masterAvailable = true) + { + Write("web", "index.html", "Home"); + Write("web", "404.html", "Niet gevonden"); + Write("web", "over-mij.html", "Over mij"); + Write("admin", "index.html", "Admin"); + Write("admin", "assets/index-abc123.js", "console.log(1)"); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions + { + EnvironmentName = Environments.Production, + ContentRootPath = _root, + WebRootPath = Path.Combine(_root, "wwwroot") + }); + builder.WebHost.UseTestServer(); + builder.Logging.ClearProviders(); + builder.Configuration.AddInMemoryCollection(new Dictionary + { + ["SecurityHeaders:DefaultPolicy"] = "StrictSite", + ["Website:NoIndex"] = "false" + }); + builder.Services.AddCmsSecurityHeaders(builder.Configuration); + builder.Services.AddCmsWebsite(builder.Configuration); + + var localSvc = Substitute.For(); + localSvc.IsAvailableAsync().Returns(local); + var masterSvc = Substitute.For(); + masterSvc.GetMasterStatus().Returns(new MasterGateStatus(masterAvailable, masterAvailable ? null : "Down")); + var validator = Substitute.For(); + builder.Services.AddSingleton(localSvc); + builder.Services.AddSingleton(masterSvc); + builder.Services.AddSingleton(validator); + + var app = builder.Build(); + app.UseCmsSecurityHeaders(); + app.UseMiddleware(); // as the Availability module does, before the website + app.UseCmsStaticContent(WebsiteMode.PrerenderedPages); + app.UseCmsPrerenderedSite(); + app.MapGet("/api/v1/Users", () => Results.Text("users")); + app.MapGet("/api/v1/Availability/status", () => Results.Json(new { status = local.ToString() })); + app.MapGet("/health", () => Results.Text("ok")); + app.MapCmsSpaFallbacks(WebsiteMode.PrerenderedPages); + app.MapCmsWebsiteNotFound(); + _apps.Add(app); + await app.StartAsync(); + return app.GetTestClient(); + } + + [Theory] + [InlineData(AvailabilityStatus.NotAvailable, true)] + [InlineData(AvailabilityStatus.Maintenance, true)] + [InlineData(AvailabilityStatus.Available, false)] + public async Task ADisabledCms_StillServesWebsiteAndAdmin_ButNotTheApi(AvailabilityStatus status, bool blocked) + { + var client = await StartAsync(status); + + (await client.GetAsync("/")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/over-mij")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/admin/")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/admin/index.html")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/admin/assets/index-abc123.js")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/admin/some/client/route")).StatusCode.Should().Be(HttpStatusCode.OK); // SPA fallback + (await client.GetAsync("/health")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/available/status-open")).StatusCode.Should().Be(HttpStatusCode.NotFound); // the website 404 page, not a 503 + (await client.GetAsync("/api/v1/Availability/status")).StatusCode.Should().Be(HttpStatusCode.OK); // the admin app reads this + (await client.GetAsync("/api/v1/Users")).StatusCode.Should().Be(blocked ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK); + } + + [Fact] + public async Task WhenTheMasterSwitchesTheCmsOff_ItIsTheSame() + { + var client = await StartAsync(AvailabilityStatus.Available, masterAvailable: false); + + (await client.GetAsync("/")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/admin/")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/health")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/Availability/status")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/Users")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + } +} diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareMasterGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareMasterGateTests.cs index fd97599..c950806 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareMasterGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareMasterGateTests.cs @@ -1,4 +1,4 @@ -using FluentAssertions; +using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; @@ -36,7 +36,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_Passes_WhenMasterAndLocalBothAvailable() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); await _middleware.InvokeAsync(context, _localSvc, _masterSvc); @@ -46,7 +46,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_Returns503_WhenMasterGateBlocks() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, "Down for maintenance")); @@ -59,7 +59,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_DoesNotCheckLocalGate_WhenMasterGateBlocks() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null)); @@ -71,7 +71,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_Returns503_WhenLocalGateBlocksAndMasterPasses() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -84,7 +84,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_BypassesMasterAndLocalGate_ForMasterEndpoints() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/api/v1/master/register"; _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null)); _localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -98,7 +98,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_BypassesBothGates_ForMasterStatusEndpoint() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/api/v1/master/status"; _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null)); @@ -110,7 +110,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_BypassesBothGates_WhenAdminJwtPresent() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Headers.Authorization = "Bearer owner-token"; _adminTokenValidator.Validate("Bearer owner-token").Returns(new AdminTokenResult(true, default)); _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null)); @@ -125,7 +125,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_DoesNotBypass_WhenNonAdminJwtAndMasterBlocks() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); context.Request.Headers.Authorization = "Bearer user-token"; _adminTokenValidator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); @@ -140,7 +140,7 @@ public class AvailabilityMiddlewareMasterGateTests [Fact] public async Task InvokeAsync_BypassesBothGates_ForHealthEndpoint() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/health"; _masterSvc.GetMasterStatus().Returns(new MasterGateStatus(false, null)); _localSvc.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareTests.cs index 65d882b..00c042b 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityMiddlewareTests.cs @@ -1,4 +1,4 @@ -using System.IdentityModel.Tokens.Jwt; +using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using FluentAssertions; @@ -43,7 +43,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowRequest_WhenSystemAvailable() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); _service.IsAvailableAsync().Returns(AvailabilityStatus.Available); await _middleware.InvokeAsync(context, _service, _masterService); @@ -54,7 +54,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldBlockRequest_WhenSystemUnavailable() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -67,7 +67,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowBypass_ForStatusEndpoint() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/api/v1/Availability/status"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -79,7 +79,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowBypass_ForAuthEndpoints() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/api/v1/Auth/login"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -91,7 +91,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowBypass_ForSetupStatusEndpoint() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/api/v1/Setup/status"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -107,7 +107,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowBypass_ForHealthEndpoint_WhenSystemUnavailable() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/health"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -119,7 +119,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowBypass_ForHealthEndpoint_WhenMasterGateClosed() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Path = "/health"; _masterService.GetMasterStatus().Returns(new MasterGateStatus(false, "Disabled by master")); @@ -131,7 +131,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldBlockRequest_WhenSystemInMaintenance() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance); @@ -144,7 +144,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldAllowAdminBypass_WhenValidatorAcceptsTheToken() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Headers.Authorization = "Bearer some-token"; _adminTokenValidator.Validate("Bearer some-token").Returns(new AdminTokenResult(true, default)); _service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance); @@ -157,7 +157,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldNotBypass_WhenValidatorRejectsTheToken() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); context.Request.Headers.Authorization = "Bearer some-token"; _adminTokenValidator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); @@ -172,7 +172,7 @@ public class AvailabilityMiddlewareTests [Fact] public async Task InvokeAsync_ShouldNotBypass_WhenNoAuthorizationHeader() { - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); _adminTokenValidator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -225,7 +225,7 @@ public class AvailabilityMiddlewareTests claims: [new Claim(ClaimTypes.Role, "Owner")], expires: DateTime.UtcNow.AddHours(1))); - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Response.Body = new MemoryStream(); context.Request.Headers.Authorization = $"Bearer {forged}"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); @@ -249,7 +249,7 @@ public class AvailabilityMiddlewareTests expires: DateTime.UtcNow.AddHours(1), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256))); - var context = new DefaultHttpContext(); + var context = TestContexts.Api(); context.Request.Headers.Authorization = $"Bearer {genuine}"; _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); diff --git a/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs new file mode 100644 index 0000000..5179246 --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs @@ -0,0 +1,14 @@ +using Microsoft.AspNetCore.Http; + +namespace SlpModularCms.Modules.Availability.Tests; + +internal static class TestContexts +{ + /// A request to an API endpoint that is not on the gate's bypass list: the kind the gate decides about. + public static DefaultHttpContext Api(string path = "/api/v1/Items") + { + var context = new DefaultHttpContext(); + context.Request.Path = path; + return context; + } +} diff --git a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs index 7f935bd..b3ec00d 100644 --- a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs +++ b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs @@ -33,6 +33,13 @@ public class AvailabilityMiddleware // /health bypasses because it reports infrastructure liveness, which is a different // question from whether the CMS is switched on: an instance that is deliberately // disabled is still perfectly healthy, and must not be reported as down. + // Only the API is gated. The public website, the admin files (the SPA with its index.html and assets), the + // 404 page, /sentry-tunnel and /health are not CMS data or actions: a disabled CMS must still show its + // website and let the admin app load, so that the app can read /api/v1/Availability/status (open, see below) + // and show the "CMS disabled" card instead of a bare 503. Before this the gate stopped EVERY path that was not + // on the bypass list, which only went unnoticed while another server (nginx) served the website and the SPA. + private const string GatedPrefix = "/api/"; + private static readonly string[] _bypassPrefixes = [ "/api/v1/Availability/status", @@ -49,6 +56,13 @@ public class AvailabilityMiddleware IMasterAvailabilityService masterAvailabilityService) { var path = context.Request.Path.Value ?? string.Empty; + if (!path.StartsWith(GatedPrefix, StringComparison.OrdinalIgnoreCase)) + { + // Not an API call: nothing to protect, and no reason to look at (or log about) a bearer token either. + await _next(context); + return; + } + if (_bypassPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))) { await _next(context);