diff --git a/SlpModularCms.sln b/SlpModularCms.sln index aa999db..8ca0860 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -42,6 +42,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlo EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -244,6 +248,30 @@ Global {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -267,5 +295,7 @@ Global {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894} {759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} + {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894} EndGlobalSection EndGlobal diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 6671b79..cfdeda6 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-U3 Code Generation Part 1 (plan awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U3 built and committed (awaiting review); next CMS-U3b plan, then CMS-U4 - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md new file mode 100644 index 0000000..3dd97e4 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md @@ -0,0 +1,55 @@ +# CMS-U3 contact-core: code summary + +## What it delivers +New module `SlpModularCms.Modules.Contact` (+ `.Contact.Tests`), referenced by `Api.SlpSoftware` only. + +Public routes (both anonymous, `[PublicSiteEndpoint]`, reachable while the CMS is off): +- `GET /api/v1/contact-messages/token` -> `{ token, minSeconds, captcha }` (`captcha` is null unless enabled; the secret is never returned). Rate limit policy `contact-token`. +- `POST /api/v1/contact-messages` with header `Idempotency-Key: ` and body `{ name, email, subject, message, hpCheck, token, captchaToken? }` -> `202 { "status": "received" }` for genuine messages, spam and replays alike. Policy `contact-form`. Errors: `400` (`errors` per field with codes `required|tooLong|invalid|expired`, also `idempotencyKey` and `body`), `413` (problem+json), `429` (Retry-After, problem+json), `404` empty body while the form is closed. + +Behaviour: validation (limits 100/254/100/2000, e-mail regex, control characters rejected, fields trimmed) -> replay check (same key within 24 h answers 202 without a second row; a rejected request does not use up its key) -> token (forged, other-site, garbage and expired all answer `errors.token=["expired"]`: no oracle) -> classification: too-young token (< `MinSeconds`), filled `hpCheck`, or a rejected captcha is spam -> store (genuine: `New`, mail `Pending`, retention 12 months; spam: `Spam`, mail `NotApplicable`, 30 days, per-site daily cap 200 beyond which it is answered but not stored) -> after commit the mail seam `IContactMailSender` (no-op until the mail unit: result `Skipped`, message stays `Pending`). A mail problem never fails the request. Daily retention job removes expired messages and idempotency records older than 24 h. Site id comes from configuration, never from the request; no IP address is stored. + +## RELEASE CONDITION (unchanged, now enforced in code) +On the base branch the rate-limit policies are shared buckets (no per-client key, no forwarded-header handling). The contact routes therefore stay **closed** (`Contact:Enabled=false`, 404 with empty body, no database access, retention job idle) until the per-client partitioning from the ASF branch is on the base branch. Do not enable on a public host before that. + +## Gate design (two layers, per the later decision) +Route filter `ContactRouteFilter` asks `IContactFormGate.IsOpenAsync`. Today the only layer is `HostFlagContactFormGate` (`Contact:Enabled`). CMS-U4 adds the CMS-controlled switch (`/api/v1/contact-settings`) as a second layer by replacing the registration with a composite gate; the filter is not touched. The form is active only if every layer is open; otherwise 404 empty body (the website shows its mailto fallback). + +## REBASE CHECKLIST (after the ASF merge) +1. `src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs`, class `ContactRateLimitPartition`: change the single line `public static string KeyFor(HttpContext context) => GlobalKey;` to `public static string KeyFor(HttpContext context) => ClientPartitionKey.For(context);` (add the ASF `using`). Remove the `GlobalKey` constant if it is no longer used. +2. `src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs`, test `OnTheBaseBranch_EveryCallerSharesOneBucket`: replace it with "two different client addresses give two different keys" (the same two addresses are already in the test). +3. Make sure `ForwardedHeaders:KnownProxies` is configured on the host (environment). +4. Regenerate/verify migrations only if a snapshot conflicts (Contact has its own context and history, so none is expected). Re-run all test projects. +5. Only then set `Contact:Enabled=true` on the host (environment or appsettings of that host). + +## `Contact:*` configuration (keys and defaults; `Api.SlpSoftware/appsettings.json` carries them) +| Key | Default | Notes | +|---|---|---| +| `Contact:Enabled` | `false` | host switch / release condition | +| `Contact:SiteId` | `slpsoftware` in appsettings; `default` if unset | stored on rows, bound into the token purpose; never from a request | +| `Contact:MinSeconds` | `3` | returned to the client as `minSeconds`; faster = spam | +| `Contact:TokenLifetimeMinutes` | `120` | | +| `Contact:RetentionMonths` | `12` | per row at insert; no retroactive change | +| `Contact:SpamRetentionDays` | `30` | | +| `Contact:MaxSpamRowsPerDay` | `200` | per site per UTC day | +| `Contact:MaxBodyBytes` | `16384` | 413 beyond | +| `Contact:ProblemTypeBase` | none -> `about:blank` | base for the validation problem `type` (`{base}/validation`) | +| `Contact:Captcha:Enabled` | `false` | | +| `Contact:Captcha:Provider` / `SiteKey` | none | returned in the token response when enabled | +| `Contact:Captcha:Secret` | none | env / secrets manager only, never committed | +| `RateLimiting:ContactForm:PermitLimit` / `WindowSeconds` | `5` / `600` | | +| `RateLimiting:ContactToken:PermitLimit` / `WindowSeconds` | `20` / `600` | | + +## Deviations from the contract / design (for SLS to adopt) +- The honeypot JSON name is fixed `hpCheck` (no `Contact:HoneypotField`): the payload shape is a contract matter; the site's DOM name is free. A missing `hpCheck` key counts as empty (lenient) instead of a `required` error, so a real client that omits it is not rejected and a bot learns no field name from an error. +- Unbindable bodies (malformed JSON, wrong types) answer `400` with `errors.body=["invalid"]` in the same problem shape (the controller is deliberately not an `[ApiController]`). +- Validation problem `type` is configurable (`Contact:ProblemTypeBase`), default `about:blank` (approved). + +## Privacy / logging +Only the outcome (`Genuine|Spam|SpamNotStored|Replay`) and the site id are logged; mail failures are logged by exception type only. Tests prove that no name, e-mail, subject, message, captcha token, Idempotency-Key or token appears in any log entry (genuine, spam, replay, invalid, forged token, mail exception with personal data in its message, database exception). Sentry: request bodies are never captured (`MaxRequestBodySize=None`) and the existing scrubber nulls `Request.Data`. Note: like for every endpoint, a Sentry error event carries the caller's IP address (`SendDefaultPii`); nothing from the form body is in it. + +## Verification (real output) +Build 0 errors. Contact.Tests 113 passed (unit and pipeline), Core 205, Availability 95 (route table now allows exactly GetOfferings + GetToken + Submit), Offerings 86, Identity 37, Master 57, Api.Tests 4 — all against a temporary MariaDB (removed afterwards). Pipeline tests start the real SlpSoftware host: disabled -> both routes 404 empty and the contact tables do not even exist (the module never touched the database; the retention tick changes nothing); enabled -> token 200, valid POST 202 stored once, replay 202 without a second row, honeypot 202 identical body but stored as Spam, 400 shapes, 413, malformed bodies without echo, 429 with Retry-After for both policies, routes reachable while the CMS is disabled (and `/offerings/categories` 503), migration applied on a real MariaDB with a unique (site, key) constraint, retention job deletes expired rows. Each pipeline fixture creates and drops its own database. + +## Running the tests +The `Pipeline` tests need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (same requirement as `Api.Tests`). Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md index 011584f..88c8226 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md @@ -36,14 +36,14 @@ On master the rate-limit policies are global buckets (no per-client partition ke `Enabled=false`, `SiteId`, `MinSeconds=3`, `TokenLifetimeMinutes=120`, `RetentionMonths=12`, `SpamRetentionDays=30`, `MaxSpamRowsPerDay=200`, `MaxBodyBytes=16384`, `HoneypotField=hpCheck`, `Captcha:{Enabled=false,Provider,SiteKey,Secret}`; `RateLimiting:ContactForm` (5/600), `RateLimiting:ContactToken` (20/600). Recipient/sender e-mail addresses are not part of U3 (U5, env-only for ASF). `appsettings.json` of `Api.SlpSoftware` gets the section with `Enabled=false`; no addresses, no secrets. ## Steps -- [ ] **Step 1 — Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes. -- [ ] **Step 2 — Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification). -- [ ] **Step 3 — Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation. -- [ ] **Step 4 — Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service. -- [ ] **Step 5 — Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list). -- [ ] **Step 6 — Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency). -- [ ] **Step 7 — Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported. -- [ ] **Step 8 — Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push. +- [x] **Step 1 — Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes. +- [x] **Step 2 — Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification). +- [x] **Step 3 — Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation. +- [x] **Step 4 — Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service. +- [x] **Step 5 — Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list). +- [x] **Step 6 — Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency). +- [x] **Step 7 — Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported. +- [x] **Step 8 — Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push. ## Explicitly NOT touched `AddCmsRateLimiting`/Core hosting files, `AvailabilityMiddleware`, Email, Identity, ASF-owned areas, host Program.cs, frontend, the Andrea host. No admin endpoints (CMS-U4), no mail sending (CMS-U5), no OpenAPI export (CMS-U3b). diff --git a/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs new file mode 100644 index 0000000..5d379c2 --- /dev/null +++ b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs @@ -0,0 +1,3 @@ +// Exposes the top-level-statements Program class so WebApplicationFactory can start the +// composed host in tests (same approach as SlpModularCms.Api/Program.Coverage.cs). +public partial class Program { } diff --git a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj index 3f43383..bad6be2 100644 --- a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj +++ b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj @@ -20,6 +20,7 @@ + diff --git a/src/SlpModularCms.Api.SlpSoftware/appsettings.json b/src/SlpModularCms.Api.SlpSoftware/appsettings.json index f4dbb4b..8f96bf6 100644 --- a/src/SlpModularCms.Api.SlpSoftware/appsettings.json +++ b/src/SlpModularCms.Api.SlpSoftware/appsettings.json @@ -61,6 +61,22 @@ "Cors": { "AllowedOrigins": [] }, + "Contact": { + // OFF by default. Do not enable on a public host until per-client rate limiting is on the + // base branch (see ContactRateLimitPartition): until then the contact rate limits are one + // bucket shared by all visitors. + "Enabled": false, + "SiteId": "slpsoftware", + "MinSeconds": 3, + "TokenLifetimeMinutes": 120, + "RetentionMonths": 12, + "SpamRetentionDays": 30, + "MaxSpamRowsPerDay": 200, + "MaxBodyBytes": 16384, + "Captcha": { + "Enabled": false + } + }, "RateLimiting": { "Login": { "PermitLimit": 5, @@ -77,6 +93,14 @@ "OfferingsPublic": { "PermitLimit": 120, "WindowSeconds": 60 + }, + "ContactForm": { + "PermitLimit": 5, + "WindowSeconds": 600 + }, + "ContactToken": { + "PermitLimit": 20, + "WindowSeconds": 600 } }, "SecurityHeaders": { diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs index 851d37c..a2e2a84 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -13,6 +13,7 @@ using SlpModularCms.Core.Observability; using SlpModularCms.Modules.Availability.Controllers; using SlpModularCms.Modules.Availability.Middleware; using SlpModularCms.Modules.Availability.Services; +using SlpModularCms.Modules.Contact.Controllers; using SlpModularCms.Modules.Identity.Controllers; using SlpModularCms.Modules.Master.Controllers; using SlpModularCms.Modules.Offerings.Controllers; @@ -158,6 +159,8 @@ public class PublicSiteEndpointGateTests private static readonly string[] AllowedPublicActions = [ $"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}", ]; private static IReadOnlyList AllActions() => @@ -167,6 +170,7 @@ public class PublicSiteEndpointGateTests typeof(UsersController).Assembly, typeof(CmsInstanceController).Assembly, typeof(OfferingsController).Assembly, + typeof(ContactMessagesController).Assembly, typeof(SystemController).Assembly, } .Distinct() diff --git a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj index 112f182..cefb9db 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj +++ b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj @@ -34,6 +34,7 @@ + diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs new file mode 100644 index 0000000..05d2831 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs @@ -0,0 +1,292 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +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.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactMessagesControllerTests +{ + private readonly IContactTokenService _tokens = Substitute.For(); + private readonly IContactSubmissionService _submissions = Substitute.For(); + + private ContactMessagesController Create(ContactOptions? options = null, string? idempotencyKey = null) + { + var controller = new ContactMessagesController(_tokens, _submissions, Options.Create(options ?? new ContactOptions { Enabled = true })) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + if (idempotencyKey is not null) + { + controller.Request.Headers[ContactMessagesController.IdempotencyKeyHeader] = idempotencyKey; + } + + return controller; + } + + [Fact] + public void GetToken_ReturnsTheTokenTheMinimumTime_AndNoCaptchaByDefault() + { + _tokens.Issue().Returns("tok"); + + var result = Create(new ContactOptions { Enabled = true, MinSeconds = 5 }).GetToken(); + + var body = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + body.Should().Be(new ContactTokenResponse("tok", 5, null)); + } + + [Fact] + public void GetToken_ReportsTheCaptchaProviderAndSiteKey_WhenEnabled_ButNeverTheSecret() + { + _tokens.Issue().Returns("tok"); + var options = new ContactOptions + { + Enabled = true, + Captcha = new ContactCaptchaOptions { Enabled = true, Provider = "friendlycaptcha", SiteKey = "pub", Secret = "very-secret" }, + }; + + var result = Create(options).GetToken(); + + var body = (ContactTokenResponse)((OkObjectResult)result).Value!; + body.Captcha.Should().Be(new ContactCaptchaInfo("friendlycaptcha", "pub")); + System.Text.Json.JsonSerializer.Serialize(body).Should().NotContain("very-secret"); + } + + [Fact] + public async Task Submit_Returns202_WithTheFixedBody_WhenReceived() + { + _submissions.SubmitAsync(Arg.Any(), "key", Arg.Any()) + .Returns(new SubmissionResult.Received()); + + var result = await Create(idempotencyKey: "key").Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None); + + var obj = result.Should().BeOfType().Subject; + obj.StatusCode.Should().Be(202); + obj.Value.Should().Be(new ReceivedResponse("received")); + } + + [Fact] + public async Task Submit_Returns400_WithTheErrorsShape_AndTheConfiguredTypeBase() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["email"] = ["invalid"] })); + + var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" }) + .Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None); + + var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + problem.Status.Should().Be(400); + problem.Type.Should().Be("https://example.test/problems/validation"); + problem.Errors["email"].Should().Equal("invalid"); + } + + [Fact] + public async Task Submit_UsesAboutBlank_WhenNoTypeBaseIsConfigured() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["name"] = ["required"] })); + + var result = await Create().Submit(null, CancellationToken.None); + + ((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank"); + } + + [Fact] + public async Task Submit_PassesNull_WhenTheBodyCouldNotBeBound() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["body"] = ["invalid"] })); + var controller = Create(); + controller.ModelState.AddModelError("$.name", "The JSON value could not be converted"); + + await controller.Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None); + + await _submissions.Received(1).SubmitAsync(null, Arg.Any(), Arg.Any()); + } + + [Fact] + public void TheRouteTable_HasTwoPublicRoutes_BothMarkedAnonymousAndRateLimited_AndNoAdminSegment() + { + var type = typeof(ContactMessagesController); + type.GetCustomAttribute()!.Template.Should().Be("contact-messages"); + type.GetCustomAttribute().Should().BeNull(); + type.GetCustomAttribute().Should().BeNull("the management routes arrive with the admin unit"); + + var actions = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(m => m.GetCustomAttributes().Any()) + .ToDictionary(m => $"{m.GetCustomAttribute()!.HttpMethods.Single()} {m.GetCustomAttribute()!.Template}".Trim()); + + actions.Keys.Should().BeEquivalentTo(["GET token", "POST"]); + foreach (var action in actions.Values) + { + action.GetCustomAttribute().Should().NotBeNull(); + action.GetCustomAttribute().Should().NotBeNull(); + } + + actions["GET token"].GetCustomAttribute()!.PolicyName.Should().Be("contact-token"); + actions["POST"].GetCustomAttribute()!.PolicyName.Should().Be("contact-form"); + type.GetCustomAttribute()!.ServiceType.Should().Be(typeof(ContactRouteFilter)); + } +} + +public class ContactRouteFilterTests +{ + private static ResourceExecutingContext Context(string method, long? contentLength = null, IHttpMaxRequestBodySizeFeature? feature = null) + { + var http = new DefaultHttpContext(); + http.Request.Method = method; + http.Request.ContentLength = contentLength; + if (feature is not null) + { + http.Features.Set(feature); + } + + return new ResourceExecutingContext( + new ActionContext(http, new RouteData(), new ActionDescriptor()), + new List(), + new List()); + } + + private static ContactRouteFilter Create(bool enabled, int max = 1000) + { + var options = Options.Create(new ContactOptions { Enabled = enabled, MaxBodyBytes = max }); + return new ContactRouteFilter(new HostFlagContactFormGate(options), options); + } + + private static ContactRouteFilter CreateWithGate(bool open, int max = 1000) + { + var gate = Substitute.For(); + gate.IsOpenAsync(Arg.Any()).Returns(open); + return new ContactRouteFilter(gate, Options.Create(new ContactOptions { Enabled = true, MaxBodyBytes = max })); + } + + [Theory] + [InlineData("GET", false)] + [InlineData("POST", false)] + [InlineData("GET", true)] + [InlineData("POST", true)] + public async Task TheFilter_FollowsTheGateOnly_SoAnotherLayerCanBeAddedWithoutTouchingIt(string method, bool open) + { + var context = Context(method); + var nextCalled = false; + + await CreateWithGate(open).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Next(context)(); + }); + + nextCalled.Should().Be(open); + (context.Result is NotFoundResult).Should().Be(!open); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task TheHostFlagGate_ReflectsContactEnabled(bool enabled) + { + var gate = new HostFlagContactFormGate(Options.Create(new ContactOptions { Enabled = enabled })); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().Be(enabled); + } + + private static ResourceExecutionDelegate Next(ResourceExecutingContext context, Exception? exception = null) + => () => Task.FromResult(new ResourceExecutedContext(context, new List()) { Exception = exception }); + + [Theory] + [InlineData("GET")] + [InlineData("POST")] + public async Task WhileDisabled_BothRoutesAre404_AndNothingFurtherRuns(string method) + { + var context = Context(method); + var nextCalled = false; + + await Create(enabled: false).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Task.FromResult(null!); + }); + + context.Result.Should().BeOfType(); + nextCalled.Should().BeFalse(); + } + + [Fact] + public async Task APostBeyondTheLimit_Gets413_AsProblemJson() + { + var context = Context("POST", contentLength: 1001); + + await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, Next(context)); + + var result = context.Result.Should().BeOfType().Subject; + result.StatusCode.Should().Be(413); + result.ContentTypes.Should().Contain("application/problem+json"); + result.Value.Should().BeOfType().Which.Status.Should().Be(413); + } + + [Fact] + public async Task APostWithinTheLimit_PassesThrough_AndLimitsChunkedBodies() + { + var feature = Substitute.For(); + feature.IsReadOnly.Returns(false); + var context = Context("POST", contentLength: 1000, feature: feature); + var nextCalled = false; + + await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Next(context)(); + }); + + nextCalled.Should().BeTrue(); + context.Result.Should().BeNull(); + feature.MaxRequestBodySize.Should().Be(1000); + } + + [Fact] + public async Task ABodyThatTurnsOutTooLargeWhileReading_BecomesA413() + { + var context = Context("POST"); + ResourceExecutedContext? executed = null; + + await Create(enabled: true).OnResourceExecutionAsync(context, async () => + { + executed = await Next( + context, + new BadHttpRequestException("too large", StatusCodes.Status413PayloadTooLarge))(); + return executed; + }); + + executed!.ExceptionHandled.Should().BeTrue(); + executed.Result.Should().BeOfType().Which.StatusCode.Should().Be(413); + } + + [Fact] + public async Task OtherExceptions_AreLeftAlone() + { + var context = Context("POST"); + ResourceExecutedContext? executed = null; + + await Create(enabled: true).OnResourceExecutionAsync(context, async () => + { + executed = await Next(context, new InvalidOperationException("boom"))(); + return executed; + }); + + executed!.ExceptionHandled.Should().BeFalse(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs new file mode 100644 index 0000000..8e0a352 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs @@ -0,0 +1,92 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +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; + +/// +/// Nothing a visitor typed, and nothing that identifies a request (the Idempotency-Key and the +/// token are no personal data, but there is no reason to log them either), may ever appear in a log. +/// +public class ContactNoPersonalDataInLogsTests +{ + private const string MarkerName = "ZXQ-Name-Marker"; + private const string MarkerEmail = "zxq-marker@example.test"; + private const string MarkerSubject = "ZXQ-Subject-Marker"; + private const string MarkerMessage = "ZXQ-Message-Marker"; + + private static ContactMessageRequest Marked(string token, string hp = "") => + new(MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, hp, token, "ZXQ-Captcha-Marker"); + + private static void AssertClean(SubmissionHarness h, params string[] extraForbidden) + { + var forbidden = new[] { MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, "ZXQ-Captcha-Marker", "ZXQ-" } + .Concat(extraForbidden).ToArray(); + + h.Logs.Messages.Should().NotBeEmpty("outcomes are logged"); + foreach (var message in h.Logs.Messages) + { + foreach (var marker in forbidden) + { + message.Should().NotContain(marker); + } + } + } + + [Fact] + public async Task GenuineSpamReplayAndInvalid_LogNothingPersonal_NoKeyAndNoToken() + { + using var h = new SubmissionHarness(o => o.Captcha.Enabled = true); + var key = Guid.NewGuid().ToString(); + var token = h.MatureToken(); + + await h.Submit(Marked(token), key); // genuine + await h.Submit(Marked(token), key); // replay + await h.Submit(Marked(h.MatureToken(), hp: "ZXQ-Honeypot")); // spam + await h.Submit(Marked(token) with { Email = "ZXQ-not-an-address" }); // invalid fields + await h.Submit(Marked("ZXQ-forged-token")); // forged token + + AssertClean(h, key, token, "ZXQ-Honeypot"); + } + + [Fact] + public async Task AMailFailureWithPersonalDataInItsMessage_IsLoggedByTypeOnly() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException($"cannot deliver to {MarkerEmail}: {MarkerMessage}")); + + await h.Submit(Marked(h.MatureToken())); + + AssertClean(h); + h.Logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException))); + } + + [Fact] + public async Task ADatabaseFailureWithPersonalDataInItsMessage_DoesNotLeakThroughTheServiceLogs() + { + var repository = Substitute.For(); + repository.SaveChangesAsync(Arg.Any()).ThrowsAsync(new DbUpdateException("duplicate")); + using var h = new SubmissionHarness(repositoryOverride: repository); + + await h.Submit(Marked(h.MatureToken())); + + AssertClean(h); + } + + [Fact] + public async Task TheOutcomeLogLines_CarryOnlyTheOutcomeAndTheSiteId() + { + using var h = new SubmissionHarness(); + + await h.Submit(Marked(h.MatureToken())); + + h.Logs.Messages.Should().ContainSingle() + .Which.Should().Be("Contact submission handled: Genuine for site site-a"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs new file mode 100644 index 0000000..915781e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs @@ -0,0 +1,144 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +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 class ContactRetentionServiceTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + private static ContactMessage Message(string name, DateTimeOffset retentionUntil) => new() + { + Id = Guid.NewGuid(), SiteId = "s", ReceivedAt = Now.AddDays(-1), Name = name, Email = "a@b.nl", + Subject = "x", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = retentionUntil, + }; + + private static (ContactRetentionService Sut, ServiceProvider Provider, string Db) Create(bool enabled) + { + var databaseName = Guid.NewGuid().ToString(); + var services = new ServiceCollection(); + services.AddDbContext(o => o.UseInMemoryDatabase(databaseName)); + services.AddScoped(); + var provider = services.BuildServiceProvider(); + + var sut = new ContactRetentionService( + provider.GetRequiredService(), + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = enabled }), + new FakeTimeProvider(Now), + NullLogger.Instance); + return (Sut: sut, Provider: provider, Db: databaseName); + } + + [Fact] + public async Task DeletesExpiredMessagesAndOldIdempotencyRecords_AndKeepsTheRest() + { + var (sut, provider, _) = Create(enabled: true); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.ContactMessages.AddRange( + Message("expired", Now.AddSeconds(-1)), + Message("expired too", Now.AddDays(-30)), + Message("kept", Now.AddDays(1)), + Message("kept long", Now.AddMonths(11))); + db.IdempotencyRecords.AddRange( + new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-25), StatusCode = 202 }, + new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-23), StatusCode = 202 }); + await db.SaveChangesAsync(); + } + + await sut.ExecuteTickAsync(CancellationToken.None); + + await using var check = provider.CreateAsyncScope(); + var after = check.ServiceProvider.GetRequiredService(); + after.ContactMessages.Select(m => m.Name).Should().BeEquivalentTo("kept", "kept long"); + after.IdempotencyRecords.Count().Should().Be(1); + } + + [Fact] + public async Task HandlesMoreRowsThanOneBatch() + { + var (sut, provider, _) = Create(enabled: true); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.ContactMessages.AddRange(Enumerable.Range(0, 1200).Select(i => Message($"old{i}", Now.AddDays(-1)))); + await db.SaveChangesAsync(); + } + + await sut.ExecuteTickAsync(CancellationToken.None); + + await using var check = provider.CreateAsyncScope(); + check.ServiceProvider.GetRequiredService().ContactMessages.Should().BeEmpty(); + } + + [Fact] + public async Task WhileDisabled_ItDoesNothing_AndNeverEvenOpensAScope() + { + var scopeFactory = Substitute.For(); + var sut = new ContactRetentionService( + scopeFactory, + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = false }), + new FakeTimeProvider(Now), + NullLogger.Instance); + + await sut.ExecuteTickAsync(CancellationToken.None); + + scopeFactory.ReceivedCalls().Should().BeEmpty("a disabled module must not touch the database or anything else"); + } + + [Fact] + public async Task ADatabaseProblem_DoesNotCrashTheJob() + { + var scopeFactory = Substitute.For(); + scopeFactory.CreateScope().Returns(_ => throw new InvalidOperationException("db down")); + var sut = new ContactRetentionService( + scopeFactory, + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = true }), + new FakeTimeProvider(Now), + NullLogger.Instance); + + var act = () => sut.ExecuteTickAsync(CancellationToken.None); + + await act.Should().NotThrowAsync(); + } + + [Fact] + public void TheJobRunsDaily() + { + ContactRetentionService.Interval.Should().Be(TimeSpan.FromHours(24)); + } +} + +public class ContactRateLimitPartitionTests +{ + /// + /// REBASE CHECKLIST: on master there is no per-client partitioning, so every caller shares one + /// bucket and this test pins the constant. After the ASF merge the body of + /// ContactRateLimitPartition.KeyFor becomes return ClientPartitionKey.For(context); + /// and this test changes to "two different client addresses give two different keys". + /// + [Fact] + public void OnTheBaseBranch_EveryCallerSharesOneBucket() + { + var first = new DefaultHttpContext(); + first.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10"); + var second = new DefaultHttpContext(); + second.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("198.51.100.20"); + + ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.GlobalKey); + ContactRateLimitPartition.KeyFor(second).Should().Be(ContactRateLimitPartition.GlobalKey); + ContactRateLimitPartition.GlobalKey.Should().Be("global"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs new file mode 100644 index 0000000..6b8a5f4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs @@ -0,0 +1,344 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; +using SlpModularCms.Modules.Contact.Models; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactSubmissionServiceTests +{ + private static async Task> Messages(SubmissionHarness h) + => await h.Db.ContactMessages.AsNoTracking().ToListAsync(); + + [Fact] + public async Task AGenuineMessage_IsStored_AsNew_WithTwelveMonthsRetention_AndMailPending() + { + using var h = new SubmissionHarness(); + var token = h.MatureToken(); + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType(); + var stored = (await Messages(h)).Single(); + stored.Status.Should().Be(ContactMessageStatus.New); + stored.MailStatus.Should().Be(ContactMailStatus.Pending); + stored.SiteId.Should().Be("site-a"); + stored.Name.Should().Be("Jan Jansen"); + stored.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12)); + } + + [Fact] + public async Task TextFieldsAreStoredTrimmed() + { + using var h = new SubmissionHarness(); + var request = SubmissionHarness.Request(h.MatureToken()) with { Name = " Jan ", Message = "\n hallo \n" }; + + await h.Submit(request); + + var stored = (await Messages(h)).Single(); + stored.Name.Should().Be("Jan"); + stored.Message.Should().Be("hallo"); + } + + [Fact] + public async Task TheMailSender_IsCalledAfterTheMessageIsStored_AndOnlyForGenuineMessages() + { + using var h = new SubmissionHarness(); + var storedWhenMailWasCalled = false; + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(call => + { + storedWhenMailWasCalled = h.Db.ContactMessages.AsNoTracking().Any(m => m.Id == call.Arg().Id); + return ContactMailOutcome.Skipped; + }); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + + storedWhenMailWasCalled.Should().BeTrue(); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ASentMail_IsRecorded_WithOneAttempt() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Sent); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + var stored = (await Messages(h)).Single(); + stored.MailStatus.Should().Be(ContactMailStatus.Sent); + stored.MailAttempts.Should().Be(1); + } + + [Fact] + public async Task AMailFailure_NeverFailsTheRequest_AndLeavesTheMessageStored() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException("smtp said no to jan@example.nl")); + + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + result.Should().BeOfType(); + (await Messages(h)).Single().MailStatus.Should().Be(ContactMailStatus.Pending); + } + + [Fact] + public async Task AFilledHoneypot_IsStoredAsSpam_ForThirtyDays_NeverMailed_WithTheSameAnswer() + { + using var h = new SubmissionHarness(); + + var spam = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "http://spam")); + var genuine = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + spam.Should().Be(genuine, "a bot must not be able to tell the difference"); + var stored = (await Messages(h)).Single(m => m.Status == ContactMessageStatus.Spam); + stored.MailStatus.Should().Be(ContactMailStatus.NotApplicable); + stored.RetentionUntil.Should().Be(stored.ReceivedAt.AddDays(30)); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ATooFastSubmission_IsSpam() + { + using var h = new SubmissionHarness(); + var token = h.Tokens.Issue(); // no waiting + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType(); + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam); + } + + [Fact] + public async Task ARejectedCaptcha_IsSpam_WhenCaptchaIsEnabled() + { + using var h = new SubmissionHarness(o => o.Captcha.Enabled = true); + h.Captcha.VerifyAsync(Arg.Any(), Arg.Any()).Returns(false); + + await h.Submit(SubmissionHarness.Request(h.MatureToken(), captcha: "bad")); + + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam); + } + + [Fact] + public async Task TheCaptchaIsNotConsulted_WhenItIsDisabled() + { + using var h = new SubmissionHarness(); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + await h.Captcha.DidNotReceive().VerifyAsync(Arg.Any(), Arg.Any()); + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.New); + } + + [Fact] + public async Task SpamIsNotStored_OnceTheDailyCapIsReached_ButTheAnswerStaysTheSame() + { + using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 2); + + for (var i = 0; i < 4; i++) + { + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + result.Should().BeOfType(); + } + + (await Messages(h)).Count(m => m.Status == ContactMessageStatus.Spam).Should().Be(2); + h.Db.IdempotencyRecords.Count().Should().Be(4, "dropped spam still gets a replay record"); + } + + [Fact] + public async Task TheSpamCap_StartsAgainOnTheNextDay() + { + using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 1); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + (await Messages(h)).Should().HaveCount(1); + + h.Time.Advance(TimeSpan.FromDays(1)); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + + (await Messages(h)).Should().HaveCount(2); + } + + [Fact] + public async Task AReplayWithTheSameKey_ReturnsTheSameAnswer_WithoutASecondRowOrMail() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var request = SubmissionHarness.Request(h.MatureToken()); + + var first = await h.Submit(request, key); + var second = await h.Submit(request, key); + + second.Should().Be(first); + (await Messages(h)).Should().HaveCount(1); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task AReplay_StillWorks_WhenTheTokenHasExpiredInTheMeantime() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var request = SubmissionHarness.Request(h.MatureToken()); + await h.Submit(request, key); + + h.Time.Advance(TimeSpan.FromHours(3)); + var replay = await h.Submit(request, key); + + replay.Should().BeOfType(); + (await Messages(h)).Should().HaveCount(1); + } + + [Fact] + public async Task AKeyOlderThan24Hours_CanBeUsedAgain() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + await h.Submit(SubmissionHarness.Request(h.MatureToken()), key); + + h.Time.Advance(TimeSpan.FromHours(25)); + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken()), key); + + result.Should().BeOfType(); + (await Messages(h)).Should().HaveCount(2); + h.Db.IdempotencyRecords.Count().Should().Be(1, "the old record is reused, not duplicated"); + } + + [Fact] + public async Task TheIdempotencyRecord_HoldsNoRequestContent() + { + using var h = new SubmissionHarness(); + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + var record = h.Db.IdempotencyRecords.AsNoTracking().Single(); + record.SiteId.Should().Be("site-a"); + record.StatusCode.Should().Be(202); + typeof(IdempotencyRecord).GetProperties().Select(p => p.Name) + .Should().BeEquivalentTo(["SiteId", "Key", "CreatedAt", "StatusCode"]); + } + + [Fact] + public async Task InvalidFields_AreRejected_WithEveryProblemListed_AndNothingIsStored() + { + using var h = new SubmissionHarness(); + var request = SubmissionHarness.Request(h.MatureToken()) with { Name = "", Email = "nope", Message = new string('a', 2001) }; + + var result = await h.Submit(request); + + var invalid = result.Should().BeOfType().Subject; + invalid.Errors["name"].Should().Equal("required"); + invalid.Errors["email"].Should().Equal("invalid"); + invalid.Errors["message"].Should().Equal("tooLong"); + (await Messages(h)).Should().BeEmpty(); + h.Db.IdempotencyRecords.Should().BeEmpty("a rejected request must not use up its key"); + } + + [Fact] + public async Task ACorrectedRequest_CanReuseTheKeyOfARejectedOne() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var token = h.MatureToken(); + + (await h.Submit(SubmissionHarness.Request(token) with { Email = "nope" }, key)).Should().BeOfType(); + (await h.Submit(SubmissionHarness.Request(token), key)).Should().BeOfType(); + + (await Messages(h)).Should().HaveCount(1); + } + + [Theory] + [InlineData(null, "required")] + [InlineData("", "required")] + [InlineData("not-a-guid", "invalid")] + public async Task ABadIdempotencyKey_IsRejected(string? key, string code) + { + using var h = new SubmissionHarness(); + + var result = await h.Sut.SubmitAsync(SubmissionHarness.Request(h.MatureToken()), key, CancellationToken.None); + + result.Should().BeOfType().Which.Errors["idempotencyKey"].Should().Equal(code); + (await Messages(h)).Should().BeEmpty(); + } + + [Fact] + public async Task ANullBody_IsRejected_AsAnInvalidBody() + { + using var h = new SubmissionHarness(); + + var result = await h.Submit(null); + + result.Should().BeOfType().Which.Errors["body"].Should().Equal("invalid"); + } + + [Theory] + [InlineData("garbage")] + [InlineData("CfDJ8-forged")] + public async Task AForgedToken_IsReportedAsExpired_AndNothingIsStored(string token) + { + using var h = new SubmissionHarness(); + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType().Which.Errors["token"].Should().Equal("expired"); + (await Messages(h)).Should().BeEmpty(); + h.Db.IdempotencyRecords.Should().BeEmpty(); + } + + [Fact] + public async Task AnExpiredToken_IsReportedAsExpired_ExactlyLikeAForgedOne() + { + using var h = new SubmissionHarness(); + var token = h.Tokens.Issue(); + h.Time.Advance(TimeSpan.FromHours(3)); + + var expired = await h.Submit(SubmissionHarness.Request(token)); + var forged = await h.Submit(SubmissionHarness.Request("forged")); + + expired.Should().BeOfType(); + ((SubmissionResult.Invalid)expired).Errors.Should().BeEquivalentTo(((SubmissionResult.Invalid)forged).Errors); + } + + [Fact] + public async Task ARaceOnTheSameKey_IsAnsweredAsAReplay() + { + var repository = Substitute.For(); + repository.GetIdempotencyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns((IdempotencyRecord?)null); + repository.SaveChangesAsync(Arg.Any()).ThrowsAsync(new DbUpdateException("duplicate")); + using var h = new SubmissionHarness(repositoryOverride: repository); + + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + result.Should().BeOfType(); + } + + [Fact] + public async Task TheSiteId_ComesFromConfiguration_NeverFromTheRequest() + { + using var h = new SubmissionHarness(o => o.SiteId = "configured-site"); + var request = SubmissionHarness.Request(h.MatureToken()) with { Subject = "other-site" }; + + await h.Submit(request); + + (await Messages(h)).Single().SiteId.Should().Be("configured-site"); + } + + [Fact] + public async Task ARetentionConfigChange_DoesNotChangeStoredRows() + { + using var h = new SubmissionHarness(); + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + var before = (await Messages(h)).Single().RetentionUntil; + + h.Options.RetentionMonths = 1; + + (await Messages(h)).Single().RetentionUntil.Should().Be(before); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs new file mode 100644 index 0000000..d333ac2 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs @@ -0,0 +1,144 @@ +using FluentAssertions; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Time.Testing; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactTokenServiceTests +{ + private static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + private static ContactTokenService Create( + FakeTimeProvider time, string siteId = "site-a", IDataProtectionProvider? provider = null, + int minSeconds = 3, int lifetimeMinutes = 120) + => new( + provider ?? DataProtectionProvider.Create("contact-token-tests"), + Options.Create(new ContactOptions { SiteId = siteId, MinSeconds = minSeconds, TokenLifetimeMinutes = lifetimeMinutes }), + time); + + [Fact] + public void ATokenIsValid_AfterTheMinimumTime_AndBeforeItExpires() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromSeconds(3)); + sut.Check(token).Should().Be(TokenCheck.Valid); + + time.Advance(TimeSpan.FromMinutes(119)); + sut.Check(token).Should().Be(TokenCheck.Valid); + } + + [Fact] + public void ATokenIsTooYoung_BeforeTheMinimumTime() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromSeconds(2)); + + sut.Check(token).Should().Be(TokenCheck.TooYoung); + } + + [Fact] + public void ATokenExpires_AfterItsLifetime() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromMinutes(120) + TimeSpan.FromSeconds(1)); + + sut.Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATokenFromTheFuture_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var provider = DataProtectionProvider.Create("contact-token-tests"); + var later = Create(new FakeTimeProvider(Start.AddHours(1)), provider: provider); + var token = later.Issue(); + + Create(time, provider: provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATokenOfAnotherSite_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var provider = DataProtectionProvider.Create("contact-token-tests"); + var token = Create(time, "site-a", provider).Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + Create(time, "site-b", provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + Create(time, "site-a", provider).Check(token).Should().Be(TokenCheck.Valid); + } + + [Fact] + public void ATokenFromAnotherKeyRing_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var token = Create(time, provider: DataProtectionProvider.Create("one")).Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + Create(time, provider: DataProtectionProvider.Create("two")).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("garbage")] + [InlineData("CfDJ8-not-a-real-token")] + public void BlankOrGarbage_IsInvalid(string? token) + { + Create(new FakeTimeProvider(Start)).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATamperedToken_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + for (var i = 0; i < token.Length; i += 7) + { + var chars = token.ToCharArray(); + chars[i] = chars[i] == 'A' ? 'B' : 'A'; + sut.Check(new string(chars)).Should().Be(TokenCheck.InvalidOrExpired, $"changing character {i} must break the token"); + } + } + + [Fact] + public void RoundTrip_ClassifiesEveryAgeAsExpected_ForManyRandomAges() + { + var random = new Random(4242); + for (var i = 0; i < 200; i++) + { + var time = new FakeTimeProvider(Start); + var sut = Create(time, minSeconds: 3, lifetimeMinutes: 120); + var token = sut.Issue(); + + var ageSeconds = random.Next(0, 3 * 60 * 60); + time.Advance(TimeSpan.FromSeconds(ageSeconds)); + + var expected = ageSeconds > 120 * 60 ? TokenCheck.InvalidOrExpired + : ageSeconds < 3 ? TokenCheck.TooYoung + : TokenCheck.Valid; + sut.Check(token).Should().Be(expected, $"age {ageSeconds} s"); + } + } + + [Fact] + public void ThePurposeStringIsBoundToTheSite() + { + ContactTokenService.PurposeFor("slpsoftware").Should().Be("SlpModularCms.Contact.Token.slpsoftware"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs new file mode 100644 index 0000000..95170ee --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs @@ -0,0 +1,185 @@ +using FluentAssertions; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactValidatorTests +{ + private static ContactMessageRequest Valid() => new( + "Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", "", "token", null); + + private static Dictionary Check(ContactMessageRequest request) + => ContactValidator.Validate(ContactValidator.Normalize(request)); + + [Fact] + public void AValidRequest_HasNoErrors() + { + Check(Valid()).Should().BeEmpty(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void RequiredFields_AreReported_WhenMissingOrBlank(string? blank) + { + var errors = Check(new ContactMessageRequest(blank, blank, blank, blank, null, blank, null)); + + errors.Keys.Should().BeEquivalentTo("name", "email", "subject", "message", "token"); + errors.Values.Should().OnlyContain(v => v.Single() == "required"); + } + + [Theory] + [InlineData(100, true)] + [InlineData(101, false)] + public void Name_AllowsAtMost100Characters(int length, bool valid) + { + var errors = Check(Valid() with { Name = new string('a', length) }); + + (errors.ContainsKey("name") ? errors["name"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData(254, true)] + [InlineData(255, false)] + public void Email_AllowsAtMost254Characters(int length, bool valid) + { + var email = new string('a', length - "@example.nl".Length) + "@example.nl"; + var errors = Check(Valid() with { Email = email }); + + (errors.ContainsKey("email") ? errors["email"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData(2000, true)] + [InlineData(2001, false)] + public void Message_AllowsAtMost2000Characters(int length, bool valid) + { + var errors = Check(Valid() with { Message = new string('a', length) }); + + (errors.ContainsKey("message") ? errors["message"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData("jan@example.nl", true)] + [InlineData("a@b.co", true)] + [InlineData("jan.jansen+tag@sub.example.nl", true)] + [InlineData("jan@example", false)] + [InlineData("jan@example.n", false)] + [InlineData("@example.nl", false)] + [InlineData("jan example@example.nl", false)] + [InlineData("jan@@example.nl", false)] + public void Email_MustLookLikeAnAddress(string email, bool valid) + { + var errors = Check(Valid() with { Email = email }); + + errors.ContainsKey("email").Should().Be(!valid); + if (!valid) + { + errors["email"].Single().Should().Be("invalid"); + } + } + + [Fact] + public void Trimming_HappensBeforeTheLengthCheck() + { + var errors = Check(Valid() with { Name = " " + new string('a', 100) + " " }); + + errors.Should().BeEmpty(); + } + + [Fact] + public void Normalize_IsIdempotent_ForManyRandomInputs() + { + var random = new Random(20261109); + for (var i = 0; i < 300; i++) + { + var request = new ContactMessageRequest( + Noise(random, 120), Noise(random, 40), Noise(random, 120), Noise(random, 300), Noise(random, 3), Noise(random, 50), null); + + var once = ContactValidator.Normalize(request); + ContactValidator.Normalize(once).Should().Be(once); + } + } + + [Fact] + public void Validation_NeverChangesBetweenARequestAndItsNormalizedForm() + { + // Validating twice (before and after another trim) must give the same answer. + var random = new Random(7); + for (var i = 0; i < 300; i++) + { + var request = new ContactMessageRequest( + Noise(random, 130), Noise(random, 300), Noise(random, 130), Noise(random, 2100), "", Noise(random, 20), null); + + var normalized = ContactValidator.Normalize(request); + ContactValidator.Validate(normalized).Should().BeEquivalentTo(ContactValidator.Validate(ContactValidator.Normalize(normalized))); + } + } + + [Theory] + [InlineData("name")] + [InlineData("email")] + [InlineData("subject")] + public void AnyControlCharacter_IsInvalid_InSingleLineFields(string field) + { + for (var code = 0; code < 32; code++) + { + var bad = $"a{(char)code}b"; + var request = field switch + { + "name" => Valid() with { Name = bad }, + "email" => Valid() with { Email = $"a{(char)code}b@example.nl" }, + _ => Valid() with { Subject = bad }, + }; + + var errors = ContactValidator.Validate(request); // not trimmed: control characters inside stay + errors.Should().ContainKey(field, $"control character U+{code:X4} must be rejected"); + errors[field].Single().Should().Be("invalid"); + } + + var del = field switch + { + "name" => Valid() with { Name = "a\u007Fb" }, + "email" => Valid() with { Email = "a\u007Fb@example.nl" }, + _ => Valid() with { Subject = "a\u007Fb" }, + }; + ContactValidator.Validate(del).Should().ContainKey(field); + } + + [Fact] + public void Message_AllowsLineBreaksAndTabs_ButNoOtherControlCharacters() + { + ContactValidator.Validate(Valid() with { Message = "regel 1\r\nregel 2\n\tingesprongen" }).Should().BeEmpty(); + + for (var code = 0; code < 32; code++) + { + if (code is '\n' or '\r' or '\t') + { + continue; + } + + var errors = ContactValidator.Validate(Valid() with { Message = $"a{(char)code}b" }); + errors.Should().ContainKey("message", $"control character U+{code:X4} must be rejected"); + } + } + + [Fact] + public void ErrorCodes_AreExactlyTheContractedOnes() + { + var codes = new[] + { + ContactErrorCodes.Required, ContactErrorCodes.TooLong, ContactErrorCodes.Invalid, ContactErrorCodes.Expired, + }; + + codes.Should().Equal("required", "tooLong", "invalid", "expired"); + } + + private static string Noise(Random random, int maxLength) + { + const string alphabet = "abcXYZ019 @.+-_\t\né€"; + var length = random.Next(0, maxLength + 1); + return new string(Enumerable.Range(0, length).Select(_ => alphabet[random.Next(alphabet.Length)]).ToArray()); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs new file mode 100644 index 0000000..0dd3cb1 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs @@ -0,0 +1,113 @@ +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Modules.Contact.Data; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// +/// Starts the real, composed SlpSoftware host (all modules, the real pipeline) against a real +/// MariaDB/MySQL. Like SlpModularCms.Api.Tests this needs a reachable database: set the +/// environment variable ConnectionStrings__DefaultConnection to a server you may create +/// 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 +{ + private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection"; + + private readonly Dictionary _settings; + private readonly string _databaseName = "SlpContactPipeline_" + Guid.NewGuid().ToString("N")[..12]; + + public ContactHostFactory(Dictionary? settings = null) + { + _settings = settings ?? []; + } + + public static string BaseConnectionString => + Environment.GetEnvironmentVariable(EnvironmentVariable) + ?? throw new InvalidOperationException( + $"Set {EnvironmentVariable} to a MariaDB/MySQL server for the contact pipeline tests " + + "(or run the unit tests only with --filter \"FullyQualifiedName!~Pipeline\")."); + + public string ConnectionString => + Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase) + ? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase) + : $"{BaseConnectionString};Database={_databaseName}"; + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + builder.ConfigureAppConfiguration((_, config) => + { + var all = new Dictionary + { + ["ConnectionStrings:DefaultConnection"] = ConnectionString, + // Fresh availability answers instead of a cached one. + ["Availability:StatusCacheSeconds"] = "0", + }; + foreach (var (key, value) in _settings) + { + all[key] = value; + } + + config.AddInMemoryCollection(all); + }); + } + + public async Task WithDb(Func> action) + { + await using var scope = Services.CreateAsyncScope(); + return await action(scope.ServiceProvider.GetRequiredService()); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + try + { + using var scope = Services.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.EnsureDeleted(); + } + catch + { + // Best effort clean-up of the throwaway database. + } + } + + base.Dispose(disposing); + } +} + +public sealed class EnabledContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:SiteId"] = "pipeline-site", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}); + +public sealed class DisabledContactHostFactory() : ContactHostFactory; + +/// Only the form policy is tight, so a token can still be fetched freely. +public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "2", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}); + +/// Only the token policy is tight. +public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "2", +}); diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs new file mode 100644 index 0000000..890b297 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs @@ -0,0 +1,318 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +internal static class Http +{ + public const string Route = "/api/v1/contact-messages"; + + public static async Task GetTokenAsync(HttpClient client) + { + var response = await client.GetAsync($"{Route}/token"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("token").GetString()!; + } + + public static Task PostAsync( + HttpClient client, string json, string? key = "new", bool useKey = true) + { + var request = new HttpRequestMessage(HttpMethod.Post, Route) + { + Content = new StringContent(json, Encoding.UTF8, "application/json"), + }; + if (useKey) + { + request.Headers.Add("Idempotency-Key", key == "new" ? Guid.NewGuid().ToString() : key); + } + + return client.SendAsync(request); + } + + public static string Body(string token, string name = "Jan Jansen", string hp = "") => + JsonSerializer.Serialize(new + { + name, + email = "jan@example.nl", + subject = "website", + message = "Ik wil graag een offerte.", + hpCheck = hp, + token, + }); +} + +public class ContactPipelineEnabledTests(EnabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheTokenRoute_ReturnsATokenTheMinimumTime_AndNoCaptcha() + { + var response = await factory.CreateClient().GetAsync($"{Http.Route}/token"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + json.RootElement.GetProperty("token").GetString().Should().NotBeNullOrWhiteSpace(); + json.RootElement.GetProperty("minSeconds").GetInt32().Should().Be(0); + json.RootElement.GetProperty("captcha").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task AValidSubmission_Returns202_IsStoredOnce_AndAReplayDoesNotStoreAgain() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + var key = Guid.NewGuid().ToString(); + var body = Http.Body(token, name: "Pipeline Genuine"); + + var first = await Http.PostAsync(client, body, key); + var second = await Http.PostAsync(client, body, key); + + first.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await first.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + second.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await second.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + + var rows = await factory.WithDb(db => db.ContactMessages.AsNoTracking().Where(m => m.Name == "Pipeline Genuine").ToListAsync()); + rows.Should().ContainSingle(); + rows[0].Status.Should().Be(ContactMessageStatus.New); + rows[0].SiteId.Should().Be("pipeline-site"); + rows[0].RetentionUntil.Should().BeAfter(DateTimeOffset.UtcNow.AddMonths(11)); + } + + [Fact] + public async Task AFilledHoneypot_GetsTheIdenticalAnswer_ButIsStoredAsSpam() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + var response = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Bot", hp: "http://spam")); + + response.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await response.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Pipeline Bot")); + row.Status.Should().Be(ContactMessageStatus.Spam); + row.MailStatus.Should().Be(ContactMailStatus.NotApplicable); + row.RetentionUntil.Should().BeBefore(DateTimeOffset.UtcNow.AddDays(31)); + } + + [Fact] + public async Task InvalidFields_Return400_WithTheContractedShape() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + var json = JsonSerializer.Serialize(new { name = "", email = "nope", subject = "s", message = "m", hpCheck = "", token }); + + var response = await Http.PostAsync(client, json); + + 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()); + var root = doc.RootElement; + root.GetProperty("status").GetInt32().Should().Be(400); + root.GetProperty("type").GetString().Should().Be("about:blank"); + root.GetProperty("errors").GetProperty("name")[0].GetString().Should().Be("required"); + root.GetProperty("errors").GetProperty("email")[0].GetString().Should().Be("invalid"); + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Subject == "s"))).Should().Be(0); + } + + [Fact] + public async Task AMissingIdempotencyKey_Returns400() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + var response = await Http.PostAsync(client, Http.Body(token), useKey: false); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("idempotencyKey")[0].GetString().Should().Be("required"); + } + + [Fact] + public async Task AForgedToken_IsReportedAsExpired() + { + var response = await Http.PostAsync(factory.CreateClient(), Http.Body("forged-token")); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("token")[0].GetString().Should().Be("expired"); + } + + [Theory] + [InlineData("{ this is not json")] + [InlineData("""{"name": 123, "email": "a@b.nl"}""")] + [InlineData("")] + public async Task AnUnbindableBody_Returns400_InOurShape_WithoutEchoingTheInput(string body) + { + var response = await Http.PostAsync(factory.CreateClient(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(text); + doc.RootElement.GetProperty("errors").GetProperty("body")[0].GetString().Should().Be("invalid"); + text.Should().NotContain("this is not json").And.NotContain("a@b.nl"); + } + + [Fact] + public async Task ABodyBeyondTheLimit_Returns413_AsProblemJson() + { + var client = factory.CreateClient(); + var huge = new string('x', 20_000); + + var response = await Http.PostAsync(client, JsonSerializer.Serialize(new { message = huge })); + + response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("status").GetInt32().Should().Be(413); + } + + [Fact] + public async Task TheMigration_CreatedBothTables_AndTheIdempotencyKeyIsUnique() + { + var count = await factory.WithDb(async db => + { + var key = Guid.NewGuid(); + db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); + await db.SaveChangesAsync(); + db.ChangeTracker.Clear(); + + db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); + var act = () => db.SaveChangesAsync(); + await act.Should().ThrowAsync("the same site cannot use a key twice"); + + return await db.ContactMessages.CountAsync(); + }); + + count.Should().BeGreaterThanOrEqualTo(0); + } + + [Fact] + public async Task TheRetentionJob_RemovesExpiredRows_InTheRealDatabase() + { + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = Guid.NewGuid(), SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddYears(-2), + Name = "Pipeline Expired", Email = "a@b.nl", Subject = "s", Message = "m", + Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddDays(-1), + }); + await db.SaveChangesAsync(); + return 0; + }); + + var job = factory.Services.GetServices().OfType().Single(); + await job.ExecuteTickAsync(CancellationToken.None); + + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Expired"))).Should().Be(0); + } +} + +public class ContactPipelineDisabledTests(DisabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task WhileDisabled_BothRoutesAre404_WithAnEmptyBody() + { + var client = factory.CreateClient(); + + var token = await client.GetAsync($"{Http.Route}/token"); + var post = await Http.PostAsync(client, Http.Body("anything")); + + token.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await token.Content.ReadAsStringAsync()).Should().BeEmpty(); + post.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await post.Content.ReadAsStringAsync()).Should().BeEmpty(); + } + + [Fact] + public async Task WhileDisabled_TheModuleNeverTouchedTheDatabase_AndTheRetentionJobDoesNothing() + { + // The host has started (other modules migrated their tables), but the contact tables do + // not exist: the module neither migrated nor queried anything. + await using var connection = new MySql.Data.MySqlClient.MySqlConnection(factory.ConnectionString); + await connection.OpenAsync(); + await using var command = connection.CreateCommand(); + command.CommandText = + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name IN ('ContactMessages','ContactIdempotency')"; + Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0); + + _ = factory.CreateClient(); // make sure the host is up + var job = factory.Services.GetServices().OfType().Single(); + await job.ExecuteTickAsync(CancellationToken.None); + + Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0, "the disabled job must not create or touch anything"); + } +} + +public class ContactPipelineFormRateLimitTests(TightFormLimitContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheFormPolicy_Answers429_WithRetryAfter_AndOnlyTheStandardFields() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await Http.PostAsync(client, Http.Body(token, name: $"Pipeline Limit {i}")); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); + int.Parse(retryAfter!.Single()).Should().BeInRange(1, 600); + last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await last.Content.ReadAsStringAsync()); + doc.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]); + } + +} + +public class ContactPipelineTokenRateLimitTests(TightTokenLimitContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheTokenPolicy_AnswersAfterItsOwnLimit_With429AndRetryAfter() + { + var client = factory.CreateClient(); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await client.GetAsync($"{Http.Route}/token"); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + last.Headers.Contains("Retry-After").Should().BeTrue(); + } +} + +public class ContactPipelineGateTests(EnabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheContactRoutes_StayReachable_WhileTheCmsIsDisabled_ButAdminRoutesAreBlocked() + { + // Switch the CMS off through the availability state of the real database. + await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( + "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')")); + var client = factory.CreateClient(); + + (await client.GetAsync("/api/v1/offerings/categories")).StatusCode + .Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed"); + + var token = await Http.GetTokenAsync(client); + var post = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Gate")); + + post.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Gate"))).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj b/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj new file mode 100644 index 0000000..08c6e9f --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj @@ -0,0 +1,39 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs b/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs new file mode 100644 index 0000000..afe9db2 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs @@ -0,0 +1,97 @@ +using Microsoft.AspNetCore.DataProtection; +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.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +/// Captures every log entry so tests can prove nothing personal is ever logged. +public sealed class CapturingLoggerProvider : ILoggerProvider +{ + public List Messages { get; } = []; + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(Messages); + public void Dispose() { } + + private sealed class CapturingLogger(List messages) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + lock (messages) + { + messages.Add(formatter(state, exception)); + if (exception is not null) + { + messages.Add(exception.ToString()); + } + } + } + } +} + +/// +/// The submission service wired to a real in-memory database, a real token service and a fake +/// clock; only the captcha and the mail sender are substitutes. +/// +public sealed class SubmissionHarness : IDisposable +{ + public static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + public FakeTimeProvider Time { get; } = new(Start); + public ContactOptions Options { get; } + public ContactDbContext Db { get; } + public IContactRepository Repository { get; } + public IContactTokenService Tokens { get; } + public ICaptchaVerifier Captcha { get; } = Substitute.For(); + public IContactMailSender Mail { get; } = Substitute.For(); + public CapturingLoggerProvider Logs { get; } = new(); + public ContactSubmissionService Sut { get; } + + public SubmissionHarness(Action? configure = null, IContactRepository? repositoryOverride = null) + { + Options = new ContactOptions { Enabled = true, SiteId = "site-a", MinSeconds = 3 }; + configure?.Invoke(Options); + + Db = new ContactDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options); + Repository = repositoryOverride ?? new ContactRepository(Db); + + var wrapped = Microsoft.Extensions.Options.Options.Create(Options); + Tokens = new ContactTokenService(DataProtectionProvider.Create("submission-tests"), wrapped, Time); + + Captcha.VerifyAsync(Arg.Any(), Arg.Any()).Returns(true); + Mail.SendAsync(Arg.Any(), Arg.Any()) + .Returns(ContactMailOutcome.Skipped); + + var loggerFactory = LoggerFactory.Create(b => b.AddProvider(Logs)); + Sut = new ContactSubmissionService( + Repository, Tokens, Captcha, Mail, wrapped, Time, loggerFactory.CreateLogger()); + } + + /// A token that is old enough to pass the minimum-time check. + public string MatureToken() + { + var token = Tokens.Issue(); + Time.Advance(TimeSpan.FromSeconds(Options.MinSeconds + 1)); + return token; + } + + public static ContactMessageRequest Request(string token, string hp = "", string? captcha = null) => new( + "Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", hp, token, captcha); + + public Task Submit(ContactMessageRequest? request, string? key = null) + => Sut.SubmitAsync(request, key ?? Guid.NewGuid().ToString(), CancellationToken.None); + + public void Dispose() => Db.Dispose(); +} diff --git a/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs b/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs new file mode 100644 index 0000000..1d122b4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs @@ -0,0 +1,52 @@ +namespace SlpModularCms.Modules.Contact.Config; + +/// +/// Per-host configuration of the contact module (section Contact). +/// +public class ContactOptions +{ + public const string SectionName = "Contact"; + + /// + /// Master switch. While false the contact routes answer 404 and the module touches nothing. + /// It must only be switched on for a public host once per-client rate limiting is in place + /// (see ). + /// + public bool Enabled { get; set; } + + /// Identifies the site on stored rows and in the token purpose. Never taken from a request. + public string? SiteId { get; set; } + + /// Minimum seconds between issuing the token and submitting; faster submissions are treated as spam. + public int MinSeconds { get; set; } = 3; + + public int TokenLifetimeMinutes { get; set; } = 120; + + /// Months a genuine message is kept (fixed per row at insert). + public int RetentionMonths { get; set; } = 12; + + /// Days a message classified as spam is kept. + public int SpamRetentionDays { get; set; } = 30; + + /// Per site and UTC day; beyond it spam is answered normally but not stored. + public int MaxSpamRowsPerDay { get; set; } = 200; + + public int MaxBodyBytes { get; set; } = 16384; + + /// Base of the validation problem type URI. When empty the type is about:blank. + public string? ProblemTypeBase { get; set; } + + public ContactCaptchaOptions Captcha { get; set; } = new(); + + public string EffectiveSiteId => string.IsNullOrWhiteSpace(SiteId) ? "default" : SiteId.Trim(); +} + +public class ContactCaptchaOptions +{ + public bool Enabled { get; set; } + public string? Provider { get; set; } + public string? SiteKey { get; set; } + + /// Server-side secret; supply it through the environment or a secrets manager, never committed. + public string? Secret { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs new file mode 100644 index 0000000..06ac096 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -0,0 +1,89 @@ +using System.Diagnostics.CodeAnalysis; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Modules; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact; + +[ExcludeFromCodeCoverage] +public class ContactModule : IModule +{ + public string Name => "Contact"; + public string Version => "1.0.0"; + + public void RegisterServices(IServiceCollection services) + { + services.AddOptions() + .Configure((options, config) => + config.GetSection(ContactOptions.SectionName).Bind(options)); + + services.AddDbContext((serviceProvider, options) => + { + var config = serviceProvider.GetRequiredService(); + options.UseMySQL(config.GetConnectionString("DefaultConnection")!); + options.ReplaceService(); + }); + + services.TryAddSingleton(TimeProvider.System); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); + + // Rate-limit policies live in this module so the shared limiter setup stays untouched. + // The bucket key comes from one function; see ContactRateLimitPartition. + services.AddOptions() + .Configure((limiter, config) => + { + limiter.AddPolicy(ContactMessagesController.FormPolicy, context => + Window(config, "ContactForm", 5, 600, context)); + limiter.AddPolicy(ContactMessagesController.TokenPolicy, context => + Window(config, "ContactToken", 20, 600, context)); + }); + } + + public void UseModule(IApplicationBuilder app) + { + // Nothing is touched while the module is switched off: not even the database. + var enabled = app.ApplicationServices.GetRequiredService>().Value.Enabled; + if (!enabled) + { + return; + } + + using var scope = app.ApplicationServices.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + } + + private static RateLimitPartition Window( + IConfiguration config, string name, int defaultPermits, int defaultSeconds, Microsoft.AspNetCore.Http.HttpContext context) + { + var section = config.GetSection($"RateLimiting:{name}"); + return RateLimitPartition.GetFixedWindowLimiter( + ContactRateLimitPartition.KeyFor(context), + _ => new FixedWindowRateLimiterOptions + { + PermitLimit = section.GetValue("PermitLimit", defaultPermits), + Window = TimeSpan.FromSeconds(section.GetValue("WindowSeconds", defaultSeconds)), + QueueLimit = 0, + }); + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs new file mode 100644 index 0000000..246199d --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs @@ -0,0 +1,71 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// The public contact routes. Deliberately not an [ApiController]: a body that cannot be +/// bound must produce our own problem shape, never the framework's, and must not echo values. +/// The management routes (list, read, delete, resend) are added with the admin unit. +/// +[Route("contact-messages")] +[ServiceFilter(typeof(ContactRouteFilter))] +public class ContactMessagesController( + IContactTokenService tokens, + IContactSubmissionService submissions, + IOptions options) : ControllerBase +{ + public const string IdempotencyKeyHeader = "Idempotency-Key"; + public const string TokenPolicy = "contact-token"; + public const string FormPolicy = "contact-form"; + + [HttpGet("token")] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting(TokenPolicy)] + public IActionResult GetToken() + { + var settings = options.Value; + var captcha = settings.Captcha is { Enabled: true } c && !string.IsNullOrWhiteSpace(c.Provider) + ? new ContactCaptchaInfo(c.Provider!, c.SiteKey ?? string.Empty) + : null; + + return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha)); + } + + [HttpPost] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting(FormPolicy)] + public async Task Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken) + { + var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault(); + + // An unbindable body (malformed JSON, wrong types) arrives as null. + var result = await submissions.SubmitAsync(ModelState.IsValid ? request : null, key, cancellationToken); + + return result switch + { + SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)), + _ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted }, + }; + } + + private ValidationProblemDetails Problem(IReadOnlyDictionary errors) + { + var baseUri = options.Value.ProblemTypeBase?.TrimEnd('/'); + return new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value)) + { + Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation", + Title = "Validation failed", + Status = StatusCodes.Status400BadRequest, + }; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs new file mode 100644 index 0000000..aada5a8 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// Runs before model binding on the public contact routes: +/// 1. While the form is not open (see ) the route does not exist +/// (404, empty body). +/// 2. Caps the request body (413 as problem+json), also when the size is only known while reading. +/// +public sealed class ContactRouteFilter(IContactFormGate gate, IOptions options) : IAsyncResourceFilter +{ + public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) + { + var settings = options.Value; + if (!await gate.IsOpenAsync(context.HttpContext.RequestAborted)) + { + context.Result = new NotFoundResult(); + return; + } + + var request = context.HttpContext.Request; + if (HttpMethods.IsPost(request.Method)) + { + if (request.ContentLength > settings.MaxBodyBytes) + { + context.Result = TooLarge(); + return; + } + + // For chunked bodies the length is unknown up front; Kestrel enforces the cap while reading. + var feature = context.HttpContext.Features.Get(); + if (feature is { IsReadOnly: false }) + { + feature.MaxRequestBodySize = settings.MaxBodyBytes; + } + } + + var executed = await next(); + + if (executed.Exception is BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge }) + { + executed.ExceptionHandled = true; + executed.Result = TooLarge(); + } + } + + private static ObjectResult TooLarge() => new(new ProblemDetails + { + Status = StatusCodes.Status413PayloadTooLarge, + Title = "Payload too large", + }) + { + StatusCode = StatusCodes.Status413PayloadTooLarge, + ContentTypes = { "application/problem+json" }, + }; +} diff --git a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs new file mode 100644 index 0000000..cbb12e4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs @@ -0,0 +1,44 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Data; + +public class ContactDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet ContactMessages => Set(); + public DbSet IdempotencyRecords => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("ContactMessages"); + entity.HasKey(e => e.Id); + entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100); + entity.Property(e => e.ReceivedAt).IsRequired(); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.Email).IsRequired().HasMaxLength(254); + entity.Property(e => e.Subject).IsRequired().HasMaxLength(100); + entity.Property(e => e.Message).IsRequired().HasMaxLength(2000); + entity.Property(e => e.Status).IsRequired().HasConversion().HasMaxLength(20); + entity.Property(e => e.MailStatus).IsRequired().HasConversion().HasMaxLength(20); + entity.Property(e => e.MailError).HasMaxLength(100); + entity.Property(e => e.RetentionUntil).IsRequired(); + + entity.HasIndex(e => new { e.SiteId, e.Status, e.ReceivedAt }); + entity.HasIndex(e => e.RetentionUntil); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ContactIdempotency"); + entity.HasKey(e => new { e.SiteId, e.Key }); + entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.StatusCode).IsRequired(); + entity.HasIndex(e => e.CreatedAt); + }); + } +} diff --git a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs new file mode 100644 index 0000000..82ac5ae --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs @@ -0,0 +1,58 @@ +namespace SlpModularCms.Modules.Contact.Data.Entities; + +public enum ContactMessageStatus +{ + New, + Read, + Archived, + Spam, + Converted, +} + +public enum ContactMailStatus +{ + /// Waiting to be mailed (also the state while no mail sender is available). + Pending, + Sent, + Failed, + /// Never mailed on purpose (spam). + NotApplicable, +} + +/// +/// A message sent through the website's contact form. Has its own id and status so that it can +/// later be turned into an assignment (quotes, invoices); that is not built yet. +/// +public class ContactMessage +{ + public Guid Id { get; set; } + public string SiteId { get; set; } = string.Empty; + public DateTimeOffset ReceivedAt { get; set; } + public string Name { get; set; } = string.Empty; + public string Email { get; set; } = string.Empty; + + /// Opaque value chosen by the site (a package id, a slug, or 'other'). + public string Subject { get; set; } = string.Empty; + + public string Message { get; set; } = string.Empty; + public ContactMessageStatus Status { get; set; } + public ContactMailStatus MailStatus { get; set; } + + /// Short error code of the last failed mail attempt (never an address or content). + public string? MailError { get; set; } + + public int MailAttempts { get; set; } + public DateTimeOffset? NextMailAttemptAt { get; set; } + + /// Fixed at insert: a later configuration change does not apply retroactively. + public DateTimeOffset RetentionUntil { get; set; } +} + +/// Remembers an Idempotency-Key for 24 hours. Holds no request content. +public class IdempotencyRecord +{ + public string SiteId { get; set; } = string.Empty; + public Guid Key { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public int StatusCode { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs new file mode 100644 index 0000000..f95d4d6 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs @@ -0,0 +1,115 @@ +// +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("20261109200014_InitialCreate")] + partial class InitialCreate + { + /// + 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.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/20261109200014_InitialCreate.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs new file mode 100644 index 0000000..1c2d26c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs @@ -0,0 +1,82 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ContactIdempotency", + columns: table => new + { + SiteId = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Key = table.Column(type: "char(36)", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + StatusCode = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactIdempotency", x => new { x.SiteId, x.Key }); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ContactMessages", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + SiteId = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + ReceivedAt = table.Column(type: "datetime", nullable: false), + Name = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Email = table.Column(type: "varchar(254)", maxLength: 254, nullable: false), + Subject = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Message = table.Column(type: "varchar(2000)", maxLength: 2000, nullable: false), + Status = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + MailStatus = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + MailError = table.Column(type: "varchar(100)", maxLength: 100, nullable: true), + MailAttempts = table.Column(type: "int", nullable: false), + NextMailAttemptAt = table.Column(type: "datetime", nullable: true), + RetentionUntil = table.Column(type: "datetime", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactMessages", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ContactIdempotency_CreatedAt", + table: "ContactIdempotency", + column: "CreatedAt"); + + migrationBuilder.CreateIndex( + name: "IX_ContactMessages_RetentionUntil", + table: "ContactMessages", + column: "RetentionUntil"); + + migrationBuilder.CreateIndex( + name: "IX_ContactMessages_SiteId_Status_ReceivedAt", + table: "ContactMessages", + columns: new[] { "SiteId", "Status", "ReceivedAt" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ContactIdempotency"); + + migrationBuilder.DropTable( + name: "ContactMessages"); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs new file mode 100644 index 0000000..52b5f28 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs @@ -0,0 +1,112 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Contact.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + [DbContext(typeof(ContactDbContext))] + partial class ContactDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(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.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/Models/ContactModels.cs b/src/SlpModularCms.Modules.Contact/Models/ContactModels.cs new file mode 100644 index 0000000..6f0367c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Models/ContactModels.cs @@ -0,0 +1,44 @@ +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Contact.Models; + +/// +/// The body of POST /contact-messages. Everything is nullable on purpose: a missing field is +/// reported as the validation code required in our own problem shape instead of a +/// framework binding error. HpCheck is the honeypot (JSON name hpCheck). +/// +public record ContactMessageRequest( + string? Name, + string? Email, + string? Subject, + string? Message, + string? HpCheck, + string? Token, + string? CaptchaToken); + +[ExcludeFromCodeCoverage] +public record ContactCaptchaInfo(string Provider, string SiteKey); + +[ExcludeFromCodeCoverage] +public record ContactTokenResponse(string Token, int MinSeconds, ContactCaptchaInfo? Captcha); + +[ExcludeFromCodeCoverage] +public record ReceivedResponse(string Status); + +/// Validation error codes, as the client maps them to texts. +public static class ContactErrorCodes +{ + public const string Required = "required"; + public const string TooLong = "tooLong"; + public const string Invalid = "invalid"; + public const string Expired = "expired"; +} + +/// Outcome of handling one submission. +public abstract record SubmissionResult +{ + /// Accepted: genuine, spam and replays all look the same to the caller. + public sealed record Received : SubmissionResult; + + public sealed record Invalid(IReadOnlyDictionary Errors) : SubmissionResult; +} diff --git a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs new file mode 100644 index 0000000..fb26df7 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs @@ -0,0 +1,75 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Repositories; + +public interface IContactRepository +{ + Task GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken); + Task CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken); + void Add(ContactMessage message); + void Add(IdempotencyRecord record); + Task SaveChangesAsync(CancellationToken cancellationToken); + Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken); + Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); +} + +public class ContactRepository(ContactDbContext context) : IContactRepository +{ + private const int BatchSize = 500; + + public Task GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken) + => context.IdempotencyRecords.FirstOrDefaultAsync(r => r.SiteId == siteId && r.Key == key, cancellationToken); + + public Task CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken) + => context.ContactMessages.CountAsync( + m => m.SiteId == siteId && m.Status == ContactMessageStatus.Spam && m.ReceivedAt >= since, + cancellationToken); + + public void Add(ContactMessage message) => context.ContactMessages.Add(message); + + public void Add(IdempotencyRecord record) => context.IdempotencyRecords.Add(record); + + public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken); + + public async Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var total = 0; + while (true) + { + var batch = await context.ContactMessages + .Where(m => m.RetentionUntil < now) + .Take(BatchSize) + .ToListAsync(cancellationToken); + if (batch.Count == 0) + { + return total; + } + + context.ContactMessages.RemoveRange(batch); + await context.SaveChangesAsync(cancellationToken); + total += batch.Count; + } + } + + public async Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + var total = 0; + while (true) + { + var batch = await context.IdempotencyRecords + .Where(r => r.CreatedAt < cutoff) + .Take(BatchSize) + .ToListAsync(cancellationToken); + if (batch.Count == 0) + { + return total; + } + + context.IdempotencyRecords.RemoveRange(batch); + await context.SaveChangesAsync(cancellationToken); + total += batch.Count; + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs b/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs new file mode 100644 index 0000000..7676c17 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Decides whether the public contact form is active. The form is active only when every layer +/// says so; if any layer is off the public routes answer 404 with an empty body (the website +/// then shows its mailto fallback). +/// +/// +/// Layers: (1) the host switch Contact:Enabled (release condition, default off) and, +/// from the admin unit on, (2) a switch an administrator controls in the CMS. The route filter +/// only knows this interface, so adding the second layer does not touch the filter. +/// +public interface IContactFormGate +{ + Task IsOpenAsync(CancellationToken cancellationToken); +} + +/// Layer 1: the host configuration. +public sealed class HostFlagContactFormGate(IOptions options) : IContactFormGate +{ + public Task IsOpenAsync(CancellationToken cancellationToken) => Task.FromResult(options.Value.Enabled); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs new file mode 100644 index 0000000..3b3a0a8 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs @@ -0,0 +1,58 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Daily clean-up: deletes messages past their retention date and idempotency records older +/// than 24 hours. While the module is disabled it does nothing at all (no database access). +/// +public class ContactRetentionService( + IServiceScopeFactory scopeFactory, + IOptions options, + TimeProvider time, + ILogger logger) : BackgroundService +{ + internal static readonly TimeSpan Interval = TimeSpan.FromHours(24); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await ExecuteTickAsync(stoppingToken); + + using var timer = new PeriodicTimer(Interval); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + await ExecuteTickAsync(stoppingToken); + } + } + + internal async Task ExecuteTickAsync(CancellationToken stoppingToken) + { + if (!options.Value.Enabled) + { + return; + } + + try + { + await using var scope = scopeFactory.CreateAsyncScope(); + var repository = scope.ServiceProvider.GetRequiredService(); + var now = time.GetUtcNow(); + + var messages = await repository.DeleteExpiredMessagesAsync(now, stoppingToken); + var records = await repository.DeleteIdempotencyOlderThanAsync(now - TimeSpan.FromHours(24), stoppingToken); + + logger.LogInformation( + "Contact retention: removed {Messages} expired message(s) and {Records} idempotency record(s)", + messages, records); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError("Contact retention run failed ({ExceptionType})", ex.GetType().Name); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs new file mode 100644 index 0000000..c68ea7a --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Http; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Verifies a captcha token server-side. Implementations must fail open: when the provider +/// itself is unreachable they return true (and log without personal data), so real +/// visitors are never locked out by a provider outage. +/// +public interface ICaptchaVerifier +{ + Task VerifyAsync(string? captchaToken, CancellationToken cancellationToken); +} + +/// Used while no captcha is configured: everything passes. +public sealed class NullCaptchaVerifier : ICaptchaVerifier +{ + public Task VerifyAsync(string? captchaToken, CancellationToken cancellationToken) => Task.FromResult(true); +} + +public enum ContactMailOutcome +{ + /// No mail was attempted (no sender available yet); the message stays pending. + Skipped, + Sent, + Failed, +} + +/// +/// Sends the notification mail for a genuine message. Called after the message is stored; a +/// failure must never fail the request. The real implementation arrives with the mail unit. +/// +public interface IContactMailSender +{ + Task SendAsync(ContactMessage message, CancellationToken cancellationToken); +} + +public sealed class NoOpContactMailSender : IContactMailSender +{ + public Task SendAsync(ContactMessage message, CancellationToken cancellationToken) + => Task.FromResult(ContactMailOutcome.Skipped); +} + +/// +/// The single place that decides which rate-limit bucket a request belongs to. +/// +/// +/// On the base branch the rate limiter has no per-client partitioning (no forwarded-header +/// handling, no client key): every visitor is the same caller. This returns a constant, so the +/// contact policies behave as ONE shared bucket per policy, which is why the contact routes are +/// disabled (Contact:Enabled=false) until the per-client partitioning from the ASF branch +/// has been merged. Switching to per-client is the one-line change documented in the rebase +/// checklist: replace the body with ClientPartitionKey.For(context). +/// +public static class ContactRateLimitPartition +{ + public const string GlobalKey = "global"; + + public static string KeyFor(HttpContext context) => GlobalKey; +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs new file mode 100644 index 0000000..1b47483 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs @@ -0,0 +1,205 @@ +using Microsoft.EntityFrameworkCore; +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; + +public interface IContactSubmissionService +{ + Task SubmitAsync(ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken); +} + +/// +/// Handles one submission: validate, de-duplicate, classify (genuine or spam), store, mail. +/// Genuine messages, spam and replays are indistinguishable to the caller (the same 202), so +/// bots learn nothing. Nothing personal is ever logged: only the outcome and the site id. +/// +public sealed class ContactSubmissionService( + IContactRepository repository, + IContactTokenService tokens, + ICaptchaVerifier captcha, + IContactMailSender mailSender, + IOptions options, + TimeProvider time, + ILogger logger) : IContactSubmissionService +{ + private static readonly TimeSpan IdempotencyWindow = TimeSpan.FromHours(24); + + private enum Outcome { Genuine, Spam, SpamNotStored, Replay } + + public async Task SubmitAsync( + ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken) + { + var o = options.Value; + var siteId = o.EffectiveSiteId; + + // 1. Header and fields (one response lists every problem). + var errors = new Dictionary(); + Guid key = default; + if (string.IsNullOrWhiteSpace(idempotencyKey)) + { + errors["idempotencyKey"] = [ContactErrorCodes.Required]; + } + else if (!Guid.TryParse(idempotencyKey, out key)) + { + errors["idempotencyKey"] = [ContactErrorCodes.Invalid]; + } + + if (request is null) + { + errors["body"] = [ContactErrorCodes.Invalid]; + } + else + { + request = ContactValidator.Normalize(request); + foreach (var (field, codes) in ContactValidator.Validate(request)) + { + errors[field] = codes; + } + } + + if (errors.Count > 0) + { + return new SubmissionResult.Invalid(errors); + } + + var now = time.GetUtcNow(); + + // 2. Replay within 24 hours: the same answer, nothing stored twice. + var existing = await repository.GetIdempotencyAsync(siteId, key, cancellationToken); + if (existing is not null && now - existing.CreatedAt < IdempotencyWindow) + { + Log(Outcome.Replay, siteId); + return new SubmissionResult.Received(); + } + + // 3. Token. Forged, other-site and expired tokens all look the same ('expired'): no oracle. + var tokenCheck = tokens.Check(request!.Token); + if (tokenCheck == TokenCheck.InvalidOrExpired) + { + return new SubmissionResult.Invalid(new Dictionary + { + ["token"] = [ContactErrorCodes.Expired], + }); + } + + // 4. Classify. A filled honeypot, a too-fast submission or a rejected captcha is spam. + var isSpam = tokenCheck == TokenCheck.TooYoung + || !string.IsNullOrEmpty(request.HpCheck) + || (o.Captcha.Enabled && !await captcha.VerifyAsync(request.CaptchaToken, cancellationToken)); + + // 5. Store. Spam is kept for a short time (a real visitor may have tripped a check) but + // capped per day so a flood cannot fill the table. + ContactMessage? message = null; + var outcome = Outcome.Genuine; + if (isSpam) + { + var startOfDay = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero); + var spamToday = await repository.CountSpamSinceAsync(siteId, startOfDay, cancellationToken); + if (spamToday < o.MaxSpamRowsPerDay) + { + message = NewMessage(request, siteId, now, ContactMessageStatus.Spam, ContactMailStatus.NotApplicable, + now.AddDays(o.SpamRetentionDays)); + outcome = Outcome.Spam; + } + else + { + outcome = Outcome.SpamNotStored; + } + } + else + { + message = NewMessage(request, siteId, now, ContactMessageStatus.New, ContactMailStatus.Pending, + now.AddMonths(o.RetentionMonths)); + } + + if (message is not null) + { + repository.Add(message); + } + + if (existing is null) + { + repository.Add(new IdempotencyRecord + { + SiteId = siteId, + Key = key, + CreatedAt = now, + StatusCode = StatusCodes202, + }); + } + else + { + // An expired record that the daily job has not removed yet: reuse its row. + existing.CreatedAt = now; + existing.StatusCode = StatusCodes202; + } + + try + { + await repository.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Two requests with the same key raced; the other one won. Same answer, nothing twice. + Log(Outcome.Replay, siteId); + return new SubmissionResult.Received(); + } + + // 6. Mail, only for genuine messages and only after the message is safely stored. A mail + // problem never fails the request. + if (outcome == Outcome.Genuine && message is not null) + { + await TryMailAsync(message, cancellationToken); + } + + Log(outcome, siteId); + return new SubmissionResult.Received(); + } + + private const int StatusCodes202 = 202; + + private async Task TryMailAsync(ContactMessage message, CancellationToken cancellationToken) + { + try + { + var result = await mailSender.SendAsync(message, cancellationToken); + if (result == ContactMailOutcome.Skipped) + { + return; + } + + message.MailAttempts++; + message.MailStatus = result == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed; + await repository.SaveChangesAsync(cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Type only: the exception message could carry addresses or content. + logger.LogError("Notification mail for a contact message failed ({ExceptionType})", ex.GetType().Name); + } + } + + private static ContactMessage NewMessage( + ContactMessageRequest request, string siteId, DateTimeOffset now, + ContactMessageStatus status, ContactMailStatus mailStatus, DateTimeOffset retentionUntil) => new() + { + Id = Guid.NewGuid(), + SiteId = siteId, + ReceivedAt = now, + Name = request.Name!, + Email = request.Email!, + Subject = request.Subject!, + Message = request.Message!, + Status = status, + MailStatus = mailStatus, + RetentionUntil = retentionUntil, + }; + + private void Log(Outcome outcome, string siteId) + => logger.LogInformation("Contact submission handled: {Outcome} for site {SiteId}", outcome, siteId); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs new file mode 100644 index 0000000..ed167ed --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs @@ -0,0 +1,83 @@ +using System.Globalization; +using System.Security.Cryptography; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; + +namespace SlpModularCms.Modules.Contact.Services; + +public enum TokenCheck +{ + Valid, + + /// Issued less than MinSeconds ago: the form was filled in faster than a person can. + TooYoung, + + /// Forged, garbage, from another site, or older than its lifetime. Never distinguished to the caller. + InvalidOrExpired, +} + +public interface IContactTokenService +{ + string Issue(); + TokenCheck Check(string? token); +} + +/// +/// Server-signed token for the minimum-time check. Protected with ASP.NET Data Protection (the +/// host stores the key ring in the database), bound to the site by the purpose string, so a token +/// of one site is garbage to another. Nothing is stored. +/// +public sealed class ContactTokenService : IContactTokenService +{ + private const string Version = "v1"; + + private readonly IDataProtector _protector; + private readonly ContactOptions _options; + private readonly TimeProvider _time; + + public ContactTokenService(IDataProtectionProvider provider, IOptions options, TimeProvider time) + { + _options = options.Value; + _time = time; + _protector = provider.CreateProtector(PurposeFor(_options.EffectiveSiteId)); + } + + public static string PurposeFor(string siteId) => $"SlpModularCms.Contact.Token.{siteId}"; + + public string Issue() + => _protector.Protect($"{Version}|{_time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}"); + + public TokenCheck Check(string? token) + { + if (string.IsNullOrWhiteSpace(token)) + { + return TokenCheck.InvalidOrExpired; + } + + string payload; + try + { + payload = _protector.Unprotect(token); + } + catch (CryptographicException) + { + return TokenCheck.InvalidOrExpired; + } + + var parts = payload.Split('|'); + if (parts.Length != 2 || parts[0] != Version + || !long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var issuedAt)) + { + return TokenCheck.InvalidOrExpired; + } + + var age = _time.GetUtcNow().ToUnixTimeSeconds() - issuedAt; + if (age < 0 || age > TimeSpan.FromMinutes(_options.TokenLifetimeMinutes).TotalSeconds) + { + return TokenCheck.InvalidOrExpired; + } + + return age < _options.MinSeconds ? TokenCheck.TooYoung : TokenCheck.Valid; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs b/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs new file mode 100644 index 0000000..2392e2c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs @@ -0,0 +1,115 @@ +using System.Text.RegularExpressions; +using SlpModularCms.Modules.Contact.Models; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Field rules of the contact form. Pure: no I/O, no clock. The same limits and codes are used +/// by the client so the two can never disagree silently. +/// +public static class ContactValidator +{ + public const int NameMax = 100; + public const int EmailMax = 254; + public const int SubjectMax = 100; + public const int MessageMax = 2000; + + private static readonly Regex EmailPattern = + new(@"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$", RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250)); + + /// The request with all text fields trimmed (null stays null). + public static ContactMessageRequest Normalize(ContactMessageRequest request) => request with + { + Name = request.Name?.Trim(), + Email = request.Email?.Trim(), + Subject = request.Subject?.Trim(), + Message = request.Message?.Trim(), + Token = request.Token?.Trim(), + }; + + /// Validates an already normalized request. Keys are the JSON field names. + public static Dictionary Validate(ContactMessageRequest request) + { + var errors = new Dictionary(); + + Check(errors, "name", request.Name, NameMax, allowLineBreaks: false); + CheckEmail(errors, request.Email); + Check(errors, "subject", request.Subject, SubjectMax, allowLineBreaks: false); + Check(errors, "message", request.Message, MessageMax, allowLineBreaks: true); + + if (string.IsNullOrWhiteSpace(request.Token)) + { + errors["token"] = [ContactErrorCodes.Required]; + } + + return errors; + } + + private static void Check(Dictionary errors, string field, string? value, int max, bool allowLineBreaks) + { + if (string.IsNullOrEmpty(value)) + { + errors[field] = [ContactErrorCodes.Required]; + } + else if (value.Length > max) + { + errors[field] = [ContactErrorCodes.TooLong]; + } + else if (HasControlCharacters(value, allowLineBreaks)) + { + errors[field] = [ContactErrorCodes.Invalid]; + } + } + + private static void CheckEmail(Dictionary errors, string? value) + { + if (string.IsNullOrEmpty(value)) + { + errors["email"] = [ContactErrorCodes.Required]; + } + else if (value.Length > EmailMax) + { + errors["email"] = [ContactErrorCodes.TooLong]; + } + else if (HasControlCharacters(value, allowLineBreaks: false) || !IsEmailShaped(value)) + { + errors["email"] = [ContactErrorCodes.Invalid]; + } + } + + private static bool IsEmailShaped(string value) + { + try + { + return EmailPattern.IsMatch(value); + } + catch (RegexMatchTimeoutException) + { + return false; + } + } + + /// + /// Control characters would end up in mail headers (header injection) or break displays. + /// In the message, tabs and line breaks are normal text and allowed. + /// + internal static bool HasControlCharacters(string value, bool allowLineBreaks) + { + foreach (var c in value) + { + if (!char.IsControl(c)) + { + continue; + } + + if (allowLineBreaks && (c is '\n' or '\r' or '\t')) + { + continue; + } + + return true; + } + + return false; + } +} diff --git a/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj b/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj new file mode 100644 index 0000000..c323c4e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + + + + + <_Parameter1>SlpModularCms.Modules.Contact.Tests + + + + + + + +