diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 0b79319..de74d2f 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**: PHASE 2 planning - rebased on master e671078; plans CMS-U5, U6, U7 awaiting approval by Redesign - SLS +- **Current Stage**: PHASE 2 - CMS-U7 built and committed; next CMS-U5, then CMS-U6 - **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-u7-availability-restful-status/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md new file mode 100644 index 0000000..ac4872f --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md @@ -0,0 +1,20 @@ +# CMS-U7 availability-restful-status: code summary + +## RELEASE NOTE: this unit must go out as ONE release together with the admin app +`POST /api/v1/Availability/admin/status` is removed (no alias) and replaced by `PUT /api/v1/Availability/status`. The API and the admin app (`frontend/`) change together. Deploying only one half breaks the status change in Settings: a new API with an old admin bundle gets a non-JSON fallback page on the old route; a new bundle on an old API gets 405/404. During a deploy window a still-open old browser tab fails until its next page load. + +## Result +- `PUT /api/v1/Availability/status` (AdminOnly), body unchanged `{ "newStatus": "Available"|"Maintenance"|"NotAvailable", "reason": string|null }`. `200` with the **updated resource**, same JSON as `GET /api/v1/Availability/status` (`{ status, checkedAt, message, isMasterControlled }`); `409` problem+json when the status is master-controlled (unchanged); `400` for an invalid status or a service that cannot persist; `401`/`403` like every admin route. +- `GET /api/v1/Availability/status` is unchanged (public, open for everyone, also while the CMS is off). +- Old route removed; `openapi/slpsoftware.v1.json` regenerated. +- **Gate** (`AvailabilityMiddleware`, small isolated diff): the exemption for `/api/v1/Availability/status` now applies to `GET`/`HEAD` only. `PUT` (and any other method) follows the normal gate: a verified Owner/Administrator passes, an expired token gets `401`, everyone else `503`. Before, the prefix exemption let any method through. +- Frontend: `useUpdateAvailability` uses `PUT` and writes the answer into the status cache; msw default handler and the two failure handlers in `SettingsPage.test.tsx` moved to `PUT`; a new test asserts method, path (no `admin`) and body. + +## Callers of the old route (checked repository-wide: code, docs, CI, configs) +Only the admin frontend: `features/availability/services/useAvailability.ts`, `features/availability/mocks/handlers.ts`, two handlers in `features/settings/pages/SettingsPage.test.tsx`. No server-side caller: the master pushes with `POST /Master/status`, slaves read `GET /SlaveStatus`; no proxy, deploy script or workflow mentions it; the README names only the GET. Historic `aidlc-docs` mentions are history and unchanged. + +## Changes to existing tests (for the record) +Three existing tests built a request without an HTTP method (the default is empty) and relied on the old method-less prefix exemption. They now set `GET` like a real request does: `TestContexts.Api()` and `AvailabilityGateScopeTests.RunAsync` (shared helpers) and `PublicSiteEndpointGateTests.TheAvailabilityStatusEndpoint_StaysOpen...`. `AvailabilityControllerTests.UpdateStatus_ReturnsOk...` now asserts the body (`OkObjectResult`, same four fields as the GET) instead of `OkResult`. No assertion about gate behaviour was weakened. + +## Verification (real output) +Build 0 errors. Availability.Tests 165 passed (11 new in `AvailabilityStatusRouteTests`: GET/HEAD stay open; PUT/POST/DELETE/PATCH are gated; a verified administrator passes while the CMS is disabled; an expired token on PUT = 401; case-insensitive path; route table = exactly `GET status` + `PUT status`, PUT is AdminOnly and not public-marked, no `admin` in any route). Contact.Tests 228 passed (3 new pipeline tests on the real host: anonymous PUT 401, user 403, administrator PUT Maintenance -> body is the updated resource -> anonymous GET shows it -> visitor gets 503 on a gated route and on the PUT itself -> administrator switches it back; invalid status 400 and unchanged state; the old route behaves like a route that never existed and changes nothing). Api.AndreaSlopFotografie 11, Api 4, Core 625, Identity 145, Master 61, Offerings 86. Frontend: `pnpm lint` clean, `npx tsc -b` clean, vitest 57 files / 432 tests passed (1 new). diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md index 135cefb..1cd8103 100644 --- a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -51,7 +51,7 @@ All answer `404` with an empty body while the **host** switch `Contact:Enabled` `status`: `new|read|archived|spam|converted`; `mailStatus`: `pending|sent|failed|notApplicable`. ### Unchanged but relevant -`POST /availability/admin/status` still has its `admin` segment; it becomes `PUT /availability/status` in phase 2 (CMS-U7, after the ASF merge; callers to check then: master/slave status, poll client, frontend). `GET /availability/status` stays public. +`PUT /availability/status` (AdminOnly; body `{ newStatus, reason }`; `200` with the updated resource in the GET shape, `409` master-controlled) replaced `POST /availability/admin/status` (CMS-U7, no alias; API and admin app must be released together). `GET /availability/status` stays public; the gate exempts it for GET/HEAD only. ## 2. `Contact:*` and related configuration keys (Api.SlpSoftware `appsettings.json`) | Key | Default | Notes | diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md index ffe8669..f58bbef 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md @@ -15,13 +15,13 @@ Phase 2, on the rebased branch. Decision (Bryan via SLS): no `/admin` segment in 4. Frontend: `useUpdateAvailability` uses `PUT` and updates the cached status from the response; mocks and the two Settings tests change to `PUT`. ## Steps -- [ ] **Step 1 — Controller**: `[HttpPut("status")]` replaces `admin/status`; returns the updated status object (shared builder with GET); remove the old route. -- [ ] **Step 2 — Middleware**: method-aware bypass for `Availability/status` (small, isolated diff); comment explains why. -- [ ] **Step 3 — Frontend**: `useAvailability.ts` mutation (PUT + cache update), `availability/mocks/handlers.ts`, `SettingsPage.test.tsx` (2 handlers); no other change. -- [ ] **Step 4 — Docs/contract**: regenerate `openapi/slpsoftware.v1.json`; update `phase-1-handoff.md`; README mention only if it names the route (it does not). -- [ ] **Step 5 — Tests**: controller (PUT 200 body equals GET shape, 409 master-controlled, 400 invalid status, GET unchanged and anonymous); route-table test: the only anonymous action on the controller is `GetStatus`, `UpdateStatus` is `AdminOnly`, no route contains `admin`, old route absent; middleware: `PUT /api/v1/Availability/status` without token is blocked by the gate while the CMS is off (not bypassed), `GET` still open, a verified administrator can `PUT` while the CMS is disabled (existing guarantee), expired token on PUT = `401`; pipeline on the real host: login as administrator, `PUT` Maintenance → `GET` shows it, visitors get `503` on a gated route, `PUT` back to Available; old `POST admin/status` = `404`; frontend: Settings page test uses PUT and shows the new status. -- [ ] **Step 6 — Verification (automatic)**: build; all test projects incl. pipeline tests (temporary MariaDB, removed afterwards); `pnpm lint`, `npx tsc -b`, `pnpm test`; real output reported. -- [ ] **Step 7 — Commit**: one commit; no push. +- [x] **Step 1 — Controller**: `[HttpPut("status")]` replaces `admin/status`; returns the updated status object (shared builder with GET); remove the old route. +- [x] **Step 2 — Middleware**: method-aware bypass for `Availability/status` (small, isolated diff); comment explains why. +- [x] **Step 3 — Frontend**: `useAvailability.ts` mutation (PUT + cache update), `availability/mocks/handlers.ts`, `SettingsPage.test.tsx` (2 handlers); no other change. +- [x] **Step 4 — Docs/contract**: regenerate `openapi/slpsoftware.v1.json`; update `phase-1-handoff.md`; README mention only if it names the route (it does not). +- [x] **Step 5 — Tests**: controller (PUT 200 body equals GET shape, 409 master-controlled, 400 invalid status, GET unchanged and anonymous); route-table test: the only anonymous action on the controller is `GetStatus`, `UpdateStatus` is `AdminOnly`, no route contains `admin`, old route absent; middleware: `PUT /api/v1/Availability/status` without token is blocked by the gate while the CMS is off (not bypassed), `GET` still open, a verified administrator can `PUT` while the CMS is disabled (existing guarantee), expired token on PUT = `401`; pipeline on the real host: login as administrator, `PUT` Maintenance → `GET` shows it, visitors get `503` on a gated route, `PUT` back to Available; old `POST admin/status` = `404`; frontend: Settings page test uses PUT and shows the new status. +- [x] **Step 6 — Verification (automatic)**: build; all test projects incl. pipeline tests (temporary MariaDB, removed afterwards); `pnpm lint`, `npx tsc -b`, `pnpm test`; real output reported. +- [x] **Step 7 — Commit**: one commit; no push. ## Explicitly NOT touched Master/slave endpoints (`Master/*`, `SlaveStatus`, `CmsInstances/{id}/status`), the gate logic for any other route, `GET /Availability/status` behaviour, polling/circuit-breaker code. diff --git a/frontend/src/features/availability/mocks/handlers.ts b/frontend/src/features/availability/mocks/handlers.ts index c09c7ad..397c8d8 100644 --- a/frontend/src/features/availability/mocks/handlers.ts +++ b/frontend/src/features/availability/mocks/handlers.ts @@ -10,5 +10,12 @@ export const availabilityHandlers = [ }), ), - http.post('*/Availability/admin/status', () => new HttpResponse(null, { status: 200 })), + http.put('*/Availability/status', () => + HttpResponse.json({ + status: 'Available', + checkedAt: new Date().toISOString(), + message: '', + isMasterControlled: false, + }), + ), ]; diff --git a/frontend/src/features/availability/services/useAvailability.ts b/frontend/src/features/availability/services/useAvailability.ts index bf5f876..988e5e7 100644 --- a/frontend/src/features/availability/services/useAvailability.ts +++ b/frontend/src/features/availability/services/useAvailability.ts @@ -17,8 +17,12 @@ export function useAvailabilityStatus() { export function useUpdateAvailability() { const queryClient = useQueryClient(); - return useMutation({ - mutationFn: (data) => api.post('/api/v1/Availability/admin/status', data), - onSuccess: () => queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }), + return useMutation({ + mutationFn: (data) => api.put('/api/v1/Availability/status', data), + onSuccess: (updated) => { + // The PUT answers with the updated resource (same shape as the GET): use it at once. + queryClient.setQueryData(['availability', 'status'], updated); + return queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }); + }, }); } diff --git a/frontend/src/features/settings/pages/SettingsPage.test.tsx b/frontend/src/features/settings/pages/SettingsPage.test.tsx index 960c179..3941579 100644 --- a/frontend/src/features/settings/pages/SettingsPage.test.tsx +++ b/frontend/src/features/settings/pages/SettingsPage.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; @@ -60,6 +60,37 @@ describe('SettingsPage', () => { expect(maintenanceBtn.className).toContain('bg-primary'); }); + it('changes the status with PUT on the status resource (no admin route), sending the chosen status', async () => { + let sent: { method: string; url: string; body: { newStatus: string } } | undefined; + server.use( + http.put(`${API_BASE}/api/v1/Availability/status`, async ({ request }) => { + sent = { + method: request.method, + url: new URL(request.url).pathname, + body: (await request.json()) as { newStatus: string }, + }; + return HttpResponse.json({ + status: 'Maintenance', + checkedAt: new Date().toISOString(), + message: '', + isMasterControlled: false, + }); + }), + ); + mockAuthenticated(); + renderApp('/settings'); + + await screen.findByTestId('availability-mode-selector', {}, { timeout: 10000 }); + await userEvent.click(screen.getByTestId('mode-option-Maintenance')); + await userEvent.click(screen.getByTestId('availability-save-button')); + + await vi.waitFor(() => expect(sent).toBeDefined()); + expect(sent!.method).toBe('PUT'); + expect(sent!.url).toBe('/api/v1/Availability/status'); + expect(sent!.url).not.toContain('admin'); + expect(sent!.body.newStatus).toBe('Maintenance'); + }); + it('saves availability and shows success toast', async () => { mockAuthenticated(); renderApp('/settings'); @@ -72,7 +103,7 @@ describe('SettingsPage', () => { it('shows error toast when save fails', async () => { server.use( - http.post(`${API_BASE}/api/v1/Availability/admin/status`, () => + http.put(`${API_BASE}/api/v1/Availability/status`, () => HttpResponse.json({ title: 'Error' }, { status: 500 }), ), ); @@ -118,7 +149,7 @@ describe('SettingsPage', () => { it('shows a master-controlled error toast on a 409 conflict from the server', async () => { server.use( - http.post(`${API_BASE}/api/v1/Availability/admin/status`, () => + http.put(`${API_BASE}/api/v1/Availability/status`, () => HttpResponse.json({ title: 'Conflict' }, { status: 409 }), ), ); diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index b64ad04..e9ae40b 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -887,8 +887,18 @@ }, "openapi": "3.1.1", "paths": { - "/api/v1/Availability/admin/status": { - "post": { + "/api/v1/Availability/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + }, + "put": { "requestBody": { "content": { "application/*+json": { @@ -919,18 +929,6 @@ ] } }, - "/api/v1/Availability/status": { - "get": { - "responses": { - "200": { - "description": "OK" - } - }, - "tags": [ - "Availability" - ] - } - }, "/api/v1/CmsInstances": { "get": { "responses": { diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs index 75fb60a..f26865b 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs @@ -39,6 +39,7 @@ public class AvailabilityGateScopeTests var middleware = new AvailabilityMiddleware(next, NullLogger.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); diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs new file mode 100644 index 0000000..6a3243e --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs @@ -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; + +/// +/// 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. +/// +public class AvailabilityStatusRouteTests +{ + private readonly IAvailabilityService _service = Substitute.For(); + private readonly IMasterAvailabilityService _master = Substitute.For(); + private readonly IAdminTokenValidator _validator = Substitute.For(); + private readonly RequestDelegate _next = Substitute.For(); + private readonly AvailabilityMiddleware _middleware; + + public AvailabilityStatusRouteTests() + { + _middleware = new AvailabilityMiddleware(_next, NullLogger.Instance, _validator); + _master.GetMasterStatus().Returns(new MasterGateStatus(true, null)); + _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); + } + + private async Task 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()); + } + + [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()); + context.Response.StatusCode.Should().Be(503); + } + + [Fact] + public async Task AVerifiedAdministrator_CanStillChangeTheStatus_WhileTheCmsIsDisabled() + { + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(true, default)); + + await Call("PUT"); + + await _next.Received(1).Invoke(Arg.Any()); + } + + [Fact] + public async Task AnExpiredAdministratorToken_OnThePut_Gets401_SoTheAppRefreshesItsSession() + { + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Expired)); + + var context = await Call("PUT"); + + context.Response.StatusCode.Should().Be(401); + await _next.DidNotReceive().Invoke(Arg.Any()); + } + + [Fact] + public async Task ThePathMatchIsCaseInsensitive_ForReadingToo() + { + await Call("GET", "/api/v1/availability/STATUS"); + + await _next.Received(1).Invoke(Arg.Any()); + } + + // ---- 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().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().Should().NotBeNull(); + put.GetCustomAttribute().Should().BeNull(); + put.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + put.GetCustomAttribute().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")); + } +} diff --git a/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs b/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs index 259667a..236dbd7 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs @@ -95,7 +95,12 @@ public class AvailabilityControllerTests var result = await controller.UpdateStatus( new UpdateStatusRequest(AvailabilityStatus.Maintenance, "Test maintenance")); - result.Should().BeOfType(); + // The answer is the updated resource, in the same shape as GET /Availability/status. + var ok = result.Should().BeOfType().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] diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs index 96a7ae7..5f22a89 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -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); diff --git a/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs index 5179246..e5ed3a2 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs @@ -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; } } diff --git a/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs b/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs index 4da4318..cde9127 100644 --- a/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs +++ b/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs @@ -20,18 +20,21 @@ public class AvailabilityController : ControllerBase [HttpGet("status")] [AllowAnonymous] public async Task 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, + }; + + /// + /// 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. + /// + [HttpPut("status")] [Authorize(Policy = "AdminOnly")] public async Task 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) { diff --git a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs index 162e356..30d1324 100644 --- a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs +++ b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs @@ -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; diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs new file mode 100644 index 0000000..26fef6a --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs @@ -0,0 +1,83 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// The availability status as one RESTful resource, on the real composed host. +public class AvailabilityStatusPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture +{ + private const string Status = "/api/v1/Availability/status"; + + private static async Task 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"); + } +}