Halve of foute mailconfiguratie: host start, mail uit, een duidelijke Error-logregel

Eén bron (IMailAvailability) bepaalt of mail aan staat: SMTP-host gezet EN de hele mailconfiguratie geldig.
Anders start de host gewoon, gebruikt de Null-verzender, meldt emailEnabled=false en logt eenmalig
mail_configuration_invalid met de namen van de ontbrekende of ongeldige instellingen (nooit waarden of
geheimen). Getest: halve config, elke soort fout, geen geheim in het log, volledige config werkt als
voorheen, geen mailinstelling geeft geen enkele waarschuwing, alle verbruikers zien mail als uit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 20:51:41 +01:00
co-authored by Claude Sonnet 5.5
parent 142815a3ab
commit bd9790819d
12 changed files with 308 additions and 40 deletions
@@ -39,6 +39,7 @@ public class IdentityMailServiceTests
Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" }),
Options.Create(new InvitationSettings { ExpiryHours = hours }),
Options.Create(new SlpModularCms.Core.Identity.Services.PasswordResetSettings()),
new FixedAvailability(!string.IsNullOrWhiteSpace(smtpHost)),
NullLogger<IdentityMailService>.Instance);
[Fact]
@@ -0,0 +1,181 @@
using System.Collections.Concurrent;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Tests.Email;
internal sealed class FixedAvailability(bool enabled) : IMailAvailability
{
public bool IsEnabled { get; } = enabled;
public IReadOnlyList<string> Problems { get; } = [];
}
internal sealed class LogCapture : ILoggerProvider
{
public ConcurrentQueue<(LogLevel Level, string Message)> Entries { get; } = new();
public ILogger CreateLogger(string categoryName) => new CaptureLogger(Entries);
public void Dispose() { }
private sealed class CaptureLogger(ConcurrentQueue<(LogLevel, string)> entries) : 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) =>
entries.Enqueue((logLevel, formatter(state, exception)));
}
}
/// <summary>
/// A half-finished or wrong mail configuration must not stop the host from starting (mail is secondary to the
/// site being up): the host starts with mail OFF and one clear Error line naming each setting, never a value.
/// </summary>
public class MailSoftFailureTests
{
private const string Secret = "pw-very-secret-123";
private const string User = "user-very-secret-456";
private static Dictionary<string, string?> Full() => new()
{
["Email:Smtp:Host"] = "mail.example.nl",
["Email:Smtp:Username"] = User,
["Email:Smtp:Password"] = Secret,
["Email:FromAddress"] = "no-reply@example.nl",
["Email:FromName"] = "Example",
["App:PublicBaseUrl"] = "https://example.nl"
};
private static async Task<(IHost Host, LogCapture Logs)> StartAsync(Dictionary<string, string?> values)
{
var logs = new LogCapture();
var host = new HostBuilder()
.ConfigureLogging(l => l.AddProvider(logs))
.ConfigureServices(s =>
{
s.AddCmsEmail(new ConfigurationBuilder().AddInMemoryCollection(values).Build());
s.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(Guid.NewGuid().ToString()));
})
.Build();
await host.StartAsync(); // must not throw, whatever the mail configuration looks like
return (host, logs);
}
[Fact]
public async Task AHalfConfiguration_StartsTheHost_WithMailOff_AndOneErrorNamingTheMissingSetting()
{
var values = Full();
values.Remove("App:PublicBaseUrl"); // the incident: host and credentials set, base URL missing
var (host, logs) = await StartAsync(values);
using var _ = host;
var availability = host.Services.GetRequiredService<IMailAvailability>();
availability.IsEnabled.Should().BeFalse();
availability.Problems.Should().ContainSingle().Which.Should().Contain("App:PublicBaseUrl");
host.Services.GetRequiredService<IEmailSender>().Should().BeOfType<NullEmailSender>();
var errors = logs.Entries.Where(e => e.Level == LogLevel.Error).ToList();
errors.Should().ContainSingle();
errors[0].Message.Should().Contain("mail_configuration_invalid").And.Contain("App:PublicBaseUrl").And.Contain("OFF");
}
[Fact]
public async Task TheErrorLine_NeverContainsASecretOrAValue()
{
var values = Full();
values["Email:FromAddress"] = "not-an-address-xyz";
values["Email:Smtp:Port"] = "0";
values["App:PublicBaseUrl"] = "http://insecure.example.nl/with/path";
values["Email:BrandColor"] = "red-ish-color";
var (host, logs) = await StartAsync(values);
using var _ = host;
var all = string.Join("\n", logs.Entries.Select(e => e.Message));
all.Should().Contain("Email:FromAddress").And.Contain("Email:Smtp:Port").And.Contain("App:PublicBaseUrl").And.Contain("Email:BrandColor");
all.Should().NotContain(Secret).And.NotContain(User)
.And.NotContain("mail.example.nl").And.NotContain("insecure.example.nl")
.And.NotContain("not-an-address-xyz").And.NotContain("red-ish-color");
}
[Theory]
[InlineData("Email:FromAddress", "nope", "Email:FromAddress")]
[InlineData("Email:FromName", "", "Email:FromName")]
[InlineData("Email:Smtp:Port", "70000", "Email:Smtp:Port")]
[InlineData("Email:Smtp:TimeoutSeconds", "0", "Email:Smtp:TimeoutSeconds")]
[InlineData("Email:Smtp:Password", "", "Email:Smtp:Password")]
[InlineData("Email:LogoUrl", "javascript:x", "Email:LogoUrl")]
[InlineData("App:PublicBaseUrl", "", "App:PublicBaseUrl")]
[InlineData("App:PublicBaseUrl", "http://example.nl", "App:PublicBaseUrl")]
[InlineData("App:DefaultLanguage", "xx", "App:DefaultLanguage")]
public async Task EveryKindOfProblem_SwitchesMailOff_AndNamesItsSetting(string key, string value, string expectedName)
{
var values = Full();
values[key] = value;
var (host, logs) = await StartAsync(values);
using var _ = host;
host.Services.GetRequiredService<IMailAvailability>().IsEnabled.Should().BeFalse();
logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error && e.Message.Contains(expectedName));
}
[Fact]
public async Task AFullConfiguration_WorksAsBefore_MailOn_NoError()
{
var (host, logs) = await StartAsync(Full());
using var _ = host;
var availability = host.Services.GetRequiredService<IMailAvailability>();
availability.IsEnabled.Should().BeTrue();
availability.Problems.Should().BeEmpty();
host.Services.GetRequiredService<IEmailSender>().Should().BeOfType<SmtpEmailSender>();
logs.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning);
}
[Fact]
public async Task WithoutAnyMailSetting_MailIsOff_AndNothingIsLoggedAsAProblem()
{
var (host, logs) = await StartAsync([]);
using var _ = host;
host.Services.GetRequiredService<IMailAvailability>().IsEnabled.Should().BeFalse();
host.Services.GetRequiredService<IEmailSender>().Should().BeOfType<NullEmailSender>();
logs.Entries.Should().NotContain(e => e.Level >= LogLevel.Warning);
}
[Fact]
public async Task WhenMailIsOffBecauseOfAProblem_EveryConsumerSeesItAsOff()
{
var values = Full();
values.Remove("App:PublicBaseUrl");
var (host, _) = await StartAsync(values);
using var __ = host;
using var scope = host.Services.CreateScope();
// The sender never sends.
(await host.Services.GetRequiredService<IEmailSender>().SendAsync(new OutgoingMail("a@example.org", "S", "x")))
.Should().Be(MailSendResult.Fail(MailSendResult.Disabled));
// The site settings say mail is off and refuse changes.
var settings = scope.ServiceProvider.GetRequiredService<ISiteSettingsService>();
(await settings.GetMailAsync()).EmailEnabled.Should().BeFalse();
(await settings.SetMailAsync("no-reply@example.nl", "Example", null)).Error.Should().Be(SetMailResult.MailDisabled);
// The capabilities endpoint tells the UI to hide every mail feature.
var controller = new SystemController(new ModuleOrchestrator(NullLogger<ModuleOrchestrator>.Instance),
host.Services.GetRequiredService<IMailAvailability>(), host.Services.GetRequiredService<IOptions<AppMailOptions>>());
var body = ((OkObjectResult)controller.GetCapabilities()).Value!;
body.GetType().GetProperty("EmailEnabled")!.GetValue(body).Should().Be(false);
}
}
@@ -27,7 +27,7 @@ public class SiteSettingsServiceTests : IDisposable
FromName = "Example",
AllowedFromAddresses = allowed ?? ["info@andreaslop.nl"],
Smtp = { Host = host }
}));
}), new FixedAvailability(!string.IsNullOrWhiteSpace(host)));
[Fact]
public async Task WithNothingStored_TheConfiguredDefaultsApply()
@@ -135,13 +135,15 @@ public class EmailRegistrationTests
}
[Fact]
public void WithAHostButABrokenConfiguration_OptionsFail()
public void WithAHostButABrokenConfiguration_TheHostStillStarts_WithMailOff()
{
var sp = Build(new() { ["Email:Smtp:Host"] = "mail.example.nl", ["App:PublicBaseUrl"] = "http://example.nl" });
var act = () => sp.GetRequiredService<IOptions<EmailOptions>>().Value;
var availability = sp.GetRequiredService<IMailAvailability>();
act.Should().Throw<OptionsValidationException>().WithMessage("*FromAddress*");
availability.IsEnabled.Should().BeFalse();
availability.Problems.Should().Contain(p => p.Contains("Email:FromAddress"));
sp.GetRequiredService<IEmailSender>().Should().BeOfType<NullEmailSender>();
}
[Fact]
@@ -1,5 +1,6 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting.Observability;
@@ -139,37 +140,46 @@ public class DeployedConfigurationTests
/// </summary>
[Theory]
[MemberData(nameof(HostConfigurations))]
public void HostConfiguration_StartsWithoutAnyMailSettings(string relativePath)
public void HostConfiguration_StartsWithoutAnyMailSettings_MailOff_NothingLogged(string relativePath)
{
var configuration = Load(relativePath);
var logs = new SlpModularCms.Core.Tests.Email.LogCapture();
var services = new ServiceCollection();
services.AddLogging();
services.AddLogging(b => b.AddProvider(logs));
SlpModularCms.Core.Email.EmailServiceCollectionExtensions.AddCmsEmail(services, configuration);
using var sp = services.BuildServiceProvider();
var act = () => sp.GetRequiredService<IStartupValidator>().Validate();
var availability = sp.GetRequiredService<SlpModularCms.Core.Email.IMailAvailability>();
act.Should().NotThrow();
availability.IsEnabled.Should().BeFalse();
availability.Problems.Should().BeEmpty();
logs.Entries.Should().BeEmpty();
configuration.IsEmailEnabledForTest().Should().BeFalse();
}
/// <summary>
/// Setting only an SMTP host (the half-finished configuration that once made a test host return 502) must not
/// stop the host: mail stays off and the missing setting is named in an Error log line.
/// </summary>
[Theory]
[MemberData(nameof(HostConfigurations))]
public void HostConfiguration_NeedsPublicBaseUrl_OnlyOnceAnSmtpHostIsSet(string relativePath)
public void HostConfiguration_WithOnlyAnSmtpHost_StillStarts_MailOff_AndNamesTheMissingBaseUrl(string relativePath)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile(relativePath, optional: false)
.AddInMemoryCollection(new Dictionary<string, string?> { ["Email:Smtp:Host"] = "mail.example.nl" })
.Build();
var logs = new SlpModularCms.Core.Tests.Email.LogCapture();
var services = new ServiceCollection();
services.AddLogging();
services.AddLogging(b => b.AddProvider(logs));
SlpModularCms.Core.Email.EmailServiceCollectionExtensions.AddCmsEmail(services, configuration);
using var sp = services.BuildServiceProvider();
var act = () => sp.GetRequiredService<IStartupValidator>().Validate();
var availability = sp.GetRequiredService<SlpModularCms.Core.Email.IMailAvailability>();
// With a host but no App__PublicBaseUrl the host refuses to start, and says which setting is missing.
act.Should().Throw<OptionsValidationException>().WithMessage("*App:PublicBaseUrl*");
availability.IsEnabled.Should().BeFalse();
availability.Problems.Should().Contain(p => p.Contains("App:PublicBaseUrl"));
logs.Entries.Should().ContainSingle(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Error && e.Message.Contains("App:PublicBaseUrl"));
}
}