Contactformulier-module, banners, thema's, taalbestanden en CI-herstructurering #15
@@ -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
|
||||
|
||||
+20
@@ -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).
|
||||
@@ -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 |
|
||||
|
||||
+7
-7
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -17,8 +17,12 @@ export function useAvailabilityStatus() {
|
||||
|
||||
export function useUpdateAvailability() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, UpdateAvailabilityPayload>({
|
||||
mutationFn: (data) => api.post<void>('/api/v1/Availability/admin/status', data),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }),
|
||||
return useMutation<AvailabilityResponse, Error, UpdateAvailabilityPayload>({
|
||||
mutationFn: (data) => api.put<AvailabilityResponse>('/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'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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 }),
|
||||
),
|
||||
);
|
||||
|
||||
+12
-14
@@ -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": {
|
||||
|
||||
@@ -39,6 +39,7 @@ public class AvailabilityGateScopeTests
|
||||
var middleware = new AvailabilityMiddleware(next, NullLogger<AvailabilityMiddleware>.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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class AvailabilityStatusRouteTests
|
||||
{
|
||||
private readonly IAvailabilityService _service = Substitute.For<IAvailabilityService>();
|
||||
private readonly IMasterAvailabilityService _master = Substitute.For<IMasterAvailabilityService>();
|
||||
private readonly IAdminTokenValidator _validator = Substitute.For<IAdminTokenValidator>();
|
||||
private readonly RequestDelegate _next = Substitute.For<RequestDelegate>();
|
||||
private readonly AvailabilityMiddleware _middleware;
|
||||
|
||||
public AvailabilityStatusRouteTests()
|
||||
{
|
||||
_middleware = new AvailabilityMiddleware(_next, NullLogger<AvailabilityMiddleware>.Instance, _validator);
|
||||
_master.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent));
|
||||
}
|
||||
|
||||
private async Task<DefaultHttpContext> 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<HttpContext>());
|
||||
}
|
||||
|
||||
[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<HttpContext>());
|
||||
context.Response.StatusCode.Should().Be(503);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AVerifiedAdministrator_CanStillChangeTheStatus_WhileTheCmsIsDisabled()
|
||||
{
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(true, default));
|
||||
|
||||
await Call("PUT");
|
||||
|
||||
await _next.Received(1).Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnExpiredAdministratorToken_OnThePut_Gets401_SoTheAppRefreshesItsSession()
|
||||
{
|
||||
_validator.Validate(Arg.Any<string>()).Returns(new AdminTokenResult(false, BypassRejectionReason.Expired));
|
||||
|
||||
var context = await Call("PUT");
|
||||
|
||||
context.Response.StatusCode.Should().Be(401);
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePathMatchIsCaseInsensitive_ForReadingToo()
|
||||
{
|
||||
await Call("GET", "/api/v1/availability/STATUS");
|
||||
|
||||
await _next.Received(1).Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
// ---- 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<HttpMethodAttribute>().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<AllowAnonymousAttribute>().Should().NotBeNull();
|
||||
put.GetCustomAttribute<AllowAnonymousAttribute>().Should().BeNull();
|
||||
put.GetCustomAttribute<AuthorizeAttribute>()!.Policy.Should().Be("AdminOnly");
|
||||
put.GetCustomAttribute<PublicSiteEndpointAttribute>().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"));
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -95,7 +95,12 @@ public class AvailabilityControllerTests
|
||||
var result = await controller.UpdateStatus(
|
||||
new UpdateStatusRequest(AvailabilityStatus.Maintenance, "Test maintenance"));
|
||||
|
||||
result.Should().BeOfType<OkResult>();
|
||||
// The answer is the updated resource, in the same shape as GET /Availability/status.
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,18 +20,21 @@ public class AvailabilityController : ControllerBase
|
||||
[HttpGet("status")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> 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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[HttpPut("status")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public async Task<IActionResult> 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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>The availability status as one RESTful resource, on the real composed host.</summary>
|
||||
public class AvailabilityStatusPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture<ClosedCmsSwitchContactHostFactory>
|
||||
{
|
||||
private const string Status = "/api/v1/Availability/status";
|
||||
|
||||
private static async Task<JsonElement> 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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user