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");
}
}
@@ -156,6 +156,35 @@ public class ContactSettingsController(IContactSettingsService service, IOptions
return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken));
}
[HttpPut("recipient")]
[Consumes("application/json")]
[ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
public async Task<IActionResult> PutRecipient([FromBody] UpdateContactRecipientRequest? request, CancellationToken cancellationToken)
{
if (!ModelState.IsValid || request is null)
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
}
// null or blank clears the setting (back to the server configuration); anything else must be a plain address.
var address = string.IsNullOrWhiteSpace(request.RecipientEmail) ? null : request.RecipientEmail.Trim();
if (!string.IsNullOrEmpty(address))
{
if (address.Length > 254)
{
return ContactProblems.Validation(new Dictionary<string, string[]> { ["recipientEmail"] = ["tooLong"] }, options.Value.ProblemTypeBase);
}
if (!SlpModularCms.Core.Email.EmailAddressRules.IsValidAddress(address))
{
return ContactProblems.Invalid(options.Value.ProblemTypeBase, "recipientEmail");
}
}
return Ok(await service.SetRecipientAsync(address, CallerId(), cancellationToken));
}
private Guid CallerId()
{
var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
@@ -42,6 +42,7 @@ public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbCo
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Enabled).IsRequired();
entity.Property(e => e.RecipientEmail).HasMaxLength(254);
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.UpdatedByUserId).IsRequired();
});
@@ -68,6 +68,10 @@ public class ContactSettings
public int Id { get; set; } = SingletonId;
public bool Enabled { get; set; }
/// <summary>The address contact mails are sent to, chosen by an administrator. Null = use Contact:RecipientEmail from the environment.</summary>
public string? RecipientEmail { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public Guid UpdatedByUserId { get; set; }
}
@@ -0,0 +1,139 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
[Migration("20261110224342_ContactSettingsRecipient")]
partial class ContactSettingsRecipient
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<int>("MailAttempts")
.HasColumnType("int");
b.Property<string>("MailError")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("MailStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset?>("NextMailAttemptAt")
.IsConcurrencyToken()
.HasColumnType("datetime");
b.Property<DateTimeOffset>("ReceivedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("RetentionUntil")
.HasColumnType("datetime");
b.Property<string>("SiteId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("RetentionUntil");
b.HasIndex("SiteId", "Status", "ReceivedAt");
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<string>("RecipientEmail")
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<Guid>("UpdatedByUserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.ToTable("ContactSettings", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<Guid>("Key")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.HasKey("SiteId", "Key");
b.HasIndex("CreatedAt");
b.ToTable("ContactIdempotency", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
/// <inheritdoc />
public partial class ContactSettingsRecipient : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "RecipientEmail",
table: "ContactSettings",
type: "varchar(254)",
maxLength: 254,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RecipientEmail",
table: "ContactSettings");
}
}
}
@@ -94,6 +94,10 @@ namespace SlpModularCms.Modules.Contact.Migrations
b.Property<bool>("Enabled")
.HasColumnType("tinyint(1)");
b.Property<string>("RecipientEmail")
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
@@ -47,7 +47,22 @@ public record UpdateContactMessageStatusRequest(string? Status);
public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed, string? MailError = null);
[ExcludeFromCodeCoverage]
public record ContactSettingsDto(bool Enabled, bool HostEnabled);
public record ContactSettingsDto(
bool Enabled,
bool HostEnabled,
string? RecipientEmail = null,
string RecipientSource = ContactRecipientSource.None);
/// <summary>Where the address contact mails go to comes from. The address from the environment is never returned.</summary>
public static class ContactRecipientSource
{
public const string Setting = "setting";
public const string Config = "config";
public const string None = "none";
}
/// <summary>Body of PUT /contact-settings/recipient. null or empty clears the setting (back to the server configuration).</summary>
public record UpdateContactRecipientRequest(string? RecipientEmail);
/// <summary>Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled.</summary>
public record UpdateContactSettingsRequest(bool? Enabled);
@@ -18,25 +18,27 @@ public sealed class ContactMailSender(
IMailTemplateRenderer renderer,
ILanguageResolver languages,
ISiteSettingsService siteSettings,
IContactSettingsService contactSettings,
IMailAvailability availability,
IOptions<EmailOptions> email,
IOptions<AppMailOptions> app,
IOptions<ContactOptions> contact,
ILogger<ContactMailSender> logger) : IContactMailSender
{
public string? NotReadyReason()
public async Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken)
{
if (!availability.IsEnabled)
{
return ContactMailResult.Disabled;
}
return EmailAddressRules.IsValidAddress(contact.Value.RecipientEmail) ? null : ContactMailResult.RecipientNotConfigured;
var (address, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
return address is null ? ContactMailResult.RecipientNotConfigured : null;
}
public async Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken)
{
var notReady = NotReadyReason();
var notReady = await NotReadyReasonAsync(cancellationToken);
if (notReady is not null)
{
return new ContactMailResult(ContactMailOutcome.Skipped, notReady);
@@ -44,6 +46,8 @@ public sealed class ContactMailSender(
try
{
// Read per send: the administrator's setting wins over the environment and changes without a restart.
var (recipient, _) = await contactSettings.GetEffectiveRecipientAsync(cancellationToken);
var (fromAddress, fromName) = await siteSettings.GetEffectiveSenderAsync(cancellationToken);
var baseUrl = app.Value.PublicBaseUrl.TrimEnd('/');
var language = languages.Resolve(null);
@@ -65,7 +69,7 @@ public sealed class ContactMailSender(
var rendered = renderer.Render(MailKind.ContactMessage, language, model);
var result = await sender.SendAsync(
new OutgoingMail(
contact.Value.RecipientEmail!.Trim(), rendered.Subject, rendered.Html, rendered.Text,
recipient!, rendered.Subject, rendered.Html, rendered.Text,
fromAddress, fromName,
ReplyToAddress: message.Email,
ReplyToName: EmailAddressRules.IsValidDisplayName(message.Name) ? message.Name : null),
@@ -66,7 +66,7 @@ public class ContactMailService(
}
// Mail cannot be sent at all: say why on the messages, count nothing, retry nothing in a loop.
var notReady = sender.NotReadyReason();
var notReady = await sender.NotReadyReasonAsync(cancellationToken);
if (!string.IsNullOrEmpty(notReady))
{
foreach (var message in due.Where(m => m.MailError != notReady))
@@ -47,7 +47,7 @@ public readonly record struct ContactMailResult(ContactMailOutcome Outcome, stri
public interface IContactMailSender
{
/// <summary>Null (or empty) when mail can be sent now, otherwise the short reason code.</summary>
string? NotReadyReason();
Task<string?> NotReadyReasonAsync(CancellationToken cancellationToken);
Task<ContactMailResult> SendAsync(ContactMessage message, CancellationToken cancellationToken);
}
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
@@ -53,13 +54,23 @@ public interface IContactSettingsService
Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken);
Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken);
/// <summary>
/// The address contact mails go to: the administrator's setting if filled in and valid, otherwise
/// Contact:RecipientEmail from the configuration, otherwise none. Read from the database on every call.
/// </summary>
Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken);
/// <summary>null or empty clears the setting. The caller has validated the address.</summary>
Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken);
}
public sealed class ContactSettingsService(
IContactRepository repository,
ContactSettingsCache cache,
IOptions<ContactOptions> options,
TimeProvider time) : IContactSettingsService
TimeProvider time,
IContactMailSignal mailSignal) : IContactSettingsService
{
public async Task<bool> IsEnabledAsync(CancellationToken cancellationToken)
{
@@ -76,8 +87,56 @@ public sealed class ContactSettingsService(
public async Task<ContactSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// The administrator's own view is never served from the cache.
var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false;
return new ContactSettingsDto(enabled, options.Value.Enabled);
var settings = await repository.GetSettingsAsync(cancellationToken);
return ToDto(settings);
}
public async Task<(string? Address, string Source)> GetEffectiveRecipientAsync(CancellationToken cancellationToken)
{
var settings = await repository.GetSettingsAsync(cancellationToken);
return Resolve(settings);
}
private (string? Address, string Source) Resolve(ContactSettings? settings)
{
var fromSetting = settings?.RecipientEmail?.Trim();
if (EmailAddressRules.IsValidAddress(fromSetting))
{
return (fromSetting, ContactRecipientSource.Setting);
}
var fromConfig = options.Value.RecipientEmail?.Trim();
return EmailAddressRules.IsValidAddress(fromConfig)
? (fromConfig, ContactRecipientSource.Config)
: (null, ContactRecipientSource.None);
}
// The administrator sees their own setting, and only where the address comes from (never the environment's address).
private ContactSettingsDto ToDto(ContactSettings? settings)
{
var (_, source) = Resolve(settings);
return new ContactSettingsDto(
settings?.Enabled ?? false, options.Value.Enabled,
string.IsNullOrWhiteSpace(settings?.RecipientEmail) ? null : settings.RecipientEmail, source);
}
public async Task<ContactSettingsDto> SetRecipientAsync(string? recipientEmail, Guid userId, CancellationToken cancellationToken)
{
var settings = await repository.GetSettingsAsync(cancellationToken);
if (settings is null)
{
settings = new ContactSettings();
repository.Add(settings);
}
settings.RecipientEmail = string.IsNullOrWhiteSpace(recipientEmail) ? null : recipientEmail.Trim();
settings.UpdatedAt = time.GetUtcNow();
settings.UpdatedByUserId = userId;
await repository.SaveChangesAsync(cancellationToken);
// Messages that waited for an address go out at once.
mailSignal.Notify();
return ToDto(settings);
}
public async Task<ContactSettingsDto> SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken)
@@ -95,7 +154,7 @@ public sealed class ContactSettingsService(
await repository.SaveChangesAsync(cancellationToken);
cache.Invalidate();
return new ContactSettingsDto(enabled, options.Value.Enabled);
return ToDto(settings);
}
}