using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SlpModularCms.Core.Availability; using SlpModularCms.Core.Hosting.Security; using SlpModularCms.Core.Observability; using SlpModularCms.Modules.Availability.Services; namespace SlpModularCms.Modules.Availability.Middleware; public class AvailabilityMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly IAdminTokenValidator _adminTokenValidator; public AvailabilityMiddleware( RequestDelegate next, ILogger logger, IAdminTokenValidator adminTokenValidator) { _next = next; _logger = logger; _adminTokenValidator = adminTokenValidator; } // Paths that are always accessible regardless of system availability. // Auth and Setup must stay open so admins can log in and the frontend // can determine whether the system is initialized. // Master endpoints bypass so master can always push status or re-register. // SlaveStatus bypasses so a slave can always pull the master's status, even if the // master instance is (for whatever reason) reporting itself as locally unavailable. // /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/"; // 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/Auth/", "/api/v1/Setup/status", "/api/v1/master/", "/api/v1/SlaveStatus", "/health", ]; public async Task InvokeAsync( HttpContext context, IAvailabilityService availabilityService, 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; } 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; } // Public site functionality (e.g. the offerings list the website shows) stays reachable // whatever the status: the statuses only stop the CMS. Deny-by-default: only an endpoint // that explicitly carries the marker passes here. if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) { await _next(context); return; } var admin = CheckAdmin(context); if (admin.IsVerifiedAdmin) { await _next(context); return; } var masterStatus = masterAvailabilityService.GetMasterStatus(); if (!masterStatus.IsAvailable) { _logger.LogWarning( "Request blocked by master gate. Path: {Path}, DisableMessage: {DisableMessage}", path, masterStatus.DisableMessage); if (await TryAnswerExpiredTokenAsync(context, admin)) return; context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await context.Response.WriteAsJsonAsync(new ProblemDetails { Status = StatusCodes.Status503ServiceUnavailable, Title = "Service Unavailable", Detail = masterStatus.DisableMessage ?? "De service is tijdelijk niet beschikbaar.", Instance = context.Request.Path }); return; } var status = await availabilityService.IsAvailableAsync(); if (status == AvailabilityStatus.Available) { await _next(context); return; } _logger.LogWarning("Request geblokkeerd vanwege systeemstatus: {Status}. Path: {Path}", status, context.Request.Path); if (await TryAnswerExpiredTokenAsync(context, admin)) return; context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await context.Response.WriteAsJsonAsync(new ProblemDetails { Status = StatusCodes.Status503ServiceUnavailable, Title = "Service Unavailable", Detail = status == AvailabilityStatus.Maintenance ? "Het systeem is momenteel in onderhoud. Probeer het later opnieuw." : "De service is tijdelijk niet beschikbaar.", Instance = context.Request.Path }); } /// /// Lets a verified Owner or Administrator through the gate, so administrators can always /// reach a disabled instance to switch it back on. /// /// /// The token is fully validated — signature, issuer, audience and lifetime — against the /// same parameters as the JWT bearer scheme. An earlier implementation read the claims /// without verifying the signature, which meant an unauthenticated caller could present a /// self-made token carrying an Owner role claim and bypass the gate. /// private AdminTokenResult CheckAdmin(HttpContext context) { var result = _adminTokenValidator.Validate(context.Request.Headers.Authorization.ToString()); // A rejected bypass only became a meaningful signal once the gate started verifying // signatures: before that, a forged token succeeded silently. An absent header is not // reported — every anonymous request to a disabled instance has one, so reporting it // would drown the cases that matter. if (!result.IsVerifiedAdmin && result.Reason != BypassRejectionReason.Absent) { SecurityEvents.AdminBypassRejected(_logger, context.Request.Path, result.Reason); } return result; } /// /// A token that has merely EXPIRED is answered with 401 instead of 503. The 503 left a signed-in Owner stuck on a /// disabled CMS: the app only refreshes its session on a 401, so it never got a fresh token and never got back /// through the gate as an admin. An expired token reveals nothing; a missing, forged or non-admin token still gets 503. /// private async Task TryAnswerExpiredTokenAsync(HttpContext context, AdminTokenResult admin) { if (admin.Reason != BypassRejectionReason.Expired) return false; context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsJsonAsync(new ProblemDetails { Status = StatusCodes.Status401Unauthorized, Title = "Unauthorized", Detail = "De sessie is verlopen. Ververs de sessie en probeer het opnieuw.", Instance = context.Request.Path }); return true; } }