From a58374abeba96fb1b6aea108aad1471377903e57 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:53:15 +0100 Subject: [PATCH] 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 --- .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u2-gate-and-limiter/code/summary.md | 18 ++ ...2-gate-and-limiter-code-generation-plan.md | 14 +- src/SlpModularCms.Api.Tests/PipelineTests.cs | 10 + .../Hosting/RateLimiterOnRejectedTests.cs | 152 +++++++++++ .../PublicSiteEndpointAttribute.cs | 15 ++ .../Hosting/ServiceCollectionExtensions.cs | 17 +- .../PublicSiteEndpointGateTests.cs | 241 ++++++++++++++++++ ...dularCms.Modules.Availability.Tests.csproj | 8 + .../Middleware/AvailabilityMiddleware.cs | 9 + .../Controllers/OfferingsPublicMarkerTests.cs | 32 +++ .../Controllers/OfferingsController.cs | 2 + 12 files changed, 510 insertions(+), 10 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md create mode 100644 src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs create mode 100644 src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs create mode 100644 src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index e7a7b23..674a488 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: contact-forms-module - **Project Type**: Brownfield - **Start Date**: 2026-11-09 -- **Current Stage**: CONSTRUCTION - CMS-U2 Code Generation Part 1 (plan awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U2 built and committed (awaiting review); next CMS-U3 plan - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md new file mode 100644 index 0000000..024ca54 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md @@ -0,0 +1,18 @@ +# CMS-U2 gate-and-limiter: code summary + +## What changed +- `Core/Availability/PublicSiteEndpointAttribute` (sealed, methods only). `AvailabilityMiddleware`: right after the prefix bypass, an endpoint whose metadata carries the marker is let through before the master/local gate (deny-by-default; prefix bypasses and the verified-admin bypass untouched). Marked now: `OfferingsController.GetOfferings` only. +- `AddCmsRateLimiting.OnRejected`: still logs the security event, now also sets `Retry-After` (whole seconds, rounded up, minimum 1, from the limiter lease; 60 when the lease reports none) and writes `application/problem+json` with only `type`, `title`, `status`. Policy numbers and bucket behaviour are unchanged. + +## RELEASE CONDITION (must be met before the contact routes go live) +On the base branch (master) the rate-limit policies are **global buckets**: there is no per-client partition key and no ForwardedHeaders handling (both exist only on the ASF branch `feature/identity-email-notifications`). Any per-IP policy added in CMS-U3 (ContactForm 5 per 10 minutes, ContactToken 20 per 10 minutes, ContactResend) would therefore be shared by all visitors: after five submissions the whole site would be blocked. **The contact routes must not be enabled on a public host before the per-client partitioning from the ASF branch is on the base branch (after the ASF merge and the rebase).** Also required on that host: `ForwardedHeaders:KnownProxies` (env). Recorded in contract § 4.5 and repeated in the CMS-U3 plan. + +## Verification (real output) +- Build: 0 errors. Tests: Core.Tests 205 passed (9 new in RateLimiterOnRejectedTests: Retry-After rounding, fallback 60, problem+json with exactly type/title/status, no leak of policy name/path/limiter terms, only `Retry-After` and `Content-Type` headers, security event logged once, 429 status), Availability.Tests 95 passed (13 new in PublicSiteEndpointGateTests: marked endpoint passes for CMS disabled / maintenance / master blocks; unmarked, and no endpoint, still 503; Availability/status open; route table: marker on exactly `OfferingsController.GetOfferings`, marked actions are anonymous and never `[Authorize]`, every other action of the Availability/Identity/Master/Offerings/System controllers answers 503 at a closed gate, and the only action that passes is `GetOfferings`), Offerings.Tests 86 passed (2 new marker tests), Identity.Tests 37, Master.Tests 57, Api.Tests 4 passed with a temporary MariaDB (the existing Sentry-tunnel limiter test now also asserts Retry-After, `application/problem+json` and the three-field body). +- Real pipeline smoke (SlpSoftware host against the temporary MariaDB, CMS state set via the AvailabilityState table): with the CMS **disabled** `GET /api/v1/offerings` 200, `GET /api/v1/offerings/categories` 503, `GET /api/v1/System/capabilities` 503, `GET /api/v1/Availability/status` 200, unauthenticated `PUT /api/v1/offerings/order` 503; in **maintenance** offerings 200 and capabilities 503. The host was stopped and the container removed afterwards. + +## Handoff +Public site endpoints stay reachable when the CMS is off or in maintenance; the frontend 503 fallback now only applies to admin calls. Extending the public set is deliberate: add the action to `AllowedPublicActions` in `PublicSiteEndpointGateTests` in the same change (CMS-U3 adds the contact token GET and POST). + +## Rebase notes (after the ASF merge) +Expected conflicts: `AvailabilityMiddleware.cs` (one block) and `AddCmsRateLimiting` (`OnRejected`). Re-run the Core, Availability and Offerings tests and the Api.Tests after the rebase. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md index 3ad4fc0..86b92ea 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md @@ -13,18 +13,18 @@ Phase 1, base: current branch (master `d9cc539` + CMS-U0/U1/U1b). Decisions: D6 3. **Marked now**: only `OfferingsController.GetOfferings`. (U3 adds the two contact routes.) ## Steps -- [ ] **Step 1 — Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`. -- [ ] **Step 2 — Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change. -- [ ] **Step 3 — OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON. -- [ ] **Step 4 — Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module). -- [ ] **Step 5 — Tests**: +- [x] **Step 1 — Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`. +- [x] **Step 2 — Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change. +- [x] **Step 3 — OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON. +- [x] **Step 4 — Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module). +- [x] **Step 5 — Tests**: - Core.Tests: `OnRejected` (resolved from `IOptions` after `AddCmsRateLimiting`, called with a fake lease): sets `Retry-After` rounded up from the lease value (e.g. 0.2 s -> 1, 61.5 s -> 62), falls back to 60 without lease metadata, writes `application/problem+json` with status 429, still logs the security event with policy name and path, status code is 429. - Api.Tests (existing real-pipeline test `Sentry_tunnel_rate_limiter_engages_after_the_configured_permit_limit`): additionally assert the `Retry-After` header and the problem+json content type on the 429 (needs the local database; run with the container). - Availability.Tests (middleware): marked endpoint passes while the system is disabled, in maintenance, and with the master gate closed; an unmarked endpoint with the same state still gets 503; a marked endpoint does not bypass anything else (a request without endpoint metadata is still blocked); `/api/v1/Availability/status` stays open. - Availability.Tests (route-table style, SLS request): reflection over the controllers of the referenced modules (Availability, Identity, Master, Offerings; test-only project references): (a) the set of actions carrying the marker is exactly `{ OfferingsController.GetOfferings }` (the test names the allowlist so CMS-U3 extends it deliberately); (b) for every other controller action the middleware, given an endpoint with that action's attributes and a closed gate, answers 503 — which covers all admin routes, and the marker is never on an `AdminOnly`/`[Authorize]` action. - Offerings.Tests: `GetOfferings` has the marker and `[AllowAnonymous]`; no other action of the controller has the marker. -- [ ] **Step 6 — Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output. -- [ ] **Step 7 — Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push. +- [x] **Step 6 — Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output. +- [x] **Step 7 — Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push. ## Explicitly NOT touched Policy numbers and partitioning (no `ClientPartitionKey` here; that is the ASF branch), ForwardedHeaders, host config, Email, Identity, Master, bypass-prefix list, other controllers' routes, `POST admin/status` (CMS-U7, phase 2). diff --git a/src/SlpModularCms.Api.Tests/PipelineTests.cs b/src/SlpModularCms.Api.Tests/PipelineTests.cs index 5b9e182..ddeb709 100644 --- a/src/SlpModularCms.Api.Tests/PipelineTests.cs +++ b/src/SlpModularCms.Api.Tests/PipelineTests.cs @@ -102,5 +102,15 @@ public class PipelineTests : IClassFixture // request instead, which would otherwise mask a rate limiter that silently stopped // engaging). last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + + // The rejection tells the client when to retry and carries a machine-readable body with + // only the standard fields (nothing about the limiter, the policy or the caller). + last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); + int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1); + last.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + var body = await last.Content.ReadAsStringAsync(); + using var json = System.Text.Json.JsonDocument.Parse(body); + json.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]); + json.RootElement.GetProperty("status").GetInt32().Should().Be(429); } } diff --git a/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs b/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs new file mode 100644 index 0000000..db6c6f0 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs @@ -0,0 +1,152 @@ +using System.Text.Json; +using System.Threading.RateLimiting; +using FluentAssertions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Observability; +using Xunit; + +namespace SlpModularCms.Core.Tests.Hosting; + +/// +/// The 429 response of every rate-limit policy: a retry hint and a machine-readable body, and +/// nothing about the limiter or the caller. +/// +public class RateLimiterOnRejectedTests +{ + private sealed class TestLease(TimeSpan? retryAfter) : RateLimitLease + { + public override bool IsAcquired => false; + public override IEnumerable MetadataNames => + retryAfter is null ? [] : [MetadataName.RetryAfter.Name]; + + public override bool TryGetMetadata(string metadataName, out object? metadata) + { + if (retryAfter is not null && metadataName == MetadataName.RetryAfter.Name) + { + metadata = retryAfter.Value; + return true; + } + + metadata = null; + return false; + } + } + + private sealed class CapturingLoggerProvider : ILoggerProvider + { + public List<(EventId EventId, string Message)> Entries { get; } = []; + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(Entries); + public void Dispose() { } + + private sealed class CapturingLogger(List<(EventId, string)> entries) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) => entries.Add((eventId, formatter(state, exception))); + } + } + + private static async Task<(HttpContext Context, string Body, CapturingLoggerProvider Logs)> RejectAsync( + TimeSpan? retryAfter, string policy = "login") + { + var logs = new CapturingLoggerProvider(); + var services = new ServiceCollection(); + services.AddLogging(b => b.AddProvider(logs)); + services.AddCmsRateLimiting(new ConfigurationBuilder().Build()); + var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().Value; + + var context = new DefaultHttpContext { RequestServices = provider }; + context.Request.Path = "/api/v1/Auth/login"; + context.Response.Body = new MemoryStream(); + context.SetEndpoint(new Endpoint( + _ => Task.CompletedTask, + new EndpointMetadataCollection(new EnableRateLimitingAttribute(policy)), + "test")); + + await options.OnRejected!( + new OnRejectedContext { HttpContext = context, Lease = new TestLease(retryAfter) }, + CancellationToken.None); + + context.Response.Body.Position = 0; + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + return (context, body, logs); + } + + [Fact] + public void RejectionStatusCode_Is429() + { + var provider = new ServiceCollection() + .AddLogging() + .AddCmsRateLimiting(new ConfigurationBuilder().Build()) + .BuildServiceProvider(); + + provider.GetRequiredService>().Value.RejectionStatusCode + .Should().Be(StatusCodes.Status429TooManyRequests); + } + + [Theory] + [InlineData(0.2, "1")] + [InlineData(1.0, "1")] + [InlineData(59.01, "60")] + [InlineData(61.5, "62")] + public async Task OnRejected_SetsRetryAfter_InWholeSecondsRoundedUp(double seconds, string expected) + { + var (context, _, _) = await RejectAsync(TimeSpan.FromSeconds(seconds)); + + context.Response.Headers.RetryAfter.ToString().Should().Be(expected); + } + + [Fact] + public async Task OnRejected_FallsBackTo60Seconds_WhenTheLeaseReportsNoWait() + { + var (context, _, _) = await RejectAsync(retryAfter: null); + + context.Response.Headers.RetryAfter.ToString().Should().Be("60"); + } + + [Fact] + public async Task OnRejected_WritesProblemJson_WithOnlyTypeTitleAndStatus() + { + var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30)); + + context.Response.ContentType.Should().StartWith("application/problem+json"); + using var json = JsonDocument.Parse(body); + json.RootElement.EnumerateObject().Select(p => p.Name) + .Should().BeEquivalentTo(["type", "title", "status"]); + json.RootElement.GetProperty("status").GetInt32().Should().Be(429); + json.RootElement.GetProperty("title").GetString().Should().Be("Too many requests"); + } + + [Fact] + public async Task OnRejected_DoesNotLeakThePolicyPathOrTheLimiterInTheResponse() + { + var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "super-secret-policy"); + + body.Should().NotContain("super-secret-policy"); + body.Should().NotContain("/api/v1/Auth/login"); + body.ToLowerInvariant().Should().NotContain("permit").And.NotContain("window").And.NotContain("lease"); + context.Response.Headers.Keys.Should().BeEquivalentTo(["Retry-After", "Content-Type"]); + } + + [Fact] + public async Task OnRejected_StillLogsTheRateLimitSecurityEvent_ExactlyOnce() + { + // The message template is deliberately constant (see SecurityEventsTests); the policy and + // path travel as structured properties, so only the event id is asserted here. + var (_, _, logs) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "login"); + + logs.Entries.Count(e => e.EventId.Id == SecurityEvents.RateLimitTriggeredEventId).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs new file mode 100644 index 0000000..b63669a --- /dev/null +++ b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs @@ -0,0 +1,15 @@ +namespace SlpModularCms.Core.Availability; + +/// +/// Marks an endpoint as public site functionality that stays reachable while the CMS is +/// switched off, in maintenance or blocked by the master. +/// +/// +/// The availability statuses exist to stop the CMS (changing data and settings through the +/// admin). Visitors of the public website must keep working, so the few endpoints the website +/// itself calls carry this marker. The gate is deny-by-default: an endpoint without the marker +/// is blocked, and the marker must never be placed on an endpoint that requires authorization. +/// It is read from the endpoint metadata by AvailabilityMiddleware. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class PublicSiteEndpointAttribute : Attribute; diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index ee4b76b..6f82dc7 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -171,7 +171,7 @@ public static class ServiceCollectionExtensions // Without this callback a brute-force attempt against /api/v1/Auth/login returns 429 // and leaves NO trace anywhere — the one rate limiter this application has would be // entirely unobservable, and the alert rule for it could never fire. - options.OnRejected = (context, _) => + options.OnRejected = async (context, cancellationToken) => { var logger = context.HttpContext.RequestServices .GetRequiredService() @@ -202,11 +202,24 @@ public static class ServiceCollectionExtensions var window = configuration.GetValue($"RateLimiting:{section}:WindowSeconds", 60); waitSeconds = policyName == "refresh" ? window / 4.0 : window; } + // Every 429 carries a retry hint, also for policies that report no wait (the contact and offerings policies). + waitSeconds ??= 60; if (waitSeconds is not null) context.HttpContext.Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(waitSeconds.Value)).ToString(System.Globalization.CultureInfo.InvariantCulture); - return ValueTask.CompletedTask; + + // Machine-readable body with only the standard type/title/status: nothing about the limiter, the policy or the caller. + await context.HttpContext.Response.WriteAsJsonAsync( + new Microsoft.AspNetCore.Mvc.ProblemDetails + { + Type = "https://www.rfc-editor.org/rfc/rfc6585#section-4", + Title = "Too many requests", + Status = StatusCodes.Status429TooManyRequests, + }, + options: null, + contentType: "application/problem+json", + cancellationToken: cancellationToken); }; // Every named policy is partitioned per client address (ClientPartitionKey). Behind a diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs new file mode 100644 index 0000000..851d37c --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -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; + +/// +/// 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. +/// +public class PublicSiteEndpointGateTests +{ + private readonly IAvailabilityService _service = Substitute.For(); + private readonly IMasterAvailabilityService _masterService = Substitute.For(); + private readonly IAdminTokenValidator _adminTokenValidator = Substitute.For(); + private readonly RequestDelegate _next = Substitute.For(); + private readonly AvailabilityMiddleware _middleware; + + public PublicSiteEndpointGateTests() + { + _middleware = new AvailabilityMiddleware( + _next, NullLogger.Instance, _adminTokenValidator); + + // No admin token on any request in these tests. + _adminTokenValidator.Validate(Arg.Any()) + .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 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"); + + /// The metadata MVC would attach to an action: the controller's attributes, then the action's. + 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 ---- + + /// + /// 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.) + /// + private static readonly string[] AllowedPublicActions = + [ + $"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}", + ]; + + private static IReadOnlyList 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().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() is not null) + .Select(Name) + .Should().BeEquivalentTo(AllowedPublicActions); + } + + [Fact] + public void AMarkedActionIsAnonymous_AndNeverAnAuthorizedOne() + { + foreach (var action in AllActions().Where(m => m.GetCustomAttribute() is not null)) + { + action.GetCustomAttribute() + .Should().NotBeNull($"{Name(action)} is public so it must be explicitly anonymous"); + action.GetCustomAttributes() + .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() is null) + .ToList(); + others.Should().NotBeEmpty(); + + var reachable = new List(); + 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(); + foreach (var action in AllActions()) + { + if (await StatusFor(EndpointOf(action)) == 200) + { + passing.Add(Name(action)); + } + } + + passing.Should().BeEquivalentTo(AllowedPublicActions); + } +} diff --git a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj index 9767b63..112f182 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj +++ b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj @@ -31,4 +31,12 @@ + + + + + + + \ No newline at end of file diff --git a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs index ef816d2..162e356 100644 --- a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs +++ b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs @@ -69,6 +69,15 @@ public class AvailabilityMiddleware 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) { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs new file mode 100644 index 0000000..78aed46 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Offerings.Controllers; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingsPublicMarkerTests +{ + private static IEnumerable Actions() => + new[] { typeof(OfferingsController), typeof(OfferingCategoriesController) } + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + + [Fact] + public void GetOfferings_IsMarkedAsPublicSiteEndpoint_AndAnonymous() + { + var action = typeof(OfferingsController).GetMethod(nameof(OfferingsController.GetOfferings))!; + + action.GetCustomAttribute().Should().NotBeNull(); + action.GetCustomAttribute().Should().NotBeNull(); + } + + [Fact] + public void NoOtherOfferingsAction_CarriesTheMarker() + { + Actions() + .Where(m => m.Name != nameof(OfferingsController.GetOfferings)) + .Where(m => m.GetCustomAttribute() is not null) + .Should().BeEmpty("writes and the category management stay behind the availability gate"); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs index 8d170d4..5005b6c 100644 --- a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; +using SlpModularCms.Core.Availability; using SlpModularCms.Modules.Offerings.Models; using SlpModularCms.Modules.Offerings.Services; @@ -20,6 +21,7 @@ public class OfferingsController(IOfferingsService service) : ControllerBase { [HttpGet] [AllowAnonymous] + [PublicSiteEndpoint] [EnableRateLimiting("offerings-public")] public async Task GetOfferings() {