diff --git a/aidlc-docs/features/identity-email-notifications/construction/mail-foundation/infrastructure-design/infrastructure-design.md b/aidlc-docs/features/identity-email-notifications/construction/mail-foundation/infrastructure-design/infrastructure-design.md index 9798c6c..7a13737 100644 --- a/aidlc-docs/features/identity-email-notifications/construction/mail-foundation/infrastructure-design/infrastructure-design.md +++ b/aidlc-docs/features/identity-email-notifications/construction/mail-foundation/infrastructure-design/infrastructure-design.md @@ -51,6 +51,6 @@ Read-only checks done from the developer PC (by "CMS & API"): `mail.andreaslop.n ## Release notes for the host manager (required environment variables per release) - **This release adds NO required environment variable.** A host without any mail setting starts exactly as before; this is tested for every deployed host configuration (master, slave, SlpSoftware, ASF). -- Mail is switched on only by setting `Email__Smtp__Host`. **Once a host is set, all of these must be set too, or the host refuses to start** (502 behind the proxy) with a message naming the missing setting: `App__PublicBaseUrl` (https, no path), `Email__FromAddress`/`Email__FromName` (have committed defaults), and `Email__Smtp__Username` together with `Email__Smtp__Password`. Set `App__PublicBaseUrl` BEFORE or together with `Email__Smtp__Host`. +- Mail is switched on only by setting `Email__Smtp__Host`, and it only turns ON when the whole mail configuration is valid: `App__PublicBaseUrl` (https, no path), `Email__FromAddress`/`Email__FromName` (committed defaults), `Email__Smtp__Username` together with `Email__Smtp__Password`, and sane port, timeout, colour and logo values. **A half-finished or wrong mail configuration never stops the host from starting** (decided by Bryan after the 2026-11-08 incident): the host starts with mail OFF (`emailEnabled=false`, all mail UI hidden, the copy-link flow keeps working) and logs ONE Error line, `mail_configuration_invalid`, that names each missing or invalid setting (names only, never values or secrets; Sentry sees it). Check the log after changing mail settings. Set `App__PublicBaseUrl` together with `Email__Smtp__Host`. - Optional: `Identity__Invitation__ExpiryHours` (24), `Identity__PasswordReset__TokenLifetimeMinutes` (60), `Identity__PasswordReset__CooldownMinutes` (5), `App__DefaultLanguage` (nl), `Email__AllowedFromAddresses__0..n`, `Website__LogLevel`. -- Incident 2026-11-08: ASF test returned 502 after a restart because `Email__Smtp__Host` was set but `App__PublicBaseUrl` was not (start-up validation, by design: a half-configured mail setup is refused rather than silently ignored). Not a deploy without mail configuration. A softer behaviour (start with mail switched off and an error log) is a possible change, see the open question to Bryan. +- Incident 2026-11-08: ASF test returned 502 after a restart because `Email__Smtp__Host` was set but `App__PublicBaseUrl` was not (the start-up validation at that time refused a half-configured mail setup). Not a deploy without mail configuration. Since changed: the soft behaviour above. diff --git a/aidlc-docs/features/identity-email-notifications/inception/requirements/requirements.md b/aidlc-docs/features/identity-email-notifications/inception/requirements/requirements.md index e32c748..af09573 100644 --- a/aidlc-docs/features/identity-email-notifications/inception/requirements/requirements.md +++ b/aidlc-docs/features/identity-email-notifications/inception/requirements/requirements.md @@ -28,7 +28,7 @@ ## 3. Functional requirements - **FR-01 Sender abstraction.** `IEmailSender.SendAsync(toAddress, subject, htmlBody, cancellationToken)` in Core; `SmtpEmailSender` (MailKit/MimeKit; StartTls when `EnableSsl`; authenticate only when a username is set). `EmailOptions` (section `Email`): `FromAddress`, `FromName`, `Smtp{Host, Port=587, EnableSsl=true, Username, Password}`, plus a connect/send timeout (new, default 10 s). - **FR-02 Enabled by configuration.** Mail is enabled when `Email:Smtp:Host` is non-empty. When disabled, every flow behaves exactly as today. `GET` system capabilities exposes `emailEnabled` so the UI knows which actions to offer. -- **FR-03 Start-up validation.** When enabled: valid `FromAddress`, a host, a port in range, and an absolute https (or localhost) `App:PublicBaseUrl` without a path; otherwise start-up fails with a clear message (no secrets in it). +- **FR-03 Start-up validation (changed by Bryan, 2026-11-08: soft).** When an SMTP host is set: valid `FromAddress`/`FromName`, a port in range, credentials as a pair, and an absolute https (or localhost) `App:PublicBaseUrl` without a path. If anything is missing or invalid the host STILL starts, mail stays OFF (`emailEnabled=false`) and one Error log line names each setting (names only, no values, no secrets). - **FR-04 Invitation mail.** Creating an invitation sends a mail with the link `PublicBaseUrl + /admin + /invite/complete?token=...`. The response still returns `inviteLink` and now also `mail: { sent: true|false, error?: }`. A failure never rolls back the invitation. - **FR-05 New link mail.** The "create new invite link" action (existing) also sends the mail when enabled, with the same result object. - **FR-06 Resend.** Admin action "Mail opnieuw versturen" for a pending invitation: resends the mail with the current valid link; if the invitation is expired it first regenerates it (new token, new lifetime), then sends. Same hierarchy rules as the other invitation actions (Administrator only for role User). diff --git a/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs index 872f737..f534ffb 100644 --- a/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs +++ b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs @@ -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.Instance); [Fact] diff --git a/src/SlpModularCms.Core.Tests/Email/MailSoftFailureTests.cs b/src/SlpModularCms.Core.Tests/Email/MailSoftFailureTests.cs new file mode 100644 index 0000000..99772ed --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Email/MailSoftFailureTests.cs @@ -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 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 state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + entries.Enqueue((logLevel, formatter(state, exception))); + } +} + +/// +/// 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. +/// +public class MailSoftFailureTests +{ + private const string Secret = "pw-very-secret-123"; + private const string User = "user-very-secret-456"; + + private static Dictionary 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 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(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(); + availability.IsEnabled.Should().BeFalse(); + availability.Problems.Should().ContainSingle().Which.Should().Contain("App:PublicBaseUrl"); + host.Services.GetRequiredService().Should().BeOfType(); + + 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().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(); + availability.IsEnabled.Should().BeTrue(); + availability.Problems.Should().BeEmpty(); + host.Services.GetRequiredService().Should().BeOfType(); + 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().IsEnabled.Should().BeFalse(); + host.Services.GetRequiredService().Should().BeOfType(); + 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().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(); + (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.Instance), + host.Services.GetRequiredService(), host.Services.GetRequiredService>()); + var body = ((OkObjectResult)controller.GetCapabilities()).Value!; + body.GetType().GetProperty("EmailEnabled")!.GetValue(body).Should().Be(false); + } +} diff --git a/src/SlpModularCms.Core.Tests/Email/SiteSettingsAndRegistrationTests.cs b/src/SlpModularCms.Core.Tests/Email/SiteSettingsAndRegistrationTests.cs index 0a354ad..27952de 100644 --- a/src/SlpModularCms.Core.Tests/Email/SiteSettingsAndRegistrationTests.cs +++ b/src/SlpModularCms.Core.Tests/Email/SiteSettingsAndRegistrationTests.cs @@ -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>().Value; + var availability = sp.GetRequiredService(); - act.Should().Throw().WithMessage("*FromAddress*"); + availability.IsEnabled.Should().BeFalse(); + availability.Problems.Should().Contain(p => p.Contains("Email:FromAddress")); + sp.GetRequiredService().Should().BeOfType(); } [Fact] diff --git a/src/SlpModularCms.Core.Tests/Hosting/DeployedConfigurationTests.cs b/src/SlpModularCms.Core.Tests/Hosting/DeployedConfigurationTests.cs index a796bbe..ae1d981 100644 --- a/src/SlpModularCms.Core.Tests/Hosting/DeployedConfigurationTests.cs +++ b/src/SlpModularCms.Core.Tests/Hosting/DeployedConfigurationTests.cs @@ -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 /// [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().Validate(); + var availability = sp.GetRequiredService(); - act.Should().NotThrow(); + availability.IsEnabled.Should().BeFalse(); + availability.Problems.Should().BeEmpty(); + logs.Entries.Should().BeEmpty(); configuration.IsEmailEnabledForTest().Should().BeFalse(); } + /// + /// 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. + /// [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 { ["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().Validate(); + var availability = sp.GetRequiredService(); - // With a host but no App__PublicBaseUrl the host refuses to start, and says which setting is missing. - act.Should().Throw().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")); } } diff --git a/src/SlpModularCms.Core/Email/EmailOptionsValidator.cs b/src/SlpModularCms.Core/Email/EmailOptionsValidator.cs index 48e93ef..bc08402 100644 --- a/src/SlpModularCms.Core/Email/EmailOptionsValidator.cs +++ b/src/SlpModularCms.Core/Email/EmailOptionsValidator.cs @@ -10,9 +10,19 @@ namespace SlpModularCms.Core.Email; public sealed class EmailOptionsValidator(IOptions app) : IValidateOptions { public ValidateOptionsResult Validate(string? name, EmailOptions options) + { + var failures = Check(options, app.Value); + return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures); + } + + /// + /// The problems of a mail configuration (setting names only, never values). Empty when mail is off (no host) + /// or the configuration is valid. + /// + public static IReadOnlyList Check(EmailOptions options, AppMailOptions appOptions) { if (string.IsNullOrWhiteSpace(options.Smtp.Host)) - return ValidateOptionsResult.Success; // mail disabled + return []; // mail disabled var failures = new List(); @@ -34,16 +44,16 @@ public sealed class EmailOptionsValidator(IOptions 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) diff --git a/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs index 2a4c7df..d7426fb 100644 --- a/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Email/EmailServiceCollectionExtensions.cs @@ -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 { /// - /// Registers the mail building blocks. Mail is on when Email:Smtp:Host is set; otherwise a - /// 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 Email:Smtp:Host is set AND the whole mail + /// configuration is valid (see ); otherwise the 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. /// public static IServiceCollection AddCmsEmail(this IServiceCollection services, IConfiguration configuration) { services.AddOptions().Bind(configuration.GetSection(AppMailOptions.SectionName)); - services.AddOptions().Bind(configuration.GetSection(EmailOptions.SectionName)).ValidateOnStart(); - services.AddSingleton, EmailOptionsValidator>(); + // Deliberately not validated through the options pipeline: that would stop the host from starting. + services.AddOptions().Bind(configuration.GetSection(EmailOptions.SectionName)); - var enabled = !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]); - if (enabled) - services.TryAddSingleton(); - else - services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddHostedService(); + services.TryAddSingleton(sp => + sp.GetRequiredService().IsEnabled + ? ActivatorUtilities.CreateInstance(sp) + : new NullEmailSender()); services.TryAddSingleton(); services.TryAddSingleton(); @@ -32,7 +33,7 @@ public static class EmailServiceCollectionExtensions return services; } - /// True when an SMTP host is configured. + /// True when an SMTP host is set (configured, not necessarily valid: see ). public static bool IsEmailEnabled(this IConfiguration configuration) => !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]); } diff --git a/src/SlpModularCms.Core/Email/IdentityMailService.cs b/src/SlpModularCms.Core/Email/IdentityMailService.cs index a49c853..ac08689 100644 --- a/src/SlpModularCms.Core/Email/IdentityMailService.cs +++ b/src/SlpModularCms.Core/Email/IdentityMailService.cs @@ -13,7 +13,7 @@ namespace SlpModularCms.Core.Email; /// public interface IIdentityMailService { - /// True when this site can send mail (an SMTP host is configured). + /// True when this site can send mail (SMTP host set and the configuration valid). bool IsEnabled { get; } Task SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default); @@ -32,9 +32,10 @@ public sealed class IdentityMailService( IOptions app, IOptions invitation, IOptions resetSettings, + IMailAvailability availability, ILogger logger) : IIdentityMailService { - public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host); + public bool IsEnabled => availability.IsEnabled; public Task SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default) => SendAsync( diff --git a/src/SlpModularCms.Core/Email/MailAvailability.cs b/src/SlpModularCms.Core/Email/MailAvailability.cs new file mode 100644 index 0000000..c9d826b --- /dev/null +++ b/src/SlpModularCms.Core/Email/MailAvailability.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace SlpModularCms.Core.Email; + +/// +/// 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. +/// +public interface IMailAvailability +{ + /// True only when an SMTP host is set AND the whole mail configuration is valid. + bool IsEnabled { get; } + + /// Why mail is off although a host was set (setting names only, never values). Empty otherwise. + IReadOnlyList Problems { get; } +} + +/// +/// 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. +/// +public sealed class MailAvailability : IMailAvailability +{ + public bool IsEnabled { get; } + public IReadOnlyList Problems { get; } + + public MailAvailability(IOptions email, IOptions app, ILogger 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)); + } + } +} + +/// Makes the decision (and its Error log line) happen at start-up instead of at the first mail. +public sealed class MailStartupCheck(IMailAvailability availability, ILogger 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; +} diff --git a/src/SlpModularCms.Core/Hosting/SystemController.cs b/src/SlpModularCms.Core/Hosting/SystemController.cs index c232f1f..600065f 100644 --- a/src/SlpModularCms.Core/Hosting/SystemController.cs +++ b/src/SlpModularCms.Core/Hosting/SystemController.cs @@ -14,13 +14,13 @@ namespace SlpModularCms.Core.Hosting; public class SystemController : ControllerBase { private readonly ModuleOrchestrator _orchestrator; - private readonly IOptions _email; + private readonly IMailAvailability _mail; private readonly IOptions _app; - public SystemController(ModuleOrchestrator orchestrator, IOptions email, IOptions app) + public SystemController(ModuleOrchestrator orchestrator, IMailAvailability mail, IOptions 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 }); } diff --git a/src/SlpModularCms.Core/SiteSettings/SiteSettingsService.cs b/src/SlpModularCms.Core/SiteSettings/SiteSettingsService.cs index 8481ad5..6fe745b 100644 --- a/src/SlpModularCms.Core/SiteSettings/SiteSettingsService.cs +++ b/src/SlpModularCms.Core/SiteSettings/SiteSettingsService.cs @@ -36,11 +36,11 @@ public interface ISiteSettingsService Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default); } -public sealed class SiteSettingsService(ApplicationDbContext db, IOptions options) : ISiteSettingsService +public sealed class SiteSettingsService(ApplicationDbContext db, IOptions 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 Allowed() => new[] { _options.FromAddress }.Concat(_options.AllowedFromAddresses)