Contact: ontvangstadres uit de site-instellingen (instelling > env), PUT /contact-settings/recipient en Berichten-veld (CMS-U11)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:54:03 +01:00
co-authored by Claude Sonnet 5.5
parent 9ff5c8bd94
commit 62f4d4dfe0
29 changed files with 1165 additions and 24 deletions
@@ -248,6 +248,7 @@ public class ContactAdminControllerTests
"POST contact-messages/{id:guid}/resend",
"GET contact-settings",
"PUT contact-settings",
"PUT contact-settings/recipient",
]);
}
@@ -45,6 +45,14 @@ public class ContactMailSenderTests
public CapturingLoggerProvider Logs { get; } = new();
public OutgoingMail? Sent;
private readonly ContactDbContext _db = new(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
/// <summary>The real settings service on an in-memory database: the administrator's setting and the environment.</summary>
public IContactSettingsService ContactSettings => new ContactSettingsService(
new ContactRepository(_db), new ContactSettingsCache(TimeProvider.System), Options.Create(Contact),
TimeProvider.System, Substitute.For<IContactMailSignal>());
public Rig()
{
Availability.IsEnabled.Returns(true);
@@ -62,7 +70,7 @@ public class ContactMailSenderTests
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,
Email, new MailTemplateRenderer(), languages, settings, ContactSettings, Availability,
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger<ContactMailSender>());
}
@@ -179,7 +187,7 @@ public class ContactMailSenderTests
var result = await sut.SendAsync(Message(), CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "disabled"));
sut.NotReadyReason().Should().Be("disabled");
(await sut.NotReadyReasonAsync(CancellationToken.None)).Should().Be("disabled");
await rig.Email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
}
@@ -212,7 +220,7 @@ public class ContactMailServiceTests : IDisposable
public ContactMailServiceTests()
{
_sender.NotReadyReason().Returns((string?)null);
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
_sender.SendAsync(Arg.Any<ContactMessage>(), Arg.Any<CancellationToken>()).Returns(ContactMailOutcome.Sent);
var services = new ServiceCollection();
@@ -330,7 +338,7 @@ public class ContactMailServiceTests : IDisposable
[Fact]
public async Task WhenMailCannotBeSent_NothingIsAttemptedOrCounted_AndTheReasonIsShown()
{
_sender.NotReadyReason().Returns("disabled");
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns("disabled");
var id = Add();
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(0);
@@ -342,7 +350,7 @@ public class ContactMailServiceTests : IDisposable
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);
_sender.NotReadyReasonAsync(Arg.Any<CancellationToken>()).Returns((string?)null);
(await Sut().SweepAsync(CancellationToken.None)).Should().Be(1);
Get(id).MailAttempts.Should().Be(1);
}
@@ -0,0 +1,241 @@
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Time.Testing;
using NSubstitute;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.SiteSettings;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Contact.Data;
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>The recipient of contact mails: the administrator's setting wins over the environment, which stays the default.</summary>
public class ContactRecipientTests : IDisposable
{
private const string FromEnvironment = "env-inbox@example.org";
private const string FromSetting = "setting-inbox@example.org";
private readonly ContactOptions _options = new() { Enabled = true, RecipientEmail = FromEnvironment };
private readonly ContactDbContext _db = new(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
private readonly IContactMailSignal _signal = Substitute.For<IContactMailSignal>();
private readonly FakeTimeProvider _time = new(new DateTimeOffset(2026, 11, 10, 12, 0, 0, TimeSpan.Zero));
public void Dispose() => _db.Dispose();
private ContactSettingsService Settings() => new(
new ContactRepository(_db), new ContactSettingsCache(_time), Options.Create(_options), _time, _signal);
[Fact]
public async Task WithoutASetting_TheEnvironmentIsTheDefault()
{
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
}
[Fact]
public async Task AFilledSetting_Wins_AndTheEnvironmentIsTheFallbackAgainAfterClearing()
{
var sut = Settings();
await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
(await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromSetting, "setting"));
await sut.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None);
(await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
await sut.SetRecipientAsync(" ", Guid.NewGuid(), CancellationToken.None);
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Source.Should().Be("config");
}
[Fact]
public async Task WithNeitherOfThem_ThereIsNoRecipient()
{
_options.RecipientEmail = null;
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be(((string?)null, "none"));
}
[Fact]
public async Task AnInvalidStoredAddress_IsIgnored_NotUsed()
{
_db.ContactSettings.Add(new ContactSettings { Enabled = true, RecipientEmail = "not an address\r\nBcc: x@y.z", UpdatedAt = _time.GetUtcNow() });
await _db.SaveChangesAsync();
(await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config"));
}
[Fact]
public async Task TheAdminView_ShowsTheSettingAndTheSource_ButNeverTheEnvironmentAddress()
{
var sut = Settings();
var onlyEnvironment = await sut.GetAsync(CancellationToken.None);
onlyEnvironment.RecipientEmail.Should().BeNull();
onlyEnvironment.RecipientSource.Should().Be("config");
var withSetting = await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
withSetting.RecipientEmail.Should().Be(FromSetting);
withSetting.RecipientSource.Should().Be("setting");
System.Text.Json.JsonSerializer.Serialize(onlyEnvironment).Should().NotContain(FromEnvironment);
_options.RecipientEmail = null;
(await Settings().SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None)).RecipientSource.Should().Be("none");
}
[Fact]
public async Task SettingTheAddress_KeepsTheSwitch_RemembersWho_AndWakesTheMailSender()
{
var sut = Settings();
var user = Guid.NewGuid();
await sut.SetEnabledAsync(true, user, CancellationToken.None);
var saved = await sut.SetRecipientAsync(FromSetting, user, CancellationToken.None);
saved.Enabled.Should().BeTrue("setting the address does not touch the switch");
(await _db.ContactSettings.SingleAsync()).UpdatedByUserId.Should().Be(user);
_signal.Received(1).Notify();
}
[Fact]
public async Task SettingTheAddressFirst_CreatesTheRowWithTheSwitchOff()
{
var saved = await Settings().SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
saved.Enabled.Should().BeFalse();
saved.RecipientEmail.Should().Be(FromSetting);
}
[Fact]
public async Task TheMailSender_UsesTheSettingAtOnce_WithoutRestart_AndFallsBackToTheEnvironment()
{
var email = Substitute.For<IEmailSender>();
OutgoingMail? sent = null;
email.SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>()).Returns(call =>
{
sent = call.Arg<OutgoingMail>();
return MailSendResult.Ok;
});
var availability = Substitute.For<IMailAvailability>();
availability.IsEnabled.Returns(true);
var languages = Substitute.For<ILanguageResolver>();
languages.Resolve(Arg.Any<string?>()).Returns("nl");
var siteSettings = Substitute.For<ISiteSettingsService>();
siteSettings.GetEffectiveSenderAsync(Arg.Any<CancellationToken>()).Returns(("noreply@example.org", "De Site"));
var settings = Settings();
var sender = new ContactMailSender(
email, new MailTemplateRenderer(), languages, siteSettings, settings, availability,
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }),
Options.Create(_options), LoggerFactory.Create(_ => { }).CreateLogger<ContactMailSender>());
var message = new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "Jan", Email = "jan@example.nl", Subject = "Website", Message = "Hallo" };
await sender.SendAsync(message, CancellationToken.None);
sent!.ToAddress.Should().Be(FromEnvironment);
await settings.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None);
await sender.SendAsync(message, CancellationToken.None);
sent.ToAddress.Should().Be(FromSetting);
await settings.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None);
await sender.SendAsync(message, CancellationToken.None);
sent.ToAddress.Should().Be(FromEnvironment);
}
[Fact]
public async Task WithoutAnyAddress_TheSenderIsNotReady_WithAClearReason_AndNothingIsSent()
{
_options.RecipientEmail = null;
var email = Substitute.For<IEmailSender>();
var availability = Substitute.For<IMailAvailability>();
availability.IsEnabled.Returns(true);
var sender = new ContactMailSender(
email, new MailTemplateRenderer(), Substitute.For<ILanguageResolver>(), Substitute.For<ISiteSettingsService>(), Settings(), availability,
Options.Create(new EmailOptions()), Options.Create(new AppMailOptions()), Options.Create(_options),
LoggerFactory.Create(_ => { }).CreateLogger<ContactMailSender>());
(await sender.NotReadyReasonAsync(CancellationToken.None)).Should().Be("recipient_not_configured");
var result = await sender.SendAsync(new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "J", Email = "j@example.nl", Subject = "S", Message = "M" }, CancellationToken.None);
result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "recipient_not_configured"));
await email.DidNotReceive().SendAsync(Arg.Any<OutgoingMail>(), Arg.Any<CancellationToken>());
}
}
public class ContactRecipientControllerTests
{
private readonly IContactSettingsService _settings = Substitute.For<IContactSettingsService>();
private readonly ContactSettingsController _sut;
public ContactRecipientControllerTests()
{
_sut = new ContactSettingsController(_settings, Options.Create(new ContactOptions()))
{
ControllerContext = new ControllerContext { HttpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext() },
};
_settings.SetRecipientAsync(Arg.Any<string?>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(call => new ContactSettingsDto(false, true, call.Arg<string?>(), call.Arg<string?>() is null ? "config" : "setting"));
}
[Theory]
[InlineData("jan@example.nl")]
[InlineData(" jan@example.nl ")]
public async Task AValidAddress_IsSavedTrimmed(string address)
{
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
result.Should().BeOfType<OkObjectResult>();
await _settings.Received(1).SetRecipientAsync("jan@example.nl", Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task NullOrBlank_ClearsTheSetting(string? address)
{
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
result.Should().BeOfType<OkObjectResult>();
await _settings.Received(1).SetRecipientAsync(null, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Theory]
[InlineData("not-an-address")]
[InlineData("a@b")]
[InlineData("jan@example.nl\r\nBcc: evil@example.com")]
[InlineData("jan@example.nl, other@example.nl")]
[InlineData("<script>@example.nl")]
public async Task AnInvalidAddress_IsA400_NamingTheField_AndNothingIsSaved(string address)
{
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None);
var problem = result.Should().BeOfType<ObjectResult>().Subject;
problem.StatusCode.Should().Be(400);
problem.Value.Should().BeOfType<ValidationProblemDetails>().Which.Errors.Should().ContainKey("recipientEmail");
await _settings.DidNotReceiveWithAnyArgs().SetRecipientAsync(default, default, default);
}
[Fact]
public async Task ATooLongAddress_IsReportedAsTooLong()
{
var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(new string('a', 250) + "@example.nl"), CancellationToken.None);
result.Should().BeOfType<ObjectResult>().Which.Value.Should().BeOfType<ValidationProblemDetails>()
.Which.Errors["recipientEmail"].Should().Equal("tooLong");
}
[Fact]
public async Task AMissingBody_IsA400()
{
var result = await _sut.PutRecipient(null, CancellationToken.None);
result.Should().BeOfType<ObjectResult>().Which.StatusCode.Should().Be(400);
}
}
@@ -20,13 +20,14 @@ public class ContactSettingsServiceTests
public ContactDbContext Db { get; } = new(new DbContextOptionsBuilder<ContactDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
public ContactSettingsCache Cache { get; }
public IContactMailSignal Signal { get; } = Substitute.For<IContactMailSignal>();
public ContactSettingsService Sut { get; }
public Setup()
{
Cache = new ContactSettingsCache(Time);
Sut = new ContactSettingsService(
new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time);
new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time, Signal);
}
public void Dispose() => Db.Dispose();
@@ -148,7 +148,7 @@ public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings);
response.StatusCode.Should().Be(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}""");
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true,"recipientEmail":null,"recipientSource":"none"}""");
}
[Theory]
@@ -182,7 +182,7 @@ public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory
var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
on.StatusCode.Should().Be(HttpStatusCode.OK);
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}""");
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true,"recipientEmail":null,"recipientSource":"none"}""");
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK);
var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
@@ -0,0 +1,163 @@
using System.Net;
using System.Text.Json;
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>Contact open, an address only in the environment, no mail sender needed (the management routes only).</summary>
public sealed class RecipientEnvContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["Contact:RecipientEmail"] = "env-pipeline@example.org",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>The real host with a capturing mail sender and NO address in the environment.</summary>
public sealed class MailNoRecipientHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["Contact:Mail:SweepSeconds"] = "5",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
})
{
public CapturingEmailSender Mailer { get; } = new();
protected override bool OpenCmsSwitch => true;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
var availability = Substitute.For<IMailAvailability>();
availability.IsEnabled.Returns(true);
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IEmailSender>(Mailer);
services.AddSingleton(availability);
});
}
}
public class ContactRecipientPipelineTests(RecipientEnvContactHostFactory factory) : IClassFixture<RecipientEnvContactHostFactory>
{
private const string Settings = "/api/v1/contact-settings";
[Fact]
public async Task TheRecipientRoute_RequiresLogin_AndTheAdminRole()
{
(await factory.CreateClient().PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"x@example.org"}""")))
.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
var user = await Jwt.ClientWithRoleAsync(factory, "User");
(await user.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"x@example.org"}""")))
.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}
[Fact]
public async Task TheAdminView_NeverShowsTheEnvironmentAddress_OnlyWhereItComesFrom()
{
var admin = await Jwt.ClientWithRoleAsync(factory, "Administrator");
var text = await admin.GetStringAsync(Settings);
text.Should().NotContain("env-pipeline@example.org");
using var json = JsonDocument.Parse(text);
json.RootElement.GetProperty("recipientSource").GetString().Should().Be("config");
json.RootElement.GetProperty("recipientEmail").ValueKind.Should().Be(JsonValueKind.Null);
}
[Fact]
public async Task SetInvalidAndClear_WorkEndToEnd()
{
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
var invalid = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"not-an-address"}"""));
invalid.StatusCode.Should().Be(HttpStatusCode.BadRequest);
invalid.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
(await invalid.Content.ReadAsStringAsync()).Should().Contain("recipientEmail").And.NotContain("not-an-address");
var set = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":" inbox@example.org "}"""));
set.StatusCode.Should().Be(HttpStatusCode.OK);
using (var json = JsonDocument.Parse(await set.Content.ReadAsStringAsync()))
{
json.RootElement.GetProperty("recipientEmail").GetString().Should().Be("inbox@example.org");
json.RootElement.GetProperty("recipientSource").GetString().Should().Be("setting");
}
var stored = await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync());
stored.RecipientEmail.Should().Be("inbox@example.org");
var cleared = await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":null}"""));
using var after = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync());
after.RootElement.GetProperty("recipientSource").GetString().Should().Be("config");
after.RootElement.GetProperty("recipientEmail").ValueKind.Should().Be(JsonValueKind.Null);
}
[Fact]
public async Task TheAddress_IsNeverInThePublicTokenResponse()
{
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
await admin.PutAsync($"{Settings}/recipient", Jwt.Json("""{"recipientEmail":"public-leak-check@example.org"}"""));
var text = await factory.CreateClient().GetStringAsync($"{Http.Route}/token");
text.Should().NotContain("public-leak-check").And.NotContain("env-pipeline");
}
}
public class ContactRecipientMailPipelineTests(MailNoRecipientHostFactory factory) : IClassFixture<MailNoRecipientHostFactory>
{
[Fact]
public async Task WithoutAnyAddress_TheMessageIsStoredAndStaysPending_ThenGoesOutOnceAnAddressIsSet()
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
(await Http.PostAsync(client, Http.Body(token, name: "Recipient Later"))).StatusCode.Should().Be(HttpStatusCode.Accepted);
// No address anywhere: not attempted, not counted, the reason is on the message.
ContactMessage row = null!;
var deadline = DateTime.UtcNow.AddSeconds(30);
do
{
row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Recipient Later"));
if (row.MailError == "recipient_not_configured") break;
await Task.Delay(200);
}
while (DateTime.UtcNow < deadline);
row.MailError.Should().Be("recipient_not_configured");
row.MailStatus.Should().Be(ContactMailStatus.Pending);
row.MailAttempts.Should().Be(0);
factory.Mailer.Sent.Should().BeEmpty();
// The administrator fills in the address: the waiting message is sent to it without a restart.
var admin = await Jwt.ClientWithRoleAsync(factory, "Owner");
(await admin.PutAsync("/api/v1/contact-settings/recipient", Jwt.Json("""{"recipientEmail":"later@example.org"}""")))
.StatusCode.Should().Be(HttpStatusCode.OK);
deadline = DateTime.UtcNow.AddSeconds(30);
do
{
row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Recipient Later"));
if (row.MailStatus == ContactMailStatus.Sent) break;
await Task.Delay(200);
}
while (DateTime.UtcNow < deadline);
row.MailStatus.Should().Be(ContactMailStatus.Sent);
row.MailError.Should().BeNull();
factory.Mailer.Sent.Single().ToAddress.Should().Be("later@example.org");
}
}