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:
@@ -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",
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user