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