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:
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,19 @@ namespace SlpModularCms.Core.Email;
|
||||
public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValidateOptions<EmailOptions>
|
||||
{
|
||||
public ValidateOptionsResult Validate(string? name, EmailOptions options)
|
||||
{
|
||||
var failures = Check(options, app.Value);
|
||||
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The problems of a mail configuration (setting names only, never values). Empty when mail is off (no host)
|
||||
/// or the configuration is valid.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Check(EmailOptions options, AppMailOptions appOptions)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(options.Smtp.Host))
|
||||
return ValidateOptionsResult.Success; // mail disabled
|
||||
return []; // mail disabled
|
||||
|
||||
var failures = new List<string>();
|
||||
|
||||
@@ -34,16 +44,16 @@ public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValid
|
||||
failures.Add("Email:AllowedFromAddresses contains an invalid e-mail address.");
|
||||
}
|
||||
|
||||
var baseUrl = app.Value.PublicBaseUrl;
|
||||
var baseUrl = appOptions.PublicBaseUrl;
|
||||
if (!IsValidPublicBaseUrl(baseUrl))
|
||||
failures.Add("App:PublicBaseUrl must be an absolute https URL (http only for localhost) without a path.");
|
||||
if (!MailLanguages.IsSupported(app.Value.DefaultLanguage))
|
||||
if (!MailLanguages.IsSupported(appOptions.DefaultLanguage))
|
||||
failures.Add("App:DefaultLanguage must be 'nl' or 'en'.");
|
||||
|
||||
if (!string.IsNullOrEmpty(options.LogoUrl) && !IsValidLogoUrl(options.LogoUrl))
|
||||
failures.Add("Email:LogoUrl must be an https URL or a path starting with '/'.");
|
||||
|
||||
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
|
||||
return failures;
|
||||
}
|
||||
|
||||
public static bool IsValidPublicBaseUrl(string? value)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
@@ -9,21 +8,23 @@ namespace SlpModularCms.Core.Email;
|
||||
public static class EmailServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the mail building blocks. Mail is on when <c>Email:Smtp:Host</c> is set; otherwise a
|
||||
/// <see cref="NullEmailSender"/> is registered and every flow behaves as before mail existed.
|
||||
/// The options are validated at start-up (only when mail is on).
|
||||
/// Registers the mail building blocks. Mail is on only when <c>Email:Smtp:Host</c> is set AND the whole mail
|
||||
/// configuration is valid (see <see cref="IMailAvailability"/>); otherwise the <see cref="NullEmailSender"/> is used
|
||||
/// and every flow behaves as before mail existed. A host with a half-finished mail configuration still starts: mail
|
||||
/// stays off and one Error log line names what is missing or invalid.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddCmsEmail(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<AppMailOptions>().Bind(configuration.GetSection(AppMailOptions.SectionName));
|
||||
services.AddOptions<EmailOptions>().Bind(configuration.GetSection(EmailOptions.SectionName)).ValidateOnStart();
|
||||
services.AddSingleton<IValidateOptions<EmailOptions>, EmailOptionsValidator>();
|
||||
// Deliberately not validated through the options pipeline: that would stop the host from starting.
|
||||
services.AddOptions<EmailOptions>().Bind(configuration.GetSection(EmailOptions.SectionName));
|
||||
|
||||
var enabled = !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
|
||||
if (enabled)
|
||||
services.TryAddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
else
|
||||
services.TryAddSingleton<IEmailSender, NullEmailSender>();
|
||||
services.TryAddSingleton<IMailAvailability, MailAvailability>();
|
||||
services.AddHostedService<MailStartupCheck>();
|
||||
services.TryAddSingleton<IEmailSender>(sp =>
|
||||
sp.GetRequiredService<IMailAvailability>().IsEnabled
|
||||
? ActivatorUtilities.CreateInstance<SmtpEmailSender>(sp)
|
||||
: new NullEmailSender());
|
||||
|
||||
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
|
||||
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
|
||||
@@ -32,7 +33,7 @@ public static class EmailServiceCollectionExtensions
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>True when an SMTP host is configured.</summary>
|
||||
/// <summary>True when an SMTP host is set (configured, not necessarily valid: see <see cref="IMailAvailability"/>).</summary>
|
||||
public static bool IsEmailEnabled(this IConfiguration configuration) =>
|
||||
!string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace SlpModularCms.Core.Email;
|
||||
/// </summary>
|
||||
public interface IIdentityMailService
|
||||
{
|
||||
/// <summary>True when this site can send mail (an SMTP host is configured).</summary>
|
||||
/// <summary>True when this site can send mail (SMTP host set and the configuration valid).</summary>
|
||||
bool IsEnabled { get; }
|
||||
|
||||
Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default);
|
||||
@@ -32,9 +32,10 @@ public sealed class IdentityMailService(
|
||||
IOptions<AppMailOptions> app,
|
||||
IOptions<InvitationSettings> invitation,
|
||||
IOptions<PasswordResetSettings> resetSettings,
|
||||
IMailAvailability availability,
|
||||
ILogger<IdentityMailService> logger) : IIdentityMailService
|
||||
{
|
||||
public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host);
|
||||
public bool IsEnabled => availability.IsEnabled;
|
||||
|
||||
public Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default) =>
|
||||
SendAsync(
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this host can send mail. THE single answer: the sender, the mail service, the site settings and
|
||||
/// the capabilities endpoint all ask this, so they can never disagree.
|
||||
/// </summary>
|
||||
public interface IMailAvailability
|
||||
{
|
||||
/// <summary>True only when an SMTP host is set AND the whole mail configuration is valid.</summary>
|
||||
bool IsEnabled { get; }
|
||||
|
||||
/// <summary>Why mail is off although a host was set (setting names only, never values). Empty otherwise.</summary>
|
||||
IReadOnlyList<string> Problems { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decides once, at start-up. A host without mail settings simply has mail off. A host with a half-finished or
|
||||
/// wrong mail configuration does NOT fail to start (mail is secondary to the site being up): it starts with mail
|
||||
/// off and one clear Error log line naming each missing or invalid setting. No secret or value is ever logged.
|
||||
/// </summary>
|
||||
public sealed class MailAvailability : IMailAvailability
|
||||
{
|
||||
public bool IsEnabled { get; }
|
||||
public IReadOnlyList<string> Problems { get; }
|
||||
|
||||
public MailAvailability(IOptions<EmailOptions> email, IOptions<AppMailOptions> app, ILogger<MailAvailability> logger)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email.Value.Smtp.Host))
|
||||
{
|
||||
Problems = [];
|
||||
IsEnabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
Problems = EmailOptionsValidator.Check(email.Value, app.Value);
|
||||
IsEnabled = Problems.Count == 0;
|
||||
|
||||
if (!IsEnabled)
|
||||
{
|
||||
// The messages name settings (for example "App:PublicBaseUrl"), never their values.
|
||||
logger.LogError(
|
||||
"mail_configuration_invalid: an SMTP host is set but the mail configuration is incomplete or invalid, so mail stays OFF and the site runs without it. Fix these settings and restart: {Problems}",
|
||||
string.Join(" | ", Problems));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Makes the decision (and its Error log line) happen at start-up instead of at the first mail.</summary>
|
||||
public sealed class MailStartupCheck(IMailAvailability availability, ILogger<MailStartupCheck> logger) : IHostedService
|
||||
{
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation("mail_status enabled={Enabled}", availability.IsEnabled);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
@@ -14,13 +14,13 @@ namespace SlpModularCms.Core.Hosting;
|
||||
public class SystemController : ControllerBase
|
||||
{
|
||||
private readonly ModuleOrchestrator _orchestrator;
|
||||
private readonly IOptions<EmailOptions> _email;
|
||||
private readonly IMailAvailability _mail;
|
||||
private readonly IOptions<AppMailOptions> _app;
|
||||
|
||||
public SystemController(ModuleOrchestrator orchestrator, IOptions<EmailOptions> email, IOptions<AppMailOptions> app)
|
||||
public SystemController(ModuleOrchestrator orchestrator, IMailAvailability mail, IOptions<AppMailOptions> app)
|
||||
{
|
||||
_orchestrator = orchestrator;
|
||||
_email = email;
|
||||
_mail = mail;
|
||||
_app = app;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ public class SystemController : ControllerBase
|
||||
return Ok(new
|
||||
{
|
||||
Modules = _orchestrator.ModuleNames,
|
||||
EmailEnabled = !string.IsNullOrWhiteSpace(_email.Value.Smtp.Host),
|
||||
EmailEnabled = _mail.IsEnabled,
|
||||
DefaultLanguage = MailLanguages.Normalize(_app.Value.DefaultLanguage) ?? MailLanguages.Dutch
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,11 +36,11 @@ public interface ISiteSettingsService
|
||||
Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class SiteSettingsService(ApplicationDbContext db, IOptions<EmailOptions> options) : ISiteSettingsService
|
||||
public sealed class SiteSettingsService(ApplicationDbContext db, IOptions<EmailOptions> options, IMailAvailability availability) : ISiteSettingsService
|
||||
{
|
||||
private readonly EmailOptions _options = options.Value;
|
||||
|
||||
private bool Enabled => !string.IsNullOrWhiteSpace(_options.Smtp.Host);
|
||||
private bool Enabled => availability.IsEnabled;
|
||||
|
||||
private IReadOnlyList<string> Allowed() =>
|
||||
new[] { _options.FromAddress }.Concat(_options.AllowedFromAddresses)
|
||||
|
||||
Reference in New Issue
Block a user