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:
@@ -19,10 +19,17 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
public List<string> Recipients { get; } = [];
|
||||
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
private readonly string? _rejectMailFrom;
|
||||
private readonly string? _rejectRcpt;
|
||||
|
||||
/// <param name="silent">Accept connections but never answer (to provoke the timeout).</param>
|
||||
public StubSmtpServer(bool silent = false)
|
||||
/// <param name="rejectMailFrom">Reply to MAIL FROM with this full line (for example "553 5.7.1 ...").</param>
|
||||
/// <param name="rejectRcpt">Reply to RCPT TO with this full line.</param>
|
||||
public StubSmtpServer(bool silent = false, string? rejectMailFrom = null, string? rejectRcpt = null)
|
||||
{
|
||||
_silent = silent;
|
||||
_rejectMailFrom = rejectMailFrom;
|
||||
_rejectRcpt = rejectRcpt;
|
||||
_listener.Start();
|
||||
_loop = Task.Run(Serve);
|
||||
}
|
||||
@@ -41,8 +48,8 @@ internal sealed class StubSmtpServer : IDisposable
|
||||
while (await reader.ReadLineAsync() is { } line)
|
||||
{
|
||||
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) await writer.WriteLineAsync("250 stub");
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync("250 ok"); }
|
||||
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync("250 ok"); }
|
||||
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync(_rejectMailFrom ?? "250 ok"); }
|
||||
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync(_rejectRcpt ?? "250 ok"); }
|
||||
else if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await writer.WriteLineAsync("354 go");
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
using System.Net.Sockets;
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Email;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Email;
|
||||
|
||||
public class SmtpFailureTests(ITestOutputHelper output)
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("553 5.7.1 <no-reply@slpsoftware.nl>: Sender address rejected", "[adres]")]
|
||||
[InlineData("550 relay denied for jan@example.org", "relay denied for [adres]")]
|
||||
[InlineData("554 user@host.example.nl: not allowed", "[adres]: not allowed")]
|
||||
public void SafeReply_ReplacesEveryAddress(string reply, string expectedFragment)
|
||||
{
|
||||
var safe = SmtpFailure.SafeReply(reply);
|
||||
|
||||
safe.Should().Contain(expectedFragment);
|
||||
safe.Should().NotContain("@");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeReply_ControlCharactersCannotGlueAnAddressTogether()
|
||||
{
|
||||
// Found by the property test: "x-@" CR "host.example.nl" becomes an address once the CR is removed.
|
||||
var safe = SmtpFailure.SafeReply("550 x-@\rhost.example.nl y");
|
||||
|
||||
safe.Should().NotContain("@");
|
||||
safe.Should().Contain("[adres]");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeReply_KeepsOnlyTheFirstLine_DropsControlCharacters_AndCutsLongText()
|
||||
{
|
||||
SmtpFailure.SafeReply("550 first line\r\n550-second line with secret").Should().Be("550 first line");
|
||||
SmtpFailure.SafeReply("550 bad\u0000char\u0007").Should().Be("550 badchar");
|
||||
var cut = SmtpFailure.SafeReply("550 " + new string('x', 400));
|
||||
cut.Length.Should().BeLessThanOrEqualTo(SmtpFailure.MaxReplyLength + 3);
|
||||
cut.Should().EndWith("...");
|
||||
SmtpFailure.SafeReply(null).Should().BeEmpty();
|
||||
SmtpFailure.SafeReply(" ").Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Classify_IsAsSpecificAsTheFailureAllows()
|
||||
{
|
||||
var none = CancellationToken.None;
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.SenderNotAccepted, SmtpStatusCode.MailboxUnavailable, "x"), none)
|
||||
.Should().Be(MailSendResult.RejectedSender);
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.RecipientNotAccepted, SmtpStatusCode.MailboxUnavailable, "x"), none)
|
||||
.Should().Be(MailSendResult.RejectedRecipient);
|
||||
SmtpFailure.Classify(new SmtpCommandException(SmtpErrorCode.MessageNotAccepted, SmtpStatusCode.TransactionFailed, "x"), none)
|
||||
.Should().Be(MailSendResult.Rejected);
|
||||
SmtpFailure.Classify(new AuthenticationException("bad pw-secret"), none).Should().Be(MailSendResult.AuthFailed);
|
||||
SmtpFailure.Classify(new TimeoutException(), none).Should().Be(MailSendResult.Timeout);
|
||||
SmtpFailure.Classify(new OperationCanceledException(), none).Should().Be(MailSendResult.Timeout);
|
||||
SmtpFailure.Classify(new SocketException(), none).Should().Be(MailSendResult.ConnectionFailed);
|
||||
SmtpFailure.Classify(new InvalidOperationException(), none).Should().Be(MailSendResult.Unknown);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Describe_ForACommandNamesPhaseAndStatus_ForAuthNeverTheReply()
|
||||
{
|
||||
var command = new SmtpCommandException(SmtpErrorCode.SenderNotAccepted, SmtpStatusCode.MailboxNameNotAllowed, "553 no for jan@example.org");
|
||||
var describedCommand = SmtpFailure.Describe(command);
|
||||
describedCommand.Should().Contain("SenderNotAccepted").And.Contain("MailboxNameNotAllowed(553)").And.Contain("[adres]");
|
||||
describedCommand.Should().NotContain("jan@example.org");
|
||||
|
||||
var auth = SmtpFailure.Describe(new AuthenticationException("535 wrong password pw-secret-123"));
|
||||
auth.Should().Contain("AuthenticationException").And.Contain("AUTH");
|
||||
auth.Should().NotContain("pw-secret-123").And.NotContain("535");
|
||||
}
|
||||
|
||||
// PBT-03: whatever a server says, the reply that reaches the log has no address, no control character and a bounded length.
|
||||
[Fact]
|
||||
public void Property_TheLoggedReply_NeverHasAnAddressOrControlCharacters_AndIsBounded()
|
||||
{
|
||||
string[] pieces = ["550 ", " ", "a", "Z9", "@", ".", "-", "_", "<", ">", "\r", "\n", "\0", "\t", "\"", "example", "nl", "user", "x", "😀", "é"];
|
||||
var arb = Gen.Elements(pieces).ArrayOf().Select(p => string.Concat(p)).ToArbitrary();
|
||||
Prop.ForAll(arb, reply =>
|
||||
{
|
||||
var safe = SmtpFailure.SafeReply(reply);
|
||||
return !safe.Any(char.IsControl)
|
||||
&& safe.Length <= SmtpFailure.MaxReplyLength + 3
|
||||
&& !System.Text.RegularExpressions.Regex.IsMatch(safe, @"[A-Za-z0-9._-]+@[A-Za-z0-9.-]+");
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
|
||||
output.WriteLine("Property held for 1500 generated server replies.");
|
||||
}
|
||||
}
|
||||
|
||||
public class SmtpSenderDiagnosticsTests
|
||||
{
|
||||
private static (SmtpEmailSender Sender, LogCapture Logs) Sender(StubSmtpServer server)
|
||||
{
|
||||
var logs = new LogCapture();
|
||||
var factory = LoggerFactory.Create(b => b.AddProvider(logs));
|
||||
var sender = new SmtpEmailSender(
|
||||
Options.Create(new EmailOptions
|
||||
{
|
||||
FromAddress = "no-reply@slpsoftware.nl", FromName = "Site",
|
||||
Smtp = { Host = "127.0.0.1", Port = server.Port, EnableSsl = false, Username = "", Password = "", TimeoutSeconds = 5 }
|
||||
}),
|
||||
factory.CreateLogger<SmtpEmailSender>());
|
||||
return (sender, logs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefusedSender_IsNamedAsSuch_AndTheLogShowsPhaseStatusAndARedactedReply_NoAddresses()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectMailFrom: "553 5.7.1 <no-reply@slpsoftware.nl>: Sender address rejected: not owned by user jan@andreaslop.nl");
|
||||
var (sender, logs) = Sender(server);
|
||||
|
||||
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;
|
||||
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.
|
||||
line.Should().NotContain("no-reply@").And.NotContain("someone@").And.NotContain("jan@").And.NotContain("gmail.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefusedRecipient_IsNamedAsSuch()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectRcpt: "550 5.7.1 <someone@gmail.com>: Relay access denied");
|
||||
var (sender, logs) = Sender(server);
|
||||
|
||||
var result = await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
result.Should().Be(MailSendResult.Fail(MailSendResult.RejectedRecipient));
|
||||
logs.Entries.Single(e => e.Level == LogLevel.Warning).Message.Should().Contain("RecipientNotAccepted").And.NotContain("someone@");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheLog_NeverContainsTheCredentials()
|
||||
{
|
||||
using var server = new StubSmtpServer(rejectMailFrom: "553 5.7.1 rejected");
|
||||
var logs = new LogCapture();
|
||||
var factory = LoggerFactory.Create(b => b.AddProvider(logs));
|
||||
var sender = new SmtpEmailSender(
|
||||
Options.Create(new EmailOptions
|
||||
{
|
||||
FromAddress = "no-reply@slpsoftware.nl", FromName = "Site",
|
||||
Smtp = { Host = "127.0.0.1", Port = server.Port, EnableSsl = false, Username = "user-secret-1", Password = "pw-secret-2", TimeoutSeconds = 5 }
|
||||
}),
|
||||
factory.CreateLogger<SmtpEmailSender>());
|
||||
|
||||
await sender.SendAsync(new OutgoingMail("someone@gmail.com", "Subject", "<p>x</p>"));
|
||||
|
||||
string.Join("\n", logs.Entries.Select(e => e.Message)).Should().NotContain("user-secret-1").And.NotContain("pw-secret-2");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user