Contactmodule: token- en inzendroute met spamafhandeling, idempotentie en retentietaak

Nieuwe module SlpModularCms.Modules.Contact met eigen DbContext en migratie InitialCreate. GET contact-messages/token en POST contact-messages zijn publiek ([PublicSiteEndpoint]), geven bij echte inzendingen, spam en herhalingen hetzelfde 202 en slaan spam apart op (30 dagen, dagplafond). Standaard staat de module uit (Contact:Enabled=false, 404 met lege body, geen databasetoegang) totdat de rate limiting per client op de basisbranch staat; de rate-limit-sleutel zit in een enkele functie zodat dat later een regel wijzigen is. Mail zit achter een seam (nog een no-op).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:07:27 +01:00
co-authored by Claude Sonnet 5.5
parent 0f6f5475a1
commit 7748bbe9c9
37 changed files with 3266 additions and 9 deletions
@@ -0,0 +1,3 @@
// Exposes the top-level-statements Program class so WebApplicationFactory<Program> can start the
// composed host in tests (same approach as SlpModularCms.Api/Program.Coverage.cs).
public partial class Program { }
@@ -20,6 +20,7 @@
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
@@ -61,6 +61,22 @@
"Cors": {
"AllowedOrigins": []
},
"Contact": {
// OFF by default. Do not enable on a public host until per-client rate limiting is on the
// base branch (see ContactRateLimitPartition): until then the contact rate limits are one
// bucket shared by all visitors.
"Enabled": false,
"SiteId": "slpsoftware",
"MinSeconds": 3,
"TokenLifetimeMinutes": 120,
"RetentionMonths": 12,
"SpamRetentionDays": 30,
"MaxSpamRowsPerDay": 200,
"MaxBodyBytes": 16384,
"Captcha": {
"Enabled": false
}
},
"RateLimiting": {
"Login": {
"PermitLimit": 5,
@@ -77,6 +93,14 @@
"OfferingsPublic": {
"PermitLimit": 120,
"WindowSeconds": 60
},
"ContactForm": {
"PermitLimit": 5,
"WindowSeconds": 600
},
"ContactToken": {
"PermitLimit": 20,
"WindowSeconds": 600
}
},
"SecurityHeaders": {
@@ -13,6 +13,7 @@ using SlpModularCms.Core.Observability;
using SlpModularCms.Modules.Availability.Controllers;
using SlpModularCms.Modules.Availability.Middleware;
using SlpModularCms.Modules.Availability.Services;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Identity.Controllers;
using SlpModularCms.Modules.Master.Controllers;
using SlpModularCms.Modules.Offerings.Controllers;
@@ -158,6 +159,8 @@ public class PublicSiteEndpointGateTests
private static readonly string[] AllowedPublicActions =
[
$"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}",
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}",
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}",
];
private static IReadOnlyList<MethodInfo> AllActions() =>
@@ -167,6 +170,7 @@ public class PublicSiteEndpointGateTests
typeof(UsersController).Assembly,
typeof(CmsInstanceController).Assembly,
typeof(OfferingsController).Assembly,
typeof(ContactMessagesController).Assembly,
typeof(SystemController).Assembly,
}
.Distinct()
@@ -34,6 +34,7 @@
<!-- Only for the route-table test (PublicSiteEndpointGateTests): it inspects the controllers of
every module a host can load to prove which endpoints stay reachable behind the gate. -->
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Offerings\SlpModularCms.Modules.Offerings.csproj" />
@@ -0,0 +1,292 @@
using System.Reflection;
using FluentAssertions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.Routing;
using NSubstitute;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactMessagesControllerTests
{
private readonly IContactTokenService _tokens = Substitute.For<IContactTokenService>();
private readonly IContactSubmissionService _submissions = Substitute.For<IContactSubmissionService>();
private ContactMessagesController Create(ContactOptions? options = null, string? idempotencyKey = null)
{
var controller = new ContactMessagesController(_tokens, _submissions, Options.Create(options ?? new ContactOptions { Enabled = true }))
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() },
};
if (idempotencyKey is not null)
{
controller.Request.Headers[ContactMessagesController.IdempotencyKeyHeader] = idempotencyKey;
}
return controller;
}
[Fact]
public void GetToken_ReturnsTheTokenTheMinimumTime_AndNoCaptchaByDefault()
{
_tokens.Issue().Returns("tok");
var result = Create(new ContactOptions { Enabled = true, MinSeconds = 5 }).GetToken();
var body = result.Should().BeOfType<OkObjectResult>().Subject.Value.Should().BeOfType<ContactTokenResponse>().Subject;
body.Should().Be(new ContactTokenResponse("tok", 5, null));
}
[Fact]
public void GetToken_ReportsTheCaptchaProviderAndSiteKey_WhenEnabled_ButNeverTheSecret()
{
_tokens.Issue().Returns("tok");
var options = new ContactOptions
{
Enabled = true,
Captcha = new ContactCaptchaOptions { Enabled = true, Provider = "friendlycaptcha", SiteKey = "pub", Secret = "very-secret" },
};
var result = Create(options).GetToken();
var body = (ContactTokenResponse)((OkObjectResult)result).Value!;
body.Captcha.Should().Be(new ContactCaptchaInfo("friendlycaptcha", "pub"));
System.Text.Json.JsonSerializer.Serialize(body).Should().NotContain("very-secret");
}
[Fact]
public async Task Submit_Returns202_WithTheFixedBody_WhenReceived()
{
_submissions.SubmitAsync(Arg.Any<ContactMessageRequest?>(), "key", Arg.Any<CancellationToken>())
.Returns(new SubmissionResult.Received());
var result = await Create(idempotencyKey: "key").Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None);
var obj = result.Should().BeOfType<ObjectResult>().Subject;
obj.StatusCode.Should().Be(202);
obj.Value.Should().Be(new ReceivedResponse("received"));
}
[Fact]
public async Task Submit_Returns400_WithTheErrorsShape_AndTheConfiguredTypeBase()
{
_submissions.SubmitAsync(Arg.Any<ContactMessageRequest?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(new SubmissionResult.Invalid(new Dictionary<string, string[]> { ["email"] = ["invalid"] }));
var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" })
.Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None);
var problem = result.Should().BeOfType<BadRequestObjectResult>().Subject.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
problem.Status.Should().Be(400);
problem.Type.Should().Be("https://example.test/problems/validation");
problem.Errors["email"].Should().Equal("invalid");
}
[Fact]
public async Task Submit_UsesAboutBlank_WhenNoTypeBaseIsConfigured()
{
_submissions.SubmitAsync(Arg.Any<ContactMessageRequest?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(new SubmissionResult.Invalid(new Dictionary<string, string[]> { ["name"] = ["required"] }));
var result = await Create().Submit(null, CancellationToken.None);
((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank");
}
[Fact]
public async Task Submit_PassesNull_WhenTheBodyCouldNotBeBound()
{
_submissions.SubmitAsync(Arg.Any<ContactMessageRequest?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(new SubmissionResult.Invalid(new Dictionary<string, string[]> { ["body"] = ["invalid"] }));
var controller = Create();
controller.ModelState.AddModelError("$.name", "The JSON value could not be converted");
await controller.Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None);
await _submissions.Received(1).SubmitAsync(null, Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public void TheRouteTable_HasTwoPublicRoutes_BothMarkedAnonymousAndRateLimited_AndNoAdminSegment()
{
var type = typeof(ContactMessagesController);
type.GetCustomAttribute<RouteAttribute>()!.Template.Should().Be("contact-messages");
type.GetCustomAttribute<ApiControllerAttribute>().Should().BeNull();
type.GetCustomAttribute<AuthorizeAttribute>().Should().BeNull("the management routes arrive with the admin unit");
var actions = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(m => m.GetCustomAttributes<HttpMethodAttribute>().Any())
.ToDictionary(m => $"{m.GetCustomAttribute<HttpMethodAttribute>()!.HttpMethods.Single()} {m.GetCustomAttribute<HttpMethodAttribute>()!.Template}".Trim());
actions.Keys.Should().BeEquivalentTo(["GET token", "POST"]);
foreach (var action in actions.Values)
{
action.GetCustomAttribute<AllowAnonymousAttribute>().Should().NotBeNull();
action.GetCustomAttribute<PublicSiteEndpointAttribute>().Should().NotBeNull();
}
actions["GET token"].GetCustomAttribute<EnableRateLimitingAttribute>()!.PolicyName.Should().Be("contact-token");
actions["POST"].GetCustomAttribute<EnableRateLimitingAttribute>()!.PolicyName.Should().Be("contact-form");
type.GetCustomAttribute<ServiceFilterAttribute>()!.ServiceType.Should().Be(typeof(ContactRouteFilter));
}
}
public class ContactRouteFilterTests
{
private static ResourceExecutingContext Context(string method, long? contentLength = null, IHttpMaxRequestBodySizeFeature? feature = null)
{
var http = new DefaultHttpContext();
http.Request.Method = method;
http.Request.ContentLength = contentLength;
if (feature is not null)
{
http.Features.Set(feature);
}
return new ResourceExecutingContext(
new ActionContext(http, new RouteData(), new ActionDescriptor()),
new List<IFilterMetadata>(),
new List<IValueProviderFactory>());
}
private static ContactRouteFilter Create(bool enabled, int max = 1000)
{
var options = Options.Create(new ContactOptions { Enabled = enabled, MaxBodyBytes = max });
return new ContactRouteFilter(new HostFlagContactFormGate(options), options);
}
private static ContactRouteFilter CreateWithGate(bool open, int max = 1000)
{
var gate = Substitute.For<IContactFormGate>();
gate.IsOpenAsync(Arg.Any<CancellationToken>()).Returns(open);
return new ContactRouteFilter(gate, Options.Create(new ContactOptions { Enabled = true, MaxBodyBytes = max }));
}
[Theory]
[InlineData("GET", false)]
[InlineData("POST", false)]
[InlineData("GET", true)]
[InlineData("POST", true)]
public async Task TheFilter_FollowsTheGateOnly_SoAnotherLayerCanBeAddedWithoutTouchingIt(string method, bool open)
{
var context = Context(method);
var nextCalled = false;
await CreateWithGate(open).OnResourceExecutionAsync(context, () =>
{
nextCalled = true;
return Next(context)();
});
nextCalled.Should().Be(open);
(context.Result is NotFoundResult).Should().Be(!open);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TheHostFlagGate_ReflectsContactEnabled(bool enabled)
{
var gate = new HostFlagContactFormGate(Options.Create(new ContactOptions { Enabled = enabled }));
(await gate.IsOpenAsync(CancellationToken.None)).Should().Be(enabled);
}
private static ResourceExecutionDelegate Next(ResourceExecutingContext context, Exception? exception = null)
=> () => Task.FromResult(new ResourceExecutedContext(context, new List<IFilterMetadata>()) { Exception = exception });
[Theory]
[InlineData("GET")]
[InlineData("POST")]
public async Task WhileDisabled_BothRoutesAre404_AndNothingFurtherRuns(string method)
{
var context = Context(method);
var nextCalled = false;
await Create(enabled: false).OnResourceExecutionAsync(context, () =>
{
nextCalled = true;
return Task.FromResult<ResourceExecutedContext>(null!);
});
context.Result.Should().BeOfType<NotFoundResult>();
nextCalled.Should().BeFalse();
}
[Fact]
public async Task APostBeyondTheLimit_Gets413_AsProblemJson()
{
var context = Context("POST", contentLength: 1001);
await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, Next(context));
var result = context.Result.Should().BeOfType<ObjectResult>().Subject;
result.StatusCode.Should().Be(413);
result.ContentTypes.Should().Contain("application/problem+json");
result.Value.Should().BeOfType<ProblemDetails>().Which.Status.Should().Be(413);
}
[Fact]
public async Task APostWithinTheLimit_PassesThrough_AndLimitsChunkedBodies()
{
var feature = Substitute.For<IHttpMaxRequestBodySizeFeature>();
feature.IsReadOnly.Returns(false);
var context = Context("POST", contentLength: 1000, feature: feature);
var nextCalled = false;
await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, () =>
{
nextCalled = true;
return Next(context)();
});
nextCalled.Should().BeTrue();
context.Result.Should().BeNull();
feature.MaxRequestBodySize.Should().Be(1000);
}
[Fact]
public async Task ABodyThatTurnsOutTooLargeWhileReading_BecomesA413()
{
var context = Context("POST");
ResourceExecutedContext? executed = null;
await Create(enabled: true).OnResourceExecutionAsync(context, async () =>
{
executed = await Next(
context,
new BadHttpRequestException("too large", StatusCodes.Status413PayloadTooLarge))();
return executed;
});
executed!.ExceptionHandled.Should().BeTrue();
executed.Result.Should().BeOfType<ObjectResult>().Which.StatusCode.Should().Be(413);
}
[Fact]
public async Task OtherExceptions_AreLeftAlone()
{
var context = Context("POST");
ResourceExecutedContext? executed = null;
await Create(enabled: true).OnResourceExecutionAsync(context, async () =>
{
executed = await Next(context, new InvalidOperationException("boom"))();
return executed;
});
executed!.ExceptionHandled.Should().BeFalse();
}
}
@@ -0,0 +1,92 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
/// <summary>
/// Nothing a visitor typed, and nothing that identifies a request (the Idempotency-Key and the
/// token are no personal data, but there is no reason to log them either), may ever appear in a log.
/// </summary>
public class ContactNoPersonalDataInLogsTests
{
private const string MarkerName = "ZXQ-Name-Marker";
private const string MarkerEmail = "zxq-marker@example.test";
private const string MarkerSubject = "ZXQ-Subject-Marker";
private const string MarkerMessage = "ZXQ-Message-Marker";
private static ContactMessageRequest Marked(string token, string hp = "") =>
new(MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, hp, token, "ZXQ-Captcha-Marker");
private static void AssertClean(SubmissionHarness h, params string[] extraForbidden)
{
var forbidden = new[] { MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, "ZXQ-Captcha-Marker", "ZXQ-" }
.Concat(extraForbidden).ToArray();
h.Logs.Messages.Should().NotBeEmpty("outcomes are logged");
foreach (var message in h.Logs.Messages)
{
foreach (var marker in forbidden)
{
message.Should().NotContain(marker);
}
}
}
[Fact]
public async Task GenuineSpamReplayAndInvalid_LogNothingPersonal_NoKeyAndNoToken()
{
using var h = new SubmissionHarness(o => o.Captcha.Enabled = true);
var key = Guid.NewGuid().ToString();
var token = h.MatureToken();
await h.Submit(Marked(token), key); // genuine
await h.Submit(Marked(token), key); // replay
await h.Submit(Marked(h.MatureToken(), hp: "ZXQ-Honeypot")); // spam
await h.Submit(Marked(token) with { Email = "ZXQ-not-an-address" }); // invalid fields
await h.Submit(Marked("ZXQ-forged-token")); // forged token
AssertClean(h, key, token, "ZXQ-Honeypot");
}
[Fact]
public async Task AMailFailureWithPersonalDataInItsMessage_IsLoggedByTypeOnly()
{
using var h = new SubmissionHarness();
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new InvalidOperationException($"cannot deliver to {MarkerEmail}: {MarkerMessage}"));
await h.Submit(Marked(h.MatureToken()));
AssertClean(h);
h.Logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException)));
}
[Fact]
public async Task ADatabaseFailureWithPersonalDataInItsMessage_DoesNotLeakThroughTheServiceLogs()
{
var repository = Substitute.For<IContactRepository>();
repository.SaveChangesAsync(Arg.Any<CancellationToken>()).ThrowsAsync(new DbUpdateException("duplicate"));
using var h = new SubmissionHarness(repositoryOverride: repository);
await h.Submit(Marked(h.MatureToken()));
AssertClean(h);
}
[Fact]
public async Task TheOutcomeLogLines_CarryOnlyTheOutcomeAndTheSiteId()
{
using var h = new SubmissionHarness();
await h.Submit(Marked(h.MatureToken()));
h.Logs.Messages.Should().ContainSingle()
.Which.Should().Be("Contact submission handled: Genuine for site site-a");
}
}
@@ -0,0 +1,144 @@
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactRetentionServiceTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
private static ContactMessage Message(string name, DateTimeOffset retentionUntil) => new()
{
Id = Guid.NewGuid(), SiteId = "s", ReceivedAt = Now.AddDays(-1), Name = name, Email = "a@b.nl",
Subject = "x", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending,
RetentionUntil = retentionUntil,
};
private static (ContactRetentionService Sut, ServiceProvider Provider, string Db) Create(bool enabled)
{
var databaseName = Guid.NewGuid().ToString();
var services = new ServiceCollection();
services.AddDbContext<ContactDbContext>(o => o.UseInMemoryDatabase(databaseName));
services.AddScoped<IContactRepository, ContactRepository>();
var provider = services.BuildServiceProvider();
var sut = new ContactRetentionService(
provider.GetRequiredService<IServiceScopeFactory>(),
Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = enabled }),
new FakeTimeProvider(Now),
NullLogger<ContactRetentionService>.Instance);
return (Sut: sut, Provider: provider, Db: databaseName);
}
[Fact]
public async Task DeletesExpiredMessagesAndOldIdempotencyRecords_AndKeepsTheRest()
{
var (sut, provider, _) = Create(enabled: true);
await using (var scope = provider.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
db.ContactMessages.AddRange(
Message("expired", Now.AddSeconds(-1)),
Message("expired too", Now.AddDays(-30)),
Message("kept", Now.AddDays(1)),
Message("kept long", Now.AddMonths(11)));
db.IdempotencyRecords.AddRange(
new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-25), StatusCode = 202 },
new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-23), StatusCode = 202 });
await db.SaveChangesAsync();
}
await sut.ExecuteTickAsync(CancellationToken.None);
await using var check = provider.CreateAsyncScope();
var after = check.ServiceProvider.GetRequiredService<ContactDbContext>();
after.ContactMessages.Select(m => m.Name).Should().BeEquivalentTo("kept", "kept long");
after.IdempotencyRecords.Count().Should().Be(1);
}
[Fact]
public async Task HandlesMoreRowsThanOneBatch()
{
var (sut, provider, _) = Create(enabled: true);
await using (var scope = provider.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
db.ContactMessages.AddRange(Enumerable.Range(0, 1200).Select(i => Message($"old{i}", Now.AddDays(-1))));
await db.SaveChangesAsync();
}
await sut.ExecuteTickAsync(CancellationToken.None);
await using var check = provider.CreateAsyncScope();
check.ServiceProvider.GetRequiredService<ContactDbContext>().ContactMessages.Should().BeEmpty();
}
[Fact]
public async Task WhileDisabled_ItDoesNothing_AndNeverEvenOpensAScope()
{
var scopeFactory = Substitute.For<IServiceScopeFactory>();
var sut = new ContactRetentionService(
scopeFactory,
Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = false }),
new FakeTimeProvider(Now),
NullLogger<ContactRetentionService>.Instance);
await sut.ExecuteTickAsync(CancellationToken.None);
scopeFactory.ReceivedCalls().Should().BeEmpty("a disabled module must not touch the database or anything else");
}
[Fact]
public async Task ADatabaseProblem_DoesNotCrashTheJob()
{
var scopeFactory = Substitute.For<IServiceScopeFactory>();
scopeFactory.CreateScope().Returns(_ => throw new InvalidOperationException("db down"));
var sut = new ContactRetentionService(
scopeFactory,
Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = true }),
new FakeTimeProvider(Now),
NullLogger<ContactRetentionService>.Instance);
var act = () => sut.ExecuteTickAsync(CancellationToken.None);
await act.Should().NotThrowAsync();
}
[Fact]
public void TheJobRunsDaily()
{
ContactRetentionService.Interval.Should().Be(TimeSpan.FromHours(24));
}
}
public class ContactRateLimitPartitionTests
{
/// <summary>
/// REBASE CHECKLIST: on master there is no per-client partitioning, so every caller shares one
/// bucket and this test pins the constant. After the ASF merge the body of
/// <c>ContactRateLimitPartition.KeyFor</c> becomes <c>return ClientPartitionKey.For(context);</c>
/// and this test changes to "two different client addresses give two different keys".
/// </summary>
[Fact]
public void OnTheBaseBranch_EveryCallerSharesOneBucket()
{
var first = new DefaultHttpContext();
first.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10");
var second = new DefaultHttpContext();
second.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("198.51.100.20");
ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.GlobalKey);
ContactRateLimitPartition.KeyFor(second).Should().Be(ContactRateLimitPartition.GlobalKey);
ContactRateLimitPartition.GlobalKey.Should().Be("global");
}
}
@@ -0,0 +1,344 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
using SlpModularCms.Modules.Contact.Models;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactSubmissionServiceTests
{
private static async Task<List<ContactMessage>> Messages(SubmissionHarness h)
=> await h.Db.ContactMessages.AsNoTracking().ToListAsync();
[Fact]
public async Task AGenuineMessage_IsStored_AsNew_WithTwelveMonthsRetention_AndMailPending()
{
using var h = new SubmissionHarness();
var token = h.MatureToken();
var result = await h.Submit(SubmissionHarness.Request(token));
result.Should().BeOfType<SubmissionResult.Received>();
var stored = (await Messages(h)).Single();
stored.Status.Should().Be(ContactMessageStatus.New);
stored.MailStatus.Should().Be(ContactMailStatus.Pending);
stored.SiteId.Should().Be("site-a");
stored.Name.Should().Be("Jan Jansen");
stored.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12));
}
[Fact]
public async Task TextFieldsAreStoredTrimmed()
{
using var h = new SubmissionHarness();
var request = SubmissionHarness.Request(h.MatureToken()) with { Name = " Jan ", Message = "\n hallo \n" };
await h.Submit(request);
var stored = (await Messages(h)).Single();
stored.Name.Should().Be("Jan");
stored.Message.Should().Be("hallo");
}
[Fact]
public async Task TheMailSender_IsCalledAfterTheMessageIsStored_AndOnlyForGenuineMessages()
{
using var h = new SubmissionHarness();
var storedWhenMailWasCalled = false;
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(call =>
{
storedWhenMailWasCalled = h.Db.ContactMessages.AsNoTracking().Any(m => m.Id == call.Arg<ContactMessage>().Id);
return ContactMailOutcome.Skipped;
});
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
storedWhenMailWasCalled.Should().BeTrue();
await h.Mail.Received(1).SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ASentMail_IsRecorded_WithOneAttempt()
{
using var h = new SubmissionHarness();
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
var stored = (await Messages(h)).Single();
stored.MailStatus.Should().Be(ContactMailStatus.Sent);
stored.MailAttempts.Should().Be(1);
}
[Fact]
public async Task AMailFailure_NeverFailsTheRequest_AndLeavesTheMessageStored()
{
using var h = new SubmissionHarness();
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
.ThrowsAsync(new InvalidOperationException("smtp said no to jan@example.nl"));
var result = await h.Submit(SubmissionHarness.Request(h.MatureToken()));
result.Should().BeOfType<SubmissionResult.Received>();
(await Messages(h)).Single().MailStatus.Should().Be(ContactMailStatus.Pending);
}
[Fact]
public async Task AFilledHoneypot_IsStoredAsSpam_ForThirtyDays_NeverMailed_WithTheSameAnswer()
{
using var h = new SubmissionHarness();
var spam = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "http://spam"));
var genuine = await h.Submit(SubmissionHarness.Request(h.MatureToken()));
spam.Should().Be(genuine, "a bot must not be able to tell the difference");
var stored = (await Messages(h)).Single(m => m.Status == ContactMessageStatus.Spam);
stored.MailStatus.Should().Be(ContactMailStatus.NotApplicable);
stored.RetentionUntil.Should().Be(stored.ReceivedAt.AddDays(30));
await h.Mail.Received(1).SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ATooFastSubmission_IsSpam()
{
using var h = new SubmissionHarness();
var token = h.Tokens.Issue(); // no waiting
var result = await h.Submit(SubmissionHarness.Request(token));
result.Should().BeOfType<SubmissionResult.Received>();
(await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam);
}
[Fact]
public async Task ARejectedCaptcha_IsSpam_WhenCaptchaIsEnabled()
{
using var h = new SubmissionHarness(o => o.Captcha.Enabled = true);
h.Captcha.VerifyAsync(Arg.Any<string?>(), Arg.Any<CancellationToken>()).Returns(false);
await h.Submit(SubmissionHarness.Request(h.MatureToken(), captcha: "bad"));
(await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam);
}
[Fact]
public async Task TheCaptchaIsNotConsulted_WhenItIsDisabled()
{
using var h = new SubmissionHarness();
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
await h.Captcha.DidNotReceive().VerifyAsync(Arg.Any<string?>(), Arg.Any<CancellationToken>());
(await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.New);
}
[Fact]
public async Task SpamIsNotStored_OnceTheDailyCapIsReached_ButTheAnswerStaysTheSame()
{
using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 2);
for (var i = 0; i < 4; i++)
{
var result = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
result.Should().BeOfType<SubmissionResult.Received>();
}
(await Messages(h)).Count(m => m.Status == ContactMessageStatus.Spam).Should().Be(2);
h.Db.IdempotencyRecords.Count().Should().Be(4, "dropped spam still gets a replay record");
}
[Fact]
public async Task TheSpamCap_StartsAgainOnTheNextDay()
{
using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 1);
await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
(await Messages(h)).Should().HaveCount(1);
h.Time.Advance(TimeSpan.FromDays(1));
await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
(await Messages(h)).Should().HaveCount(2);
}
[Fact]
public async Task AReplayWithTheSameKey_ReturnsTheSameAnswer_WithoutASecondRowOrMail()
{
using var h = new SubmissionHarness();
var key = Guid.NewGuid().ToString();
var request = SubmissionHarness.Request(h.MatureToken());
var first = await h.Submit(request, key);
var second = await h.Submit(request, key);
second.Should().Be(first);
(await Messages(h)).Should().HaveCount(1);
await h.Mail.Received(1).SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task AReplay_StillWorks_WhenTheTokenHasExpiredInTheMeantime()
{
using var h = new SubmissionHarness();
var key = Guid.NewGuid().ToString();
var request = SubmissionHarness.Request(h.MatureToken());
await h.Submit(request, key);
h.Time.Advance(TimeSpan.FromHours(3));
var replay = await h.Submit(request, key);
replay.Should().BeOfType<SubmissionResult.Received>();
(await Messages(h)).Should().HaveCount(1);
}
[Fact]
public async Task AKeyOlderThan24Hours_CanBeUsedAgain()
{
using var h = new SubmissionHarness();
var key = Guid.NewGuid().ToString();
await h.Submit(SubmissionHarness.Request(h.MatureToken()), key);
h.Time.Advance(TimeSpan.FromHours(25));
var result = await h.Submit(SubmissionHarness.Request(h.MatureToken()), key);
result.Should().BeOfType<SubmissionResult.Received>();
(await Messages(h)).Should().HaveCount(2);
h.Db.IdempotencyRecords.Count().Should().Be(1, "the old record is reused, not duplicated");
}
[Fact]
public async Task TheIdempotencyRecord_HoldsNoRequestContent()
{
using var h = new SubmissionHarness();
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
var record = h.Db.IdempotencyRecords.AsNoTracking().Single();
record.SiteId.Should().Be("site-a");
record.StatusCode.Should().Be(202);
typeof(IdempotencyRecord).GetProperties().Select(p => p.Name)
.Should().BeEquivalentTo(["SiteId", "Key", "CreatedAt", "StatusCode"]);
}
[Fact]
public async Task InvalidFields_AreRejected_WithEveryProblemListed_AndNothingIsStored()
{
using var h = new SubmissionHarness();
var request = SubmissionHarness.Request(h.MatureToken()) with { Name = "", Email = "nope", Message = new string('a', 2001) };
var result = await h.Submit(request);
var invalid = result.Should().BeOfType<SubmissionResult.Invalid>().Subject;
invalid.Errors["name"].Should().Equal("required");
invalid.Errors["email"].Should().Equal("invalid");
invalid.Errors["message"].Should().Equal("tooLong");
(await Messages(h)).Should().BeEmpty();
h.Db.IdempotencyRecords.Should().BeEmpty("a rejected request must not use up its key");
}
[Fact]
public async Task ACorrectedRequest_CanReuseTheKeyOfARejectedOne()
{
using var h = new SubmissionHarness();
var key = Guid.NewGuid().ToString();
var token = h.MatureToken();
(await h.Submit(SubmissionHarness.Request(token) with { Email = "nope" }, key)).Should().BeOfType<SubmissionResult.Invalid>();
(await h.Submit(SubmissionHarness.Request(token), key)).Should().BeOfType<SubmissionResult.Received>();
(await Messages(h)).Should().HaveCount(1);
}
[Theory]
[InlineData(null, "required")]
[InlineData("", "required")]
[InlineData("not-a-guid", "invalid")]
public async Task ABadIdempotencyKey_IsRejected(string? key, string code)
{
using var h = new SubmissionHarness();
var result = await h.Sut.SubmitAsync(SubmissionHarness.Request(h.MatureToken()), key, CancellationToken.None);
result.Should().BeOfType<SubmissionResult.Invalid>().Which.Errors["idempotencyKey"].Should().Equal(code);
(await Messages(h)).Should().BeEmpty();
}
[Fact]
public async Task ANullBody_IsRejected_AsAnInvalidBody()
{
using var h = new SubmissionHarness();
var result = await h.Submit(null);
result.Should().BeOfType<SubmissionResult.Invalid>().Which.Errors["body"].Should().Equal("invalid");
}
[Theory]
[InlineData("garbage")]
[InlineData("CfDJ8-forged")]
public async Task AForgedToken_IsReportedAsExpired_AndNothingIsStored(string token)
{
using var h = new SubmissionHarness();
var result = await h.Submit(SubmissionHarness.Request(token));
result.Should().BeOfType<SubmissionResult.Invalid>().Which.Errors["token"].Should().Equal("expired");
(await Messages(h)).Should().BeEmpty();
h.Db.IdempotencyRecords.Should().BeEmpty();
}
[Fact]
public async Task AnExpiredToken_IsReportedAsExpired_ExactlyLikeAForgedOne()
{
using var h = new SubmissionHarness();
var token = h.Tokens.Issue();
h.Time.Advance(TimeSpan.FromHours(3));
var expired = await h.Submit(SubmissionHarness.Request(token));
var forged = await h.Submit(SubmissionHarness.Request("forged"));
expired.Should().BeOfType<SubmissionResult.Invalid>();
((SubmissionResult.Invalid)expired).Errors.Should().BeEquivalentTo(((SubmissionResult.Invalid)forged).Errors);
}
[Fact]
public async Task ARaceOnTheSameKey_IsAnsweredAsAReplay()
{
var repository = Substitute.For<IContactRepository>();
repository.GetIdempotencyAsync(Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((IdempotencyRecord?)null);
repository.SaveChangesAsync(Arg.Any<CancellationToken>()).ThrowsAsync(new DbUpdateException("duplicate"));
using var h = new SubmissionHarness(repositoryOverride: repository);
var result = await h.Submit(SubmissionHarness.Request(h.MatureToken()));
result.Should().BeOfType<SubmissionResult.Received>();
}
[Fact]
public async Task TheSiteId_ComesFromConfiguration_NeverFromTheRequest()
{
using var h = new SubmissionHarness(o => o.SiteId = "configured-site");
var request = SubmissionHarness.Request(h.MatureToken()) with { Subject = "other-site" };
await h.Submit(request);
(await Messages(h)).Single().SiteId.Should().Be("configured-site");
}
[Fact]
public async Task ARetentionConfigChange_DoesNotChangeStoredRows()
{
using var h = new SubmissionHarness();
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
var before = (await Messages(h)).Single().RetentionUntil;
h.Options.RetentionMonths = 1;
(await Messages(h)).Single().RetentionUntil.Should().Be(before);
}
}
@@ -0,0 +1,144 @@
using FluentAssertions;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Time.Testing;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactTokenServiceTests
{
private static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
private static ContactTokenService Create(
FakeTimeProvider time, string siteId = "site-a", IDataProtectionProvider? provider = null,
int minSeconds = 3, int lifetimeMinutes = 120)
=> new(
provider ?? DataProtectionProvider.Create("contact-token-tests"),
Options.Create(new ContactOptions { SiteId = siteId, MinSeconds = minSeconds, TokenLifetimeMinutes = lifetimeMinutes }),
time);
[Fact]
public void ATokenIsValid_AfterTheMinimumTime_AndBeforeItExpires()
{
var time = new FakeTimeProvider(Start);
var sut = Create(time);
var token = sut.Issue();
time.Advance(TimeSpan.FromSeconds(3));
sut.Check(token).Should().Be(TokenCheck.Valid);
time.Advance(TimeSpan.FromMinutes(119));
sut.Check(token).Should().Be(TokenCheck.Valid);
}
[Fact]
public void ATokenIsTooYoung_BeforeTheMinimumTime()
{
var time = new FakeTimeProvider(Start);
var sut = Create(time);
var token = sut.Issue();
time.Advance(TimeSpan.FromSeconds(2));
sut.Check(token).Should().Be(TokenCheck.TooYoung);
}
[Fact]
public void ATokenExpires_AfterItsLifetime()
{
var time = new FakeTimeProvider(Start);
var sut = Create(time);
var token = sut.Issue();
time.Advance(TimeSpan.FromMinutes(120) + TimeSpan.FromSeconds(1));
sut.Check(token).Should().Be(TokenCheck.InvalidOrExpired);
}
[Fact]
public void ATokenFromTheFuture_IsInvalid()
{
var time = new FakeTimeProvider(Start);
var provider = DataProtectionProvider.Create("contact-token-tests");
var later = Create(new FakeTimeProvider(Start.AddHours(1)), provider: provider);
var token = later.Issue();
Create(time, provider: provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired);
}
[Fact]
public void ATokenOfAnotherSite_IsInvalid()
{
var time = new FakeTimeProvider(Start);
var provider = DataProtectionProvider.Create("contact-token-tests");
var token = Create(time, "site-a", provider).Issue();
time.Advance(TimeSpan.FromSeconds(10));
Create(time, "site-b", provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired);
Create(time, "site-a", provider).Check(token).Should().Be(TokenCheck.Valid);
}
[Fact]
public void ATokenFromAnotherKeyRing_IsInvalid()
{
var time = new FakeTimeProvider(Start);
var token = Create(time, provider: DataProtectionProvider.Create("one")).Issue();
time.Advance(TimeSpan.FromSeconds(10));
Create(time, provider: DataProtectionProvider.Create("two")).Check(token).Should().Be(TokenCheck.InvalidOrExpired);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("garbage")]
[InlineData("CfDJ8-not-a-real-token")]
public void BlankOrGarbage_IsInvalid(string? token)
{
Create(new FakeTimeProvider(Start)).Check(token).Should().Be(TokenCheck.InvalidOrExpired);
}
[Fact]
public void ATamperedToken_IsInvalid()
{
var time = new FakeTimeProvider(Start);
var sut = Create(time);
var token = sut.Issue();
time.Advance(TimeSpan.FromSeconds(10));
for (var i = 0; i < token.Length; i += 7)
{
var chars = token.ToCharArray();
chars[i] = chars[i] == 'A' ? 'B' : 'A';
sut.Check(new string(chars)).Should().Be(TokenCheck.InvalidOrExpired, $"changing character {i} must break the token");
}
}
[Fact]
public void RoundTrip_ClassifiesEveryAgeAsExpected_ForManyRandomAges()
{
var random = new Random(4242);
for (var i = 0; i < 200; i++)
{
var time = new FakeTimeProvider(Start);
var sut = Create(time, minSeconds: 3, lifetimeMinutes: 120);
var token = sut.Issue();
var ageSeconds = random.Next(0, 3 * 60 * 60);
time.Advance(TimeSpan.FromSeconds(ageSeconds));
var expected = ageSeconds > 120 * 60 ? TokenCheck.InvalidOrExpired
: ageSeconds < 3 ? TokenCheck.TooYoung
: TokenCheck.Valid;
sut.Check(token).Should().Be(expected, $"age {ageSeconds} s");
}
}
[Fact]
public void ThePurposeStringIsBoundToTheSite()
{
ContactTokenService.PurposeFor("slpsoftware").Should().Be("SlpModularCms.Contact.Token.slpsoftware");
}
}
@@ -0,0 +1,185 @@
using FluentAssertions;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
public class ContactValidatorTests
{
private static ContactMessageRequest Valid() => new(
"Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", "", "token", null);
private static Dictionary<string, string[]> Check(ContactMessageRequest request)
=> ContactValidator.Validate(ContactValidator.Normalize(request));
[Fact]
public void AValidRequest_HasNoErrors()
{
Check(Valid()).Should().BeEmpty();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void RequiredFields_AreReported_WhenMissingOrBlank(string? blank)
{
var errors = Check(new ContactMessageRequest(blank, blank, blank, blank, null, blank, null));
errors.Keys.Should().BeEquivalentTo("name", "email", "subject", "message", "token");
errors.Values.Should().OnlyContain(v => v.Single() == "required");
}
[Theory]
[InlineData(100, true)]
[InlineData(101, false)]
public void Name_AllowsAtMost100Characters(int length, bool valid)
{
var errors = Check(Valid() with { Name = new string('a', length) });
(errors.ContainsKey("name") ? errors["name"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong");
}
[Theory]
[InlineData(254, true)]
[InlineData(255, false)]
public void Email_AllowsAtMost254Characters(int length, bool valid)
{
var email = new string('a', length - "@example.nl".Length) + "@example.nl";
var errors = Check(Valid() with { Email = email });
(errors.ContainsKey("email") ? errors["email"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong");
}
[Theory]
[InlineData(2000, true)]
[InlineData(2001, false)]
public void Message_AllowsAtMost2000Characters(int length, bool valid)
{
var errors = Check(Valid() with { Message = new string('a', length) });
(errors.ContainsKey("message") ? errors["message"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong");
}
[Theory]
[InlineData("jan@example.nl", true)]
[InlineData("a@b.co", true)]
[InlineData("jan.jansen+tag@sub.example.nl", true)]
[InlineData("jan@example", false)]
[InlineData("jan@example.n", false)]
[InlineData("@example.nl", false)]
[InlineData("jan example@example.nl", false)]
[InlineData("jan@@example.nl", false)]
public void Email_MustLookLikeAnAddress(string email, bool valid)
{
var errors = Check(Valid() with { Email = email });
errors.ContainsKey("email").Should().Be(!valid);
if (!valid)
{
errors["email"].Single().Should().Be("invalid");
}
}
[Fact]
public void Trimming_HappensBeforeTheLengthCheck()
{
var errors = Check(Valid() with { Name = " " + new string('a', 100) + " " });
errors.Should().BeEmpty();
}
[Fact]
public void Normalize_IsIdempotent_ForManyRandomInputs()
{
var random = new Random(20261109);
for (var i = 0; i < 300; i++)
{
var request = new ContactMessageRequest(
Noise(random, 120), Noise(random, 40), Noise(random, 120), Noise(random, 300), Noise(random, 3), Noise(random, 50), null);
var once = ContactValidator.Normalize(request);
ContactValidator.Normalize(once).Should().Be(once);
}
}
[Fact]
public void Validation_NeverChangesBetweenARequestAndItsNormalizedForm()
{
// Validating twice (before and after another trim) must give the same answer.
var random = new Random(7);
for (var i = 0; i < 300; i++)
{
var request = new ContactMessageRequest(
Noise(random, 130), Noise(random, 300), Noise(random, 130), Noise(random, 2100), "", Noise(random, 20), null);
var normalized = ContactValidator.Normalize(request);
ContactValidator.Validate(normalized).Should().BeEquivalentTo(ContactValidator.Validate(ContactValidator.Normalize(normalized)));
}
}
[Theory]
[InlineData("name")]
[InlineData("email")]
[InlineData("subject")]
public void AnyControlCharacter_IsInvalid_InSingleLineFields(string field)
{
for (var code = 0; code < 32; code++)
{
var bad = $"a{(char)code}b";
var request = field switch
{
"name" => Valid() with { Name = bad },
"email" => Valid() with { Email = $"a{(char)code}b@example.nl" },
_ => Valid() with { Subject = bad },
};
var errors = ContactValidator.Validate(request); // not trimmed: control characters inside stay
errors.Should().ContainKey(field, $"control character U+{code:X4} must be rejected");
errors[field].Single().Should().Be("invalid");
}
var del = field switch
{
"name" => Valid() with { Name = "a\u007Fb" },
"email" => Valid() with { Email = "a\u007Fb@example.nl" },
_ => Valid() with { Subject = "a\u007Fb" },
};
ContactValidator.Validate(del).Should().ContainKey(field);
}
[Fact]
public void Message_AllowsLineBreaksAndTabs_ButNoOtherControlCharacters()
{
ContactValidator.Validate(Valid() with { Message = "regel 1\r\nregel 2\n\tingesprongen" }).Should().BeEmpty();
for (var code = 0; code < 32; code++)
{
if (code is '\n' or '\r' or '\t')
{
continue;
}
var errors = ContactValidator.Validate(Valid() with { Message = $"a{(char)code}b" });
errors.Should().ContainKey("message", $"control character U+{code:X4} must be rejected");
}
}
[Fact]
public void ErrorCodes_AreExactlyTheContractedOnes()
{
var codes = new[]
{
ContactErrorCodes.Required, ContactErrorCodes.TooLong, ContactErrorCodes.Invalid, ContactErrorCodes.Expired,
};
codes.Should().Equal("required", "tooLong", "invalid", "expired");
}
private static string Noise(Random random, int maxLength)
{
const string alphabet = "abcXYZ019 @.+-_\t\né€";
var length = random.Next(0, maxLength + 1);
return new string(Enumerable.Range(0, length).Select(_ => alphabet[random.Next(alphabet.Length)]).ToArray());
}
}
@@ -0,0 +1,113 @@
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Contact.Data;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>
/// Starts the real, composed SlpSoftware host (all modules, the real pipeline) against a real
/// MariaDB/MySQL. Like <c>SlpModularCms.Api.Tests</c> this needs a reachable database: set the
/// environment variable <c>ConnectionStrings__DefaultConnection</c> to a server you may create
/// databases on. Every factory uses its own freshly created database and drops it again.
/// To run only the pure unit tests use <c>--filter "FullyQualifiedName!~Pipeline"</c>.
/// </summary>
public class ContactHostFactory : WebApplicationFactory<Program>
{
private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection";
private readonly Dictionary<string, string?> _settings;
private readonly string _databaseName = "SlpContactPipeline_" + Guid.NewGuid().ToString("N")[..12];
public ContactHostFactory(Dictionary<string, string?>? settings = null)
{
_settings = settings ?? [];
}
public static string BaseConnectionString =>
Environment.GetEnvironmentVariable(EnvironmentVariable)
?? throw new InvalidOperationException(
$"Set {EnvironmentVariable} to a MariaDB/MySQL server for the contact pipeline tests " +
"(or run the unit tests only with --filter \"FullyQualifiedName!~Pipeline\").");
public string ConnectionString =>
Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase)
? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase)
: $"{BaseConnectionString};Database={_databaseName}";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) =>
{
var all = new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] = ConnectionString,
// Fresh availability answers instead of a cached one.
["Availability:StatusCacheSeconds"] = "0",
};
foreach (var (key, value) in _settings)
{
all[key] = value;
}
config.AddInMemoryCollection(all);
});
}
public async Task<T> WithDb<T>(Func<ContactDbContext, Task<T>> action)
{
await using var scope = Services.CreateAsyncScope();
return await action(scope.ServiceProvider.GetRequiredService<ContactDbContext>());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
using var scope = Services.CreateScope();
scope.ServiceProvider.GetRequiredService<ContactDbContext>().Database.EnsureDeleted();
}
catch
{
// Best effort clean-up of the throwaway database.
}
}
base.Dispose(disposing);
}
}
public sealed class EnabledContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
public sealed class DisabledContactHostFactory() : ContactHostFactory;
/// <summary>Only the form policy is tight, so a token can still be fetched freely.</summary>
public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "2",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
/// <summary>Only the token policy is tight.</summary>
public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "2",
});
@@ -0,0 +1,318 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
internal static class Http
{
public const string Route = "/api/v1/contact-messages";
public static async Task<string> GetTokenAsync(HttpClient client)
{
var response = await client.GetAsync($"{Route}/token");
response.StatusCode.Should().Be(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return json.RootElement.GetProperty("token").GetString()!;
}
public static Task<HttpResponseMessage> PostAsync(
HttpClient client, string json, string? key = "new", bool useKey = true)
{
var request = new HttpRequestMessage(HttpMethod.Post, Route)
{
Content = new StringContent(json, Encoding.UTF8, "application/json"),
};
if (useKey)
{
request.Headers.Add("Idempotency-Key", key == "new" ? Guid.NewGuid().ToString() : key);
}
return client.SendAsync(request);
}
public static string Body(string token, string name = "Jan Jansen", string hp = "") =>
JsonSerializer.Serialize(new
{
name,
email = "jan@example.nl",
subject = "website",
message = "Ik wil graag een offerte.",
hpCheck = hp,
token,
});
}
public class ContactPipelineEnabledTests(EnabledContactHostFactory factory) : IClassFixture<EnabledContactHostFactory>
{
[Fact]
public async Task TheTokenRoute_ReturnsATokenTheMinimumTime_AndNoCaptcha()
{
var response = await factory.CreateClient().GetAsync($"{Http.Route}/token");
response.StatusCode.Should().Be(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
json.RootElement.GetProperty("token").GetString().Should().NotBeNullOrWhiteSpace();
json.RootElement.GetProperty("minSeconds").GetInt32().Should().Be(0);
json.RootElement.GetProperty("captcha").ValueKind.Should().Be(JsonValueKind.Null);
}
[Fact]
public async Task AValidSubmission_Returns202_IsStoredOnce_AndAReplayDoesNotStoreAgain()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
var key = Guid.NewGuid().ToString();
var body = Http.Body(token, name: "Pipeline Genuine");
var first = await Http.PostAsync(client, body, key);
var second = await Http.PostAsync(client, body, key);
first.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await first.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}""");
second.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await second.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}""");
var rows = await factory.WithDb(db => db.ContactMessages.AsNoTracking().Where(m => m.Name == "Pipeline Genuine").ToListAsync());
rows.Should().ContainSingle();
rows[0].Status.Should().Be(ContactMessageStatus.New);
rows[0].SiteId.Should().Be("pipeline-site");
rows[0].RetentionUntil.Should().BeAfter(DateTimeOffset.UtcNow.AddMonths(11));
}
[Fact]
public async Task AFilledHoneypot_GetsTheIdenticalAnswer_ButIsStoredAsSpam()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
var response = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Bot", hp: "http://spam"));
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await response.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}""");
var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Pipeline Bot"));
row.Status.Should().Be(ContactMessageStatus.Spam);
row.MailStatus.Should().Be(ContactMailStatus.NotApplicable);
row.RetentionUntil.Should().BeBefore(DateTimeOffset.UtcNow.AddDays(31));
}
[Fact]
public async Task InvalidFields_Return400_WithTheContractedShape()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
var json = JsonSerializer.Serialize(new { name = "", email = "nope", subject = "s", message = "m", hpCheck = "", token });
var response = await Http.PostAsync(client, json);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = doc.RootElement;
root.GetProperty("status").GetInt32().Should().Be(400);
root.GetProperty("type").GetString().Should().Be("about:blank");
root.GetProperty("errors").GetProperty("name")[0].GetString().Should().Be("required");
root.GetProperty("errors").GetProperty("email")[0].GetString().Should().Be("invalid");
(await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Subject == "s"))).Should().Be(0);
}
[Fact]
public async Task AMissingIdempotencyKey_Returns400()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
var response = await Http.PostAsync(client, Http.Body(token), useKey: false);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("errors").GetProperty("idempotencyKey")[0].GetString().Should().Be("required");
}
[Fact]
public async Task AForgedToken_IsReportedAsExpired()
{
var response = await Http.PostAsync(factory.CreateClient(), Http.Body("forged-token"));
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("errors").GetProperty("token")[0].GetString().Should().Be("expired");
}
[Theory]
[InlineData("{ this is not json")]
[InlineData("""{"name": 123, "email": "a@b.nl"}""")]
[InlineData("")]
public async Task AnUnbindableBody_Returns400_InOurShape_WithoutEchoingTheInput(string body)
{
var response = await Http.PostAsync(factory.CreateClient(), body);
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
var text = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(text);
doc.RootElement.GetProperty("errors").GetProperty("body")[0].GetString().Should().Be("invalid");
text.Should().NotContain("this is not json").And.NotContain("a@b.nl");
}
[Fact]
public async Task ABodyBeyondTheLimit_Returns413_AsProblemJson()
{
var client = factory.CreateClient();
var huge = new string('x', 20_000);
var response = await Http.PostAsync(client, JsonSerializer.Serialize(new { message = huge }));
response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge);
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
doc.RootElement.GetProperty("status").GetInt32().Should().Be(413);
}
[Fact]
public async Task TheMigration_CreatedBothTables_AndTheIdempotencyKeyIsUnique()
{
var count = await factory.WithDb(async db =>
{
var key = Guid.NewGuid();
db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 });
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 });
var act = () => db.SaveChangesAsync();
await act.Should().ThrowAsync<DbUpdateException>("the same site cannot use a key twice");
return await db.ContactMessages.CountAsync();
});
count.Should().BeGreaterThanOrEqualTo(0);
}
[Fact]
public async Task TheRetentionJob_RemovesExpiredRows_InTheRealDatabase()
{
await factory.WithDb(async db =>
{
db.ContactMessages.Add(new ContactMessage
{
Id = Guid.NewGuid(), SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddYears(-2),
Name = "Pipeline Expired", Email = "a@b.nl", Subject = "s", Message = "m",
Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending,
RetentionUntil = DateTimeOffset.UtcNow.AddDays(-1),
});
await db.SaveChangesAsync();
return 0;
});
var job = factory.Services.GetServices<IHostedService>().OfType<ContactRetentionService>().Single();
await job.ExecuteTickAsync(CancellationToken.None);
(await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Expired"))).Should().Be(0);
}
}
public class ContactPipelineDisabledTests(DisabledContactHostFactory factory) : IClassFixture<DisabledContactHostFactory>
{
[Fact]
public async Task WhileDisabled_BothRoutesAre404_WithAnEmptyBody()
{
var client = factory.CreateClient();
var token = await client.GetAsync($"{Http.Route}/token");
var post = await Http.PostAsync(client, Http.Body("anything"));
token.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await token.Content.ReadAsStringAsync()).Should().BeEmpty();
post.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await post.Content.ReadAsStringAsync()).Should().BeEmpty();
}
[Fact]
public async Task WhileDisabled_TheModuleNeverTouchedTheDatabase_AndTheRetentionJobDoesNothing()
{
// The host has started (other modules migrated their tables), but the contact tables do
// not exist: the module neither migrated nor queried anything.
await using var connection = new MySql.Data.MySqlClient.MySqlConnection(factory.ConnectionString);
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText =
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name IN ('ContactMessages','ContactIdempotency')";
Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0);
_ = factory.CreateClient(); // make sure the host is up
var job = factory.Services.GetServices<IHostedService>().OfType<ContactRetentionService>().Single();
await job.ExecuteTickAsync(CancellationToken.None);
Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0, "the disabled job must not create or touch anything");
}
}
public class ContactPipelineFormRateLimitTests(TightFormLimitContactHostFactory factory) : IClassFixture<TightFormLimitContactHostFactory>
{
[Fact]
public async Task TheFormPolicy_Answers429_WithRetryAfter_AndOnlyTheStandardFields()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
HttpResponseMessage? last = null;
for (var i = 0; i < 3; i++)
{
last = await Http.PostAsync(client, Http.Body(token, name: $"Pipeline Limit {i}"));
}
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue();
int.Parse(retryAfter!.Single()).Should().BeInRange(1, 600);
last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
using var doc = JsonDocument.Parse(await last.Content.ReadAsStringAsync());
doc.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]);
}
}
public class ContactPipelineTokenRateLimitTests(TightTokenLimitContactHostFactory factory) : IClassFixture<TightTokenLimitContactHostFactory>
{
[Fact]
public async Task TheTokenPolicy_AnswersAfterItsOwnLimit_With429AndRetryAfter()
{
var client = factory.CreateClient();
HttpResponseMessage? last = null;
for (var i = 0; i < 3; i++)
{
last = await client.GetAsync($"{Http.Route}/token");
}
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
last.Headers.Contains("Retry-After").Should().BeTrue();
}
}
public class ContactPipelineGateTests(EnabledContactHostFactory factory) : IClassFixture<EnabledContactHostFactory>
{
[Fact]
public async Task TheContactRoutes_StayReachable_WhileTheCmsIsDisabled_ButAdminRoutesAreBlocked()
{
// Switch the CMS off through the availability state of the real database.
await factory.WithDb(db => db.Database.ExecuteSqlRawAsync(
"INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')"));
var client = factory.CreateClient();
(await client.GetAsync("/api/v1/offerings/categories")).StatusCode
.Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed");
var token = await Http.GetTokenAsync(client);
var post = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Gate"));
post.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Gate"))).Should().Be(1);
}
}
@@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
<!-- Pinned above the version DataProtection pulls transitively (FR-22, OPEN-03) — see Core.csproj -->
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" />
<!-- WebApplicationFactory: the real-pipeline tests exercise the composed SlpSoftware host. -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Microsoft.Extensions.Options" />
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
<!-- Only the composed host is referenced (for the real-pipeline tests); it is the one place
where Contact, Offerings, Availability and the shared hosting meet. -->
<ProjectReference Include="..\SlpModularCms.Api.SlpSoftware\SlpModularCms.Api.SlpSoftware.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,97 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
/// <summary>Captures every log entry so tests can prove nothing personal is ever logged.</summary>
public sealed class CapturingLoggerProvider : ILoggerProvider
{
public List<string> Messages { get; } = [];
public ILogger CreateLogger(string categoryName) => new CapturingLogger(Messages);
public void Dispose() { }
private sealed class CapturingLogger(List<string> messages) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
lock (messages)
{
messages.Add(formatter(state, exception));
if (exception is not null)
{
messages.Add(exception.ToString());
}
}
}
}
}
/// <summary>
/// The submission service wired to a real in-memory database, a real token service and a fake
/// clock; only the captcha and the mail sender are substitutes.
/// </summary>
public sealed class SubmissionHarness : IDisposable
{
public static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
public FakeTimeProvider Time { get; } = new(Start);
public ContactOptions Options { get; }
public ContactDbContext Db { get; }
public IContactRepository Repository { get; }
public IContactTokenService Tokens { get; }
public ICaptchaVerifier Captcha { get; } = Substitute.For<ICaptchaVerifier>();
public IContactMailSender Mail { get; } = Substitute.For<IContactMailSender>();
public CapturingLoggerProvider Logs { get; } = new();
public ContactSubmissionService Sut { get; }
public SubmissionHarness(Action<ContactOptions>? configure = null, IContactRepository? repositoryOverride = null)
{
Options = new ContactOptions { Enabled = true, SiteId = "site-a", MinSeconds = 3 };
configure?.Invoke(Options);
Db = new ContactDbContext(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options);
Repository = repositoryOverride ?? new ContactRepository(Db);
var wrapped = Microsoft.Extensions.Options.Options.Create(Options);
Tokens = new ContactTokenService(DataProtectionProvider.Create("submission-tests"), wrapped, Time);
Captcha.VerifyAsync(Arg.Any<string?>(), Arg.Any<CancellationToken>()).Returns(true);
Mail.SendAsync(Arg.Any<Data.Entities.ContactMessage>(), Arg.Any<CancellationToken>())
.Returns(ContactMailOutcome.Skipped);
var loggerFactory = LoggerFactory.Create(b => b.AddProvider(Logs));
Sut = new ContactSubmissionService(
Repository, Tokens, Captcha, Mail, wrapped, Time, loggerFactory.CreateLogger<ContactSubmissionService>());
}
/// <summary>A token that is old enough to pass the minimum-time check.</summary>
public string MatureToken()
{
var token = Tokens.Issue();
Time.Advance(TimeSpan.FromSeconds(Options.MinSeconds + 1));
return token;
}
public static ContactMessageRequest Request(string token, string hp = "", string? captcha = null) => new(
"Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", hp, token, captcha);
public Task<SubmissionResult> Submit(ContactMessageRequest? request, string? key = null)
=> Sut.SubmitAsync(request, key ?? Guid.NewGuid().ToString(), CancellationToken.None);
public void Dispose() => Db.Dispose();
}
@@ -0,0 +1,52 @@
namespace SlpModularCms.Modules.Contact.Config;
/// <summary>
/// Per-host configuration of the contact module (section <c>Contact</c>).
/// </summary>
public class ContactOptions
{
public const string SectionName = "Contact";
/// <summary>
/// Master switch. While false the contact routes answer 404 and the module touches nothing.
/// It must only be switched on for a public host once per-client rate limiting is in place
/// (see <see cref="Services.ContactRateLimitPartition"/>).
/// </summary>
public bool Enabled { get; set; }
/// <summary>Identifies the site on stored rows and in the token purpose. Never taken from a request.</summary>
public string? SiteId { get; set; }
/// <summary>Minimum seconds between issuing the token and submitting; faster submissions are treated as spam.</summary>
public int MinSeconds { get; set; } = 3;
public int TokenLifetimeMinutes { get; set; } = 120;
/// <summary>Months a genuine message is kept (fixed per row at insert).</summary>
public int RetentionMonths { get; set; } = 12;
/// <summary>Days a message classified as spam is kept.</summary>
public int SpamRetentionDays { get; set; } = 30;
/// <summary>Per site and UTC day; beyond it spam is answered normally but not stored.</summary>
public int MaxSpamRowsPerDay { get; set; } = 200;
public int MaxBodyBytes { get; set; } = 16384;
/// <summary>Base of the validation problem <c>type</c> URI. When empty the type is <c>about:blank</c>.</summary>
public string? ProblemTypeBase { get; set; }
public ContactCaptchaOptions Captcha { get; set; } = new();
public string EffectiveSiteId => string.IsNullOrWhiteSpace(SiteId) ? "default" : SiteId.Trim();
}
public class ContactCaptchaOptions
{
public bool Enabled { get; set; }
public string? Provider { get; set; }
public string? SiteKey { get; set; }
/// <summary>Server-side secret; supply it through the environment or a secrets manager, never committed.</summary>
public string? Secret { get; set; }
}
@@ -0,0 +1,89 @@
using System.Diagnostics.CodeAnalysis;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Modules;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact;
[ExcludeFromCodeCoverage]
public class ContactModule : IModule
{
public string Name => "Contact";
public string Version => "1.0.0";
public void RegisterServices(IServiceCollection services)
{
services.AddOptions<ContactOptions>()
.Configure<IConfiguration>((options, config) =>
config.GetSection(ContactOptions.SectionName).Bind(options));
services.AddDbContext<ContactDbContext>((serviceProvider, options) =>
{
var config = serviceProvider.GetRequiredService<IConfiguration>();
options.UseMySQL(config.GetConnectionString("DefaultConnection")!);
options.ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>();
});
services.TryAddSingleton(TimeProvider.System);
services.AddScoped<IContactRepository, ContactRepository>();
services.AddScoped<IContactSubmissionService, ContactSubmissionService>();
services.AddSingleton<IContactTokenService, ContactTokenService>();
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
services.AddScoped<IContactMailSender, NoOpContactMailSender>();
services.AddScoped<IContactFormGate, HostFlagContactFormGate>();
services.AddScoped<ContactRouteFilter>();
services.AddHostedService<ContactRetentionService>();
// Rate-limit policies live in this module so the shared limiter setup stays untouched.
// The bucket key comes from one function; see ContactRateLimitPartition.
services.AddOptions<RateLimiterOptions>()
.Configure<IConfiguration>((limiter, config) =>
{
limiter.AddPolicy(ContactMessagesController.FormPolicy, context =>
Window(config, "ContactForm", 5, 600, context));
limiter.AddPolicy(ContactMessagesController.TokenPolicy, context =>
Window(config, "ContactToken", 20, 600, context));
});
}
public void UseModule(IApplicationBuilder app)
{
// Nothing is touched while the module is switched off: not even the database.
var enabled = app.ApplicationServices.GetRequiredService<IOptions<ContactOptions>>().Value.Enabled;
if (!enabled)
{
return;
}
using var scope = app.ApplicationServices.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
db.Database.Migrate();
}
private static RateLimitPartition<string> Window(
IConfiguration config, string name, int defaultPermits, int defaultSeconds, Microsoft.AspNetCore.Http.HttpContext context)
{
var section = config.GetSection($"RateLimiting:{name}");
return RateLimitPartition.GetFixedWindowLimiter(
ContactRateLimitPartition.KeyFor(context),
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = section.GetValue("PermitLimit", defaultPermits),
Window = TimeSpan.FromSeconds(section.GetValue("WindowSeconds", defaultSeconds)),
QueueLimit = 0,
});
}
}
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>
/// The public contact routes. Deliberately not an <c>[ApiController]</c>: a body that cannot be
/// bound must produce our own problem shape, never the framework's, and must not echo values.
/// The management routes (list, read, delete, resend) are added with the admin unit.
/// </summary>
[Route("contact-messages")]
[ServiceFilter(typeof(ContactRouteFilter))]
public class ContactMessagesController(
IContactTokenService tokens,
IContactSubmissionService submissions,
IOptions<ContactOptions> options) : ControllerBase
{
public const string IdempotencyKeyHeader = "Idempotency-Key";
public const string TokenPolicy = "contact-token";
public const string FormPolicy = "contact-form";
[HttpGet("token")]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting(TokenPolicy)]
public IActionResult GetToken()
{
var settings = options.Value;
var captcha = settings.Captcha is { Enabled: true } c && !string.IsNullOrWhiteSpace(c.Provider)
? new ContactCaptchaInfo(c.Provider!, c.SiteKey ?? string.Empty)
: null;
return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha));
}
[HttpPost]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting(FormPolicy)]
public async Task<IActionResult> Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken)
{
var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault();
// An unbindable body (malformed JSON, wrong types) arrives as null.
var result = await submissions.SubmitAsync(ModelState.IsValid ? request : null, key, cancellationToken);
return result switch
{
SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)),
_ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted },
};
}
private ValidationProblemDetails Problem(IReadOnlyDictionary<string, string[]> errors)
{
var baseUri = options.Value.ProblemTypeBase?.TrimEnd('/');
return new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value))
{
Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation",
Title = "Validation failed",
Status = StatusCodes.Status400BadRequest,
};
}
}
@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>
/// Runs before model binding on the public contact routes:
/// 1. While the form is not open (see <see cref="IContactFormGate"/>) the route does not exist
/// (404, empty body).
/// 2. Caps the request body (413 as problem+json), also when the size is only known while reading.
/// </summary>
public sealed class ContactRouteFilter(IContactFormGate gate, IOptions<ContactOptions> options) : IAsyncResourceFilter
{
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var settings = options.Value;
if (!await gate.IsOpenAsync(context.HttpContext.RequestAborted))
{
context.Result = new NotFoundResult();
return;
}
var request = context.HttpContext.Request;
if (HttpMethods.IsPost(request.Method))
{
if (request.ContentLength > settings.MaxBodyBytes)
{
context.Result = TooLarge();
return;
}
// For chunked bodies the length is unknown up front; Kestrel enforces the cap while reading.
var feature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
if (feature is { IsReadOnly: false })
{
feature.MaxRequestBodySize = settings.MaxBodyBytes;
}
}
var executed = await next();
if (executed.Exception is BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge })
{
executed.ExceptionHandled = true;
executed.Result = TooLarge();
}
}
private static ObjectResult TooLarge() => new(new ProblemDetails
{
Status = StatusCodes.Status413PayloadTooLarge,
Title = "Payload too large",
})
{
StatusCode = StatusCodes.Status413PayloadTooLarge,
ContentTypes = { "application/problem+json" },
};
}
@@ -0,0 +1,44 @@
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Data;
public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbContext(options)
{
public DbSet<ContactMessage> ContactMessages => Set<ContactMessage>();
public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ContactMessage>(entity =>
{
entity.ToTable("ContactMessages");
entity.HasKey(e => e.Id);
entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100);
entity.Property(e => e.ReceivedAt).IsRequired();
entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
entity.Property(e => e.Email).IsRequired().HasMaxLength(254);
entity.Property(e => e.Subject).IsRequired().HasMaxLength(100);
entity.Property(e => e.Message).IsRequired().HasMaxLength(2000);
entity.Property(e => e.Status).IsRequired().HasConversion<string>().HasMaxLength(20);
entity.Property(e => e.MailStatus).IsRequired().HasConversion<string>().HasMaxLength(20);
entity.Property(e => e.MailError).HasMaxLength(100);
entity.Property(e => e.RetentionUntil).IsRequired();
entity.HasIndex(e => new { e.SiteId, e.Status, e.ReceivedAt });
entity.HasIndex(e => e.RetentionUntil);
});
modelBuilder.Entity<IdempotencyRecord>(entity =>
{
entity.ToTable("ContactIdempotency");
entity.HasKey(e => new { e.SiteId, e.Key });
entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100);
entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.StatusCode).IsRequired();
entity.HasIndex(e => e.CreatedAt);
});
}
}
@@ -0,0 +1,58 @@
namespace SlpModularCms.Modules.Contact.Data.Entities;
public enum ContactMessageStatus
{
New,
Read,
Archived,
Spam,
Converted,
}
public enum ContactMailStatus
{
/// <summary>Waiting to be mailed (also the state while no mail sender is available).</summary>
Pending,
Sent,
Failed,
/// <summary>Never mailed on purpose (spam).</summary>
NotApplicable,
}
/// <summary>
/// A message sent through the website's contact form. Has its own id and status so that it can
/// later be turned into an assignment (quotes, invoices); that is not built yet.
/// </summary>
public class ContactMessage
{
public Guid Id { get; set; }
public string SiteId { get; set; } = string.Empty;
public DateTimeOffset ReceivedAt { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
/// <summary>Opaque value chosen by the site (a package id, a slug, or 'other').</summary>
public string Subject { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public ContactMessageStatus Status { get; set; }
public ContactMailStatus MailStatus { get; set; }
/// <summary>Short error code of the last failed mail attempt (never an address or content).</summary>
public string? MailError { get; set; }
public int MailAttempts { get; set; }
public DateTimeOffset? NextMailAttemptAt { get; set; }
/// <summary>Fixed at insert: a later configuration change does not apply retroactively.</summary>
public DateTimeOffset RetentionUntil { get; set; }
}
/// <summary>Remembers an Idempotency-Key for 24 hours. Holds no request content.</summary>
public class IdempotencyRecord
{
public string SiteId { get; set; } = string.Empty;
public Guid Key { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public int StatusCode { get; set; }
}
@@ -0,0 +1,115 @@
// <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("20261109200014_InitialCreate")]
partial class InitialCreate
{
/// <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.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,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "ContactIdempotency",
columns: table => new
{
SiteId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Key = table.Column<Guid>(type: "char(36)", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
StatusCode = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactIdempotency", x => new { x.SiteId, x.Key });
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "ContactMessages",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
SiteId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
ReceivedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Email = table.Column<string>(type: "varchar(254)", maxLength: 254, nullable: false),
Subject = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Message = table.Column<string>(type: "varchar(2000)", maxLength: 2000, nullable: false),
Status = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
MailStatus = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
MailError = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
MailAttempts = table.Column<int>(type: "int", nullable: false),
NextMailAttemptAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
RetentionUntil = table.Column<DateTimeOffset>(type: "datetime", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactMessages", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_ContactIdempotency_CreatedAt",
table: "ContactIdempotency",
column: "CreatedAt");
migrationBuilder.CreateIndex(
name: "IX_ContactMessages_RetentionUntil",
table: "ContactMessages",
column: "RetentionUntil");
migrationBuilder.CreateIndex(
name: "IX_ContactMessages_SiteId_Status_ReceivedAt",
table: "ContactMessages",
columns: new[] { "SiteId", "Status", "ReceivedAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContactIdempotency");
migrationBuilder.DropTable(
name: "ContactMessages");
}
}
}
@@ -0,0 +1,112 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
partial class ContactDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
{
b.Property<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.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,44 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Contact.Models;
/// <summary>
/// The body of POST /contact-messages. Everything is nullable on purpose: a missing field is
/// reported as the validation code <c>required</c> in our own problem shape instead of a
/// framework binding error. <c>HpCheck</c> is the honeypot (JSON name <c>hpCheck</c>).
/// </summary>
public record ContactMessageRequest(
string? Name,
string? Email,
string? Subject,
string? Message,
string? HpCheck,
string? Token,
string? CaptchaToken);
[ExcludeFromCodeCoverage]
public record ContactCaptchaInfo(string Provider, string SiteKey);
[ExcludeFromCodeCoverage]
public record ContactTokenResponse(string Token, int MinSeconds, ContactCaptchaInfo? Captcha);
[ExcludeFromCodeCoverage]
public record ReceivedResponse(string Status);
/// <summary>Validation error codes, as the client maps them to texts.</summary>
public static class ContactErrorCodes
{
public const string Required = "required";
public const string TooLong = "tooLong";
public const string Invalid = "invalid";
public const string Expired = "expired";
}
/// <summary>Outcome of handling one submission.</summary>
public abstract record SubmissionResult
{
/// <summary>Accepted: genuine, spam and replays all look the same to the caller.</summary>
public sealed record Received : SubmissionResult;
public sealed record Invalid(IReadOnlyDictionary<string, string[]> Errors) : SubmissionResult;
}
@@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Repositories;
public interface IContactRepository
{
Task<IdempotencyRecord?> GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken);
Task<int> CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken);
void Add(ContactMessage message);
void Add(IdempotencyRecord record);
Task SaveChangesAsync(CancellationToken cancellationToken);
Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken);
Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
}
public class ContactRepository(ContactDbContext context) : IContactRepository
{
private const int BatchSize = 500;
public Task<IdempotencyRecord?> GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken)
=> context.IdempotencyRecords.FirstOrDefaultAsync(r => r.SiteId == siteId && r.Key == key, cancellationToken);
public Task<int> CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken)
=> context.ContactMessages.CountAsync(
m => m.SiteId == siteId && m.Status == ContactMessageStatus.Spam && m.ReceivedAt >= since,
cancellationToken);
public void Add(ContactMessage message) => context.ContactMessages.Add(message);
public void Add(IdempotencyRecord record) => context.IdempotencyRecords.Add(record);
public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
public async Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
var total = 0;
while (true)
{
var batch = await context.ContactMessages
.Where(m => m.RetentionUntil < now)
.Take(BatchSize)
.ToListAsync(cancellationToken);
if (batch.Count == 0)
{
return total;
}
context.ContactMessages.RemoveRange(batch);
await context.SaveChangesAsync(cancellationToken);
total += batch.Count;
}
}
public async Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
{
var total = 0;
while (true)
{
var batch = await context.IdempotencyRecords
.Where(r => r.CreatedAt < cutoff)
.Take(BatchSize)
.ToListAsync(cancellationToken);
if (batch.Count == 0)
{
return total;
}
context.IdempotencyRecords.RemoveRange(batch);
await context.SaveChangesAsync(cancellationToken);
total += batch.Count;
}
}
}
@@ -0,0 +1,25 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Decides whether the public contact form is active. The form is active only when every layer
/// says so; if any layer is off the public routes answer 404 with an empty body (the website
/// then shows its mailto fallback).
/// </summary>
/// <remarks>
/// Layers: (1) the host switch <c>Contact:Enabled</c> (release condition, default off) and,
/// from the admin unit on, (2) a switch an administrator controls in the CMS. The route filter
/// only knows this interface, so adding the second layer does not touch the filter.
/// </remarks>
public interface IContactFormGate
{
Task<bool> IsOpenAsync(CancellationToken cancellationToken);
}
/// <summary>Layer 1: the host configuration.</summary>
public sealed class HostFlagContactFormGate(IOptions<ContactOptions> options) : IContactFormGate
{
public Task<bool> IsOpenAsync(CancellationToken cancellationToken) => Task.FromResult(options.Value.Enabled);
}
@@ -0,0 +1,58 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Daily clean-up: deletes messages past their retention date and idempotency records older
/// than 24 hours. While the module is disabled it does nothing at all (no database access).
/// </summary>
public class ContactRetentionService(
IServiceScopeFactory scopeFactory,
IOptions<ContactOptions> options,
TimeProvider time,
ILogger<ContactRetentionService> logger) : BackgroundService
{
internal static readonly TimeSpan Interval = TimeSpan.FromHours(24);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ExecuteTickAsync(stoppingToken);
using var timer = new PeriodicTimer(Interval);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await ExecuteTickAsync(stoppingToken);
}
}
internal async Task ExecuteTickAsync(CancellationToken stoppingToken)
{
if (!options.Value.Enabled)
{
return;
}
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<IContactRepository>();
var now = time.GetUtcNow();
var messages = await repository.DeleteExpiredMessagesAsync(now, stoppingToken);
var records = await repository.DeleteIdempotencyOlderThanAsync(now - TimeSpan.FromHours(24), stoppingToken);
logger.LogInformation(
"Contact retention: removed {Messages} expired message(s) and {Records} idempotency record(s)",
messages, records);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError("Contact retention run failed ({ExceptionType})", ex.GetType().Name);
}
}
}
@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Http;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Verifies a captcha token server-side. Implementations must fail open: when the provider
/// itself is unreachable they return <c>true</c> (and log without personal data), so real
/// visitors are never locked out by a provider outage.
/// </summary>
public interface ICaptchaVerifier
{
Task<bool> VerifyAsync(string? captchaToken, CancellationToken cancellationToken);
}
/// <summary>Used while no captcha is configured: everything passes.</summary>
public sealed class NullCaptchaVerifier : ICaptchaVerifier
{
public Task<bool> VerifyAsync(string? captchaToken, CancellationToken cancellationToken) => Task.FromResult(true);
}
public enum ContactMailOutcome
{
/// <summary>No mail was attempted (no sender available yet); the message stays pending.</summary>
Skipped,
Sent,
Failed,
}
/// <summary>
/// Sends the notification mail for a genuine message. Called after the message is stored; a
/// failure must never fail the request. The real implementation arrives with the mail unit.
/// </summary>
public interface IContactMailSender
{
Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken);
}
public sealed class NoOpContactMailSender : IContactMailSender
{
public Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken)
=> Task.FromResult(ContactMailOutcome.Skipped);
}
/// <summary>
/// The single place that decides which rate-limit bucket a request belongs to.
/// </summary>
/// <remarks>
/// On the base branch the rate limiter has no per-client partitioning (no forwarded-header
/// handling, no client key): every visitor is the same caller. This returns a constant, so the
/// contact policies behave as ONE shared bucket per policy, which is why the contact routes are
/// disabled (<c>Contact:Enabled=false</c>) until the per-client partitioning from the ASF branch
/// has been merged. Switching to per-client is the one-line change documented in the rebase
/// checklist: replace the body with <c>ClientPartitionKey.For(context)</c>.
/// </remarks>
public static class ContactRateLimitPartition
{
public const string GlobalKey = "global";
public static string KeyFor(HttpContext context) => GlobalKey;
}
@@ -0,0 +1,205 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
public interface IContactSubmissionService
{
Task<SubmissionResult> SubmitAsync(ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken);
}
/// <summary>
/// Handles one submission: validate, de-duplicate, classify (genuine or spam), store, mail.
/// Genuine messages, spam and replays are indistinguishable to the caller (the same 202), so
/// bots learn nothing. Nothing personal is ever logged: only the outcome and the site id.
/// </summary>
public sealed class ContactSubmissionService(
IContactRepository repository,
IContactTokenService tokens,
ICaptchaVerifier captcha,
IContactMailSender mailSender,
IOptions<ContactOptions> options,
TimeProvider time,
ILogger<ContactSubmissionService> logger) : IContactSubmissionService
{
private static readonly TimeSpan IdempotencyWindow = TimeSpan.FromHours(24);
private enum Outcome { Genuine, Spam, SpamNotStored, Replay }
public async Task<SubmissionResult> SubmitAsync(
ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken)
{
var o = options.Value;
var siteId = o.EffectiveSiteId;
// 1. Header and fields (one response lists every problem).
var errors = new Dictionary<string, string[]>();
Guid key = default;
if (string.IsNullOrWhiteSpace(idempotencyKey))
{
errors["idempotencyKey"] = [ContactErrorCodes.Required];
}
else if (!Guid.TryParse(idempotencyKey, out key))
{
errors["idempotencyKey"] = [ContactErrorCodes.Invalid];
}
if (request is null)
{
errors["body"] = [ContactErrorCodes.Invalid];
}
else
{
request = ContactValidator.Normalize(request);
foreach (var (field, codes) in ContactValidator.Validate(request))
{
errors[field] = codes;
}
}
if (errors.Count > 0)
{
return new SubmissionResult.Invalid(errors);
}
var now = time.GetUtcNow();
// 2. Replay within 24 hours: the same answer, nothing stored twice.
var existing = await repository.GetIdempotencyAsync(siteId, key, cancellationToken);
if (existing is not null && now - existing.CreatedAt < IdempotencyWindow)
{
Log(Outcome.Replay, siteId);
return new SubmissionResult.Received();
}
// 3. Token. Forged, other-site and expired tokens all look the same ('expired'): no oracle.
var tokenCheck = tokens.Check(request!.Token);
if (tokenCheck == TokenCheck.InvalidOrExpired)
{
return new SubmissionResult.Invalid(new Dictionary<string, string[]>
{
["token"] = [ContactErrorCodes.Expired],
});
}
// 4. Classify. A filled honeypot, a too-fast submission or a rejected captcha is spam.
var isSpam = tokenCheck == TokenCheck.TooYoung
|| !string.IsNullOrEmpty(request.HpCheck)
|| (o.Captcha.Enabled && !await captcha.VerifyAsync(request.CaptchaToken, cancellationToken));
// 5. Store. Spam is kept for a short time (a real visitor may have tripped a check) but
// capped per day so a flood cannot fill the table.
ContactMessage? message = null;
var outcome = Outcome.Genuine;
if (isSpam)
{
var startOfDay = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
var spamToday = await repository.CountSpamSinceAsync(siteId, startOfDay, cancellationToken);
if (spamToday < o.MaxSpamRowsPerDay)
{
message = NewMessage(request, siteId, now, ContactMessageStatus.Spam, ContactMailStatus.NotApplicable,
now.AddDays(o.SpamRetentionDays));
outcome = Outcome.Spam;
}
else
{
outcome = Outcome.SpamNotStored;
}
}
else
{
message = NewMessage(request, siteId, now, ContactMessageStatus.New, ContactMailStatus.Pending,
now.AddMonths(o.RetentionMonths));
}
if (message is not null)
{
repository.Add(message);
}
if (existing is null)
{
repository.Add(new IdempotencyRecord
{
SiteId = siteId,
Key = key,
CreatedAt = now,
StatusCode = StatusCodes202,
});
}
else
{
// An expired record that the daily job has not removed yet: reuse its row.
existing.CreatedAt = now;
existing.StatusCode = StatusCodes202;
}
try
{
await repository.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException)
{
// Two requests with the same key raced; the other one won. Same answer, nothing twice.
Log(Outcome.Replay, siteId);
return new SubmissionResult.Received();
}
// 6. Mail, only for genuine messages and only after the message is safely stored. A mail
// problem never fails the request.
if (outcome == Outcome.Genuine && message is not null)
{
await TryMailAsync(message, cancellationToken);
}
Log(outcome, siteId);
return new SubmissionResult.Received();
}
private const int StatusCodes202 = 202;
private async Task TryMailAsync(ContactMessage message, CancellationToken cancellationToken)
{
try
{
var result = await mailSender.SendAsync(message, cancellationToken);
if (result == ContactMailOutcome.Skipped)
{
return;
}
message.MailAttempts++;
message.MailStatus = result == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
await repository.SaveChangesAsync(cancellationToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Type only: the exception message could carry addresses or content.
logger.LogError("Notification mail for a contact message failed ({ExceptionType})", ex.GetType().Name);
}
}
private static ContactMessage NewMessage(
ContactMessageRequest request, string siteId, DateTimeOffset now,
ContactMessageStatus status, ContactMailStatus mailStatus, DateTimeOffset retentionUntil) => new()
{
Id = Guid.NewGuid(),
SiteId = siteId,
ReceivedAt = now,
Name = request.Name!,
Email = request.Email!,
Subject = request.Subject!,
Message = request.Message!,
Status = status,
MailStatus = mailStatus,
RetentionUntil = retentionUntil,
};
private void Log(Outcome outcome, string siteId)
=> logger.LogInformation("Contact submission handled: {Outcome} for site {SiteId}", outcome, siteId);
}
@@ -0,0 +1,83 @@
using System.Globalization;
using System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
namespace SlpModularCms.Modules.Contact.Services;
public enum TokenCheck
{
Valid,
/// <summary>Issued less than <c>MinSeconds</c> ago: the form was filled in faster than a person can.</summary>
TooYoung,
/// <summary>Forged, garbage, from another site, or older than its lifetime. Never distinguished to the caller.</summary>
InvalidOrExpired,
}
public interface IContactTokenService
{
string Issue();
TokenCheck Check(string? token);
}
/// <summary>
/// Server-signed token for the minimum-time check. Protected with ASP.NET Data Protection (the
/// host stores the key ring in the database), bound to the site by the purpose string, so a token
/// of one site is garbage to another. Nothing is stored.
/// </summary>
public sealed class ContactTokenService : IContactTokenService
{
private const string Version = "v1";
private readonly IDataProtector _protector;
private readonly ContactOptions _options;
private readonly TimeProvider _time;
public ContactTokenService(IDataProtectionProvider provider, IOptions<ContactOptions> options, TimeProvider time)
{
_options = options.Value;
_time = time;
_protector = provider.CreateProtector(PurposeFor(_options.EffectiveSiteId));
}
public static string PurposeFor(string siteId) => $"SlpModularCms.Contact.Token.{siteId}";
public string Issue()
=> _protector.Protect($"{Version}|{_time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}");
public TokenCheck Check(string? token)
{
if (string.IsNullOrWhiteSpace(token))
{
return TokenCheck.InvalidOrExpired;
}
string payload;
try
{
payload = _protector.Unprotect(token);
}
catch (CryptographicException)
{
return TokenCheck.InvalidOrExpired;
}
var parts = payload.Split('|');
if (parts.Length != 2 || parts[0] != Version
|| !long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var issuedAt))
{
return TokenCheck.InvalidOrExpired;
}
var age = _time.GetUtcNow().ToUnixTimeSeconds() - issuedAt;
if (age < 0 || age > TimeSpan.FromMinutes(_options.TokenLifetimeMinutes).TotalSeconds)
{
return TokenCheck.InvalidOrExpired;
}
return age < _options.MinSeconds ? TokenCheck.TooYoung : TokenCheck.Valid;
}
}
@@ -0,0 +1,115 @@
using System.Text.RegularExpressions;
using SlpModularCms.Modules.Contact.Models;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Field rules of the contact form. Pure: no I/O, no clock. The same limits and codes are used
/// by the client so the two can never disagree silently.
/// </summary>
public static class ContactValidator
{
public const int NameMax = 100;
public const int EmailMax = 254;
public const int SubjectMax = 100;
public const int MessageMax = 2000;
private static readonly Regex EmailPattern =
new(@"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$", RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250));
/// <summary>The request with all text fields trimmed (null stays null).</summary>
public static ContactMessageRequest Normalize(ContactMessageRequest request) => request with
{
Name = request.Name?.Trim(),
Email = request.Email?.Trim(),
Subject = request.Subject?.Trim(),
Message = request.Message?.Trim(),
Token = request.Token?.Trim(),
};
/// <summary>Validates an already normalized request. Keys are the JSON field names.</summary>
public static Dictionary<string, string[]> Validate(ContactMessageRequest request)
{
var errors = new Dictionary<string, string[]>();
Check(errors, "name", request.Name, NameMax, allowLineBreaks: false);
CheckEmail(errors, request.Email);
Check(errors, "subject", request.Subject, SubjectMax, allowLineBreaks: false);
Check(errors, "message", request.Message, MessageMax, allowLineBreaks: true);
if (string.IsNullOrWhiteSpace(request.Token))
{
errors["token"] = [ContactErrorCodes.Required];
}
return errors;
}
private static void Check(Dictionary<string, string[]> errors, string field, string? value, int max, bool allowLineBreaks)
{
if (string.IsNullOrEmpty(value))
{
errors[field] = [ContactErrorCodes.Required];
}
else if (value.Length > max)
{
errors[field] = [ContactErrorCodes.TooLong];
}
else if (HasControlCharacters(value, allowLineBreaks))
{
errors[field] = [ContactErrorCodes.Invalid];
}
}
private static void CheckEmail(Dictionary<string, string[]> errors, string? value)
{
if (string.IsNullOrEmpty(value))
{
errors["email"] = [ContactErrorCodes.Required];
}
else if (value.Length > EmailMax)
{
errors["email"] = [ContactErrorCodes.TooLong];
}
else if (HasControlCharacters(value, allowLineBreaks: false) || !IsEmailShaped(value))
{
errors["email"] = [ContactErrorCodes.Invalid];
}
}
private static bool IsEmailShaped(string value)
{
try
{
return EmailPattern.IsMatch(value);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
/// <summary>
/// Control characters would end up in mail headers (header injection) or break displays.
/// In the message, tabs and line breaks are normal text and allowed.
/// </summary>
internal static bool HasControlCharacters(string value, bool allowLineBreaks)
{
foreach (var c in value)
{
if (!char.IsControl(c))
{
continue;
}
if (allowLineBreaks && (c is '\n' or '\r' or '\t'))
{
continue;
}
return true;
}
return false;
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>SlpModularCms.Modules.Contact.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
</ItemGroup>
</Project>