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