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;
/// A minimal in-process SMTP server: accepts one message and records it. No TLS, no auth.
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 Recipients { get; } = [];
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
private readonly string? _rejectMailFrom;
private readonly string? _rejectRcpt;
/// Accept connections but never answer (to provoke the timeout).
/// Reply to MAIL FROM with this full line (for example "553 5.7.1 ...").
/// Reply to RCPT TO with this full line.
private readonly string? _stallAt;
/// "auth" advertises AUTH PLAIN and then never answers the login; "send" never answers MAIL FROM.
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.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", "Body
", "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", "x
", FromAddress: "info@example.nl", FromName: "Andrea"));
result.Sent.Should().BeTrue();
server.ReceivedData.Should().Contain("From: Andrea ");
}
[Fact]
public async Task ASimpleDeckAppShapedCall_Works()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync("to@example.org", "Subject", "x
");
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, "x
"));
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", "x
"));
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", "x
"));
result.Sent.Should().BeFalse();
result.ErrorCode.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task WithoutAHost_ItReportsNotConfigured()
{
var sender = new SmtpEmailSender(Options.Create(new EmailOptions()), NullLogger.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));
}