diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index d62d076..f6d42b1 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-U3b built and committed; CMS-U4 in progress +- **Current Stage**: CONSTRUCTION - CMS-U4 built and committed (awaiting review); next phase 2 after the ASF merge (CMS-U5, U6, U7) - **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/audit.md b/aidlc-docs/features/contact-forms-module/audit.md index 3f0ac40..d02d6ea 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -119,3 +119,15 @@ **Context**: Code Generation Part 1. --- + +## CMS-U3b and CMS-U4 built + +**Timestamp**: 2026-11-09 + +**User Input**: "CMS-U3b en CMS-U4 goedgekeurd ... bestandsnaam per host ... hervat CMS-U4 na onderbreking" (via Redesign - SLS) + +**AI Response**: U3b committed (0813656); U4 finished and committed after resuming: Scratch.cs removed, list query fixed, tests green. + +**Context**: Construction phase 1 complete. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md new file mode 100644 index 0000000..7bb0526 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md @@ -0,0 +1,73 @@ +# CMS-U4 contact-admin-api: code summary + +## IMPORTANT: the contact form is OFF by default, on two layers +1. **Host switch** `Contact:Enabled` (appsettings/environment of the host), default `false`. Release condition: only switch on after the per-client rate limiting from the ASF branch is on the base branch (see the CMS-U3 rebase checklist). +2. **CMS switch** (data, this unit): `PUT /api/v1/contact-settings` `{ "enabled": true }`, default **off** (no row = off). **Bryan has to switch the form on himself**, in the "Berichten" screen (CMS-U6) or through the API, before the public routes work. The form is open only when BOTH are on; otherwise `GET /contact-messages/token` and `POST /contact-messages` answer `404` with an empty body and the website shows its mailto fallback. A change of the CMS switch takes effect at once in the process that handled the change (other instances within 5 seconds). + +## Routes (all `AdminOnly`: Owner or Administrator; anonymous = 401, role `User` = 403) +Same resource names as the public routes, no `/admin` segment. All sit behind the availability gate (no `[PublicSiteEndpoint]`): for visitors they answer 503 while the CMS is off/in maintenance; a verified administrator always gets through (by design, so the CMS can be switched back on). + +**While the host switch is off every management route answers `404` with an empty body** (the contact tables do not exist then). The UI must read `404` on `GET /contact-settings` as "not available on this host" and hide the menu entry. The CMS switch never closes the management routes. + +### JSON shapes (camelCase; enums are lower-camel strings) +`status`: `new | read | archived | spam | converted`; `mailStatus`: `pending | sent | failed | notApplicable`. + +**`GET /api/v1/contact-messages?status=&page=1&pageSize=25`** -> `200` +```json +{ + "items": [ + { "id": "3f2c...-guid", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen", + "email": "jan@example.nl", "subject": "website", "status": "new", "mailStatus": "pending" } + ], + "page": 1, "pageSize": 25, "totalCount": 1, "unreadCount": 1 +} +``` +`status` (optional, one value `new|read|archived|spam`, case-insensitive): without it the list shows `new`, `read` and `archived` — **spam is never in the default list**; `status=spam` shows spam apart. Newest first. `page` >= 1, `pageSize` 1-100. `unreadCount` = number of `new` messages, **never counting spam, independent of the filter**. The list has no message text. + +**`GET /api/v1/contact-messages/{id}`** -> `200` +```json +{ + "id": "3f2c...", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen", "email": "jan@example.nl", + "subject": "website", "message": "Ik wil graag een offerte.", "status": "new", "mailStatus": "pending", + "mailAttempts": 0, "mailError": null, "retentionUntil": "2027-11-09T12:00:00+00:00" +} +``` +`404` unknown id. + +**`PATCH /api/v1/contact-messages/{id}`** body `{ "status": "new" | "read" | "archived" }` -> `200` with the detail shape above. Setting one of these on a spam message means "not spam": it then follows the normal retention (`retentionUntil` = now + `Contact:RetentionMonths`) and appears in the default list; its `mailStatus` stays `notApplicable` until resent. Anything else (`spam`, `converted`, unknown, missing, unreadable body) -> `400`. `404` unknown id. + +**`DELETE /api/v1/contact-messages/{id}`** -> `204` (hard delete, erasure request); `404` unknown id. + +**`POST /api/v1/contact-messages/{id}/resend`** (rate limit `contact-resend`, default 5 per 600 s) -> `200` +```json +{ "mailStatus": "pending", "mailAttempts": 0, "mailed": false } +``` +`mailed=true` only when a mail was really sent. Until the mail unit (CMS-U5) there is no mail sender, so the answer is `mailed:false` and nothing changes. A spam message -> `409` (problem+json; "mark it as not spam first"). `404` unknown id. `429` with `Retry-After` after the limit. + +**`GET /api/v1/contact-settings`** -> `200` +```json +{ "enabled": false, "hostEnabled": true } +``` +`enabled` = the CMS switch (default `false`); `hostEnabled` = the host switch, read-only, so the UI can explain why the form is closed. + +**`PUT /api/v1/contact-settings`** body `{ "enabled": true | false }` -> `200`, same shape as GET. Anything that is not a JSON boolean (missing, null, string, number, unreadable body) -> `400`. + +### Error shape (`400`, `application/problem+json`) +```json +{ "type": "about:blank", "title": "Validation failed", "status": 400, "errors": { "status": ["invalid"] } } +``` +Field names used: `status` (PATCH), `enabled` (PUT settings), `page`, `pageSize`, `status` (list query). Code is always `invalid`. + +## Design notes +- Separate controllers for the management side (`ContactMessagesAdminController`, `ContactSettingsController`) next to the public `ContactMessagesController`; routes cannot clash (`{id:guid}`). +- Gate: `CompositeContactFormGate` = host flag first, then `CmsFlagContactFormGate` (singleton row in table `ContactSettings`, migration `AddContactSettings`, 5-second in-process cache invalidated on every change). The public `ContactRouteFilter` was not touched. With the host flag off the database is not touched at all. +- Statuses and mail statuses are stored as strings; the list uses one flag per status in its query because a parameterized collection loses the value-converter mapping in the SQL translation (found by the pipeline test). +- Nothing personal is logged by the admin services (ids and outcomes only; tested). +- Management routes appear in `openapi/slpsoftware.v1.json` (regenerated). + +## Verification (real output) +Build 0 errors. Contact.Tests **223 passed** (unit + pipeline), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4, against a temporary MariaDB (removed afterwards). Explicit tests requested by SLS: +- Route table: exactly the seven management routes exist; every one is under class-level `AdminOnly`, none is `[AllowAnonymous]`, none is `[PublicSiteEndpoint]`, no route contains `admin`; the only `[PublicSiteEndpoint]` actions in the whole module are `GetToken` and `Submit`; the Availability route-table test (everything except `GetOfferings`, `GetToken`, `Submit` is blocked by a closed gate) covers the new routes without change. +- `PUT /contact-settings` by a non-admin -> `403` and nothing changes; by a regular user also for every other management route; anonymous -> `401` on all of them. +- Invalid body (`"yes"`, `1`, `null`, `{}`, `not json`, empty) -> `400` with `errors.enabled=["invalid"]` (and only that field). +- Real host: switch default off and reported with `hostEnabled`; PUT opens/closes the public routes at once while the management routes keep working; the changing user is recorded; full message flow (list without spam, `status=spam`, detail, status change, spam refused for resend, un-spam, delete); bad list queries -> `400`; resend `429` with `Retry-After`; host switch off -> management routes `404` (empty), anonymous still `401`; CMS disabled (availability) -> visitors `503` on the management routes, an administrator still `200`. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md index b4cd929..24fa36f 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md @@ -29,12 +29,12 @@ The admin routes need the Contact tables, which exist only when the host switch All new routes require `AdminOnly` (Owner/Administrator). They are **not** marked `[PublicSiteEndpoint]`, so the availability gate blocks them when the CMS is off or in maintenance (verified by the route-table test). ## Steps -- [ ] **Step 1 — Settings model + migration** `AddContactSettings` (generated; applied to a real MariaDB for verification). -- [ ] **Step 2 — Repositories/services**: list/detail/patch/delete/resend (`IContactMessageAdminService`), settings (`IContactSettingsService`), gates (`CmsFlagContactFormGate`, `CompositeContactFormGate`), cache with invalidation. Resend uses the existing `IContactMailSender` seam. -- [ ] **Step 3 — Controllers + filter + rate-limit policy `contact-resend`** (registered in `ContactModule`, config `RateLimiting:ContactResend`, default 5/600; same single partition function as the other contact policies, so the rebase checklist still has one line). -- [ ] **Step 4 — Tests**: services (default list excludes spam; each status filter; ordering and paging bounds; `unreadCount` ignores spam and filters; detail fields; patch transitions incl. un-spam extending retention; invalid statuses; delete; resend rules incl. spam -> 409 and `Skipped`/`Sent`/`Failed`; settings default false, PUT/GET round trip, cache invalidated on PUT); gates (host off -> closed without calling the database gate; host on + CMS off -> closed; both on -> open; unit test with substitutes proving short-circuit order); controllers (status codes, response shapes, lower-camel enum strings); **route-table test (explicit, as requested)**: every action of `ContactMessagesAdminController` is under class-level `AdminOnly`, none has `[AllowAnonymous]` or `[PublicSiteEndpoint]`, no route contains `admin`; the set of public contact actions stays exactly `{GetToken, Submit}` and `AllowedPublicActions` in the Availability route-table test is unchanged (the new routes are covered by its "everything else answers 503" check); pipeline tests on the real host and MariaDB: anonymous -> 401, authenticated without admin role -> 403 (minted JWT with the host's development JWT settings), administrator -> 200 flows (list/detail/patch/delete/resend), host switch off -> admin routes 404 empty, CMS switch off -> public routes 404 but admin routes still 200, switching it on through `PUT /contact-settings` makes the public routes work within the cache window, the CMS being disabled (availability) blocks admin routes with 503, `contact-resend` returns 429 with `Retry-After` after its limit, no personal data in any log entry written by the admin services. -- [ ] **Step 5 — Verification (automatic)**: build; all test projects; pipeline tests against a temporary MariaDB (removed afterwards); real output. -- [ ] **Step 6 — Docs/commit**: summary with the JSON shapes for the frontend handoff and the rebase notes (none new); one commit; no push. +- [x] **Step 1 — Settings model + migration** `AddContactSettings` (generated; applied to a real MariaDB for verification). +- [x] **Step 2 — Repositories/services**: list/detail/patch/delete/resend (`IContactMessageAdminService`), settings (`IContactSettingsService`), gates (`CmsFlagContactFormGate`, `CompositeContactFormGate`), cache with invalidation. Resend uses the existing `IContactMailSender` seam. +- [x] **Step 3 — Controllers + filter + rate-limit policy `contact-resend`** (registered in `ContactModule`, config `RateLimiting:ContactResend`, default 5/600; same single partition function as the other contact policies, so the rebase checklist still has one line). +- [x] **Step 4 — Tests**: services (default list excludes spam; each status filter; ordering and paging bounds; `unreadCount` ignores spam and filters; detail fields; patch transitions incl. un-spam extending retention; invalid statuses; delete; resend rules incl. spam -> 409 and `Skipped`/`Sent`/`Failed`; settings default false, PUT/GET round trip, cache invalidated on PUT); gates (host off -> closed without calling the database gate; host on + CMS off -> closed; both on -> open; unit test with substitutes proving short-circuit order); controllers (status codes, response shapes, lower-camel enum strings); **route-table test (explicit, as requested)**: every action of `ContactMessagesAdminController` is under class-level `AdminOnly`, none has `[AllowAnonymous]` or `[PublicSiteEndpoint]`, no route contains `admin`; the set of public contact actions stays exactly `{GetToken, Submit}` and `AllowedPublicActions` in the Availability route-table test is unchanged (the new routes are covered by its "everything else answers 503" check); pipeline tests on the real host and MariaDB: anonymous -> 401, authenticated without admin role -> 403 (minted JWT with the host's development JWT settings), administrator -> 200 flows (list/detail/patch/delete/resend), host switch off -> admin routes 404 empty, CMS switch off -> public routes 404 but admin routes still 200, switching it on through `PUT /contact-settings` makes the public routes work within the cache window, the CMS being disabled (availability) blocks admin routes with 503, `contact-resend` returns 429 with `Retry-After` after its limit, no personal data in any log entry written by the admin services. +- [x] **Step 5 — Verification (automatic)**: build; all test projects; pipeline tests against a temporary MariaDB (removed afterwards); real output. +- [x] **Step 6 — Docs/commit**: summary with the JSON shapes for the frontend handoff and the rebase notes (none new); one commit; no push. ## Explicitly NOT touched `ContactRouteFilter` (the public filter), the public controller, the public validation/submission logic, Core/Availability, Email, Identity, the frontend. diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index b6b6248..61a5189 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -101,6 +101,153 @@ ], "type": "object" }, + "ContactMessageDetail": { + "properties": { + "email": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mailAttempts": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "mailError": { + "type": [ + "null", + "string" + ] + }, + "mailStatus": { + "type": "string" + }, + "message": { + "type": "string" + }, + "name": { + "type": "string" + }, + "receivedAt": { + "format": "date-time", + "type": "string" + }, + "retentionUntil": { + "format": "date-time", + "type": "string" + }, + "status": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "id", + "receivedAt", + "name", + "email", + "subject", + "message", + "status", + "mailStatus", + "mailAttempts", + "mailError", + "retentionUntil" + ], + "type": "object" + }, + "ContactMessageList": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/ContactMessageListItem" + }, + "type": "array" + }, + "page": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "pageSize": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "totalCount": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "unreadCount": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + "required": [ + "items", + "page", + "pageSize", + "totalCount", + "unreadCount" + ], + "type": "object" + }, + "ContactMessageListItem": { + "properties": { + "email": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mailStatus": { + "type": "string" + }, + "name": { + "type": "string" + }, + "receivedAt": { + "format": "date-time", + "type": "string" + }, + "status": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "id", + "receivedAt", + "name", + "email", + "subject", + "status", + "mailStatus" + ], + "type": "object" + }, "ContactMessageRequest": { "properties": { "captchaToken": { @@ -143,6 +290,45 @@ ], "type": "object" }, + "ContactResendResult": { + "properties": { + "mailAttempts": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "mailStatus": { + "type": "string" + }, + "mailed": { + "type": "boolean" + } + }, + "required": [ + "mailStatus", + "mailAttempts", + "mailed" + ], + "type": "object" + }, + "ContactSettingsDto": { + "properties": { + "enabled": { + "type": "boolean" + }, + "hostEnabled": { + "type": "boolean" + } + }, + "required": [ + "enabled", + "hostEnabled" + ], + "type": "object" + }, "ContactTokenResponse": { "properties": { "captcha": { @@ -424,6 +610,34 @@ ], "type": "object" }, + "UpdateContactMessageStatusRequest": { + "properties": { + "status": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "UpdateContactSettingsRequest": { + "properties": { + "enabled": { + "type": [ + "null", + "boolean" + ] + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, "UpdateOfferingRequest": { "properties": { "categoryId": { @@ -1194,6 +1408,68 @@ } }, "/api/v1/contact-messages": { + "get": { + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "page", + "schema": { + "default": 1, + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + { + "in": "query", + "name": "pageSize", + "schema": { + "default": 25, + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageList" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, "post": { "parameters": [ { @@ -1271,6 +1547,259 @@ ] } }, + "/api/v1/contact-messages/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageDetail" + } + } + }, + "description": "OK" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, + "patch": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactMessageStatusRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactMessageStatusRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageDetail" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + } + }, + "/api/v1/contact-messages/{id}/resend": { + "post": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactResendResult" + } + } + }, + "description": "OK" + }, + "404": { + "description": "Not Found" + }, + "409": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Conflict" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Too Many Requests" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + } + }, + "/api/v1/contact-settings": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactSettingsDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "ContactSettings" + ] + }, + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactSettingsRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactSettingsRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactSettingsDto" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "ContactSettings" + ] + } + }, "/api/v1/offerings": { "get": { "responses": { @@ -1542,9 +2071,15 @@ { "name": "Master" }, + { + "name": "ContactMessagesAdmin" + }, { "name": "ContactMessages" }, + { + "name": "ContactSettings" + }, { "name": "Auth" }, diff --git a/src/SlpModularCms.Api.SlpSoftware/appsettings.json b/src/SlpModularCms.Api.SlpSoftware/appsettings.json index 8f96bf6..7bb6fd1 100644 --- a/src/SlpModularCms.Api.SlpSoftware/appsettings.json +++ b/src/SlpModularCms.Api.SlpSoftware/appsettings.json @@ -101,6 +101,10 @@ "ContactToken": { "PermitLimit": 20, "WindowSeconds": 600 + }, + "ContactResend": { + "PermitLimit": 5, + "WindowSeconds": 600 } }, "SecurityHeaders": { diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs new file mode 100644 index 0000000..c2030cd --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs @@ -0,0 +1,313 @@ +using System.Reflection; +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.AspNetCore.Routing; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactAdminControllerTests +{ + private readonly IContactAdminService _service = Substitute.For(); + private readonly IContactSettingsService _settings = Substitute.For(); + + private ContactMessagesAdminController Messages(string? typeBase = null) => new(_service, Options.Create(new ContactOptions { Enabled = true, ProblemTypeBase = typeBase })) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + + private ContactSettingsController Settings(Guid? userId = null) + { + var http = new DefaultHttpContext(); + if (userId is not null) + { + http.User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuth")); + } + + return new ContactSettingsController(_settings, Options.Create(new ContactOptions { Enabled = true })) + { + ControllerContext = new ControllerContext { HttpContext = http }, + }; + } + + private static void AssertInvalid(IActionResult result, params string[] fields) + { + var obj = result.Should().BeOfType().Subject; + obj.StatusCode.Should().Be(400); + obj.ContentTypes.Should().Contain("application/problem+json"); + var problem = obj.Value.Should().BeOfType().Subject; + problem.Errors.Keys.Should().BeEquivalentTo(fields); + problem.Errors.Values.Should().OnlyContain(v => v.Length == 1 && v[0] == "invalid"); + } + + // ---- list ---- + + [Fact] + public async Task List_Returns200_WithTheServiceResult() + { + var list = new ContactMessageList([], 1, 25, 0, 0); + _service.ListAsync(null, 1, 25, Arg.Any()).Returns(list); + + var result = await Messages().List(null, 1, 25); + + result.Should().BeOfType().Which.Value.Should().Be(list); + } + + [Theory] + [InlineData(0, 25, null, "page")] + [InlineData(-3, 25, null, "page")] + [InlineData(1, 0, null, "pageSize")] + [InlineData(1, 101, null, "pageSize")] + [InlineData(1, 25, "bogus", "status")] + [InlineData(1, 25, "converted", "status")] + public async Task List_Returns400_NamingTheBadParameter(int page, int pageSize, string? status, string field) + { + var result = await Messages().List(status, page, pageSize); + + AssertInvalid(result, field); + await _service.DidNotReceive().ListAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task List_Returns400_ForAnUnparsablePageNumber() + { + var controller = Messages(); + controller.ModelState.AddModelError("page", "The value 'abc' is not valid."); + + var result = await controller.List(null); + + AssertInvalid(result, "page"); + } + + // ---- detail, status, delete, resend ---- + + [Fact] + public async Task Get_Returns200_Or404() + { + var id = Guid.NewGuid(); + _service.GetAsync(id, Arg.Any()).Returns((ContactMessageDetail?)null); + (await Messages().Get(id, CancellationToken.None)).Should().BeOfType(); + + var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", "new", "pending", 0, null, DateTimeOffset.UtcNow); + _service.GetAsync(id, Arg.Any()).Returns(detail); + (await Messages().Get(id, CancellationToken.None)).Should().BeOfType().Which.Value.Should().Be(detail); + } + + [Theory] + [InlineData("new", ContactMessageStatus.New)] + [InlineData("read", ContactMessageStatus.Read)] + [InlineData("archived", ContactMessageStatus.Archived)] + [InlineData("ARCHIVED", ContactMessageStatus.Archived)] + public async Task SetStatus_AcceptsNewReadArchived(string value, ContactMessageStatus expected) + { + var id = Guid.NewGuid(); + var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", value.ToLowerInvariant(), "pending", 0, null, DateTimeOffset.UtcNow); + _service.SetStatusAsync(id, expected, Arg.Any()).Returns(detail); + + var result = await Messages().SetStatus(id, new UpdateContactMessageStatusRequest(value), CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(detail); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("spam")] + [InlineData("converted")] + [InlineData("deleted")] + public async Task SetStatus_RejectsEverythingElse_WithErrorsStatus(string? value) + { + var result = await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest(value), CancellationToken.None); + + AssertInvalid(result, "status"); + await _service.DidNotReceive().SetStatusAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SetStatus_RejectsAnUnreadableBody() + { + var controller = Messages(); + controller.ModelState.AddModelError("$.status", "bad"); + + AssertInvalid(await controller.SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status"); + AssertInvalid(await Messages().SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status"); + } + + [Fact] + public async Task SetStatus_Returns404_ForAnUnknownMessage() + { + _service.SetStatusAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns((ContactMessageDetail?)null); + + (await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest("read"), CancellationToken.None)) + .Should().BeOfType(); + } + + [Fact] + public async Task Delete_Returns204_Or404() + { + var id = Guid.NewGuid(); + _service.DeleteAsync(id, Arg.Any()).Returns(true, false); + + (await Messages().Delete(id, CancellationToken.None)).Should().BeOfType(); + (await Messages().Delete(id, CancellationToken.None)).Should().BeOfType(); + } + + [Fact] + public async Task Resend_Returns200_404_Or409ForSpam() + { + var id = Guid.NewGuid(); + var result = new ContactResendResult("sent", 1, true); + _service.ResendAsync(id, Arg.Any()).Returns(result); + (await Messages().Resend(id, CancellationToken.None)).Should().BeOfType().Which.Value.Should().Be(result); + + _service.ResendAsync(id, Arg.Any()).Returns((ContactResendResult?)null); + (await Messages().Resend(id, CancellationToken.None)).Should().BeOfType(); + + _service.ResendAsync(id, Arg.Any()).Returns>(_ => throw new ContactResendNotAllowedException()); + var conflict = (ObjectResult)await Messages().Resend(id, CancellationToken.None); + conflict.StatusCode.Should().Be(409); + conflict.ContentTypes.Should().Contain("application/problem+json"); + conflict.Value.Should().BeOfType().Which.Status.Should().Be(409); + } + + // ---- settings ---- + + [Fact] + public async Task GetSettings_ReturnsTheSingleton() + { + _settings.GetAsync(Arg.Any()).Returns(new ContactSettingsDto(false, true)); + + var result = await Settings().Get(CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(new ContactSettingsDto(false, true)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PutSettings_StoresTheBoolean_RecordingWhoDidIt(bool enabled) + { + var user = Guid.NewGuid(); + _settings.SetEnabledAsync(enabled, user, Arg.Any()).Returns(new ContactSettingsDto(enabled, true)); + + var result = await Settings(user).Put(new UpdateContactSettingsRequest(enabled), CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(new ContactSettingsDto(enabled, true)); + } + + [Fact] + public async Task PutSettings_RejectsAMissingNullOrNonBooleanValue_WithErrorsEnabled() + { + AssertInvalid(await Settings().Put(null, CancellationToken.None), "enabled"); + AssertInvalid(await Settings().Put(new UpdateContactSettingsRequest(null), CancellationToken.None), "enabled"); + + var controller = Settings(); + controller.ModelState.AddModelError("$.enabled", "The JSON value could not be converted to System.Boolean."); + AssertInvalid(await controller.Put(new UpdateContactSettingsRequest(true), CancellationToken.None), "enabled"); + + await _settings.DidNotReceive().SetEnabledAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + // ---- route table (every route of the management side) ---- + + private static readonly Type[] AdminControllers = [typeof(ContactMessagesAdminController), typeof(ContactSettingsController)]; + + private static IEnumerable<(Type Controller, MethodInfo Action, HttpMethodAttribute Http)> AdminActions() => + AdminControllers.SelectMany(c => c + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(m => (Controller: c, Action: m, Http: m.GetCustomAttributes().SingleOrDefault())) + .Where(x => x.Http is not null) + .Select(x => (x.Controller, x.Action, x.Http!))); + + [Fact] + public void RouteTable_TheManagementRoutesAreExactlyTheAgreedSet() + { + AdminActions().Select(a => + $"{a.Http.HttpMethods.Single()} {a.Controller.GetCustomAttribute()!.Template}/{a.Http.Template}".TrimEnd('/')) + .Should().BeEquivalentTo( + [ + "GET contact-messages", + "GET contact-messages/{id:guid}", + "PATCH contact-messages/{id:guid}", + "DELETE contact-messages/{id:guid}", + "POST contact-messages/{id:guid}/resend", + "GET contact-settings", + "PUT contact-settings", + ]); + } + + [Fact] + public void RouteTable_EveryManagementRoute_IsAdminOnly_NeverAnonymous_NeverPublic_AndHasNoAdminSegment() + { + foreach (var controller in AdminControllers) + { + controller.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + controller.GetCustomAttribute()!.ServiceType.Should().Be(typeof(ContactAdminRouteFilter)); + controller.GetCustomAttribute()!.Template.Should().NotContainEquivalentOf("admin"); + } + + foreach (var (controller, action, http) in AdminActions()) + { + var name = $"{controller.Name}.{action.Name}"; + action.GetCustomAttribute().Should().BeNull($"{name} must not be anonymous"); + action.GetCustomAttribute().Should().BeNull($"{name} must stay behind the availability gate"); + action.GetCustomAttributes().Where(a => a.Policy != "AdminOnly").Should().BeEmpty(); + (http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin"); + } + } + + [Fact] + public void RouteTable_OnlyTwoActionsOfTheWholeContactModuleArePublic() + { + var publicActions = typeof(ContactModule).Assembly.GetTypes() + .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract) + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + .Where(m => m.GetCustomAttribute() is not null) + .Select(m => $"{m.DeclaringType!.Name}.{m.Name}"); + + publicActions.Should().BeEquivalentTo( + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}"); + } + + [Fact] + public void ResendHasItsOwnRateLimitPolicy() + { + typeof(ContactMessagesAdminController).GetMethod(nameof(ContactMessagesAdminController.Resend))! + .GetCustomAttribute()!.PolicyName.Should().Be("contact-resend"); + } + + // ---- the host switch on the management side ---- + + private static ResourceExecutingContext ResourceContext() => new( + new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), + new List(), + new List()); + + [Fact] + public void AdminRouteFilter_Answers404_WhileTheHostSwitchIsOff_AndPassesWhenItIsOn() + { + var off = ResourceContext(); + new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = false })).OnResourceExecuting(off); + off.Result.Should().BeOfType(); + + var on = ResourceContext(); + new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = true })).OnResourceExecuting(on); + on.Result.Should().BeNull(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs new file mode 100644 index 0000000..19c8daf --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs @@ -0,0 +1,321 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public sealed class AdminHarness : IDisposable +{ + public static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + public FakeTimeProvider Time { get; } = new(Now); + public ContactOptions Options { get; } = new() { Enabled = true, SiteId = "site-a", RetentionMonths = 12 }; + public ContactDbContext Db { get; } + public IContactMailSender Mail { get; } = Substitute.For(); + public CapturingLoggerProvider Logs { get; } = new(); + public ContactAdminService Sut { get; } + + public AdminHarness() + { + Db = new ContactDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options); + Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Skipped); + + Sut = new ContactAdminService( + new ContactRepository(Db), + Mail, + Microsoft.Extensions.Options.Options.Create(Options), + Time, + LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger()); + } + + public ContactMessage Add( + ContactMessageStatus status = ContactMessageStatus.New, int minutesAgo = 0, string site = "site-a", + string name = "Jan", ContactMailStatus mail = ContactMailStatus.Pending) + { + var message = new ContactMessage + { + Id = Guid.NewGuid(), + SiteId = site, + ReceivedAt = Now.AddMinutes(-minutesAgo), + Name = name, + Email = "jan@example.nl", + Subject = "website", + Message = "Hallo", + Status = status, + MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : mail, + RetentionUntil = status == ContactMessageStatus.Spam ? Now.AddDays(10) : Now.AddMonths(11), + }; + Db.ContactMessages.Add(message); + Db.SaveChanges(); + return message; + } + + public void Dispose() => Db.Dispose(); +} + +public class ContactAdminServiceTests +{ + [Fact] + public async Task TheDefaultList_ExcludesSpam_ShowsTheRest_NewestFirst() + { + using var h = new AdminHarness(); + var oldest = h.Add(ContactMessageStatus.Archived, minutesAgo: 30); + var newest = h.Add(ContactMessageStatus.New, minutesAgo: 1); + var middle = h.Add(ContactMessageStatus.Read, minutesAgo: 10); + h.Add(ContactMessageStatus.Spam, minutesAgo: 0); + + var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + + list!.Items.Select(i => i.Id).Should().Equal(newest.Id.ToString(), middle.Id.ToString(), oldest.Id.ToString()); + list.TotalCount.Should().Be(3); + list.Items.Should().NotContain(i => i.Status == "spam"); + } + + [Theory] + [InlineData("new", "new")] + [InlineData("read", "read")] + [InlineData("archived", "archived")] + [InlineData("spam", "spam")] + [InlineData("SPAM", "spam")] + public async Task AStatusFilter_ShowsOnlyThatStatus(string filter, string expected) + { + using var h = new AdminHarness(); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.Read); + h.Add(ContactMessageStatus.Archived); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + + var list = await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None); + + list!.Items.Should().OnlyContain(i => i.Status == expected); + list.TotalCount.Should().Be(expected == "spam" ? 2 : 1); + } + + [Theory] + [InlineData("converted")] + [InlineData("nonsense")] + public async Task AnUnknownOrUnlistableStatus_IsRejected(string filter) + { + using var h = new AdminHarness(); + + (await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None)).Should().BeNull(); + } + + [Theory] + [InlineData(0, 25)] + [InlineData(-1, 25)] + [InlineData(1, 0)] + [InlineData(1, 101)] + public async Task PageAndPageSize_MustBeInRange(int page, int pageSize) + { + using var h = new AdminHarness(); + + (await h.Sut.ListAsync(null, page, pageSize, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task Paging_ReturnsTheRequestedSliceAndTheTotal() + { + using var h = new AdminHarness(); + for (var i = 0; i < 30; i++) + { + h.Add(ContactMessageStatus.Read, minutesAgo: i); + } + + var third = await h.Sut.ListAsync(null, 3, 10, CancellationToken.None); + var fourth = await h.Sut.ListAsync(null, 4, 10, CancellationToken.None); + + third!.Items.Should().HaveCount(10); + third.Page.Should().Be(3); + third.PageSize.Should().Be(10); + third.TotalCount.Should().Be(30); + fourth!.Items.Should().BeEmpty(); + fourth.TotalCount.Should().Be(30); + third.Items.Select(i => i.ReceivedAt).Should().BeInDescendingOrder(); + } + + [Fact] + public async Task TheUnreadCount_CountsOnlyNew_NeverSpam_AndIgnoresTheFilter() + { + using var h = new AdminHarness(); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.Read); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.New, site: "another-site"); + + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2); + (await h.Sut.ListAsync("spam", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2, "spam does not count and the filter does not matter"); + (await h.Sut.ListAsync("read", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2); + } + + [Fact] + public async Task OtherSitesMessages_AreInvisible() + { + using var h = new AdminHarness(); + var foreign = h.Add(site: "another-site"); + + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.TotalCount.Should().Be(0); + (await h.Sut.GetAsync(foreign.Id, CancellationToken.None)).Should().BeNull(); + (await h.Sut.DeleteAsync(foreign.Id, CancellationToken.None)).Should().BeFalse(); + (await h.Sut.SetStatusAsync(foreign.Id, ContactMessageStatus.Read, CancellationToken.None)).Should().BeNull(); + (await h.Sut.ResendAsync(foreign.Id, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task TheListItems_DoNotCarryTheMessageText_ButTheDetailDoes() + { + using var h = new AdminHarness(); + var message = h.Add(); + + var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + var detail = await h.Sut.GetAsync(message.Id, CancellationToken.None); + + typeof(SlpModularCms.Modules.Contact.Models.ContactMessageListItem).GetProperties().Select(p => p.Name) + .Should().NotContain("Message"); + list!.Items.Single().Name.Should().Be("Jan"); + detail!.Message.Should().Be("Hallo"); + detail.MailAttempts.Should().Be(0); + detail.RetentionUntil.Should().Be(message.RetentionUntil); + detail.Status.Should().Be("new"); + detail.MailStatus.Should().Be("pending"); + } + + [Fact] + public async Task AnUnknownId_GivesNull() + { + using var h = new AdminHarness(); + + (await h.Sut.GetAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull(); + } + + [Theory] + [InlineData(ContactMessageStatus.New)] + [InlineData(ContactMessageStatus.Read)] + [InlineData(ContactMessageStatus.Archived)] + public async Task TheStatusOfARegularMessage_CanBeChanged_WithoutTouchingItsRetention(ContactMessageStatus target) + { + using var h = new AdminHarness(); + var message = h.Add(ContactMessageStatus.Read); + var retention = message.RetentionUntil; + + var result = await h.Sut.SetStatusAsync(message.Id, target, CancellationToken.None); + + result!.Status.Should().Be(target.ToString().ToLowerInvariant()); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).RetentionUntil.Should().Be(retention); + } + + [Fact] + public async Task MarkingSpamAsNotSpam_FollowsTheNormalRetention_AndKeepsMailNotApplicable() + { + using var h = new AdminHarness(); + var spam = h.Add(ContactMessageStatus.Spam); + h.Options.RetentionMonths = 12; + + var result = await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.Read, CancellationToken.None); + + result!.Status.Should().Be("read"); + result.MailStatus.Should().Be("notApplicable"); + result.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12)); + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.Items.Should().ContainSingle(i => i.Id == spam.Id.ToString()); + } + + [Fact] + public async Task Delete_RemovesTheMessageForGood() + { + using var h = new AdminHarness(); + var message = h.Add(); + + (await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeTrue(); + + h.Db.ContactMessages.Should().BeEmpty(); + (await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeFalse(); + } + + [Fact] + public async Task Resend_OfASpamMessage_IsNotAllowed_AndNothingIsSent() + { + using var h = new AdminHarness(); + var spam = h.Add(ContactMessageStatus.Spam); + + var act = () => h.Sut.ResendAsync(spam.Id, CancellationToken.None); + + await act.Should().ThrowAsync(); + await h.Mail.DidNotReceive().SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Resend_RecordsASentMail() + { + using var h = new AdminHarness(); + var message = h.Add(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Sent); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("sent", 1, true)); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailStatus.Should().Be(ContactMailStatus.Sent); + } + + [Fact] + public async Task Resend_RecordsAFailedMail() + { + using var h = new AdminHarness(); + var message = h.Add(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Failed); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("failed", 1, false)); + } + + [Fact] + public async Task Resend_WhenNoMailCanBeSent_ChangesNothing_AndSaysSo() + { + using var h = new AdminHarness(); + var message = h.Add(); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("pending", 0, false)); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailAttempts.Should().Be(0); + } + + [Fact] + public async Task Resend_OfAnUnknownMessage_GivesNull() + { + using var h = new AdminHarness(); + + (await h.Sut.ResendAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task NoPersonalDataIsLogged_ByAnyAdminAction() + { + using var h = new AdminHarness(); + var message = h.Add(name: "ZXQ-Admin-Marker"); + var spam = h.Add(ContactMessageStatus.Spam, name: "ZXQ-Spam-Marker"); + + await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + await h.Sut.GetAsync(message.Id, CancellationToken.None); + await h.Sut.SetStatusAsync(message.Id, ContactMessageStatus.Read, CancellationToken.None); + await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.New, CancellationToken.None); + await h.Sut.ResendAsync(message.Id, CancellationToken.None); + await h.Sut.DeleteAsync(message.Id, CancellationToken.None); + + h.Logs.Messages.Should().NotBeEmpty(); + h.Logs.Messages.Should().NotContain(m => m.Contains("ZXQ") || m.Contains("example.nl") || m.Contains("Hallo")); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs new file mode 100644 index 0000000..8a87e4b --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs @@ -0,0 +1,175 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactSettingsServiceTests +{ + private sealed class Setup : IDisposable + { + public FakeTimeProvider Time { get; } = new(new DateTimeOffset(2026, 11, 9, 12, 0, 0, TimeSpan.Zero)); + public ContactOptions Options { get; } = new() { Enabled = true }; + public ContactDbContext Db { get; } = new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); + public ContactSettingsCache Cache { get; } + public ContactSettingsService Sut { get; } + + public Setup() + { + Cache = new ContactSettingsCache(Time); + Sut = new ContactSettingsService( + new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time); + } + + public void Dispose() => Db.Dispose(); + } + + [Fact] + public async Task WithoutARow_TheSwitchIsOff() + { + using var s = new Setup(); + + (await s.Sut.GetAsync(CancellationToken.None)).Should().Be(new ContactSettingsDto(false, true)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse(); + } + + [Fact] + public async Task HostEnabled_ReflectsTheHostSwitch_ReadOnly() + { + using var s = new Setup(); + s.Options.Enabled = false; + + (await s.Sut.GetAsync(CancellationToken.None)).HostEnabled.Should().BeFalse(); + } + + [Fact] + public async Task SettingTheSwitch_CreatesTheSingletonRow_ThenUpdatesIt_AndRemembersWhoAndWhen() + { + using var s = new Setup(); + var user = Guid.NewGuid(); + + var on = await s.Sut.SetEnabledAsync(true, user, CancellationToken.None); + s.Time.Advance(TimeSpan.FromMinutes(5)); + var off = await s.Sut.SetEnabledAsync(false, Guid.NewGuid(), CancellationToken.None); + + on.Should().Be(new ContactSettingsDto(true, true)); + off.Should().Be(new ContactSettingsDto(false, true)); + var rows = await s.Db.ContactSettings.AsNoTracking().ToListAsync(); + rows.Should().ContainSingle().Which.Id.Should().Be(ContactSettings.SingletonId); + rows[0].Enabled.Should().BeFalse(); + rows[0].UpdatedAt.Should().Be(s.Time.GetUtcNow()); + } + + [Fact] + public async Task TheUserWhoChangedItIsStored() + { + using var s = new Setup(); + var user = Guid.NewGuid(); + + await s.Sut.SetEnabledAsync(true, user, CancellationToken.None); + + (await s.Db.ContactSettings.AsNoTracking().SingleAsync()).UpdatedByUserId.Should().Be(user); + } + + [Fact] + public async Task ThePublicCheck_IsCachedBriefly_AndRefreshedAfterwards() + { + using var s = new Setup(); + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue(); // fills the cache + + // Another instance flips the row behind this one's back. + var row = await s.Db.ContactSettings.SingleAsync(); + row.Enabled = false; + await s.Db.SaveChangesAsync(); + + s.Time.Advance(TimeSpan.FromSeconds(4)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue("still within the cache lifetime"); + + s.Time.Advance(TimeSpan.FromSeconds(2)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse("the cache expired"); + } + + [Fact] + public async Task ChangingTheSwitch_TakesEffectAtOnceInThisProcess() + { + using var s = new Setup(); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse(); // cached: off + + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue(); + } + + [Fact] + public async Task TheAdministratorsOwnView_IsNeverServedFromTheCache() + { + using var s = new Setup(); + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + await s.Sut.IsEnabledAsync(CancellationToken.None); + var row = await s.Db.ContactSettings.SingleAsync(); + row.Enabled = false; + await s.Db.SaveChangesAsync(); + + (await s.Sut.GetAsync(CancellationToken.None)).Enabled.Should().BeFalse(); + } + + [Fact] + public void TheCacheLifetime_IsFiveSeconds() + { + ContactSettingsCache.Lifetime.Should().Be(TimeSpan.FromSeconds(5)); + } +} + +public class ContactFormGateTests +{ + private static IContactFormGate Layer(bool open) + { + var gate = Substitute.For(); + gate.IsOpenAsync(Arg.Any()).Returns(open); + return gate; + } + + [Theory] + [InlineData(true, true, true)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, false)] + public async Task TheFormIsOpen_OnlyWhenEveryLayerIsOpen(bool host, bool cms, bool expected) + { + var gate = new CompositeContactFormGate([Layer(host), Layer(cms)]); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().Be(expected); + } + + [Fact] + public async Task WhenTheFirstLayerIsClosed_TheSecondIsNeverAsked_SoTheDatabaseIsNotTouched() + { + var host = Layer(false); + var cms = Layer(true); + + await new CompositeContactFormGate([host, cms]).IsOpenAsync(CancellationToken.None); + + await host.Received(1).IsOpenAsync(Arg.Any()); + await cms.DidNotReceive().IsOpenAsync(Arg.Any()); + } + + [Fact] + public async Task TheCmsLayer_FollowsTheSettingsService() + { + var settings = Substitute.For(); + settings.IsEnabledAsync(Arg.Any()).Returns(true, false); + var gate = new CmsFlagContactFormGate(settings); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().BeTrue(); + (await gate.IsOpenAsync(CancellationToken.None)).Should().BeFalse(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs new file mode 100644 index 0000000..5e24fdc --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs @@ -0,0 +1,343 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// Mints access tokens the way the host itself does (same settings, same claims). +internal static class Jwt +{ + public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null) + { + var settings = factory.Services.GetRequiredService().GetSection("JwtSettings"); + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings["Secret"]!)); + var token = new JwtSecurityToken( + issuer: settings["Issuer"], + audience: settings["Audience"], + claims: + [ + new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()), + new Claim(ClaimTypes.Role, role), + ], + expires: DateTime.UtcNow.AddHours(1), + signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); + + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token)); + return client; + } + + public static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json"); +} + +public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture +{ + private const string Messages = "/api/v1/contact-messages"; + private const string Settings = "/api/v1/contact-settings"; + + private async Task SeedAsync(ContactMessageStatus status, string name, int minutesAgo = 0) + { + var id = Guid.NewGuid(); + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = id, SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddMinutes(-minutesAgo), + Name = name, Email = "x@example.nl", Subject = "website", Message = "Hallo", + Status = status, + MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11), + }); + await db.SaveChangesAsync(); + return 0; + }); + return id; + } + + // ---- authentication and authorization ---- + + [Theory] + [InlineData("GET", Messages)] + [InlineData("GET", Settings)] + [InlineData("PUT", Settings)] + [InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")] + public async Task EveryManagementRoute_RequiresLogin(string method, string url) + { + var request = new HttpRequestMessage(new HttpMethod(method), url); + if (method is "PUT" or "PATCH") + { + request.Content = Jwt.Json("{}"); + } + + var response = await factory.CreateClient().SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Theory] + [InlineData("GET", Messages)] + [InlineData("GET", Settings)] + [InlineData("PUT", Settings)] + [InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")] + public async Task EveryManagementRoute_IsForbidden_ForARegularUser(string method, string url) + { + var request = new HttpRequestMessage(new HttpMethod(method), url); + if (method is "PUT" or "PATCH") + { + request.Content = Jwt.Json("""{"enabled":true,"status":"read"}"""); + } + + var response = await Jwt.ClientWithRole(factory, "User").SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task APutOnTheSwitchByANonAdmin_Is403_AndChangesNothing() + { + // The other tests in this class may have created the row; what matters is that this call changes nothing. + var before = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync()); + + var response = await Jwt.ClientWithRole(factory, "User").PutAsync(Settings, Jwt.Json("""{"enabled":true}""")); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + var after = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync()); + after.Should().BeEquivalentTo(before); + (await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK); + } + + // ---- the switch ---- + + [Fact] + public async Task TheCmsSwitch_IsOffByDefault_AndTheStateIsReportedWithTheHostSwitch() + { + var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}"""); + } + + [Theory] + [InlineData("""{"enabled":"yes"}""")] + [InlineData("""{"enabled":1}""")] + [InlineData("""{"enabled":null}""")] + [InlineData("{}")] + [InlineData("not json")] + [InlineData("")] + public async Task APutWithoutABoolean_Is400_WithErrorsEnabled(string body) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").PutAsync(Settings, Jwt.Json(body)); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("enabled")[0].GetString().Should().Be("invalid"); + doc.RootElement.GetProperty("errors").EnumerateObject().Should().ContainSingle(); + } + + [Fact] + public async Task TheSwitch_OpensAndClosesThePublicRoutes_AtOnce_WhileTheManagementRoutesKeepWorking() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + var visitor = factory.CreateClient(); + + // Default: closed. 404 with an empty body, the website shows its mailto fallback. + var closed = await visitor.GetAsync($"{Messages}/token"); + closed.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await closed.Content.ReadAsStringAsync()).Should().BeEmpty(); + + var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}""")); + on.StatusCode.Should().Be(HttpStatusCode.OK); + (await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}"""); + (await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK); + + var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}""")); + off.StatusCode.Should().Be(HttpStatusCode.OK); + (await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.NotFound); + var post = await visitor.PostAsync(Messages, Jwt.Json("{}")); + post.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await post.Content.ReadAsStringAsync()).Should().BeEmpty(); + + // The management side is never closed by the CMS switch. + (await admin.GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK); + (await admin.GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task TheUserWhoChangedTheSwitch_IsRecorded() + { + var user = Guid.NewGuid(); + + await Jwt.ClientWithRole(factory, "Owner", user).PutAsync(Settings, Jwt.Json("""{"enabled":false}""")); + + (await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync())).UpdatedByUserId.Should().Be(user); + } + + // ---- messages ---- + + [Fact] + public async Task TheMessageFlow_ListDetailStatusSpamDeleteResend() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + var first = await SeedAsync(ContactMessageStatus.New, "Flow Eerste", minutesAgo: 10); + var second = await SeedAsync(ContactMessageStatus.New, "Flow Tweede", minutesAgo: 5); + var spam = await SeedAsync(ContactMessageStatus.Spam, "Flow Spam", minutesAgo: 1); + + // Default list: no spam; unread counts only the new ones. + using (var list = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync())) + { + var names = list.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()).ToList(); + names.Should().Contain(["Flow Eerste", "Flow Tweede"]).And.NotContain("Flow Spam"); + list.RootElement.GetProperty("unreadCount").GetInt32().Should().BeGreaterThanOrEqualTo(2); + list.RootElement.GetProperty("items")[0].TryGetProperty("message", out _).Should().BeFalse("the list has no message text"); + } + + // Spam apart. + using (var spamList = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?status=spam")).Content.ReadAsStringAsync())) + { + spamList.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()) + .Should().Equal("Flow Spam"); + } + + // Detail. + using (var detail = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}/{first}")).Content.ReadAsStringAsync())) + { + detail.RootElement.GetProperty("message").GetString().Should().Be("Hallo"); + detail.RootElement.GetProperty("status").GetString().Should().Be("new"); + detail.RootElement.GetProperty("mailStatus").GetString().Should().Be("pending"); + } + + // Status change. + var patch = await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"read"}""")); + patch.StatusCode.Should().Be(HttpStatusCode.OK); + (await patch.Content.ReadAsStringAsync()).Should().Contain("\"status\":\"read\""); + (await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"spam"}"""))).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + // Resend: spam is refused, a regular message answers (no mail sender yet: mailed=false). + (await admin.PostAsync($"{Messages}/{spam}/resend", null)).StatusCode.Should().Be(HttpStatusCode.Conflict); + var resend = await admin.PostAsync($"{Messages}/{second}/resend", null); + resend.StatusCode.Should().Be(HttpStatusCode.OK); + (await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false}"""); + + // Not spam after all: now in the default list. + (await admin.PatchAsync($"{Messages}/{spam}", Jwt.Json("""{"status":"archived"}"""))).StatusCode.Should().Be(HttpStatusCode.OK); + using (var again = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync())) + { + again.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()) + .Should().Contain("Flow Spam"); + } + + // Delete. + (await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NoContent); + (await admin.GetAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound); + (await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Theory] + [InlineData("?page=0")] + [InlineData("?pageSize=101")] + [InlineData("?status=bogus")] + [InlineData("?page=abc")] + public async Task ABadListQuery_Is400_InTheContractShape(string query) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages + query); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + } + + [Fact] + public async Task ABadStatusBody_Is400_WithErrorsStatus() + { + var id = await SeedAsync(ContactMessageStatus.New, "Pipeline Patch"); + + var response = await Jwt.ClientWithRole(factory, "Administrator").PatchAsync($"{Messages}/{id}", Jwt.Json("""{"status":"nope"}""")); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("status")[0].GetString().Should().Be("invalid"); + } + + // ---- the availability gate ---- + + [Fact] + public async Task WhenTheCmsIsDisabled_TheManagementRoutesAreBlockedForVisitors_ButNotForAnAdministrator() + { + await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( + "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')")); + + // No marker on the management routes: anonymous callers meet the gate (503), not even a 401. + (await factory.CreateClient().GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await factory.CreateClient().GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await Jwt.ClientWithRole(factory, "User").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + + // By design a verified administrator can always reach a disabled CMS (to switch it back on). + (await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK); + } +} + +public class ContactAdminHostSwitchPipelineTests(DisabledContactHostFactory factory) : IClassFixture +{ + [Theory] + [InlineData("GET", "/api/v1/contact-messages")] + [InlineData("GET", "/api/v1/contact-settings")] + public async Task WhileTheHostSwitchIsOff_TheManagementRoutesAre404_WithAnEmptyBody(string method, string url) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await response.Content.ReadAsStringAsync()).Should().BeEmpty(); + } + + [Fact] + public async Task WhileTheHostSwitchIsOff_AnonymousCallersStillMeetAuthenticationFirst() + { + (await factory.CreateClient().GetAsync("/api/v1/contact-settings")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } +} + +public class ContactResendRateLimitPipelineTests(TightResendContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task Resend_Answers429_WithRetryAfter_AfterItsOwnLimit() + { + var id = Guid.NewGuid(); + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = id, SiteId = "default", ReceivedAt = DateTimeOffset.UtcNow, Name = "n", Email = "e@example.nl", + Subject = "s", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11), + }); + await db.SaveChangesAsync(); + return 0; + }); + var admin = Jwt.ClientWithRole(factory, "Administrator"); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await admin.PostAsync($"/api/v1/contact-messages/{id}/resend", null); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + 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"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs index 0dd3cb1..f26baf0 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs @@ -15,8 +15,31 @@ namespace SlpModularCms.Modules.Contact.Tests.Pipeline; /// databases on. Every factory uses its own freshly created database and drops it again. /// To run only the pure unit tests use --filter "FullyQualifiedName!~Pipeline". /// -public class ContactHostFactory : WebApplicationFactory +public class ContactHostFactory : WebApplicationFactory, IAsyncLifetime { + /// Whether the CMS switch (layer 2 of the gate) is turned on right after start-up. + protected virtual bool OpenCmsSwitch => false; + + Task IAsyncLifetime.InitializeAsync() => OpenCmsSwitch ? OpenCmsSwitchAsync() : Task.CompletedTask; + + Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask; + + private async Task OpenCmsSwitchAsync() + { + _ = CreateClient(); // starts the host (migrates the contact tables) + await WithDb(async db => + { + db.ContactSettings.Add(new Data.Entities.ContactSettings + { + Enabled = true, + UpdatedAt = DateTimeOffset.UtcNow, + UpdatedByUserId = Guid.NewGuid(), + }); + await db.SaveChangesAsync(); + return 0; + }); + } + private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection"; private readonly Dictionary _settings; @@ -83,7 +106,21 @@ public class ContactHostFactory : WebApplicationFactory } } +/// Host switch on, CMS switch ON: the contact form is fully open. public sealed class EnabledContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:SiteId"] = "pipeline-site", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}) +{ + protected override bool OpenCmsSwitch => true; +} + +/// Host switch on, CMS switch OFF (its default): the public routes are closed, the admin routes work. +public sealed class ClosedCmsSwitchContactHostFactory() : ContactHostFactory(new() { ["Contact:Enabled"] = "true", ["Contact:SiteId"] = "pipeline-site", @@ -92,6 +129,7 @@ public sealed class EnabledContactHostFactory() : ContactHostFactory(new() ["RateLimiting:ContactToken:PermitLimit"] = "1000", }); +/// Host switch OFF (the default): the whole module is inactive. public sealed class DisabledContactHostFactory() : ContactHostFactory; /// Only the form policy is tight, so a token can still be fetched freely. @@ -101,7 +139,10 @@ public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new( ["Contact:MinSeconds"] = "0", ["RateLimiting:ContactForm:PermitLimit"] = "2", ["RateLimiting:ContactToken:PermitLimit"] = "1000", -}); +}) +{ + protected override bool OpenCmsSwitch => true; +} /// Only the token policy is tight. public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new() @@ -110,4 +151,14 @@ public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new ["Contact:MinSeconds"] = "0", ["RateLimiting:ContactForm:PermitLimit"] = "1000", ["RateLimiting:ContactToken:PermitLimit"] = "2", +}) +{ + protected override bool OpenCmsSwitch => true; +} + +/// Only the resend policy is tight; the CMS switch is off. +public sealed class TightResendContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["RateLimiting:ContactResend:PermitLimit"] = "2", }); diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs index dc8312a..07787c3 100644 --- a/src/SlpModularCms.Modules.Contact/ContactModule.cs +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -45,8 +45,20 @@ public class ContactModule : IModule services.AddSingleton(); services.AddSingleton(); services.AddScoped(); - services.AddScoped(); + // Gate: the form is open only if the host switch AND the CMS switch are on. The host switch + // is asked first, so with it off the database is never touched. + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(sp => new CompositeContactFormGate( + [ + sp.GetRequiredService(), + sp.GetRequiredService(), + ])); + services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddHostedService(); // The contact details of the OpenAPI document (named options of document 'v1', so the shared @@ -62,6 +74,8 @@ public class ContactModule : IModule Window(config, "ContactForm", 5, 600, context)); limiter.AddPolicy(ContactMessagesController.TokenPolicy, context => Window(config, "ContactToken", 20, 600, context)); + limiter.AddPolicy(ContactMessagesAdminController.ResendPolicy, context => + Window(config, "ContactResend", 5, 600, context)); }); } diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs new file mode 100644 index 0000000..781d903 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs @@ -0,0 +1,164 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// The management routes need the contact tables, which exist only while the host switch +/// (Contact:Enabled) is on. While it is off they answer 404 with an empty body. The CMS +/// switch deliberately does NOT close them: otherwise nobody could switch the form back on. +/// +public sealed class ContactAdminRouteFilter(IOptions options) : IResourceFilter +{ + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (!options.Value.Enabled) + { + context.Result = new NotFoundResult(); + } + } + + public void OnResourceExecuted(ResourceExecutedContext context) + { + } +} + +/// +/// Management of the stored messages. Same resource name as the public routes, no admin segment: +/// access is decided by authorization alone (AdminOnly). Not an [ApiController], like the +/// public controller, so every 400 is in our own problem shape. +/// +[ApiExplorerSettings(IgnoreApi = false)] +[Route("contact-messages")] +[Authorize(Policy = "AdminOnly")] +[ServiceFilter(typeof(ContactAdminRouteFilter))] +public class ContactMessagesAdminController(IContactAdminService service, IOptions options) : ControllerBase +{ + public const string ResendPolicy = "contact-resend"; + + [HttpGet] + [ProducesResponseType(typeof(ContactMessageList), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + public async Task List( + [FromQuery] string? status, [FromQuery] int page = 1, [FromQuery] int pageSize = ContactAdminService.DefaultPageSize, + CancellationToken cancellationToken = default) + { + var invalid = new List(); + foreach (var (key, entry) in ModelState) + { + if (entry.Errors.Count > 0) + { + invalid.Add(key is "page" or "pageSize" or "status" ? key : "query"); + } + } + + if (page < 1 && !invalid.Contains("page")) invalid.Add("page"); + if ((pageSize < 1 || pageSize > ContactAdminService.MaxPageSize) && !invalid.Contains("pageSize")) invalid.Add("pageSize"); + if (!string.IsNullOrWhiteSpace(status) && !ContactStatusNames.TryParseListable(status, out _) && !invalid.Contains("status")) invalid.Add("status"); + + if (invalid.Count > 0) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, invalid.Distinct().ToArray()); + } + + var result = await service.ListAsync(status, page, pageSize, cancellationToken); + return result is null ? ContactProblems.Invalid(options.Value.ProblemTypeBase, "query") : Ok(result); + } + + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Get(Guid id, CancellationToken cancellationToken) + { + var message = await service.GetAsync(id, cancellationToken); + return message is null ? NotFound() : Ok(message); + } + + [HttpPatch("{id:guid}")] + [Consumes("application/json")] + [ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task SetStatus( + Guid id, [FromBody] UpdateContactMessageStatusRequest? request, CancellationToken cancellationToken) + { + if (!ModelState.IsValid || request is null || !ContactStatusNames.TryParseSettable(request.Status, out var status)) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, "status"); + } + + var message = await service.SetStatusAsync(id, status, cancellationToken); + return message is null ? NotFound() : Ok(message); + } + + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken cancellationToken) + => await service.DeleteAsync(id, cancellationToken) ? NoContent() : NotFound(); + + [HttpPost("{id:guid}/resend")] + [EnableRateLimiting(ResendPolicy)] + [ProducesResponseType(typeof(ContactResendResult), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")] + public async Task Resend(Guid id, CancellationToken cancellationToken) + { + try + { + var result = await service.ResendAsync(id, cancellationToken); + return result is null ? NotFound() : Ok(result); + } + catch (ContactResendNotAllowedException ex) + { + return ContactProblems.Conflict(ex.Message); + } + } +} + +/// +/// The CMS switch of the contact form: a singleton resource. The form is open only when this +/// switch AND the host switch are on. Default: off. +/// +[ApiExplorerSettings(IgnoreApi = false)] +[Route("contact-settings")] +[Authorize(Policy = "AdminOnly")] +[ServiceFilter(typeof(ContactAdminRouteFilter))] +public class ContactSettingsController(IContactSettingsService service, IOptions options) : ControllerBase +{ + [HttpGet] + [ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")] + public async Task Get(CancellationToken cancellationToken) + => Ok(await service.GetAsync(cancellationToken)); + + [HttpPut] + [Consumes("application/json")] + [ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + public async Task Put([FromBody] UpdateContactSettingsRequest? request, CancellationToken cancellationToken) + { + // A missing or non-boolean 'enabled' (or an unreadable body) is reported as errors.enabled. + if (!ModelState.IsValid || request?.Enabled is not { } enabled) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, "enabled"); + } + + return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken)); + } + + private Guid CallerId() + { + var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); + return Guid.TryParse(claim, out var id) ? id : Guid.Empty; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs new file mode 100644 index 0000000..8438bdb --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs @@ -0,0 +1,42 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// The problem+json answers of the contact routes, in one place. +internal static class ContactProblems +{ + public const string ContentType = "application/problem+json"; + + /// A 400 with the contract's errors map (field name -> codes). + public static ObjectResult Validation(IReadOnlyDictionary errors, string? typeBase) + { + var baseUri = typeBase?.TrimEnd('/'); + var problem = new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value)) + { + Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation", + Title = "Validation failed", + Status = StatusCodes.Status400BadRequest, + }; + + return new ObjectResult(problem) + { + StatusCode = StatusCodes.Status400BadRequest, + ContentTypes = { ContentType }, + }; + } + + /// A 400 that names the given fields as invalid. + public static ObjectResult Invalid(string? typeBase, params string[] fields) + => Validation(fields.ToDictionary(f => f, _ => new[] { "invalid" }), typeBase); + + public static ObjectResult Conflict(string title) => new(new ProblemDetails + { + Status = StatusCodes.Status409Conflict, + Title = title, + }) + { + StatusCode = StatusCodes.Status409Conflict, + ContentTypes = { ContentType }, + }; +} diff --git a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs index cbb12e4..96930e8 100644 --- a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs +++ b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs @@ -7,6 +7,7 @@ public class ContactDbContext(DbContextOptions options) : DbCo { public DbSet ContactMessages => Set(); public DbSet IdempotencyRecords => Set(); + public DbSet ContactSettings => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -31,6 +32,16 @@ public class ContactDbContext(DbContextOptions options) : DbCo entity.HasIndex(e => e.RetentionUntil); }); + modelBuilder.Entity(entity => + { + entity.ToTable("ContactSettings"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).ValueGeneratedNever(); + entity.Property(e => e.Enabled).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + entity.Property(e => e.UpdatedByUserId).IsRequired(); + }); + modelBuilder.Entity(entity => { entity.ToTable("ContactIdempotency"); diff --git a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs index 82ac5ae..7ae138e 100644 --- a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs +++ b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs @@ -56,3 +56,18 @@ public class IdempotencyRecord public DateTimeOffset CreatedAt { get; set; } public int StatusCode { get; set; } } + +/// +/// The CMS-controlled on/off switch of the contact form (a singleton row, id 1). While no row +/// exists the switch is off. It is the second layer of the gate; the host switch +/// (Contact:Enabled) is the first. +/// +public class ContactSettings +{ + public const int SingletonId = 1; + + public int Id { get; set; } = SingletonId; + public bool Enabled { get; set; } + public DateTimeOffset UpdatedAt { get; set; } + public Guid UpdatedByUserId { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs new file mode 100644 index 0000000..a1c1891 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs @@ -0,0 +1,134 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Contact.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + [DbContext(typeof(ContactDbContext))] + [Migration("20261109202158_AddContactSettings")] + partial class AddContactSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("varchar(254)"); + + b.Property("MailAttempts") + .HasColumnType("int"); + + b.Property("MailError") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("MailStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("varchar(2000)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NextMailAttemptAt") + .HasColumnType("datetime"); + + b.Property("ReceivedAt") + .HasColumnType("datetime"); + + b.Property("RetentionUntil") + .HasColumnType("datetime"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("RetentionUntil"); + + b.HasIndex("SiteId", "Status", "ReceivedAt"); + + b.ToTable("ContactMessages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.Property("UpdatedByUserId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ContactSettings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => + { + b.Property("SiteId") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Key") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.HasKey("SiteId", "Key"); + + b.HasIndex("CreatedAt"); + + b.ToTable("ContactIdempotency", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs new file mode 100644 index 0000000..eed495e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + /// + public partial class AddContactSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ContactSettings", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + Enabled = table.Column(type: "tinyint(1)", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false), + UpdatedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactSettings", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ContactSettings"); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs index 52b5f28..d56a9cb 100644 --- a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs @@ -85,6 +85,25 @@ namespace SlpModularCms.Modules.Contact.Migrations b.ToTable("ContactMessages", (string)null); }); + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.Property("UpdatedByUserId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ContactSettings", (string)null); + }); + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => { b.Property("SiteId") diff --git a/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs b/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs new file mode 100644 index 0000000..9e778d0 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs @@ -0,0 +1,93 @@ +using System.Diagnostics.CodeAnalysis; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Models; + +// JSON shapes of the management routes. Statuses are lower-camel strings: +// status: new | read | archived | spam | converted +// mailStatus: pending | sent | failed | notApplicable + +[ExcludeFromCodeCoverage] +public record ContactMessageListItem( + string Id, + DateTimeOffset ReceivedAt, + string Name, + string Email, + string Subject, + string Status, + string MailStatus); + +[ExcludeFromCodeCoverage] +public record ContactMessageList( + IReadOnlyList Items, + int Page, + int PageSize, + int TotalCount, + int UnreadCount); + +[ExcludeFromCodeCoverage] +public record ContactMessageDetail( + string Id, + DateTimeOffset ReceivedAt, + string Name, + string Email, + string Subject, + string Message, + string Status, + string MailStatus, + int MailAttempts, + string? MailError, + DateTimeOffset RetentionUntil); + +/// Body of PATCH /contact-messages/{id}. Nullable so a missing field is reported in our own shape. +public record UpdateContactMessageStatusRequest(string? Status); + +[ExcludeFromCodeCoverage] +public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed); + +[ExcludeFromCodeCoverage] +public record ContactSettingsDto(bool Enabled, bool HostEnabled); + +/// Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled. +public record UpdateContactSettingsRequest(bool? Enabled); + +/// The wire names of the statuses. +public static class ContactStatusNames +{ + public static string Of(ContactMessageStatus status) => status switch + { + ContactMessageStatus.New => "new", + ContactMessageStatus.Read => "read", + ContactMessageStatus.Archived => "archived", + ContactMessageStatus.Spam => "spam", + ContactMessageStatus.Converted => "converted", + _ => throw new ArgumentOutOfRangeException(nameof(status)), + }; + + public static string Of(ContactMailStatus status) => status switch + { + ContactMailStatus.Pending => "pending", + ContactMailStatus.Sent => "sent", + ContactMailStatus.Failed => "failed", + ContactMailStatus.NotApplicable => "notApplicable", + _ => throw new ArgumentOutOfRangeException(nameof(status)), + }; + + /// Parses a filter value (case-insensitive); only the statuses that can be listed. + public static bool TryParseListable(string? value, out ContactMessageStatus status) + { + status = default; + switch (value?.Trim().ToLowerInvariant()) + { + case "new": status = ContactMessageStatus.New; return true; + case "read": status = ContactMessageStatus.Read; return true; + case "archived": status = ContactMessageStatus.Archived; return true; + case "spam": status = ContactMessageStatus.Spam; return true; + default: return false; + } + } + + /// Parses a value an administrator may set: new, read or archived. + public static bool TryParseSettable(string? value, out ContactMessageStatus status) + => TryParseListable(value, out status) && status != ContactMessageStatus.Spam; +} diff --git a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs index fb26df7..c63ad3f 100644 --- a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs +++ b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs @@ -13,6 +13,21 @@ public interface IContactRepository Task SaveChangesAsync(CancellationToken cancellationToken); Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken); Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + + // ---- management (admin) ---- + + /// One page of messages of the given statuses, newest first, plus the total count of that selection. + Task<(IReadOnlyList Items, int TotalCount)> ListAsync( + string siteId, IReadOnlyCollection statuses, int skip, int take, CancellationToken cancellationToken); + + /// Messages with status New. Spam is never counted. + Task CountUnreadAsync(string siteId, CancellationToken cancellationToken); + + Task GetAsync(string siteId, Guid id, CancellationToken cancellationToken); + void Remove(ContactMessage message); + + Task GetSettingsAsync(CancellationToken cancellationToken); + void Add(ContactSettings settings); } public class ContactRepository(ContactDbContext context) : IContactRepository @@ -33,6 +48,52 @@ public class ContactRepository(ContactDbContext context) : IContactRepository public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken); + public async Task<(IReadOnlyList Items, int TotalCount)> ListAsync( + string siteId, IReadOnlyCollection statuses, int skip, int take, CancellationToken cancellationToken) + { + // One flag per status instead of 'statuses.Contains(m.Status)': the status is stored as a + // string through a value converter, and a parameterized collection loses that mapping in + // the SQL translation. + var wantNew = statuses.Contains(ContactMessageStatus.New); + var wantRead = statuses.Contains(ContactMessageStatus.Read); + var wantArchived = statuses.Contains(ContactMessageStatus.Archived); + var wantSpam = statuses.Contains(ContactMessageStatus.Spam); + var wantConverted = statuses.Contains(ContactMessageStatus.Converted); + + var query = context.ContactMessages + .AsNoTracking() + .Where(m => m.SiteId == siteId + && ((wantNew && m.Status == ContactMessageStatus.New) + || (wantRead && m.Status == ContactMessageStatus.Read) + || (wantArchived && m.Status == ContactMessageStatus.Archived) + || (wantSpam && m.Status == ContactMessageStatus.Spam) + || (wantConverted && m.Status == ContactMessageStatus.Converted))); + + var total = await query.CountAsync(cancellationToken); + var items = await query + .OrderByDescending(m => m.ReceivedAt) + .ThenBy(m => m.Id) + .Skip(skip) + .Take(take) + .ToListAsync(cancellationToken); + + return (items, total); + } + + public Task CountUnreadAsync(string siteId, CancellationToken cancellationToken) + => context.ContactMessages.CountAsync( + m => m.SiteId == siteId && m.Status == ContactMessageStatus.New, cancellationToken); + + public Task GetAsync(string siteId, Guid id, CancellationToken cancellationToken) + => context.ContactMessages.FirstOrDefaultAsync(m => m.SiteId == siteId && m.Id == id, cancellationToken); + + public void Remove(ContactMessage message) => context.ContactMessages.Remove(message); + + public Task GetSettingsAsync(CancellationToken cancellationToken) + => context.ContactSettings.FirstOrDefaultAsync(s => s.Id == ContactSettings.SingletonId, cancellationToken); + + public void Add(ContactSettings settings) => context.ContactSettings.Add(settings); + public async Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken) { var total = 0; diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs new file mode 100644 index 0000000..7cc1c55 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs @@ -0,0 +1,151 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// Thrown when a spam message is resent; it must be marked as not spam first. +public sealed class ContactResendNotAllowedException() : Exception("A spam message cannot be resent; mark it as not spam first."); + +public interface IContactAdminService +{ + /// Null when page or pageSize is out of range or the status filter is unknown (the caller reports 400). + Task ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken); + + Task GetAsync(Guid id, CancellationToken cancellationToken); + + /// Null when the message does not exist. + Task SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken); + + Task DeleteAsync(Guid id, CancellationToken cancellationToken); + + /// Null when the message does not exist. Throws for spam. + Task ResendAsync(Guid id, CancellationToken cancellationToken); +} + +/// +/// Everything an administrator does with the stored messages. Spam is kept apart: it is never in +/// the default list and never counted as unread. Nothing personal is logged, only ids and outcomes. +/// +public sealed class ContactAdminService( + IContactRepository repository, + IContactMailSender mailSender, + IOptions options, + TimeProvider time, + ILogger logger) : IContactAdminService +{ + public const int DefaultPageSize = 25; + public const int MaxPageSize = 100; + + private static readonly ContactMessageStatus[] DefaultStatuses = + [ContactMessageStatus.New, ContactMessageStatus.Read, ContactMessageStatus.Archived]; + + public async Task ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken) + { + if (page < 1 || pageSize < 1 || pageSize > MaxPageSize) + { + return null; + } + + ContactMessageStatus[] statuses; + if (string.IsNullOrWhiteSpace(status)) + { + statuses = DefaultStatuses; + } + else if (ContactStatusNames.TryParseListable(status, out var parsed)) + { + statuses = [parsed]; + } + else + { + return null; + } + + var siteId = options.Value.EffectiveSiteId; + var (items, total) = await repository.ListAsync(siteId, statuses, (page - 1) * pageSize, pageSize, cancellationToken); + var unread = await repository.CountUnreadAsync(siteId, cancellationToken); + + return new ContactMessageList( + items.Select(m => new ContactMessageListItem( + m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, + ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus))).ToList(), + page, pageSize, total, unread); + } + + public async Task GetAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + return message is null ? null : ToDetail(message); + } + + public async Task SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return null; + } + + // Marking a spam message as read/new/archived means "this was a real person": it then + // follows the normal retention instead of being deleted after the short spam period. + if (message.Status == ContactMessageStatus.Spam) + { + message.RetentionUntil = time.GetUtcNow().AddMonths(options.Value.RetentionMonths); + } + + message.Status = status; + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Contact message {MessageId} set to {Status}", message.Id, status); + return ToDetail(message); + } + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return false; + } + + repository.Remove(message); + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Contact message {MessageId} deleted", id); + return true; + } + + public async Task ResendAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return null; + } + + if (message.Status == ContactMessageStatus.Spam) + { + throw new ContactResendNotAllowedException(); + } + + var outcome = await mailSender.SendAsync(message, cancellationToken); + if (outcome != ContactMailOutcome.Skipped) + { + message.MailAttempts++; + message.MailStatus = outcome == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed; + await repository.SaveChangesAsync(cancellationToken); + } + + logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, outcome); + return new ContactResendResult( + ContactStatusNames.Of(message.MailStatus), message.MailAttempts, outcome == ContactMailOutcome.Sent); + } + + private static ContactMessageDetail ToDetail(ContactMessage m) => new( + m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, m.Message, + ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus), + m.MailAttempts, m.MailError, m.RetentionUntil); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs new file mode 100644 index 0000000..f458337 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs @@ -0,0 +1,126 @@ +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// The latest known value of the CMS switch, shared by all requests of this process. Short-lived +/// so the public routes do not query the database on every request, and dropped immediately when +/// the switch is changed here (other instances see a change after at most ). +/// +public sealed class ContactSettingsCache(TimeProvider time) +{ + public static readonly TimeSpan Lifetime = TimeSpan.FromSeconds(5); + + private readonly object _lock = new(); + private bool _value; + private DateTimeOffset _expires = DateTimeOffset.MinValue; + + public bool TryGet(out bool enabled) + { + lock (_lock) + { + enabled = _value; + return time.GetUtcNow() < _expires; + } + } + + public void Set(bool enabled) + { + lock (_lock) + { + _value = enabled; + _expires = time.GetUtcNow() + Lifetime; + } + } + + public void Invalidate() + { + lock (_lock) + { + _expires = DateTimeOffset.MinValue; + } + } +} + +public interface IContactSettingsService +{ + /// The CMS switch (a missing row means off). + Task IsEnabledAsync(CancellationToken cancellationToken); + + Task GetAsync(CancellationToken cancellationToken); + Task SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken); +} + +public sealed class ContactSettingsService( + IContactRepository repository, + ContactSettingsCache cache, + IOptions options, + TimeProvider time) : IContactSettingsService +{ + public async Task IsEnabledAsync(CancellationToken cancellationToken) + { + if (cache.TryGet(out var cached)) + { + return cached; + } + + var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false; + cache.Set(enabled); + return enabled; + } + + public async Task GetAsync(CancellationToken cancellationToken) + { + // The administrator's own view is never served from the cache. + var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false; + return new ContactSettingsDto(enabled, options.Value.Enabled); + } + + public async Task SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken) + { + var settings = await repository.GetSettingsAsync(cancellationToken); + if (settings is null) + { + settings = new ContactSettings(); + repository.Add(settings); + } + + settings.Enabled = enabled; + settings.UpdatedAt = time.GetUtcNow(); + settings.UpdatedByUserId = userId; + await repository.SaveChangesAsync(cancellationToken); + + cache.Invalidate(); + return new ContactSettingsDto(enabled, options.Value.Enabled); + } +} + +/// Layer 2: the switch an administrator controls in the CMS. +public sealed class CmsFlagContactFormGate(IContactSettingsService settings) : IContactFormGate +{ + public Task IsOpenAsync(CancellationToken cancellationToken) => settings.IsEnabledAsync(cancellationToken); +} + +/// +/// The form is open only if every layer is open. Layers are asked in order and the first closed +/// one ends the check, so with the host switch off the database is never touched. +/// +public sealed class CompositeContactFormGate(IReadOnlyList layers) : IContactFormGate +{ + public async Task IsOpenAsync(CancellationToken cancellationToken) + { + foreach (var layer in layers) + { + if (!await layer.IsOpenAsync(cancellationToken)) + { + return false; + } + } + + return true; + } +}