De SMTP-verzender gaf alle stappen samen een tijdsbudget; nu krijgt elke stap (verbinden met STARTTLS, inloggen, versturen) zijn eigen volledige timeout. Bij een timeout noemt de code de stap (timeout_connect, timeout_auth, timeout_send) en toont het log per stap de verstreken milliseconden. TimeoutSeconds blijft instelbaar (standaard 10), bereik nu 1 tot 120. Infra-doc met veiligheidsmodus, timeout en leeswijzer voor het journal. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
178 lines
7.7 KiB
C#
178 lines
7.7 KiB
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using FluentAssertions;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using SlpModularCms.Core.Email;
|
|
|
|
namespace SlpModularCms.Core.Tests.Email;
|
|
|
|
/// <summary>A minimal in-process SMTP server: accepts one message and records it. No TLS, no auth.</summary>
|
|
internal sealed class StubSmtpServer : IDisposable
|
|
{
|
|
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
|
private readonly bool _silent;
|
|
private readonly Task _loop;
|
|
public string? ReceivedData { get; private set; }
|
|
public string? MailFrom { get; private set; }
|
|
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>
|
|
/// <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>
|
|
private readonly string? _stallAt;
|
|
|
|
/// <param name="stallAt">"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;
|
|
_silent = silent;
|
|
_rejectMailFrom = rejectMailFrom;
|
|
_rejectRcpt = rejectRcpt;
|
|
_listener.Start();
|
|
_loop = Task.Run(Serve);
|
|
}
|
|
|
|
private async Task Serve()
|
|
{
|
|
try
|
|
{
|
|
using var client = await _listener.AcceptTcpClientAsync();
|
|
if (_silent) { await Task.Delay(TimeSpan.FromSeconds(30)); return; }
|
|
|
|
await using var stream = client.GetStream();
|
|
using var reader = new StreamReader(stream, Encoding.ASCII);
|
|
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true, NewLine = "\r\n" };
|
|
await writer.WriteLineAsync("220 stub ESMTP");
|
|
while (await reader.ReadLineAsync() is { } line)
|
|
{
|
|
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (_stallAt == "auth") { 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 == "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"); }
|
|
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");
|
|
var data = new StringBuilder();
|
|
while (await reader.ReadLineAsync() is { } d && d != ".") data.AppendLine(d);
|
|
ReceivedData = data.ToString();
|
|
await writer.WriteLineAsync("250 queued");
|
|
}
|
|
else if (line.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase)) { await writer.WriteLineAsync("221 bye"); break; }
|
|
else await writer.WriteLineAsync("250 ok");
|
|
}
|
|
}
|
|
catch (Exception) { /* the test ended or the client disconnected */ }
|
|
}
|
|
|
|
public void Dispose() => _listener.Stop();
|
|
}
|
|
|
|
public class SmtpEmailSenderTests
|
|
{
|
|
private static SmtpEmailSender Sender(int port, int timeoutSeconds = 5) => new(
|
|
Options.Create(new EmailOptions
|
|
{
|
|
FromAddress = "no-reply@example.nl",
|
|
FromName = "Example Site",
|
|
Smtp = { Host = "127.0.0.1", Port = port, EnableSsl = false, TimeoutSeconds = timeoutSeconds }
|
|
}),
|
|
NullLogger<SmtpEmailSender>.Instance);
|
|
|
|
[Fact]
|
|
public async Task Sends_TheMail_WithTheConfiguredSender()
|
|
{
|
|
using var server = new StubSmtpServer();
|
|
|
|
var result = await Sender(server.Port).SendAsync(new OutgoingMail("to@example.org", "Hello", "<p>Body</p>", "Body"));
|
|
|
|
result.Should().Be(MailSendResult.Ok);
|
|
server.MailFrom.Should().Contain("no-reply@example.nl");
|
|
server.Recipients.Should().ContainSingle().Which.Should().Contain("to@example.org");
|
|
server.ReceivedData.Should().Contain("Subject: Hello").And.Contain("Example Site").And.Contain("Body");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASenderOverride_IsUsedForTheFromHeader()
|
|
{
|
|
using var server = new StubSmtpServer();
|
|
|
|
var result = await Sender(server.Port).SendAsync(
|
|
new OutgoingMail("to@example.org", "Hi", "<p>x</p>", FromAddress: "info@example.nl", FromName: "Andrea"));
|
|
|
|
result.Sent.Should().BeTrue();
|
|
server.ReceivedData.Should().Contain("From: Andrea <info@example.nl>");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASimpleDeckAppShapedCall_Works()
|
|
{
|
|
using var server = new StubSmtpServer();
|
|
|
|
var result = await Sender(server.Port).SendAsync("to@example.org", "Subject", "<p>x</p>");
|
|
|
|
result.Sent.Should().BeTrue();
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("to@example.org\r\nBcc: victim@example.org", "Subject")]
|
|
[InlineData("not-an-address", "Subject")]
|
|
[InlineData("to@example.org", "Subject\r\nBcc: victim@example.org")]
|
|
public async Task HeaderInjectionAndBadAddresses_AreRefused_WithoutConnecting(string to, string subject)
|
|
{
|
|
using var server = new StubSmtpServer();
|
|
|
|
var result = await Sender(server.Port).SendAsync(new OutgoingMail(to, subject, "<p>x</p>"));
|
|
|
|
result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected));
|
|
server.ReceivedData.Should().BeNull();
|
|
server.Recipients.Should().BeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASlowServer_ProducesATimeout_NotAnException()
|
|
{
|
|
using var server = new StubSmtpServer(silent: true);
|
|
|
|
var started = DateTime.UtcNow;
|
|
var result = await Sender(server.Port, timeoutSeconds: 1).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
|
|
|
|
result.Should().Be(MailSendResult.Fail(MailSendResult.TimeoutConnect));
|
|
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ANeverListeningServer_IsAFailureValue_NotAnException()
|
|
{
|
|
int freePort;
|
|
using (var probe = new TcpListener(IPAddress.Loopback, 0)) { probe.Start(); freePort = ((IPEndPoint)probe.LocalEndpoint).Port; }
|
|
|
|
var result = await Sender(freePort, timeoutSeconds: 2).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
|
|
|
|
result.Sent.Should().BeFalse();
|
|
result.ErrorCode.Should().NotBeNullOrEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithoutAHost_ItReportsNotConfigured()
|
|
{
|
|
var sender = new SmtpEmailSender(Options.Create(new EmailOptions()), NullLogger<SmtpEmailSender>.Instance);
|
|
|
|
(await sender.SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.NotConfigured));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheNullSender_ReportsDisabled() =>
|
|
(await new NullEmailSender().SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.Disabled));
|
|
}
|