Contactbeheer: berichten, schakelaar en tweelaagse poort voor het formulier

Beheerroutes zonder /admin-segment op contact-messages (lijst met spam apart en ongelezen-teller zonder spam, detail, status, verwijderen, opnieuw versturen met eigen limiet) en contact-settings voor de CMS-schakelaar, allemaal AdminOnly. Het formulier is alleen open als de hostvlag EN de CMS-schakelaar (standaard uit) aan staan; de hostvlag wordt eerst gecontroleerd zodat de database niet wordt aangeraakt. Bij uitgeschakelde host antwoorden de beheerroutes 404. OpenAPI-document bijgewerkt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:07:28 +01:00
co-authored by Claude Sonnet 5.5
parent f8d45eef54
commit e53b318c31
23 changed files with 2704 additions and 10 deletions
@@ -101,6 +101,10 @@
"ContactToken": {
"PermitLimit": 20,
"WindowSeconds": 600
},
"ContactResend": {
"PermitLimit": 5,
"WindowSeconds": 600
}
},
"SecurityHeaders": {
@@ -0,0 +1,313 @@
using System.Reflection;
using System.Security.Claims;
using FluentAssertions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.Routing;
using NSubstitute;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactAdminControllerTests
{
private readonly IContactAdminService _service = Substitute.For<IContactAdminService>();
private readonly IContactSettingsService _settings = Substitute.For<IContactSettingsService>();
private ContactMessagesAdminController Messages(string? typeBase = null) => new(_service, Options.Create(new ContactOptions { Enabled = true, ProblemTypeBase = typeBase }))
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() },
};
private ContactSettingsController Settings(Guid? userId = null)
{
var http = new DefaultHttpContext();
if (userId is not null)
{
http.User = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuth"));
}
return new ContactSettingsController(_settings, Options.Create(new ContactOptions { Enabled = true }))
{
ControllerContext = new ControllerContext { HttpContext = http },
};
}
private static void AssertInvalid(IActionResult result, params string[] fields)
{
var obj = result.Should().BeOfType<ObjectResult>().Subject;
obj.StatusCode.Should().Be(400);
obj.ContentTypes.Should().Contain("application/problem+json");
var problem = obj.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
problem.Errors.Keys.Should().BeEquivalentTo(fields);
problem.Errors.Values.Should().OnlyContain(v => v.Length == 1 && v[0] == "invalid");
}
// ---- list ----
[Fact]
public async Task List_Returns200_WithTheServiceResult()
{
var list = new ContactMessageList([], 1, 25, 0, 0);
_service.ListAsync(null, 1, 25, Arg.Any<CancellationToken>()).Returns(list);
var result = await Messages().List(null, 1, 25);
result.Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(list);
}
[Theory]
[InlineData(0, 25, null, "page")]
[InlineData(-3, 25, null, "page")]
[InlineData(1, 0, null, "pageSize")]
[InlineData(1, 101, null, "pageSize")]
[InlineData(1, 25, "bogus", "status")]
[InlineData(1, 25, "converted", "status")]
public async Task List_Returns400_NamingTheBadParameter(int page, int pageSize, string? status, string field)
{
var result = await Messages().List(status, page, pageSize);
AssertInvalid(result, field);
await _service.DidNotReceive().ListAsync(Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task List_Returns400_ForAnUnparsablePageNumber()
{
var controller = Messages();
controller.ModelState.AddModelError("page", "The value 'abc' is not valid.");
var result = await controller.List(null);
AssertInvalid(result, "page");
}
// ---- detail, status, delete, resend ----
[Fact]
public async Task Get_Returns200_Or404()
{
var id = Guid.NewGuid();
_service.GetAsync(id, Arg.Any<CancellationToken>()).Returns((ContactMessageDetail?)null);
(await Messages().Get(id, CancellationToken.None)).Should().BeOfType<NotFoundResult>();
var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", "new", "pending", 0, null, DateTimeOffset.UtcNow);
_service.GetAsync(id, Arg.Any<CancellationToken>()).Returns(detail);
(await Messages().Get(id, CancellationToken.None)).Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(detail);
}
[Theory]
[InlineData("new", ContactMessageStatus.New)]
[InlineData("read", ContactMessageStatus.Read)]
[InlineData("archived", ContactMessageStatus.Archived)]
[InlineData("ARCHIVED", ContactMessageStatus.Archived)]
public async Task SetStatus_AcceptsNewReadArchived(string value, ContactMessageStatus expected)
{
var id = Guid.NewGuid();
var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", value.ToLowerInvariant(), "pending", 0, null, DateTimeOffset.UtcNow);
_service.SetStatusAsync(id, expected, Arg.Any<CancellationToken>()).Returns(detail);
var result = await Messages().SetStatus(id, new UpdateContactMessageStatusRequest(value), CancellationToken.None);
result.Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(detail);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("spam")]
[InlineData("converted")]
[InlineData("deleted")]
public async Task SetStatus_RejectsEverythingElse_WithErrorsStatus(string? value)
{
var result = await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest(value), CancellationToken.None);
AssertInvalid(result, "status");
await _service.DidNotReceive().SetStatusAsync(Arg.Any<Guid>(), Arg.Any<ContactMessageStatus>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetStatus_RejectsAnUnreadableBody()
{
var controller = Messages();
controller.ModelState.AddModelError("$.status", "bad");
AssertInvalid(await controller.SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status");
AssertInvalid(await Messages().SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status");
}
[Fact]
public async Task SetStatus_Returns404_ForAnUnknownMessage()
{
_service.SetStatusAsync(Arg.Any<Guid>(), Arg.Any<ContactMessageStatus>(), Arg.Any<CancellationToken>()).Returns((ContactMessageDetail?)null);
(await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest("read"), CancellationToken.None))
.Should().BeOfType<NotFoundResult>();
}
[Fact]
public async Task Delete_Returns204_Or404()
{
var id = Guid.NewGuid();
_service.DeleteAsync(id, Arg.Any<CancellationToken>()).Returns(true, false);
(await Messages().Delete(id, CancellationToken.None)).Should().BeOfType<NoContentResult>();
(await Messages().Delete(id, CancellationToken.None)).Should().BeOfType<NotFoundResult>();
}
[Fact]
public async Task Resend_Returns200_404_Or409ForSpam()
{
var id = Guid.NewGuid();
var result = new ContactResendResult("sent", 1, true);
_service.ResendAsync(id, Arg.Any<CancellationToken>()).Returns(result);
(await Messages().Resend(id, CancellationToken.None)).Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(result);
_service.ResendAsync(id, Arg.Any<CancellationToken>()).Returns((ContactResendResult?)null);
(await Messages().Resend(id, CancellationToken.None)).Should().BeOfType<NotFoundResult>();
_service.ResendAsync(id, Arg.Any<CancellationToken>()).Returns<Task<ContactResendResult?>>(_ => throw new ContactResendNotAllowedException());
var conflict = (ObjectResult)await Messages().Resend(id, CancellationToken.None);
conflict.StatusCode.Should().Be(409);
conflict.ContentTypes.Should().Contain("application/problem+json");
conflict.Value.Should().BeOfType<ProblemDetails>().Which.Status.Should().Be(409);
}
// ---- settings ----
[Fact]
public async Task GetSettings_ReturnsTheSingleton()
{
_settings.GetAsync(Arg.Any<CancellationToken>()).Returns(new ContactSettingsDto(false, true));
var result = await Settings().Get(CancellationToken.None);
result.Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(new ContactSettingsDto(false, true));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task PutSettings_StoresTheBoolean_RecordingWhoDidIt(bool enabled)
{
var user = Guid.NewGuid();
_settings.SetEnabledAsync(enabled, user, Arg.Any<CancellationToken>()).Returns(new ContactSettingsDto(enabled, true));
var result = await Settings(user).Put(new UpdateContactSettingsRequest(enabled), CancellationToken.None);
result.Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(new ContactSettingsDto(enabled, true));
}
[Fact]
public async Task PutSettings_RejectsAMissingNullOrNonBooleanValue_WithErrorsEnabled()
{
AssertInvalid(await Settings().Put(null, CancellationToken.None), "enabled");
AssertInvalid(await Settings().Put(new UpdateContactSettingsRequest(null), CancellationToken.None), "enabled");
var controller = Settings();
controller.ModelState.AddModelError("$.enabled", "The JSON value could not be converted to System.Boolean.");
AssertInvalid(await controller.Put(new UpdateContactSettingsRequest(true), CancellationToken.None), "enabled");
await _settings.DidNotReceive().SetEnabledAsync(Arg.Any<bool>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
// ---- route table (every route of the management side) ----
private static readonly Type[] AdminControllers = [typeof(ContactMessagesAdminController), typeof(ContactSettingsController)];
private static IEnumerable<(Type Controller, MethodInfo Action, HttpMethodAttribute Http)> AdminActions() =>
AdminControllers.SelectMany(c => c
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Select(m => (Controller: c, Action: m, Http: m.GetCustomAttributes<HttpMethodAttribute>().SingleOrDefault()))
.Where(x => x.Http is not null)
.Select(x => (x.Controller, x.Action, x.Http!)));
[Fact]
public void RouteTable_TheManagementRoutesAreExactlyTheAgreedSet()
{
AdminActions().Select(a =>
$"{a.Http.HttpMethods.Single()} {a.Controller.GetCustomAttribute<RouteAttribute>()!.Template}/{a.Http.Template}".TrimEnd('/'))
.Should().BeEquivalentTo(
[
"GET contact-messages",
"GET contact-messages/{id:guid}",
"PATCH contact-messages/{id:guid}",
"DELETE contact-messages/{id:guid}",
"POST contact-messages/{id:guid}/resend",
"GET contact-settings",
"PUT contact-settings",
]);
}
[Fact]
public void RouteTable_EveryManagementRoute_IsAdminOnly_NeverAnonymous_NeverPublic_AndHasNoAdminSegment()
{
foreach (var controller in AdminControllers)
{
controller.GetCustomAttribute<AuthorizeAttribute>()!.Policy.Should().Be("AdminOnly");
controller.GetCustomAttribute<ServiceFilterAttribute>()!.ServiceType.Should().Be(typeof(ContactAdminRouteFilter));
controller.GetCustomAttribute<RouteAttribute>()!.Template.Should().NotContainEquivalentOf("admin");
}
foreach (var (controller, action, http) in AdminActions())
{
var name = $"{controller.Name}.{action.Name}";
action.GetCustomAttribute<AllowAnonymousAttribute>().Should().BeNull($"{name} must not be anonymous");
action.GetCustomAttribute<PublicSiteEndpointAttribute>().Should().BeNull($"{name} must stay behind the availability gate");
action.GetCustomAttributes<AuthorizeAttribute>().Where(a => a.Policy != "AdminOnly").Should().BeEmpty();
(http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin");
}
}
[Fact]
public void RouteTable_OnlyTwoActionsOfTheWholeContactModuleArePublic()
{
var publicActions = typeof(ContactModule).Assembly.GetTypes()
.Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract)
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
.Where(m => m.GetCustomAttribute<PublicSiteEndpointAttribute>() is not null)
.Select(m => $"{m.DeclaringType!.Name}.{m.Name}");
publicActions.Should().BeEquivalentTo(
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}",
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}");
}
[Fact]
public void ResendHasItsOwnRateLimitPolicy()
{
typeof(ContactMessagesAdminController).GetMethod(nameof(ContactMessagesAdminController.Resend))!
.GetCustomAttribute<EnableRateLimitingAttribute>()!.PolicyName.Should().Be("contact-resend");
}
// ---- the host switch on the management side ----
private static ResourceExecutingContext ResourceContext() => new(
new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
new List<IFilterMetadata>(),
new List<IValueProviderFactory>());
[Fact]
public void AdminRouteFilter_Answers404_WhileTheHostSwitchIsOff_AndPassesWhenItIsOn()
{
var off = ResourceContext();
new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = false })).OnResourceExecuting(off);
off.Result.Should().BeOfType<NotFoundResult>();
var on = ResourceContext();
new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = true })).OnResourceExecuting(on);
on.Result.Should().BeNull();
}
}
@@ -0,0 +1,321 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public sealed class AdminHarness : IDisposable
{
public static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
public FakeTimeProvider Time { get; } = new(Now);
public ContactOptions Options { get; } = new() { Enabled = true, SiteId = "site-a", RetentionMonths = 12 };
public ContactDbContext Db { get; }
public IContactMailSender Mail { get; } = Substitute.For<IContactMailSender>();
public CapturingLoggerProvider Logs { get; } = new();
public ContactAdminService Sut { get; }
public AdminHarness()
{
Db = new ContactDbContext(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options);
Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Skipped);
Sut = new ContactAdminService(
new ContactRepository(Db),
Mail,
Microsoft.Extensions.Options.Options.Create(Options),
Time,
LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger<ContactAdminService>());
}
public ContactMessage Add(
ContactMessageStatus status = ContactMessageStatus.New, int minutesAgo = 0, string site = "site-a",
string name = "Jan", ContactMailStatus mail = ContactMailStatus.Pending)
{
var message = new ContactMessage
{
Id = Guid.NewGuid(),
SiteId = site,
ReceivedAt = Now.AddMinutes(-minutesAgo),
Name = name,
Email = "jan@example.nl",
Subject = "website",
Message = "Hallo",
Status = status,
MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : mail,
RetentionUntil = status == ContactMessageStatus.Spam ? Now.AddDays(10) : Now.AddMonths(11),
};
Db.ContactMessages.Add(message);
Db.SaveChanges();
return message;
}
public void Dispose() => Db.Dispose();
}
public class ContactAdminServiceTests
{
[Fact]
public async Task TheDefaultList_ExcludesSpam_ShowsTheRest_NewestFirst()
{
using var h = new AdminHarness();
var oldest = h.Add(ContactMessageStatus.Archived, minutesAgo: 30);
var newest = h.Add(ContactMessageStatus.New, minutesAgo: 1);
var middle = h.Add(ContactMessageStatus.Read, minutesAgo: 10);
h.Add(ContactMessageStatus.Spam, minutesAgo: 0);
var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None);
list!.Items.Select(i => i.Id).Should().Equal(newest.Id.ToString(), middle.Id.ToString(), oldest.Id.ToString());
list.TotalCount.Should().Be(3);
list.Items.Should().NotContain(i => i.Status == "spam");
}
[Theory]
[InlineData("new", "new")]
[InlineData("read", "read")]
[InlineData("archived", "archived")]
[InlineData("spam", "spam")]
[InlineData("SPAM", "spam")]
public async Task AStatusFilter_ShowsOnlyThatStatus(string filter, string expected)
{
using var h = new AdminHarness();
h.Add(ContactMessageStatus.New);
h.Add(ContactMessageStatus.Read);
h.Add(ContactMessageStatus.Archived);
h.Add(ContactMessageStatus.Spam);
h.Add(ContactMessageStatus.Spam);
var list = await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None);
list!.Items.Should().OnlyContain(i => i.Status == expected);
list.TotalCount.Should().Be(expected == "spam" ? 2 : 1);
}
[Theory]
[InlineData("converted")]
[InlineData("nonsense")]
public async Task AnUnknownOrUnlistableStatus_IsRejected(string filter)
{
using var h = new AdminHarness();
(await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None)).Should().BeNull();
}
[Theory]
[InlineData(0, 25)]
[InlineData(-1, 25)]
[InlineData(1, 0)]
[InlineData(1, 101)]
public async Task PageAndPageSize_MustBeInRange(int page, int pageSize)
{
using var h = new AdminHarness();
(await h.Sut.ListAsync(null, page, pageSize, CancellationToken.None)).Should().BeNull();
}
[Fact]
public async Task Paging_ReturnsTheRequestedSliceAndTheTotal()
{
using var h = new AdminHarness();
for (var i = 0; i < 30; i++)
{
h.Add(ContactMessageStatus.Read, minutesAgo: i);
}
var third = await h.Sut.ListAsync(null, 3, 10, CancellationToken.None);
var fourth = await h.Sut.ListAsync(null, 4, 10, CancellationToken.None);
third!.Items.Should().HaveCount(10);
third.Page.Should().Be(3);
third.PageSize.Should().Be(10);
third.TotalCount.Should().Be(30);
fourth!.Items.Should().BeEmpty();
fourth.TotalCount.Should().Be(30);
third.Items.Select(i => i.ReceivedAt).Should().BeInDescendingOrder();
}
[Fact]
public async Task TheUnreadCount_CountsOnlyNew_NeverSpam_AndIgnoresTheFilter()
{
using var h = new AdminHarness();
h.Add(ContactMessageStatus.New);
h.Add(ContactMessageStatus.New);
h.Add(ContactMessageStatus.Read);
h.Add(ContactMessageStatus.Spam);
h.Add(ContactMessageStatus.Spam);
h.Add(ContactMessageStatus.Spam);
h.Add(ContactMessageStatus.New, site: "another-site");
(await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2);
(await h.Sut.ListAsync("spam", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2, "spam does not count and the filter does not matter");
(await h.Sut.ListAsync("read", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2);
}
[Fact]
public async Task OtherSitesMessages_AreInvisible()
{
using var h = new AdminHarness();
var foreign = h.Add(site: "another-site");
(await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.TotalCount.Should().Be(0);
(await h.Sut.GetAsync(foreign.Id, CancellationToken.None)).Should().BeNull();
(await h.Sut.DeleteAsync(foreign.Id, CancellationToken.None)).Should().BeFalse();
(await h.Sut.SetStatusAsync(foreign.Id, ContactMessageStatus.Read, CancellationToken.None)).Should().BeNull();
(await h.Sut.ResendAsync(foreign.Id, CancellationToken.None)).Should().BeNull();
}
[Fact]
public async Task TheListItems_DoNotCarryTheMessageText_ButTheDetailDoes()
{
using var h = new AdminHarness();
var message = h.Add();
var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None);
var detail = await h.Sut.GetAsync(message.Id, CancellationToken.None);
typeof(SlpModularCms.Modules.Contact.Models.ContactMessageListItem).GetProperties().Select(p => p.Name)
.Should().NotContain("Message");
list!.Items.Single().Name.Should().Be("Jan");
detail!.Message.Should().Be("Hallo");
detail.MailAttempts.Should().Be(0);
detail.RetentionUntil.Should().Be(message.RetentionUntil);
detail.Status.Should().Be("new");
detail.MailStatus.Should().Be("pending");
}
[Fact]
public async Task AnUnknownId_GivesNull()
{
using var h = new AdminHarness();
(await h.Sut.GetAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull();
}
[Theory]
[InlineData(ContactMessageStatus.New)]
[InlineData(ContactMessageStatus.Read)]
[InlineData(ContactMessageStatus.Archived)]
public async Task TheStatusOfARegularMessage_CanBeChanged_WithoutTouchingItsRetention(ContactMessageStatus target)
{
using var h = new AdminHarness();
var message = h.Add(ContactMessageStatus.Read);
var retention = message.RetentionUntil;
var result = await h.Sut.SetStatusAsync(message.Id, target, CancellationToken.None);
result!.Status.Should().Be(target.ToString().ToLowerInvariant());
(await h.Db.ContactMessages.AsNoTracking().SingleAsync()).RetentionUntil.Should().Be(retention);
}
[Fact]
public async Task MarkingSpamAsNotSpam_FollowsTheNormalRetention_AndKeepsMailNotApplicable()
{
using var h = new AdminHarness();
var spam = h.Add(ContactMessageStatus.Spam);
h.Options.RetentionMonths = 12;
var result = await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.Read, CancellationToken.None);
result!.Status.Should().Be("read");
result.MailStatus.Should().Be("notApplicable");
result.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12));
(await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.Items.Should().ContainSingle(i => i.Id == spam.Id.ToString());
}
[Fact]
public async Task Delete_RemovesTheMessageForGood()
{
using var h = new AdminHarness();
var message = h.Add();
(await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeTrue();
h.Db.ContactMessages.Should().BeEmpty();
(await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeFalse();
}
[Fact]
public async Task Resend_OfASpamMessage_IsNotAllowed_AndNothingIsSent()
{
using var h = new AdminHarness();
var spam = h.Add(ContactMessageStatus.Spam);
var act = () => h.Sut.ResendAsync(spam.Id, CancellationToken.None);
await act.Should().ThrowAsync<ContactResendNotAllowedException>();
await h.Mail.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Resend_RecordsASentMail()
{
using var h = new AdminHarness();
var message = h.Add();
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None);
result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("sent", 1, true));
(await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailStatus.Should().Be(ContactMailStatus.Sent);
}
[Fact]
public async Task Resend_RecordsAFailedMail()
{
using var h = new AdminHarness();
var message = h.Add();
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Failed);
var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None);
result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("failed", 1, false));
}
[Fact]
public async Task Resend_WhenNoMailCanBeSent_ChangesNothing_AndSaysSo()
{
using var h = new AdminHarness();
var message = h.Add();
var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None);
result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("pending", 0, false));
(await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailAttempts.Should().Be(0);
}
[Fact]
public async Task Resend_OfAnUnknownMessage_GivesNull()
{
using var h = new AdminHarness();
(await h.Sut.ResendAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull();
}
[Fact]
public async Task NoPersonalDataIsLogged_ByAnyAdminAction()
{
using var h = new AdminHarness();
var message = h.Add(name: "ZXQ-Admin-Marker");
var spam = h.Add(ContactMessageStatus.Spam, name: "ZXQ-Spam-Marker");
await h.Sut.ListAsync(null, 1, 25, CancellationToken.None);
await h.Sut.GetAsync(message.Id, CancellationToken.None);
await h.Sut.SetStatusAsync(message.Id, ContactMessageStatus.Read, CancellationToken.None);
await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.New, CancellationToken.None);
await h.Sut.ResendAsync(message.Id, CancellationToken.None);
await h.Sut.DeleteAsync(message.Id, CancellationToken.None);
h.Logs.Messages.Should().NotBeEmpty();
h.Logs.Messages.Should().NotContain(m => m.Contains("ZXQ") || m.Contains("example.nl") || m.Contains("Hallo"));
}
}
@@ -0,0 +1,175 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactSettingsServiceTests
{
private sealed class Setup : IDisposable
{
public FakeTimeProvider Time { get; } = new(new DateTimeOffset(2026, 11, 9, 12, 0, 0, TimeSpan.Zero));
public ContactOptions Options { get; } = new() { Enabled = true };
public ContactDbContext Db { get; } = new(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
public ContactSettingsCache Cache { get; }
public ContactSettingsService Sut { get; }
public Setup()
{
Cache = new ContactSettingsCache(Time);
Sut = new ContactSettingsService(
new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time);
}
public void Dispose() => Db.Dispose();
}
[Fact]
public async Task WithoutARow_TheSwitchIsOff()
{
using var s = new Setup();
(await s.Sut.GetAsync(CancellationToken.None)).Should().Be(new ContactSettingsDto(false, true));
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse();
}
[Fact]
public async Task HostEnabled_ReflectsTheHostSwitch_ReadOnly()
{
using var s = new Setup();
s.Options.Enabled = false;
(await s.Sut.GetAsync(CancellationToken.None)).HostEnabled.Should().BeFalse();
}
[Fact]
public async Task SettingTheSwitch_CreatesTheSingletonRow_ThenUpdatesIt_AndRemembersWhoAndWhen()
{
using var s = new Setup();
var user = Guid.NewGuid();
var on = await s.Sut.SetEnabledAsync(true, user, CancellationToken.None);
s.Time.Advance(TimeSpan.FromMinutes(5));
var off = await s.Sut.SetEnabledAsync(false, Guid.NewGuid(), CancellationToken.None);
on.Should().Be(new ContactSettingsDto(true, true));
off.Should().Be(new ContactSettingsDto(false, true));
var rows = await s.Db.ContactSettings.AsNoTracking().ToListAsync();
rows.Should().ContainSingle().Which.Id.Should().Be(ContactSettings.SingletonId);
rows[0].Enabled.Should().BeFalse();
rows[0].UpdatedAt.Should().Be(s.Time.GetUtcNow());
}
[Fact]
public async Task TheUserWhoChangedItIsStored()
{
using var s = new Setup();
var user = Guid.NewGuid();
await s.Sut.SetEnabledAsync(true, user, CancellationToken.None);
(await s.Db.ContactSettings.AsNoTracking().SingleAsync()).UpdatedByUserId.Should().Be(user);
}
[Fact]
public async Task ThePublicCheck_IsCachedBriefly_AndRefreshedAfterwards()
{
using var s = new Setup();
await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None);
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue(); // fills the cache
// Another instance flips the row behind this one's back.
var row = await s.Db.ContactSettings.SingleAsync();
row.Enabled = false;
await s.Db.SaveChangesAsync();
s.Time.Advance(TimeSpan.FromSeconds(4));
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue("still within the cache lifetime");
s.Time.Advance(TimeSpan.FromSeconds(2));
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse("the cache expired");
}
[Fact]
public async Task ChangingTheSwitch_TakesEffectAtOnceInThisProcess()
{
using var s = new Setup();
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse(); // cached: off
await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None);
(await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue();
}
[Fact]
public async Task TheAdministratorsOwnView_IsNeverServedFromTheCache()
{
using var s = new Setup();
await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None);
await s.Sut.IsEnabledAsync(CancellationToken.None);
var row = await s.Db.ContactSettings.SingleAsync();
row.Enabled = false;
await s.Db.SaveChangesAsync();
(await s.Sut.GetAsync(CancellationToken.None)).Enabled.Should().BeFalse();
}
[Fact]
public void TheCacheLifetime_IsFiveSeconds()
{
ContactSettingsCache.Lifetime.Should().Be(TimeSpan.FromSeconds(5));
}
}
public class ContactFormGateTests
{
private static IContactFormGate Layer(bool open)
{
var gate = Substitute.For<IContactFormGate>();
gate.IsOpenAsync(Arg.Any<CancellationToken>()).Returns(open);
return gate;
}
[Theory]
[InlineData(true, true, true)]
[InlineData(true, false, false)]
[InlineData(false, true, false)]
[InlineData(false, false, false)]
public async Task TheFormIsOpen_OnlyWhenEveryLayerIsOpen(bool host, bool cms, bool expected)
{
var gate = new CompositeContactFormGate([Layer(host), Layer(cms)]);
(await gate.IsOpenAsync(CancellationToken.None)).Should().Be(expected);
}
[Fact]
public async Task WhenTheFirstLayerIsClosed_TheSecondIsNeverAsked_SoTheDatabaseIsNotTouched()
{
var host = Layer(false);
var cms = Layer(true);
await new CompositeContactFormGate([host, cms]).IsOpenAsync(CancellationToken.None);
await host.Received(1).IsOpenAsync(Arg.Any<CancellationToken>());
await cms.DidNotReceive().IsOpenAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task TheCmsLayer_FollowsTheSettingsService()
{
var settings = Substitute.For<IContactSettingsService>();
settings.IsEnabledAsync(Arg.Any<CancellationToken>()).Returns(true, false);
var gate = new CmsFlagContactFormGate(settings);
(await gate.IsOpenAsync(CancellationToken.None)).Should().BeTrue();
(await gate.IsOpenAsync(CancellationToken.None)).Should().BeFalse();
}
}
@@ -0,0 +1,343 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>Mints access tokens the way the host itself does (same settings, same claims).</summary>
internal static class Jwt
{
public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null)
{
var settings = factory.Services.GetRequiredService<IConfiguration>().GetSection("JwtSettings");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings["Secret"]!));
var token = new JwtSecurityToken(
issuer: settings["Issuer"],
audience: settings["Audience"],
claims:
[
new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()),
new Claim(ClaimTypes.Role, role),
],
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
var client = factory.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token));
return client;
}
public static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
}
public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture<ClosedCmsSwitchContactHostFactory>
{
private const string Messages = "/api/v1/contact-messages";
private const string Settings = "/api/v1/contact-settings";
private async Task<Guid> SeedAsync(ContactMessageStatus status, string name, int minutesAgo = 0)
{
var id = Guid.NewGuid();
await factory.WithDb(async db =>
{
db.ContactMessages.Add(new ContactMessage
{
Id = id, SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddMinutes(-minutesAgo),
Name = name, Email = "x@example.nl", Subject = "website", Message = "Hallo",
Status = status,
MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : ContactMailStatus.Pending,
RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11),
});
await db.SaveChangesAsync();
return 0;
});
return id;
}
// ---- authentication and authorization ----
[Theory]
[InlineData("GET", Messages)]
[InlineData("GET", Settings)]
[InlineData("PUT", Settings)]
[InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")]
[InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")]
public async Task EveryManagementRoute_RequiresLogin(string method, string url)
{
var request = new HttpRequestMessage(new HttpMethod(method), url);
if (method is "PUT" or "PATCH")
{
request.Content = Jwt.Json("{}");
}
var response = await factory.CreateClient().SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Theory]
[InlineData("GET", Messages)]
[InlineData("GET", Settings)]
[InlineData("PUT", Settings)]
[InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")]
[InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")]
public async Task EveryManagementRoute_IsForbidden_ForARegularUser(string method, string url)
{
var request = new HttpRequestMessage(new HttpMethod(method), url);
if (method is "PUT" or "PATCH")
{
request.Content = Jwt.Json("""{"enabled":true,"status":"read"}""");
}
var response = await Jwt.ClientWithRole(factory, "User").SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}
[Fact]
public async Task APutOnTheSwitchByANonAdmin_Is403_AndChangesNothing()
{
// The other tests in this class may have created the row; what matters is that this call changes nothing.
var before = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync());
var response = await Jwt.ClientWithRole(factory, "User").PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
var after = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync());
after.Should().BeEquivalentTo(before);
(await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK);
}
// ---- the switch ----
[Fact]
public async Task TheCmsSwitch_IsOffByDefault_AndTheStateIsReportedWithTheHostSwitch()
{
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings);
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}""");
}
[Theory]
[InlineData("""{"enabled":"yes"}""")]
[InlineData("""{"enabled":1}""")]
[InlineData("""{"enabled":null}""")]
[InlineData("{}")]
[InlineData("not json")]
[InlineData("")]
public async Task APutWithoutABoolean_Is400_WithErrorsEnabled(string body)
{
var response = await Jwt.ClientWithRole(factory, "Administrator").PutAsync(Settings, Jwt.Json(body));
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("errors").GetProperty("enabled")[0].GetString().Should().Be("invalid");
doc.RootElement.GetProperty("errors").EnumerateObject().Should().ContainSingle();
}
[Fact]
public async Task TheSwitch_OpensAndClosesThePublicRoutes_AtOnce_WhileTheManagementRoutesKeepWorking()
{
var admin = Jwt.ClientWithRole(factory, "Administrator");
var visitor = factory.CreateClient();
// Default: closed. 404 with an empty body, the website shows its mailto fallback.
var closed = await visitor.GetAsync($"{Messages}/token");
closed.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await closed.Content.ReadAsStringAsync()).Should().BeEmpty();
var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
on.StatusCode.Should().Be(HttpStatusCode.OK);
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}""");
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK);
var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
off.StatusCode.Should().Be(HttpStatusCode.OK);
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.NotFound);
var post = await visitor.PostAsync(Messages, Jwt.Json("{}"));
post.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await post.Content.ReadAsStringAsync()).Should().BeEmpty();
// The management side is never closed by the CMS switch.
(await admin.GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK);
(await admin.GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task TheUserWhoChangedTheSwitch_IsRecorded()
{
var user = Guid.NewGuid();
await Jwt.ClientWithRole(factory, "Owner", user).PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
(await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync())).UpdatedByUserId.Should().Be(user);
}
// ---- messages ----
[Fact]
public async Task TheMessageFlow_ListDetailStatusSpamDeleteResend()
{
var admin = Jwt.ClientWithRole(factory, "Administrator");
var first = await SeedAsync(ContactMessageStatus.New, "Flow Eerste", minutesAgo: 10);
var second = await SeedAsync(ContactMessageStatus.New, "Flow Tweede", minutesAgo: 5);
var spam = await SeedAsync(ContactMessageStatus.Spam, "Flow Spam", minutesAgo: 1);
// Default list: no spam; unread counts only the new ones.
using (var list = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync()))
{
var names = list.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()).ToList();
names.Should().Contain(["Flow Eerste", "Flow Tweede"]).And.NotContain("Flow Spam");
list.RootElement.GetProperty("unreadCount").GetInt32().Should().BeGreaterThanOrEqualTo(2);
list.RootElement.GetProperty("items")[0].TryGetProperty("message", out _).Should().BeFalse("the list has no message text");
}
// Spam apart.
using (var spamList = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?status=spam")).Content.ReadAsStringAsync()))
{
spamList.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString())
.Should().Equal("Flow Spam");
}
// Detail.
using (var detail = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}/{first}")).Content.ReadAsStringAsync()))
{
detail.RootElement.GetProperty("message").GetString().Should().Be("Hallo");
detail.RootElement.GetProperty("status").GetString().Should().Be("new");
detail.RootElement.GetProperty("mailStatus").GetString().Should().Be("pending");
}
// Status change.
var patch = await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"read"}"""));
patch.StatusCode.Should().Be(HttpStatusCode.OK);
(await patch.Content.ReadAsStringAsync()).Should().Contain("\"status\":\"read\"");
(await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"spam"}"""))).StatusCode.Should().Be(HttpStatusCode.BadRequest);
// Resend: spam is refused, a regular message answers (no mail sender yet: mailed=false).
(await admin.PostAsync($"{Messages}/{spam}/resend", null)).StatusCode.Should().Be(HttpStatusCode.Conflict);
var resend = await admin.PostAsync($"{Messages}/{second}/resend", null);
resend.StatusCode.Should().Be(HttpStatusCode.OK);
(await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false}""");
// Not spam after all: now in the default list.
(await admin.PatchAsync($"{Messages}/{spam}", Jwt.Json("""{"status":"archived"}"""))).StatusCode.Should().Be(HttpStatusCode.OK);
using (var again = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync()))
{
again.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString())
.Should().Contain("Flow Spam");
}
// Delete.
(await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NoContent);
(await admin.GetAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound);
(await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Theory]
[InlineData("?page=0")]
[InlineData("?pageSize=101")]
[InlineData("?status=bogus")]
[InlineData("?page=abc")]
public async Task ABadListQuery_Is400_InTheContractShape(string query)
{
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages + query);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
}
[Fact]
public async Task ABadStatusBody_Is400_WithErrorsStatus()
{
var id = await SeedAsync(ContactMessageStatus.New, "Pipeline Patch");
var response = await Jwt.ClientWithRole(factory, "Administrator").PatchAsync($"{Messages}/{id}", Jwt.Json("""{"status":"nope"}"""));
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("errors").GetProperty("status")[0].GetString().Should().Be("invalid");
}
// ---- the availability gate ----
[Fact]
public async Task WhenTheCmsIsDisabled_TheManagementRoutesAreBlockedForVisitors_ButNotForAnAdministrator()
{
await factory.WithDb(db => db.Database.ExecuteSqlRawAsync(
"INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')"));
// No marker on the management routes: anonymous callers meet the gate (503), not even a 401.
(await factory.CreateClient().GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
(await factory.CreateClient().GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
(await Jwt.ClientWithRole(factory, "User").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
// By design a verified administrator can always reach a disabled CMS (to switch it back on).
(await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK);
}
}
public class ContactAdminHostSwitchPipelineTests(DisabledContactHostFactory factory) : IClassFixture<DisabledContactHostFactory>
{
[Theory]
[InlineData("GET", "/api/v1/contact-messages")]
[InlineData("GET", "/api/v1/contact-settings")]
public async Task WhileTheHostSwitchIsOff_TheManagementRoutesAre404_WithAnEmptyBody(string method, string url)
{
var response = await Jwt.ClientWithRole(factory, "Administrator").SendAsync(new HttpRequestMessage(new HttpMethod(method), url));
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await response.Content.ReadAsStringAsync()).Should().BeEmpty();
}
[Fact]
public async Task WhileTheHostSwitchIsOff_AnonymousCallersStillMeetAuthenticationFirst()
{
(await factory.CreateClient().GetAsync("/api/v1/contact-settings")).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
}
public class ContactResendRateLimitPipelineTests(TightResendContactHostFactory factory) : IClassFixture<TightResendContactHostFactory>
{
[Fact]
public async Task Resend_Answers429_WithRetryAfter_AfterItsOwnLimit()
{
var id = Guid.NewGuid();
await factory.WithDb(async db =>
{
db.ContactMessages.Add(new ContactMessage
{
Id = id, SiteId = "default", ReceivedAt = DateTimeOffset.UtcNow, Name = "n", Email = "e@example.nl",
Subject = "s", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending,
RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11),
});
await db.SaveChangesAsync();
return 0;
});
var admin = Jwt.ClientWithRole(factory, "Administrator");
HttpResponseMessage? last = null;
for (var i = 0; i < 3; i++)
{
last = await admin.PostAsync($"/api/v1/contact-messages/{id}/resend", null);
}
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue();
int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1);
last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
}
}
@@ -15,8 +15,31 @@ namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// databases on. Every factory uses its own freshly created database and drops it again.
/// To run only the pure unit tests use <c>--filter "FullyQualifiedName!~Pipeline"</c>.
/// </summary>
public class ContactHostFactory : WebApplicationFactory<Program>
public class ContactHostFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
/// <summary>Whether the CMS switch (layer 2 of the gate) is turned on right after start-up.</summary>
protected virtual bool OpenCmsSwitch => false;
Task IAsyncLifetime.InitializeAsync() => OpenCmsSwitch ? OpenCmsSwitchAsync() : Task.CompletedTask;
Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
private async Task OpenCmsSwitchAsync()
{
_ = CreateClient(); // starts the host (migrates the contact tables)
await WithDb(async db =>
{
db.ContactSettings.Add(new Data.Entities.ContactSettings
{
Enabled = true,
UpdatedAt = DateTimeOffset.UtcNow,
UpdatedByUserId = Guid.NewGuid(),
});
await db.SaveChangesAsync();
return 0;
});
}
private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection";
private readonly Dictionary<string, string?> _settings;
@@ -83,7 +106,21 @@ public class ContactHostFactory : WebApplicationFactory<Program>
}
}
/// <summary>Host switch on, CMS switch ON: the contact form is fully open.</summary>
public sealed class EnabledContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Host switch on, CMS switch OFF (its default): the public routes are closed, the admin routes work.</summary>
public sealed class ClosedCmsSwitchContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
@@ -92,6 +129,7 @@ public sealed class EnabledContactHostFactory() : ContactHostFactory(new()
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
/// <summary>Host switch OFF (the default): the whole module is inactive.</summary>
public sealed class DisabledContactHostFactory() : ContactHostFactory;
/// <summary>Only the form policy is tight, so a token can still be fetched freely.</summary>
@@ -101,7 +139,10 @@ public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new(
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "2",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Only the token policy is tight.</summary>
public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new()
@@ -110,4 +151,14 @@ public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "2",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Only the resend policy is tight; the CMS switch is off.</summary>
public sealed class TightResendContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["RateLimiting:ContactResend:PermitLimit"] = "2",
});
@@ -45,8 +45,20 @@ public class ContactModule : IModule
services.AddSingleton<IContactTokenService, ContactTokenService>();
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
services.AddScoped<IContactMailSender, NoOpContactMailSender>();
services.AddScoped<IContactFormGate, HostFlagContactFormGate>();
// Gate: the form is open only if the host switch AND the CMS switch are on. The host switch
// is asked first, so with it off the database is never touched.
services.AddSingleton<ContactSettingsCache>();
services.AddScoped<IContactSettingsService, ContactSettingsService>();
services.AddScoped<HostFlagContactFormGate>();
services.AddScoped<CmsFlagContactFormGate>();
services.AddScoped<IContactFormGate>(sp => new CompositeContactFormGate(
[
sp.GetRequiredService<HostFlagContactFormGate>(),
sp.GetRequiredService<CmsFlagContactFormGate>(),
]));
services.AddScoped<IContactAdminService, ContactAdminService>();
services.AddScoped<ContactRouteFilter>();
services.AddScoped<ContactAdminRouteFilter>();
services.AddHostedService<ContactRetentionService>();
// The contact details of the OpenAPI document (named options of document 'v1', so the shared
@@ -62,6 +74,8 @@ public class ContactModule : IModule
Window(config, "ContactForm", 5, 600, context));
limiter.AddPolicy(ContactMessagesController.TokenPolicy, context =>
Window(config, "ContactToken", 20, 600, context));
limiter.AddPolicy(ContactMessagesAdminController.ResendPolicy, context =>
Window(config, "ContactResend", 5, 600, context));
});
}
@@ -0,0 +1,164 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>
/// The management routes need the contact tables, which exist only while the host switch
/// (<c>Contact:Enabled</c>) is on. While it is off they answer 404 with an empty body. The CMS
/// switch deliberately does NOT close them: otherwise nobody could switch the form back on.
/// </summary>
public sealed class ContactAdminRouteFilter(IOptions<ContactOptions> options) : IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
if (!options.Value.Enabled)
{
context.Result = new NotFoundResult();
}
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
}
/// <summary>
/// Management of the stored messages. Same resource name as the public routes, no admin segment:
/// access is decided by authorization alone (AdminOnly). Not an <c>[ApiController]</c>, like the
/// public controller, so every 400 is in our own problem shape.
/// </summary>
[ApiExplorerSettings(IgnoreApi = false)]
[Route("contact-messages")]
[Authorize(Policy = "AdminOnly")]
[ServiceFilter(typeof(ContactAdminRouteFilter))]
public class ContactMessagesAdminController(IContactAdminService service, IOptions<ContactOptions> options) : ControllerBase
{
public const string ResendPolicy = "contact-resend";
[HttpGet]
[ProducesResponseType(typeof(ContactMessageList), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
public async Task<IActionResult> List(
[FromQuery] string? status, [FromQuery] int page = 1, [FromQuery] int pageSize = ContactAdminService.DefaultPageSize,
CancellationToken cancellationToken = default)
{
var invalid = new List<string>();
foreach (var (key, entry) in ModelState)
{
if (entry.Errors.Count > 0)
{
invalid.Add(key is "page" or "pageSize" or "status" ? key : "query");
}
}
if (page < 1 && !invalid.Contains("page")) invalid.Add("page");
if ((pageSize < 1 || pageSize > ContactAdminService.MaxPageSize) && !invalid.Contains("pageSize")) invalid.Add("pageSize");
if (!string.IsNullOrWhiteSpace(status) && !ContactStatusNames.TryParseListable(status, out _) && !invalid.Contains("status")) invalid.Add("status");
if (invalid.Count > 0)
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, invalid.Distinct().ToArray());
}
var result = await service.ListAsync(status, page, pageSize, cancellationToken);
return result is null ? ContactProblems.Invalid(options.Value.ProblemTypeBase, "query") : Ok(result);
}
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
{
var message = await service.GetAsync(id, cancellationToken);
return message is null ? NotFound() : Ok(message);
}
[HttpPatch("{id:guid}")]
[Consumes("application/json")]
[ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> SetStatus(
Guid id, [FromBody] UpdateContactMessageStatusRequest? request, CancellationToken cancellationToken)
{
if (!ModelState.IsValid || request is null || !ContactStatusNames.TryParseSettable(request.Status, out var status))
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "status");
}
var message = await service.SetStatusAsync(id, status, cancellationToken);
return message is null ? NotFound() : Ok(message);
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
=> await service.DeleteAsync(id, cancellationToken) ? NoContent() : NotFound();
[HttpPost("{id:guid}/resend")]
[EnableRateLimiting(ResendPolicy)]
[ProducesResponseType(typeof(ContactResendResult), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict, "application/problem+json")]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")]
public async Task<IActionResult> Resend(Guid id, CancellationToken cancellationToken)
{
try
{
var result = await service.ResendAsync(id, cancellationToken);
return result is null ? NotFound() : Ok(result);
}
catch (ContactResendNotAllowedException ex)
{
return ContactProblems.Conflict(ex.Message);
}
}
}
/// <summary>
/// The CMS switch of the contact form: a singleton resource. The form is open only when this
/// switch AND the host switch are on. Default: off.
/// </summary>
[ApiExplorerSettings(IgnoreApi = false)]
[Route("contact-settings")]
[Authorize(Policy = "AdminOnly")]
[ServiceFilter(typeof(ContactAdminRouteFilter))]
public class ContactSettingsController(IContactSettingsService service, IOptions<ContactOptions> options) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
=> Ok(await service.GetAsync(cancellationToken));
[HttpPut]
[Consumes("application/json")]
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
public async Task<IActionResult> Put([FromBody] UpdateContactSettingsRequest? request, CancellationToken cancellationToken)
{
// A missing or non-boolean 'enabled' (or an unreadable body) is reported as errors.enabled.
if (!ModelState.IsValid || request?.Enabled is not { } enabled)
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "enabled");
}
return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken));
}
private Guid CallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
}
@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>The problem+json answers of the contact routes, in one place.</summary>
internal static class ContactProblems
{
public const string ContentType = "application/problem+json";
/// <summary>A 400 with the contract's <c>errors</c> map (field name -> codes).</summary>
public static ObjectResult Validation(IReadOnlyDictionary<string, string[]> errors, string? typeBase)
{
var baseUri = typeBase?.TrimEnd('/');
var problem = new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value))
{
Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation",
Title = "Validation failed",
Status = StatusCodes.Status400BadRequest,
};
return new ObjectResult(problem)
{
StatusCode = StatusCodes.Status400BadRequest,
ContentTypes = { ContentType },
};
}
/// <summary>A 400 that names the given fields as <c>invalid</c>.</summary>
public static ObjectResult Invalid(string? typeBase, params string[] fields)
=> Validation(fields.ToDictionary(f => f, _ => new[] { "invalid" }), typeBase);
public static ObjectResult Conflict(string title) => new(new ProblemDetails
{
Status = StatusCodes.Status409Conflict,
Title = title,
})
{
StatusCode = StatusCodes.Status409Conflict,
ContentTypes = { ContentType },
};
}
@@ -7,6 +7,7 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
{
public DbSet<ContactMessage> ContactMessages => Set<ContactMessage>();
public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();
public DbSet<ContactSettings> ContactSettings => Set<ContactSettings>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -31,6 +32,16 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
entity.HasIndex(e => e.RetentionUntil);
});
modelBuilder.Entity<ContactSettings>(entity =>
{
entity.ToTable("ContactSettings");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Enabled).IsRequired();
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.UpdatedByUserId).IsRequired();
});
modelBuilder.Entity<IdempotencyRecord>(entity =>
{
entity.ToTable("ContactIdempotency");
@@ -56,3 +56,18 @@ public class IdempotencyRecord
public DateTimeOffset CreatedAt { get; set; }
public int StatusCode { get; set; }
}
/// <summary>
/// The CMS-controlled on/off switch of the contact form (a singleton row, id 1). While no row
/// exists the switch is off. It is the second layer of the gate; the host switch
/// (<c>Contact:Enabled</c>) is the first.
/// </summary>
public class ContactSettings
{
public const int SingletonId = 1;
public int Id { get; set; } = SingletonId;
public bool Enabled { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public Guid UpdatedByUserId { get; set; }
}
@@ -0,0 +1,134 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
[Migration("20261109202158_AddContactSettings")]
partial class AddContactSettings
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<int>("MailAttempts")
.HasColumnType("int");
b.Property<string>("MailError")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("MailStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset?>("NextMailAttemptAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("ReceivedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("RetentionUntil")
.HasColumnType("datetime");
b.Property<string>("SiteId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("RetentionUntil");
b.HasIndex("SiteId", "Status", "ReceivedAt");
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<Guid>("UpdatedByUserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.ToTable("ContactSettings", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<Guid>("Key")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.HasKey("SiteId", "Key");
b.HasIndex("CreatedAt");
b.ToTable("ContactIdempotency", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,37 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
/// <inheritdoc />
public partial class AddContactSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ContactSettings",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
Enabled = table.Column<bool>(type: "tinyint(1)", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
UpdatedByUserId = table.Column<Guid>(type: "char(36)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactSettings", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContactSettings");
}
}
}
@@ -85,6 +85,25 @@ namespace SlpModularCms.Modules.Contact.Migrations
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<Guid>("UpdatedByUserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.ToTable("ContactSettings", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
@@ -0,0 +1,93 @@
using System.Diagnostics.CodeAnalysis;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Models;
// JSON shapes of the management routes. Statuses are lower-camel strings:
// status: new | read | archived | spam | converted
// mailStatus: pending | sent | failed | notApplicable
[ExcludeFromCodeCoverage]
public record ContactMessageListItem(
string Id,
DateTimeOffset ReceivedAt,
string Name,
string Email,
string Subject,
string Status,
string MailStatus);
[ExcludeFromCodeCoverage]
public record ContactMessageList(
IReadOnlyList<ContactMessageListItem> Items,
int Page,
int PageSize,
int TotalCount,
int UnreadCount);
[ExcludeFromCodeCoverage]
public record ContactMessageDetail(
string Id,
DateTimeOffset ReceivedAt,
string Name,
string Email,
string Subject,
string Message,
string Status,
string MailStatus,
int MailAttempts,
string? MailError,
DateTimeOffset RetentionUntil);
/// <summary>Body of PATCH /contact-messages/{id}. Nullable so a missing field is reported in our own shape.</summary>
public record UpdateContactMessageStatusRequest(string? Status);
[ExcludeFromCodeCoverage]
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed);
[ExcludeFromCodeCoverage]
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
/// <summary>Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled.</summary>
public record UpdateContactSettingsRequest(bool? Enabled);
/// <summary>The wire names of the statuses.</summary>
public static class ContactStatusNames
{
public static string Of(ContactMessageStatus status) => status switch
{
ContactMessageStatus.New => "new",
ContactMessageStatus.Read => "read",
ContactMessageStatus.Archived => "archived",
ContactMessageStatus.Spam => "spam",
ContactMessageStatus.Converted => "converted",
_ => throw new ArgumentOutOfRangeException(nameof(status)),
};
public static string Of(ContactMailStatus status) => status switch
{
ContactMailStatus.Pending => "pending",
ContactMailStatus.Sent => "sent",
ContactMailStatus.Failed => "failed",
ContactMailStatus.NotApplicable => "notApplicable",
_ => throw new ArgumentOutOfRangeException(nameof(status)),
};
/// <summary>Parses a filter value (case-insensitive); only the statuses that can be listed.</summary>
public static bool TryParseListable(string? value, out ContactMessageStatus status)
{
status = default;
switch (value?.Trim().ToLowerInvariant())
{
case "new": status = ContactMessageStatus.New; return true;
case "read": status = ContactMessageStatus.Read; return true;
case "archived": status = ContactMessageStatus.Archived; return true;
case "spam": status = ContactMessageStatus.Spam; return true;
default: return false;
}
}
/// <summary>Parses a value an administrator may set: new, read or archived.</summary>
public static bool TryParseSettable(string? value, out ContactMessageStatus status)
=> TryParseListable(value, out status) && status != ContactMessageStatus.Spam;
}
@@ -13,6 +13,21 @@ public interface IContactRepository
Task SaveChangesAsync(CancellationToken cancellationToken);
Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken);
Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
// ---- management (admin) ----
/// <summary>One page of messages of the given statuses, newest first, plus the total count of that selection.</summary>
Task<(IReadOnlyList<ContactMessage> Items, int TotalCount)> ListAsync(
string siteId, IReadOnlyCollection<ContactMessageStatus> statuses, int skip, int take, CancellationToken cancellationToken);
/// <summary>Messages with status New. Spam is never counted.</summary>
Task<int> CountUnreadAsync(string siteId, CancellationToken cancellationToken);
Task<ContactMessage?> GetAsync(string siteId, Guid id, CancellationToken cancellationToken);
void Remove(ContactMessage message);
Task<ContactSettings?> GetSettingsAsync(CancellationToken cancellationToken);
void Add(ContactSettings settings);
}
public class ContactRepository(ContactDbContext context) : IContactRepository
@@ -33,6 +48,52 @@ public class ContactRepository(ContactDbContext context) : IContactRepository
public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
public async Task<(IReadOnlyList<ContactMessage> Items, int TotalCount)> ListAsync(
string siteId, IReadOnlyCollection<ContactMessageStatus> statuses, int skip, int take, CancellationToken cancellationToken)
{
// One flag per status instead of 'statuses.Contains(m.Status)': the status is stored as a
// string through a value converter, and a parameterized collection loses that mapping in
// the SQL translation.
var wantNew = statuses.Contains(ContactMessageStatus.New);
var wantRead = statuses.Contains(ContactMessageStatus.Read);
var wantArchived = statuses.Contains(ContactMessageStatus.Archived);
var wantSpam = statuses.Contains(ContactMessageStatus.Spam);
var wantConverted = statuses.Contains(ContactMessageStatus.Converted);
var query = context.ContactMessages
.AsNoTracking()
.Where(m => m.SiteId == siteId
&& ((wantNew && m.Status == ContactMessageStatus.New)
|| (wantRead && m.Status == ContactMessageStatus.Read)
|| (wantArchived && m.Status == ContactMessageStatus.Archived)
|| (wantSpam && m.Status == ContactMessageStatus.Spam)
|| (wantConverted && m.Status == ContactMessageStatus.Converted)));
var total = await query.CountAsync(cancellationToken);
var items = await query
.OrderByDescending(m => m.ReceivedAt)
.ThenBy(m => m.Id)
.Skip(skip)
.Take(take)
.ToListAsync(cancellationToken);
return (items, total);
}
public Task<int> CountUnreadAsync(string siteId, CancellationToken cancellationToken)
=> context.ContactMessages.CountAsync(
m => m.SiteId == siteId && m.Status == ContactMessageStatus.New, cancellationToken);
public Task<ContactMessage?> GetAsync(string siteId, Guid id, CancellationToken cancellationToken)
=> context.ContactMessages.FirstOrDefaultAsync(m => m.SiteId == siteId && m.Id == id, cancellationToken);
public void Remove(ContactMessage message) => context.ContactMessages.Remove(message);
public Task<ContactSettings?> GetSettingsAsync(CancellationToken cancellationToken)
=> context.ContactSettings.FirstOrDefaultAsync(s => s.Id == ContactSettings.SingletonId, cancellationToken);
public void Add(ContactSettings settings) => context.ContactSettings.Add(settings);
public async Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
var total = 0;
@@ -0,0 +1,151 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>Thrown when a spam message is resent; it must be marked as not spam first.</summary>
public sealed class ContactResendNotAllowedException() : Exception("A spam message cannot be resent; mark it as not spam first.");
public interface IContactAdminService
{
/// <summary>Null when page or pageSize is out of range or the status filter is unknown (the caller reports 400).</summary>
Task<ContactMessageList?> ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken);
Task<ContactMessageDetail?> GetAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Null when the message does not exist.</summary>
Task<ContactMessageDetail?> SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken);
Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Null when the message does not exist. Throws <see cref="ContactResendNotAllowedException"/> for spam.</summary>
Task<ContactResendResult?> ResendAsync(Guid id, CancellationToken cancellationToken);
}
/// <summary>
/// Everything an administrator does with the stored messages. Spam is kept apart: it is never in
/// the default list and never counted as unread. Nothing personal is logged, only ids and outcomes.
/// </summary>
public sealed class ContactAdminService(
IContactRepository repository,
IContactMailSender mailSender,
IOptions<ContactOptions> options,
TimeProvider time,
ILogger<ContactAdminService> logger) : IContactAdminService
{
public const int DefaultPageSize = 25;
public const int MaxPageSize = 100;
private static readonly ContactMessageStatus[] DefaultStatuses =
[ContactMessageStatus.New, ContactMessageStatus.Read, ContactMessageStatus.Archived];
public async Task<ContactMessageList?> ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken)
{
if (page < 1 || pageSize < 1 || pageSize > MaxPageSize)
{
return null;
}
ContactMessageStatus[] statuses;
if (string.IsNullOrWhiteSpace(status))
{
statuses = DefaultStatuses;
}
else if (ContactStatusNames.TryParseListable(status, out var parsed))
{
statuses = [parsed];
}
else
{
return null;
}
var siteId = options.Value.EffectiveSiteId;
var (items, total) = await repository.ListAsync(siteId, statuses, (page - 1) * pageSize, pageSize, cancellationToken);
var unread = await repository.CountUnreadAsync(siteId, cancellationToken);
return new ContactMessageList(
items.Select(m => new ContactMessageListItem(
m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject,
ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus))).ToList(),
page, pageSize, total, unread);
}
public async Task<ContactMessageDetail?> GetAsync(Guid id, CancellationToken cancellationToken)
{
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
return message is null ? null : ToDetail(message);
}
public async Task<ContactMessageDetail?> SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken)
{
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
if (message is null)
{
return null;
}
// Marking a spam message as read/new/archived means "this was a real person": it then
// follows the normal retention instead of being deleted after the short spam period.
if (message.Status == ContactMessageStatus.Spam)
{
message.RetentionUntil = time.GetUtcNow().AddMonths(options.Value.RetentionMonths);
}
message.Status = status;
await repository.SaveChangesAsync(cancellationToken);
logger.LogInformation("Contact message {MessageId} set to {Status}", message.Id, status);
return ToDetail(message);
}
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken)
{
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
if (message is null)
{
return false;
}
repository.Remove(message);
await repository.SaveChangesAsync(cancellationToken);
logger.LogInformation("Contact message {MessageId} deleted", id);
return true;
}
public async Task<ContactResendResult?> ResendAsync(Guid id, CancellationToken cancellationToken)
{
var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken);
if (message is null)
{
return null;
}
if (message.Status == ContactMessageStatus.Spam)
{
throw new ContactResendNotAllowedException();
}
var outcome = await mailSender.SendAsync(message, cancellationToken);
if (outcome != ContactMailOutcome.Skipped)
{
message.MailAttempts++;
message.MailStatus = outcome == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
await repository.SaveChangesAsync(cancellationToken);
}
logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, outcome);
return new ContactResendResult(
ContactStatusNames.Of(message.MailStatus), message.MailAttempts, outcome == ContactMailOutcome.Sent);
}
private static ContactMessageDetail ToDetail(ContactMessage m) => new(
m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, m.Message,
ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus),
m.MailAttempts, m.MailError, m.RetentionUntil);
}
@@ -0,0 +1,126 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// The latest known value of the CMS switch, shared by all requests of this process. Short-lived
/// so the public routes do not query the database on every request, and dropped immediately when
/// the switch is changed here (other instances see a change after at most <see cref="Lifetime"/>).
/// </summary>
public sealed class ContactSettingsCache(TimeProvider time)
{
public static readonly TimeSpan Lifetime = TimeSpan.FromSeconds(5);
private readonly object _lock = new();
private bool _value;
private DateTimeOffset _expires = DateTimeOffset.MinValue;
public bool TryGet(out bool enabled)
{
lock (_lock)
{
enabled = _value;
return time.GetUtcNow() < _expires;
}
}
public void Set(bool enabled)
{
lock (_lock)
{
_value = enabled;
_expires = time.GetUtcNow() + Lifetime;
}
}
public void Invalidate()
{
lock (_lock)
{
_expires = DateTimeOffset.MinValue;
}
}
}
public interface IContactSettingsService
{
/// <summary>The CMS switch (a missing row means off).</summary>
Task<bool> IsEnabledAsync(CancellationToken cancellationToken);
Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken);
Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken);
}
public sealed class ContactSettingsService(
IContactRepository repository,
ContactSettingsCache cache,
IOptions<ContactOptions> options,
TimeProvider time) : IContactSettingsService
{
public async Task<bool> IsEnabledAsync(CancellationToken cancellationToken)
{
if (cache.TryGet(out var cached))
{
return cached;
}
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
cache.Set(enabled);
return enabled;
}
public async Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// The administrator's own view is never served from the cache.
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
return new ContactSettingsDto(enabled, options.Value.Enabled);
}
public async Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken)
{
var settings = await repository.GetSettingsAsync(cancellationToken);
if (settings is null)
{
settings = new ContactSettings();
repository.Add(settings);
}
settings.Enabled = enabled;
settings.UpdatedAt = time.GetUtcNow();
settings.UpdatedByUserId = userId;
await repository.SaveChangesAsync(cancellationToken);
cache.Invalidate();
return new ContactSettingsDto(enabled, options.Value.Enabled);
}
}
/// <summary>Layer 2: the switch an administrator controls in the CMS.</summary>
public sealed class CmsFlagContactFormGate(IContactSettingsService settings) : IContactFormGate
{
public Task<bool> IsOpenAsync(CancellationToken cancellationToken) => settings.IsEnabledAsync(cancellationToken);
}
/// <summary>
/// The form is open only if every layer is open. Layers are asked in order and the first closed
/// one ends the check, so with the host switch off the database is never touched.
/// </summary>
public sealed class CompositeContactFormGate(IReadOnlyList<IContactFormGate> layers) : IContactFormGate
{
public async Task<bool> IsOpenAsync(CancellationToken cancellationToken)
{
foreach (var layer in layers)
{
if (!await layer.IsOpenAsync(cancellationToken))
{
return false;
}
}
return true;
}
}