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:
@@ -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