Mail: diagnose van SMTP-weigeringen en keuze bij een nieuwe uitnodigingslink

SMTP: bij een geweigerd commando logt de verzender fase, statuscode en de eerste regel van het serverantwoord
(adressen vervangen, max 120 tekens); specifiekere foutcodes (rejected_sender, rejected_recipient, tls_failed,
connection_failed) die de beheerder in het venster ziet; opstartlog met SMTP-host, poort en standaard
afzenderdomein. Uit de property-test: besturingstekens worden eerst verwijderd, anders kon een adres weer
aan elkaar plakken.
Nieuwe uitnodigingslink: regenerate-invite mailt alleen met sendEmail=true (standaard false); eerst een
keuzevenster 'Alleen link kopieren' / 'Link kopieren en mailen' (zonder mail alleen de link).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 22:30:05 +01:00
co-authored by Claude Sonnet 5.5
parent e80d324b4f
commit daaadcbdf7
20 changed files with 614 additions and 39 deletions
@@ -50,11 +50,24 @@ public sealed class MailAvailability : IMailAvailability
}
/// <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 sealed class MailStartupCheck(IMailAvailability availability, IOptions<EmailOptions> email, ILogger<MailStartupCheck> logger) : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("mail_status enabled={Enabled}", availability.IsEnabled);
var o = email.Value;
if (availability.IsEnabled)
{
// Where mail goes through and with which default sender DOMAIN (not the address): what a refused
// MAIL FROM is checked against. A sender chosen in the site settings can differ from this default.
var at = o.FromAddress.LastIndexOf('@');
logger.LogInformation(
"mail_status enabled=true smtp_host={Host} smtp_port={Port} starttls={StartTls} default_from_domain={FromDomain}",
o.Smtp.Host, o.Smtp.Port, o.Smtp.EnableSsl, at >= 0 ? o.FromAddress[(at + 1)..] : "?");
}
else
{
logger.LogInformation("mail_status enabled=false");
}
return Task.CompletedTask;
}
@@ -8,6 +8,12 @@ public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
public const string Timeout = "timeout";
public const string AuthFailed = "auth_failed";
public const string Rejected = "rejected";
/// <summary>The server refused the sender address (MAIL FROM): the From address is not allowed for this account.</summary>
public const string RejectedSender = "rejected_sender";
/// <summary>The server refused the recipient (RCPT TO), for instance because it does not relay for that domain.</summary>
public const string RejectedRecipient = "rejected_recipient";
public const string TlsFailed = "tls_failed";
public const string ConnectionFailed = "connection_failed";
public const string Unknown = "unknown";
public static MailSendResult Ok { get; } = new(true, null);
@@ -62,21 +62,15 @@ public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<Smtp
}
catch (Exception ex)
{
var code = Map(ex, cancellationToken);
// The exception TYPE only: its message may contain the recipient or server replies.
logger.LogWarning("identity_mail_failed code={Code} exception={ExceptionType}", code, ex.GetType().Name);
var code = SmtpFailure.Classify(ex, cancellationToken);
// Never the whole exception text (it can quote addresses or credentials): the type, for a refused
// command its phase and status code, and a redacted, shortened first line of the server's reply.
logger.LogWarning("identity_mail_failed code={Code} detail={Detail} from_domain={FromDomain} smtp_port={Port}",
code, SmtpFailure.Describe(ex), DomainOf(fromAddress), _options.Smtp.Port);
return MailSendResult.Fail(code);
}
}
private static string Map(Exception ex, CancellationToken callerToken) => ex switch
{
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
TimeoutException => MailSendResult.Timeout,
OperationCanceledException => MailSendResult.Unknown,
AuthenticationException => MailSendResult.AuthFailed,
SmtpCommandException or SmtpProtocolException or SslHandshakeException => MailSendResult.Rejected,
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
_ => MailSendResult.Unknown
};
private static string DomainOf(string address) =>
address.Contains('@') ? address[(address.LastIndexOf('@') + 1)..] : "?";
}
@@ -0,0 +1,69 @@
using System.Net.Sockets;
using System.Text.RegularExpressions;
using MailKit;
using MailKit.Net.Smtp;
using MailKit.Security;
namespace SlpModularCms.Core.Email;
/// <summary>
/// What went wrong with a mail, in two forms: a short code for the screen (<see cref="Classify"/>) and a
/// careful one-line description for the log (<see cref="Describe"/>).
/// </summary>
/// <remarks>
/// The exception text is still not logged as a whole (it can quote the recipient, the sender and credentials). The
/// description is explicit and limited: status code and phase, then at most the first line of the server's reply,
/// with every e-mail address replaced by [adres] and cut to <see cref="MaxReplyLength"/> characters. Credentials
/// never appear in a server reply to MAIL/RCPT, and the AUTH reply text is not included at all.
/// </remarks>
public static partial class SmtpFailure
{
public const int MaxReplyLength = 120;
[GeneratedRegex(@"[^\s@<>""'(),;:]+@[^\s@<>""'(),;:]+")]
private static partial Regex AddressPattern();
/// <summary>The short code shown to the administrator; the most specific one the failure allows.</summary>
public static string Classify(Exception ex, CancellationToken callerToken) => ex switch
{
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
TimeoutException => MailSendResult.Timeout,
OperationCanceledException => MailSendResult.Unknown,
AuthenticationException => MailSendResult.AuthFailed,
SslHandshakeException => MailSendResult.TlsFailed,
SmtpCommandException c => c.ErrorCode switch
{
SmtpErrorCode.SenderNotAccepted => MailSendResult.RejectedSender,
SmtpErrorCode.RecipientNotAccepted => MailSendResult.RejectedRecipient,
_ => MailSendResult.Rejected
},
SmtpProtocolException => MailSendResult.Rejected,
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
SocketException => MailSendResult.ConnectionFailed,
_ => MailSendResult.Unknown
};
/// <summary>The log description of a failure: the type, and for a refused command its phase, status code and a redacted first line.</summary>
public static string Describe(Exception ex)
{
var type = ex.GetType().Name;
if (ex is SmtpCommandException c)
{
var status = (int)c.StatusCode;
return $"{type} phase={c.ErrorCode} smtp_status={c.StatusCode}({status}) reply=\"{SafeReply(c.Message)}\"";
}
if (ex is AuthenticationException) return $"{type} phase=AUTH"; // the reply text is deliberately left out
return type;
}
/// <summary>The first line of a server reply: addresses replaced, control characters dropped, cut short.</summary>
public static string SafeReply(string? reply)
{
if (string.IsNullOrWhiteSpace(reply)) return "";
var firstLine = reply.Split('\n', 2)[0].Trim();
// Control characters go FIRST: removed afterwards they could glue the parts of an address together again.
var printable = new string(firstLine.Where(ch => !char.IsControl(ch)).ToArray());
var cleaned = AddressPattern().Replace(printable, "[adres]").Replace('"', '\'');
return cleaned.Length <= MaxReplyLength ? cleaned : cleaned[..MaxReplyLength] + "...";
}
}
@@ -8,6 +8,8 @@ namespace SlpModularCms.Core.Identity.Models;
[ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null);
[ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole);
[ExcludeFromCodeCoverage] public record ForgotPasswordRequest(string Email);
/// <summary>SendEmail is false unless the caller says so: a new link is never mailed by surprise.</summary>
[ExcludeFromCodeCoverage] public record RegenerateInviteRequest(bool SendEmail = false);
[ExcludeFromCodeCoverage] public record ResetPasswordRequest(Guid UserId, string Token, string NewPassword);
[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email, string? Language = null);
[ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword);