Contact: mail via achtergrondservice met claim, backoff en maximum (CMS-U5)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,422 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
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 ContactMailOptionsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(1, 5)]
|
||||
[InlineData(2, 15)]
|
||||
[InlineData(3, 60)]
|
||||
[InlineData(4, 360)]
|
||||
[InlineData(5, 1440)]
|
||||
[InlineData(9, 1440)]
|
||||
public void TheBackoff_IsFiveMinutesFifteenMinutesOneHourSixHoursTwentyFourHours(int attempts, int minutes)
|
||||
=> new ContactMailOptions().BackoffAfter(attempts).Should().Be(TimeSpan.FromMinutes(minutes));
|
||||
|
||||
[Fact]
|
||||
public void TheDefaults_AreSixAttempts()
|
||||
=> new ContactMailOptions().MaxAttempts.Should().Be(6);
|
||||
}
|
||||
|
||||
public class ContactMailSenderTests
|
||||
{
|
||||
private const string Visitor = "jan@example.nl";
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public IEmailSender Email { get; } = Substitute.For<IEmailSender>();
|
||||
public IMailAvailability Availability { get; } = Substitute.For<IMailAvailability>();
|
||||
public ContactOptions Contact { get; } = new() { Enabled = true, RecipientEmail = "owner@example.org" };
|
||||
public CapturingLoggerProvider Logs { get; } = new();
|
||||
public OutgoingMail? Sent;
|
||||
|
||||
public Rig()
|
||||
{
|
||||
Availability.IsEnabled.Returns(true);
|
||||
Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(call =>
|
||||
{
|
||||
Sent = call.Arg<OutgoingMail>();
|
||||
return MailSendResult.Ok;
|
||||
});
|
||||
}
|
||||
|
||||
public ContactMailSender Build(string language = "nl")
|
||||
{
|
||||
var languages = Substitute.For<ILanguageResolver>();
|
||||
languages.Resolve(Arg.Any<string?>()).Returns(language);
|
||||
var settings = Substitute.For<ISiteSettingsService>();
|
||||
settings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("noreply@example.org", "De Site"));
|
||||
return new ContactMailSender(
|
||||
Email, new MailTemplateRenderer(), languages, settings, Availability,
|
||||
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
|
||||
Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger<ContactMailSender>());
|
||||
}
|
||||
}
|
||||
|
||||
private static ContactMessage Message(string name = "Jan Jansen", string subject = "website", string body = "Hallo\nwereld")
|
||||
=> new() { Id = Guid.NewGuid(), SiteId = "s", Name = name, Email = Visitor, Subject = subject, Message = body };
|
||||
|
||||
[Fact]
|
||||
public async Task ASend_GoesToTheRecipient_FromTheSiteSender_WithTheVisitorAsReplyTo()
|
||||
{
|
||||
var rig = new Rig();
|
||||
|
||||
var result = await rig.Build().SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
result.Outcome.Should().Be(ContactMailOutcome.Sent);
|
||||
rig.Sent!.ToAddress.Should().Be("owner@example.org");
|
||||
rig.Sent.FromAddress.Should().Be("noreply@example.org");
|
||||
rig.Sent.ReplyToAddress.Should().Be(Visitor);
|
||||
rig.Sent.ReplyToName.Should().Be("Jan Jansen");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSubject_NeverContainsAnythingTheVisitorTyped()
|
||||
{
|
||||
var rig = new Rig();
|
||||
|
||||
await rig.Build().SendAsync(Message(name: "ZXQ-Name", subject: "ZXQ-Subject\r\nBcc: x@y.z", body: "ZXQ-Body"), CancellationToken.None);
|
||||
|
||||
rig.Sent!.Subject.Should().NotContain("ZXQ").And.NotContain("\r").And.NotContain("\n");
|
||||
rig.Sent.Subject.Should().Be("Nieuw bericht via De Site");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheBody_EncodesHtml_AndKeepsLineBreaks_AndHasATextPart()
|
||||
{
|
||||
var rig = new Rig();
|
||||
|
||||
await rig.Build().SendAsync(Message(body: "<script>alert(1)</script>\nregel2"), CancellationToken.None);
|
||||
|
||||
rig.Sent!.HtmlBody.Should().NotContain("<script>").And.Contain("<script>").And.Contain("<br");
|
||||
rig.Sent.TextBody.Should().Contain("regel2").And.Contain("Naam:");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task English_UsesEnglishLabelsAndSubject()
|
||||
{
|
||||
var rig = new Rig();
|
||||
|
||||
await rig.Build("en").SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
rig.Sent!.Subject.Should().Be("New message via De Site");
|
||||
rig.Sent.TextBody.Should().Contain("Name:").And.Contain("Message:");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AControlCharacterInTheVisitorName_NeverReachesAHeader()
|
||||
{
|
||||
var rig = new Rig();
|
||||
|
||||
await rig.Build().SendAsync(Message(name: "Jan\r\nBcc: evil@example.com"), CancellationToken.None);
|
||||
|
||||
rig.Sent!.ReplyToName.Should().BeNull("an invalid display name is not used; the address alone is");
|
||||
rig.Sent.ReplyToAddress.Should().Be(Visitor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailure_IsReturnedAsItsShortCode_AndLogsNoPersonalData()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(MailSendResult.Fail(MailSendResult.AuthFailed));
|
||||
|
||||
var result = await rig.Build().SendAsync(Message(name: "ZXQ-Name", body: "ZXQ-Body"), CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Failed, "auth_failed"));
|
||||
rig.Logs.Messages.Should().NotContain(m => m.Contains("ZXQ") || m.Contains(Visitor) || m.Contains("owner@example.org"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnExceptionFromTheSender_BecomesUnknown_LoggedByTypeOnly()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>())
|
||||
.ThrowsAsync(new InvalidOperationException($"cannot deliver to {Visitor}"));
|
||||
|
||||
var result = await rig.Build().SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Failed, "unknown"));
|
||||
rig.Logs.Messages.Should().NotContain(m => m.Contains(Visitor));
|
||||
rig.Logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenMailIsOff_NothingIsSent_AndTheReasonIsDisabled()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Availability.IsEnabled.Returns(false);
|
||||
var sut = rig.Build();
|
||||
|
||||
var result = await sut.SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
|
||||
sut.NotReadyReason().Should().Be("disabled");
|
||||
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("not-an-address")]
|
||||
public async Task WithoutAValidRecipient_NothingIsSent(string? recipient)
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Contact.RecipientEmail = recipient;
|
||||
var sut = rig.Build();
|
||||
|
||||
var result = await sut.SendAsync(Message(), CancellationToken.None);
|
||||
|
||||
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "recipient_not_configured"));
|
||||
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactMailServiceTests : IDisposable
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero);
|
||||
private readonly string _dbName = Guid.NewGuid().ToString();
|
||||
private readonly FakeTimeProvider _time = new(Now);
|
||||
private readonly ContactOptions _options = new() { Enabled = true, SiteId = "site-a" };
|
||||
private readonly IContactMailSender _sender = Substitute.For<IContactMailSender>();
|
||||
private readonly CapturingLoggerProvider _logs = new();
|
||||
private readonly ServiceProvider _provider;
|
||||
|
||||
public ContactMailServiceTests()
|
||||
{
|
||||
_sender.NotReadyReason().Returns((string?)null);
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddDbContext<ContactDbContext>(o => o.UseInMemoryDatabase(_dbName));
|
||||
services.AddScoped<IContactRepository, ContactRepository>();
|
||||
services.AddScoped(_ => _sender);
|
||||
_provider = services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
public void Dispose() => _provider.Dispose();
|
||||
|
||||
private ContactMailService Sut() => new(
|
||||
_provider.GetRequiredService<IServiceScopeFactory>(), new ContactMailSignal(), Options.Create(_options), _time,
|
||||
LoggerFactory.Create(b => b.AddProvider(_logs)).CreateLogger<ContactMailService>());
|
||||
|
||||
private Guid Add(
|
||||
ContactMessageStatus status = ContactMessageStatus.New, ContactMailStatus mail = ContactMailStatus.Pending,
|
||||
int attempts = 0, DateTimeOffset? next = null, int minutesAgo = 0)
|
||||
{
|
||||
using var scope = _provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
|
||||
var message = new ContactMessage
|
||||
{
|
||||
Id = Guid.NewGuid(), SiteId = "site-a", ReceivedAt = Now.AddMinutes(-minutesAgo), Name = "Jan", Email = "jan@example.nl",
|
||||
Subject = "s", Message = "m", Status = status, MailStatus = mail, MailAttempts = attempts,
|
||||
NextMailAttemptAt = next ?? Now, RetentionUntil = Now.AddMonths(12),
|
||||
};
|
||||
db.ContactMessages.Add(message);
|
||||
db.SaveChanges();
|
||||
return message.Id;
|
||||
}
|
||||
|
||||
private ContactMessage Get(Guid id)
|
||||
{
|
||||
using var scope = _provider.CreateScope();
|
||||
return scope.ServiceProvider.GetRequiredService<ContactDbContext>().ContactMessages.AsNoTracking().Single(m => m.Id == id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADueMessage_IsSent_AndRecorded()
|
||||
{
|
||||
var id = Add();
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
|
||||
|
||||
var m = Get(id);
|
||||
m.MailStatus.Should().Be(ContactMailStatus.Sent);
|
||||
m.MailAttempts.Should().Be(1);
|
||||
m.NextMailAttemptAt.Should().BeNull();
|
||||
m.MailError.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SpamReadArchivedAndAlreadySentMessages_AreNeverAutoMailed()
|
||||
{
|
||||
Add(ContactMessageStatus.Spam, ContactMailStatus.NotApplicable);
|
||||
Add(ContactMessageStatus.Read);
|
||||
Add(ContactMessageStatus.Archived);
|
||||
Add(mail: ContactMailStatus.Sent);
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailure_IsRetriedWithTheBackoffSchedule_UntilTheMaximum_ThenNoMore()
|
||||
{
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new ContactMailResult(ContactMailOutcome.Failed, "rejected"));
|
||||
var id = Add();
|
||||
var sut = Sut();
|
||||
var expected = new[] { 5, 15, 60, 360, 1440 };
|
||||
|
||||
for (var attempt = 1; attempt <= 5; attempt++)
|
||||
{
|
||||
(await sut.SweepAsync(CancellationToken.None)).Should().Be(1);
|
||||
var m = Get(id);
|
||||
m.MailAttempts.Should().Be(attempt);
|
||||
m.MailStatus.Should().Be(ContactMailStatus.Failed);
|
||||
m.MailError.Should().Be("rejected");
|
||||
m.NextMailAttemptAt.Should().Be(_time.GetUtcNow() + TimeSpan.FromMinutes(expected[attempt - 1]));
|
||||
|
||||
// Before the backoff has passed nothing is attempted.
|
||||
(await sut.SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
_time.Advance(TimeSpan.FromMinutes(expected[attempt - 1]));
|
||||
}
|
||||
|
||||
(await sut.SweepAsync(CancellationToken.None)).Should().Be(1); // sixth and last
|
||||
var last = Get(id);
|
||||
last.MailAttempts.Should().Be(6);
|
||||
last.NextMailAttemptAt.Should().BeNull();
|
||||
|
||||
_time.Advance(TimeSpan.FromDays(30));
|
||||
(await sut.SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARecoveryAfterAFailure_EndsAsSent()
|
||||
{
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new ContactMailResult(ContactMailOutcome.Failed, "timeout"), new ContactMailResult(ContactMailOutcome.Sent));
|
||||
var id = Add();
|
||||
var sut = Sut();
|
||||
|
||||
await sut.SweepAsync(CancellationToken.None);
|
||||
_time.Advance(TimeSpan.FromMinutes(5));
|
||||
await sut.SweepAsync(CancellationToken.None);
|
||||
|
||||
var m = Get(id);
|
||||
m.MailStatus.Should().Be(ContactMailStatus.Sent);
|
||||
m.MailAttempts.Should().Be(2);
|
||||
m.MailError.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenMailCannotBeSent_NothingIsAttemptedOrCounted_AndTheReasonIsShown()
|
||||
{
|
||||
_sender.NotReadyReason().Returns("disabled");
|
||||
var id = Add();
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
|
||||
var m = Get(id);
|
||||
m.MailAttempts.Should().Be(0);
|
||||
m.MailStatus.Should().Be(ContactMailStatus.Pending);
|
||||
m.MailError.Should().Be("disabled");
|
||||
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
|
||||
|
||||
// Once mail works again the same message goes out without any lost attempts.
|
||||
_sender.NotReadyReason().Returns((string?)null);
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
|
||||
Get(id).MailAttempts.Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASkippedSend_CountsNothing()
|
||||
{
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
|
||||
var id = Add();
|
||||
|
||||
await Sut().SweepAsync(CancellationToken.None);
|
||||
|
||||
var m = Get(id);
|
||||
m.MailAttempts.Should().Be(0);
|
||||
m.MailStatus.Should().Be(ContactMailStatus.Pending);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheModuleIsDisabled_NothingIsDone()
|
||||
{
|
||||
_options.Enabled = false;
|
||||
Add();
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
|
||||
await _sender.DidNotReceive().SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOldestMessagesGoFirst_AndTheBatchIsLimited()
|
||||
{
|
||||
_options.Mail.BatchSize = 2;
|
||||
var oldest = Add(minutesAgo: 30);
|
||||
var middle = Add(minutesAgo: 20);
|
||||
var newest = Add(minutesAgo: 10);
|
||||
|
||||
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(2);
|
||||
|
||||
Get(oldest).MailStatus.Should().Be(ContactMailStatus.Sent);
|
||||
Get(middle).MailStatus.Should().Be(ContactMailStatus.Sent);
|
||||
Get(newest).MailStatus.Should().Be(ContactMailStatus.Pending);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMessageClaimedByAnotherInstance_IsSkipped()
|
||||
{
|
||||
var id = Add();
|
||||
// The other instance claims the message between our read and our claim.
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
|
||||
using var scope = _provider.CreateScope();
|
||||
var real = scope.ServiceProvider.GetRequiredService<IContactRepository>();
|
||||
var due = await real.GetDueForMailAsync("site-a", Now, 6, 20, CancellationToken.None);
|
||||
due.Should().HaveCount(1);
|
||||
|
||||
using (var other = _provider.CreateScope())
|
||||
{
|
||||
var db = other.ServiceProvider.GetRequiredService<ContactDbContext>();
|
||||
var row = db.ContactMessages.Single(m => m.Id == id);
|
||||
row.NextMailAttemptAt = Now.AddMinutes(5);
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
due[0].NextMailAttemptAt = Now.AddMinutes(5);
|
||||
var act = async () => await real.SaveChangesAsync(CancellationToken.None);
|
||||
await act.Should().ThrowAsync<DbUpdateConcurrencyException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheLogs_CarryNoPersonalData()
|
||||
{
|
||||
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>())
|
||||
.ThrowsAsync(new InvalidOperationException("cannot deliver to jan@example.nl"));
|
||||
Add();
|
||||
|
||||
await Sut().SweepAsync(CancellationToken.None);
|
||||
|
||||
_logs.Messages.Should().NotContain(m => m.Contains("jan@example.nl"));
|
||||
_logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSignal_WakesTheWait_AndTheTimeoutAlsoReturns()
|
||||
{
|
||||
var signal = new ContactMailSignal();
|
||||
|
||||
signal.Notify();
|
||||
await signal.WaitAsync(TimeSpan.FromSeconds(30), CancellationToken.None);
|
||||
|
||||
await signal.WaitAsync(TimeSpan.FromMilliseconds(50), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
@@ -54,19 +54,6 @@ public class ContactNoPersonalDataInLogsTests
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -45,47 +45,29 @@ public class ContactSubmissionServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMailSender_IsCalledAfterTheMessageIsStored_AndOnlyForGenuineMessages()
|
||||
public async Task AGenuineMessage_IsStoredPendingAndDueAtOnce_AndTheMailSenderIsSignalled_NeverCalledInline()
|
||||
{
|
||||
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>());
|
||||
var genuine = (await Messages(h)).Single(m => m.Status == ContactMessageStatus.New);
|
||||
genuine.MailStatus.Should().Be(ContactMailStatus.Pending);
|
||||
genuine.MailAttempts.Should().Be(0);
|
||||
genuine.NextMailAttemptAt.Should().Be(genuine.ReceivedAt);
|
||||
h.Signal.Received(1).Notify();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASentMail_IsRecorded_WithOneAttempt()
|
||||
public async Task ASpamMessage_IsNeverDueForMail()
|
||||
{
|
||||
using var h = new SubmissionHarness();
|
||||
h.Mail.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
|
||||
|
||||
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
|
||||
await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot"));
|
||||
|
||||
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);
|
||||
(await Messages(h)).Single().NextMailAttemptAt.Should().BeNull();
|
||||
h.Signal.DidNotReceive().Notify();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -100,7 +82,7 @@ public class ContactSubmissionServiceTests
|
||||
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>());
|
||||
h.Signal.Received(1).Notify();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -178,7 +160,7 @@ public class ContactSubmissionServiceTests
|
||||
|
||||
second.Should().Be(first);
|
||||
(await Messages(h)).Should().HaveCount(1);
|
||||
await h.Mail.Received(1).SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>());
|
||||
h.Signal.Received(1).Notify();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -247,11 +247,11 @@ public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory
|
||||
(await patch.Content.ReadAsStringAsync()).Should().Contain("\"status\":\"read\"");
|
||||
(await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"spam"}"""))).StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
|
||||
// Resend: spam is refused, a regular message answers (no mail sender yet: mailed=false).
|
||||
// Resend: spam is refused, a regular message answers (mail not configured on this host: mailed=false, reason shown).
|
||||
(await admin.PostAsync($"{Messages}/{spam}/resend", null)).StatusCode.Should().Be(HttpStatusCode.Conflict);
|
||||
var resend = await admin.PostAsync($"{Messages}/{second}/resend", null);
|
||||
resend.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false}""");
|
||||
(await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false,"mailError":"disabled"}""");
|
||||
|
||||
// Not spam after all: now in the default list.
|
||||
(await admin.PatchAsync($"{Messages}/{spam}", Jwt.Json("""{"status":"archived"}"""))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>An IEmailSender that records every mail and can be told to fail.</summary>
|
||||
public sealed class CapturingEmailSender : IEmailSender
|
||||
{
|
||||
public ConcurrentQueue<OutgoingMail> Sent { get; } = new();
|
||||
public volatile string? FailWith;
|
||||
|
||||
public Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (FailWith is { } code)
|
||||
{
|
||||
return Task.FromResult(MailSendResult.Fail(code));
|
||||
}
|
||||
|
||||
Sent.Enqueue(mail);
|
||||
return Task.FromResult(MailSendResult.Ok);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The real host with the contact form open, mail "on" and a capturing sender instead of SMTP.</summary>
|
||||
public sealed class MailContactHostFactory() : ContactHostFactory(new()
|
||||
{
|
||||
["Contact:Enabled"] = "true",
|
||||
["Contact:SiteId"] = "pipeline-site",
|
||||
["Contact:MinSeconds"] = "0",
|
||||
["Contact:RecipientEmail"] = "owner@example.org",
|
||||
["Contact:Mail:SweepSeconds"] = "5",
|
||||
["RateLimiting:ContactForm:PermitLimit"] = "1000",
|
||||
["RateLimiting:ContactToken:PermitLimit"] = "1000",
|
||||
})
|
||||
{
|
||||
public CapturingEmailSender Mailer { get; } = new();
|
||||
public IMailAvailability Availability { get; } = Substitute.For<IMailAvailability>();
|
||||
|
||||
protected override bool OpenCmsSwitch => true;
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
Availability.IsEnabled.Returns(true);
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.AddSingleton<IEmailSender>(Mailer);
|
||||
services.AddSingleton(Availability);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactMailPipelineTests(MailContactHostFactory factory) : IClassFixture<MailContactHostFactory>
|
||||
{
|
||||
private async Task<Guid> SubmitAsync(string name)
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
var token = await Http.GetTokenAsync(client);
|
||||
(await Http.PostAsync(client, Http.Body(token, name: name))).StatusCode.Should().Be(HttpStatusCode.Accepted);
|
||||
return (await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == name))).Id;
|
||||
}
|
||||
|
||||
private async Task<ContactMessage> WaitForAsync(Guid id, Func<ContactMessage, bool> done)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(30);
|
||||
ContactMessage row;
|
||||
do
|
||||
{
|
||||
row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Id == id));
|
||||
if (done(row))
|
||||
{
|
||||
return row;
|
||||
}
|
||||
|
||||
await Task.Delay(200);
|
||||
}
|
||||
while (DateTime.UtcNow < deadline);
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASubmission_IsMailedInTheBackground_WithinSeconds_AndRecordedAsSent()
|
||||
{
|
||||
var id = await SubmitAsync("Mail Genuine");
|
||||
|
||||
var row = await WaitForAsync(id, m => m.MailStatus == ContactMailStatus.Sent);
|
||||
|
||||
row.MailStatus.Should().Be(ContactMailStatus.Sent, "error={0} next={1} attempts={2}", row.MailError, row.NextMailAttemptAt, row.MailAttempts);
|
||||
row.MailAttempts.Should().Be(1);
|
||||
var mail = factory.Mailer.Sent.Single(m => m.HtmlBody.Contains("Mail Genuine"));
|
||||
mail.ToAddress.Should().Be("owner@example.org");
|
||||
mail.ReplyToAddress.Should().Be("jan@example.nl");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASpamSubmission_IsNeverMailed()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
var token = await Http.GetTokenAsync(client);
|
||||
await Http.PostAsync(client, Http.Body(token, name: "Mail Spam", hp: "http://spam"));
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(2));
|
||||
|
||||
factory.Mailer.Sent.Should().NotContain(m => m.HtmlBody.Contains("Mail Spam"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AResend_OfAFailedMessage_Works_AndIgnoresTheBackoff()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
await factory.WithDb(async db =>
|
||||
{
|
||||
db.ContactMessages.Add(new ContactMessage
|
||||
{
|
||||
Id = id, SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow, Name = "Mail Resend",
|
||||
Email = "x@example.nl", Subject = "s", Message = "m", Status = ContactMessageStatus.Read,
|
||||
MailStatus = ContactMailStatus.Failed, MailAttempts = 6, MailError = "rejected",
|
||||
RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
var admin = await Jwt.ClientWithRoleAsync(factory, "Administrator");
|
||||
|
||||
var response = await admin.PostAsync($"/api/v1/contact-messages/{id}/resend", null);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await response.Content.ReadAsStringAsync()).Should().Contain("\"mailed\":true");
|
||||
var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Id == id));
|
||||
row.MailStatus.Should().Be(ContactMailStatus.Sent, "error={0} next={1} attempts={2}", row.MailError, row.NextMailAttemptAt, row.MailAttempts);
|
||||
row.MailError.Should().BeNull();
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public sealed class SubmissionHarness : IDisposable
|
||||
public IContactRepository Repository { get; }
|
||||
public IContactTokenService Tokens { get; }
|
||||
public ICaptchaVerifier Captcha { get; } = Substitute.For<ICaptchaVerifier>();
|
||||
public IContactMailSender Mail { get; } = Substitute.For<IContactMailSender>();
|
||||
public IContactMailSignal Signal { get; } = Substitute.For<IContactMailSignal>();
|
||||
public CapturingLoggerProvider Logs { get; } = new();
|
||||
public ContactSubmissionService Sut { get; }
|
||||
|
||||
@@ -71,12 +71,10 @@ public sealed class SubmissionHarness : IDisposable
|
||||
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>());
|
||||
Repository, Tokens, Captcha, Signal, wrapped, Time, loggerFactory.CreateLogger<ContactSubmissionService>());
|
||||
}
|
||||
|
||||
/// <summary>A token that is old enough to pass the minimum-time check.</summary>
|
||||
|
||||
Reference in New Issue
Block a user