using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Time.Testing; using NSubstitute; using SlpModularCms.Modules.Contact.Config; using SlpModularCms.Modules.Contact.Data; using SlpModularCms.Modules.Contact.Data.Entities; using SlpModularCms.Modules.Contact.Repositories; using SlpModularCms.Modules.Contact.Services; namespace SlpModularCms.Modules.Contact.Tests; public class ContactRetentionServiceTests { private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); private static ContactMessage Message(string name, DateTimeOffset retentionUntil) => new() { Id = Guid.NewGuid(), SiteId = "s", ReceivedAt = Now.AddDays(-1), Name = name, Email = "a@b.nl", Subject = "x", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, RetentionUntil = retentionUntil, }; private static (ContactRetentionService Sut, ServiceProvider Provider, string Db) Create(bool enabled) { var databaseName = Guid.NewGuid().ToString(); var services = new ServiceCollection(); services.AddDbContext(o => o.UseInMemoryDatabase(databaseName)); services.AddScoped(); var provider = services.BuildServiceProvider(); var sut = new ContactRetentionService( provider.GetRequiredService(), Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = enabled }), new FakeTimeProvider(Now), NullLogger.Instance); return (Sut: sut, Provider: provider, Db: databaseName); } [Fact] public async Task DeletesExpiredMessagesAndOldIdempotencyRecords_AndKeepsTheRest() { var (sut, provider, _) = Create(enabled: true); await using (var scope = provider.CreateAsyncScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.ContactMessages.AddRange( Message("expired", Now.AddSeconds(-1)), Message("expired too", Now.AddDays(-30)), Message("kept", Now.AddDays(1)), Message("kept long", Now.AddMonths(11))); db.IdempotencyRecords.AddRange( new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-25), StatusCode = 202 }, new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-23), StatusCode = 202 }); await db.SaveChangesAsync(); } await sut.ExecuteTickAsync(CancellationToken.None); await using var check = provider.CreateAsyncScope(); var after = check.ServiceProvider.GetRequiredService(); after.ContactMessages.Select(m => m.Name).Should().BeEquivalentTo("kept", "kept long"); after.IdempotencyRecords.Count().Should().Be(1); } [Fact] public async Task HandlesMoreRowsThanOneBatch() { var (sut, provider, _) = Create(enabled: true); await using (var scope = provider.CreateAsyncScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.ContactMessages.AddRange(Enumerable.Range(0, 1200).Select(i => Message($"old{i}", Now.AddDays(-1)))); await db.SaveChangesAsync(); } await sut.ExecuteTickAsync(CancellationToken.None); await using var check = provider.CreateAsyncScope(); check.ServiceProvider.GetRequiredService().ContactMessages.Should().BeEmpty(); } [Fact] public async Task WhileDisabled_ItDoesNothing_AndNeverEvenOpensAScope() { var scopeFactory = Substitute.For(); var sut = new ContactRetentionService( scopeFactory, Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = false }), new FakeTimeProvider(Now), NullLogger.Instance); await sut.ExecuteTickAsync(CancellationToken.None); scopeFactory.ReceivedCalls().Should().BeEmpty("a disabled module must not touch the database or anything else"); } [Fact] public async Task ADatabaseProblem_DoesNotCrashTheJob() { var scopeFactory = Substitute.For(); scopeFactory.CreateScope().Returns(_ => throw new InvalidOperationException("db down")); var sut = new ContactRetentionService( scopeFactory, Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = true }), new FakeTimeProvider(Now), NullLogger.Instance); var act = () => sut.ExecuteTickAsync(CancellationToken.None); await act.Should().NotThrowAsync(); } [Fact] public void TheJobRunsDaily() { ContactRetentionService.Interval.Should().Be(TimeSpan.FromHours(24)); } } public class ContactRateLimitPartitionTests { /// /// Every contact policy is partitioned per client with the host's own key /// (ClientPartitionKey): different client addresses never share a bucket. /// [Fact] public void DifferentClientAddresses_GetDifferentBuckets_AndTheSameAddressTheSameBucket() { var first = new DefaultHttpContext(); first.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10"); var again = new DefaultHttpContext(); again.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().NotBe(ContactRateLimitPartition.KeyFor(second)); ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.KeyFor(again)); ContactRateLimitPartition.KeyFor(first).Should().Be("203.0.113.10"); } [Fact] public void TheKeyIsTheHostsOwnClientKey() { var context = new DefaultHttpContext(); context.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("::ffff:192.0.2.7"); ContactRateLimitPartition.KeyFor(context).Should().Be(SlpModularCms.Core.Hosting.Proxy.ClientPartitionKey.For(context)); ContactRateLimitPartition.KeyFor(new DefaultHttpContext()).Should().Be(SlpModularCms.Core.Hosting.Proxy.ClientPartitionKey.Unknown); } }