E-mailfeature Operations: deployment, monitoring, productiegereedheid; configuratiefouten als Error-log
Mislukte mails door een configuratieprobleem (auth_failed, rejected_sender, tls_failed, not_configured) worden als Error gelogd zodat Sentry een alert stuurt; timeouts en ontvangerproblemen blijven Warning. Documentatie: uitrol per host met de hand in shared/env, rollback, monitoringplan, checklist; ASF-productie op IIS als open punt voor een latere feature. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,7 +27,7 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
/// <param name="rejectRcpt">Reply to RCPT TO with this full line.</param>
|
||||
private readonly string? _stallAt;
|
||||
|
||||
/// <param name="stallAt">"auth" advertises AUTH PLAIN and then never answers the login; "send" never answers MAIL FROM.</param>
|
||||
/// <param name="stallAt">"authfail" refuses the login with 535; "auth" advertises AUTH PLAIN and then never answers the login; "send" never answers MAIL FROM.</param>
|
||||
public StubSmtpServer(bool silent = false, string? rejectMailFrom = null, string? rejectRcpt = null, string? stallAt = null)
|
||||
{
|
||||
_stallAt = stallAt;
|
||||
@@ -53,9 +53,10 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
{
|
||||
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (_stallAt == "auth") { await writer.WriteLineAsync("250-stub"); await writer.WriteLineAsync("250 AUTH PLAIN"); }
|
||||
if (_stallAt is "auth" or "authfail") { await writer.WriteLineAsync("250-stub"); await writer.WriteLineAsync("250 AUTH PLAIN"); }
|
||||
else await writer.WriteLineAsync("250 stub");
|
||||
}
|
||||
else if (line.StartsWith("AUTH", StringComparison.OrdinalIgnoreCase) && _stallAt == "authfail") await writer.WriteLineAsync("535 5.7.8 Authentication credentials invalid");
|
||||
else if (line.StartsWith("AUTH", StringComparison.OrdinalIgnoreCase) && _stallAt == "auth") await Task.Delay(TimeSpan.FromSeconds(30));
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase) && _stallAt == "send") await Task.Delay(TimeSpan.FromSeconds(30));
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync(_rejectMailFrom ?? "250 ok"); }
|
||||
|
||||
@@ -193,7 +193,7 @@ public class SmtpSenderDiagnosticsTests
|
||||
var result = await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
result.Should().Be(MailSendResult.Fail(MailSendResult.RejectedSender));
|
||||
var line = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Warning).Subject.Message;
|
||||
var line = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error).Subject.Message; // a configuration problem
|
||||
line.Should().Contain("rejected_sender").And.Contain("SenderNotAccepted").And.Contain("(553)")
|
||||
.And.Contain("[adres]").And.Contain("from_domain=slpsoftware.nl").And.Contain($"smtp_port={server.Port}");
|
||||
// No address of the sender, the recipient or the account, and not the server reply beyond the redacted first line.
|
||||
@@ -230,4 +230,61 @@ public class SmtpSenderDiagnosticsTests
|
||||
|
||||
string.Join("\n", logs.Entries.Select(e => e.Message)).Should().NotContain("user-secret-1").And.NotContain("pw-secret-2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AWrongLogin_IsAnErrorEvent_SoSentryAlerts()
|
||||
{
|
||||
using var server = new StubSmtpServer(stallAt: "authfail");
|
||||
var (sender, logs) = SenderWith(server, timeoutSeconds: 3, username: "user-secret-9");
|
||||
|
||||
var result = await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
|
||||
|
||||
result.Should().Be(MailSendResult.Fail(MailSendResult.AuthFailed));
|
||||
var error = logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error).Subject.Message;
|
||||
error.Should().Contain("code=auth_failed").And.Contain("phase=AUTH");
|
||||
error.Should().NotContain("user-secret-9").And.NotContain("pw-secret-9").And.NotContain("535");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefusedRecipient_AndATimeout_StayWarnings()
|
||||
{
|
||||
using var refusing = new StubSmtpServer(rejectRcpt: "550 5.7.1 relay denied");
|
||||
var (sender, logs) = SenderWith(refusing, timeoutSeconds: 3);
|
||||
await sender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
|
||||
logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Warning && e.Message.Contains("rejected_recipient"));
|
||||
logs.Entries.Should().NotContain(e => e.Level >= LogLevel.Error);
|
||||
|
||||
using var silent = new StubSmtpServer(silent: true);
|
||||
var (slowSender, slowLogs) = SenderWith(silent, timeoutSeconds: 1);
|
||||
await slowSender.SendAsync(new OutgoingMail("a@example.org", "S", "<p>x</p>"));
|
||||
slowLogs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Warning && e.Message.Contains("timeout_connect"));
|
||||
slowLogs.Entries.Should().NotContain(e => e.Level >= LogLevel.Error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MailSendResult.AuthFailed, LogLevel.Error)]
|
||||
[InlineData(MailSendResult.RejectedSender, LogLevel.Error)]
|
||||
[InlineData(MailSendResult.TlsFailed, LogLevel.Error)]
|
||||
[InlineData(MailSendResult.NotConfigured, LogLevel.Error)]
|
||||
[InlineData(MailSendResult.Timeout, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.TimeoutConnect, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.TimeoutAuth, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.TimeoutSend, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.RejectedRecipient, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.Rejected, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.ConnectionFailed, LogLevel.Warning)]
|
||||
[InlineData(MailSendResult.Unknown, LogLevel.Warning)]
|
||||
public void TheLogLevel_FollowsWhetherSomebodyHasToFixSomething(string code, LogLevel expected) =>
|
||||
SmtpFailure.LevelFor(code).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAHost_ItIsLoggedAsAnError()
|
||||
{
|
||||
var logs = new LogCapture();
|
||||
var sender = new SmtpEmailSender(Options.Create(new EmailOptions()), LoggerFactory.Create(b => b.AddProvider(logs)).CreateLogger<SmtpEmailSender>());
|
||||
|
||||
await sender.SendAsync(new OutgoingMail("a@example.org", "S", "x"));
|
||||
|
||||
logs.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error && e.Message.Contains("not_configured"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,10 @@ public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<Smtp
|
||||
public async Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_options.Smtp.Host))
|
||||
{
|
||||
logger.LogError("identity_mail_failed code={Code} reason=no_smtp_host", MailSendResult.NotConfigured);
|
||||
return MailSendResult.Fail(MailSendResult.NotConfigured);
|
||||
}
|
||||
|
||||
var fromAddress = mail.FromAddress ?? _options.FromAddress;
|
||||
var fromName = mail.FromName ?? _options.FromName;
|
||||
@@ -89,7 +92,8 @@ public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<Smtp
|
||||
// Never the whole exception text (it can quote addresses or credentials): the type, for a refused
|
||||
// command its phase and status code, a redacted, shortened first line of the server's reply, and the
|
||||
// time each phase took.
|
||||
logger.LogWarning(
|
||||
logger.Log(
|
||||
SmtpFailure.LevelFor(code),
|
||||
"identity_mail_failed code={Code} detail={Detail} phase={Phase} timings=\"{Timings}\" timeout_per_phase_s={TimeoutSeconds} from_domain={FromDomain} smtp_port={Port}",
|
||||
code, SmtpFailure.Describe(ex), phase, string.Join(" ", phases), _options.Smtp.TimeoutSeconds, DomainOf(fromAddress), _options.Smtp.Port);
|
||||
return MailSendResult.Fail(code);
|
||||
|
||||
@@ -47,6 +47,21 @@ public static partial class SmtpFailure
|
||||
_ => MailSendResult.Unknown
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True for failures that point at the host's mail CONFIGURATION (wrong credentials, a sender the account may not
|
||||
/// use, a TLS problem, mail not configured) and need a person to fix them. Timeouts, a refused recipient and
|
||||
/// unknown errors are not: they pass by themselves or are about one message.
|
||||
/// </summary>
|
||||
public static bool IsConfigurationProblem(string? code) =>
|
||||
code is MailSendResult.AuthFailed or MailSendResult.RejectedSender or MailSendResult.TlsFailed or MailSendResult.NotConfigured;
|
||||
|
||||
/// <summary>
|
||||
/// Log level of a failed mail: Error for a configuration problem (Sentry turns Error events into an alert to the
|
||||
/// project owner), Warning for the rest (journal and breadcrumbs only).
|
||||
/// </summary>
|
||||
public static Microsoft.Extensions.Logging.LogLevel LevelFor(string? code) =>
|
||||
IsConfigurationProblem(code) ? Microsoft.Extensions.Logging.LogLevel.Error : Microsoft.Extensions.Logging.LogLevel.Warning;
|
||||
|
||||
/// <summary>"timeout_connect", "timeout_auth" or "timeout_send" when the phase is known, else plain "timeout".</summary>
|
||||
public static string TimeoutCode(string? phase) => phase switch
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user