The Italian pack can now produce and check the e-invoice and talk to the SDI: - FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator checks it against an embedded schema and the AdE semantic rules (official codes). - SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications. - The incoming-invoice model becomes the shared EInvoice* model, read and written. - In-house ImapClient and MimeParser (no external libraries) back the PEC channel; SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries sit behind the same IEInvoiceTransport contract, with fake-server tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0debd82983
commit
709bb13532
26 files changed
+5916
-243
No files matched your search
@@ -0,0 +1,477 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Mail;
|
||||
|
||||
/// <summary>A message held by <see cref="FakeImapServer"/>.</summary>
|
||||
internal sealed class FakeImapMessage(long uid, byte[] content)
|
||||
{
|
||||
public long Uid { get; } = uid;
|
||||
|
||||
public byte[] Content { get; } = content;
|
||||
|
||||
public HashSet<string> Flags { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An IMAP server on the loopback interface, enough for the tests of the client and of the PEC channel: CAPABILITY,
|
||||
/// LOGIN (quoted or literal), SELECT, UID SEARCH (ALL, UNSEEN, FROM, SINCE ignored), UID FETCH, UID STORE, UID MOVE,
|
||||
/// UID COPY (NO [TRYCREATE] for a missing folder), CREATE, EXPUNGE, UID EXPUNGE, LOGOUT. One connection at a time.
|
||||
/// </summary>
|
||||
internal sealed partial class FakeImapServer : IAsyncDisposable
|
||||
{
|
||||
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Task _loop;
|
||||
private long _nextUid = 100;
|
||||
|
||||
public FakeImapServer(string user, string password, params byte[][] messages)
|
||||
{
|
||||
User = user;
|
||||
Password = password;
|
||||
Mailboxes["INBOX"] = [.. messages.Select(m => new FakeImapMessage(_nextUid++, m))];
|
||||
_listener.Start();
|
||||
_loop = Task.Run(AcceptAsync);
|
||||
}
|
||||
|
||||
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
public string User { get; }
|
||||
|
||||
public string Password { get; }
|
||||
|
||||
/// <summary>Whether MOVE and UIDPLUS are announced.</summary>
|
||||
public bool SupportsMove { get; init; } = true;
|
||||
|
||||
public ConcurrentDictionary<string, List<FakeImapMessage>> Mailboxes { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ConcurrentQueue<string> Commands { get; } = new();
|
||||
|
||||
public void Add(byte[] message) => Mailboxes["INBOX"].Add(new FakeImapMessage(_nextUid++, message));
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stop.CancelAsync();
|
||||
_listener.Stop();
|
||||
try
|
||||
{
|
||||
await _loop;
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task AcceptAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using (client)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ServeAsync(client.GetStream());
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ServeAsync(NetworkStream stream)
|
||||
{
|
||||
var reader = new LineReader(stream);
|
||||
async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token);
|
||||
await Send("* OK Fake IMAP ready");
|
||||
var authenticated = false;
|
||||
List<FakeImapMessage>? selected = null;
|
||||
while (true)
|
||||
{
|
||||
var (line, literals) = await reader.CommandAsync(() => Send("+ go ahead"), _stop.Token);
|
||||
if (line is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Commands.Enqueue(line);
|
||||
var space = line.IndexOf(' ', StringComparison.Ordinal);
|
||||
var tag = line[..space];
|
||||
var rest = line[(space + 1)..];
|
||||
var verb = rest.Split(' ')[0].ToUpperInvariant();
|
||||
if (verb == "UID")
|
||||
{
|
||||
verb = "UID " + rest.Split(' ')[1].ToUpperInvariant();
|
||||
}
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
case "CAPABILITY":
|
||||
await Send("* CAPABILITY IMAP4rev1" + (SupportsMove ? " MOVE UIDPLUS" : string.Empty));
|
||||
await Send(tag + " OK CAPABILITY completed");
|
||||
break;
|
||||
case "LOGIN":
|
||||
var values = Arguments(rest[6..], literals);
|
||||
authenticated = values.Count == 2 && values[0] == User && values[1] == Password;
|
||||
await Send(tag + (authenticated ? " OK LOGIN completed" : " NO [AUTHENTICATIONFAILED] Invalid credentials"));
|
||||
break;
|
||||
case "SELECT" when authenticated:
|
||||
var name = Arguments(rest[7..], literals)[0];
|
||||
selected = Mailboxes.GetValueOrDefault(name);
|
||||
await Send(selected is null ? tag + " NO Mailbox does not exist" : $"* {selected.Count} EXISTS");
|
||||
if (selected is not null)
|
||||
{
|
||||
await Send(tag + " OK [READ-WRITE] SELECT completed");
|
||||
}
|
||||
|
||||
break;
|
||||
case "UID SEARCH" when selected is not null:
|
||||
var criteria = rest[11..];
|
||||
var found = selected.Where(m =>
|
||||
(!criteria.Contains("UNSEEN", StringComparison.OrdinalIgnoreCase) || !m.Flags.Contains(@"\Seen"))
|
||||
&& !m.Flags.Contains(@"\Deleted")
|
||||
&& (FromPattern().Match(criteria) is not { Success: true } from
|
||||
|| Encoding.Latin1.GetString(m.Content).Contains(from.Groups["v"].Value, StringComparison.OrdinalIgnoreCase)));
|
||||
await Send("* SEARCH " + string.Join(' ', found.Select(m => m.Uid.ToString(CultureInfo.InvariantCulture))));
|
||||
await Send(tag + " OK SEARCH completed");
|
||||
break;
|
||||
case "UID FETCH" when selected is not null:
|
||||
var fetchUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture);
|
||||
var message = selected.FirstOrDefault(m => m.Uid == fetchUid);
|
||||
if (message is not null)
|
||||
{
|
||||
var index = selected.IndexOf(message) + 1;
|
||||
await stream.WriteAsync(Encoding.ASCII.GetBytes($"* {index} FETCH (UID {message.Uid} BODY[] {{{message.Content.Length}}}\r\n"), _stop.Token);
|
||||
await stream.WriteAsync(message.Content, _stop.Token);
|
||||
await Send(")");
|
||||
}
|
||||
|
||||
await Send(tag + " OK FETCH completed");
|
||||
break;
|
||||
case "UID STORE" when selected is not null:
|
||||
var storeUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture);
|
||||
var flags = rest[(rest.IndexOf('(', StringComparison.Ordinal) + 1)..rest.LastIndexOf(')')];
|
||||
foreach (var m in selected.Where(m => m.Uid == storeUid))
|
||||
{
|
||||
m.Flags.UnionWith(flags.Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
}
|
||||
|
||||
await Send(tag + " OK STORE completed");
|
||||
break;
|
||||
case "UID MOVE" or "UID COPY" when selected is not null:
|
||||
var parts = rest.Split(' ', 4);
|
||||
var uid = long.Parse(parts[2], CultureInfo.InvariantCulture);
|
||||
var target = Arguments(parts[3], literals)[0];
|
||||
if (!Mailboxes.TryGetValue(target, out var targetBox))
|
||||
{
|
||||
await Send(tag + " NO [TRYCREATE] Mailbox does not exist");
|
||||
break;
|
||||
}
|
||||
|
||||
foreach (var m in selected.Where(m => m.Uid == uid).ToList())
|
||||
{
|
||||
targetBox.Add(new FakeImapMessage(_nextUid++, m.Content));
|
||||
if (verb == "UID MOVE")
|
||||
{
|
||||
selected.Remove(m);
|
||||
}
|
||||
}
|
||||
|
||||
await Send(tag + " OK done");
|
||||
break;
|
||||
case "CREATE" when authenticated:
|
||||
Mailboxes.TryAdd(Arguments(rest[7..], literals)[0], []);
|
||||
await Send(tag + " OK CREATE completed");
|
||||
break;
|
||||
case "EXPUNGE" or "UID EXPUNGE" when selected is not null:
|
||||
selected.RemoveAll(m => m.Flags.Contains(@"\Deleted"));
|
||||
await Send(tag + " OK EXPUNGE completed");
|
||||
break;
|
||||
case "LOGOUT":
|
||||
await Send("* BYE Logging out");
|
||||
await Send(tag + " OK LOGOUT completed");
|
||||
return;
|
||||
default:
|
||||
await Send(tag + " BAD Unknown or not allowed: " + verb);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The arguments: quoted strings, atoms, and {n} literals taken in order.
|
||||
private static List<string> Arguments(string text, Queue<byte[]> literals)
|
||||
{
|
||||
var values = new List<string>();
|
||||
var i = 0;
|
||||
while (i < text.Length)
|
||||
{
|
||||
if (text[i] == ' ')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
else if (text[i] == '"')
|
||||
{
|
||||
var value = new StringBuilder();
|
||||
i++;
|
||||
while (i < text.Length && text[i] != '"')
|
||||
{
|
||||
if (text[i] == '\\')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
value.Append(text[i]);
|
||||
i++;
|
||||
}
|
||||
|
||||
values.Add(value.ToString());
|
||||
i++;
|
||||
}
|
||||
else if (text[i] == '{')
|
||||
{
|
||||
values.Add(Encoding.UTF8.GetString(literals.Dequeue()));
|
||||
i = text.IndexOf('}', i) + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
var end = text.IndexOf(' ', i);
|
||||
values.Add(end < 0 ? text[i..] : text[i..end]);
|
||||
i = end < 0 ? text.Length : end;
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
[GeneratedRegex("FROM \"(?<v>[^\"]*)\"", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex FromPattern();
|
||||
}
|
||||
|
||||
/// <summary>An SMTP server on the loopback interface that keeps every message it receives (no TLS).</summary>
|
||||
internal sealed class FakeSmtpServer : IAsyncDisposable
|
||||
{
|
||||
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Task _loop;
|
||||
|
||||
public FakeSmtpServer()
|
||||
{
|
||||
_listener.Start();
|
||||
_loop = Task.Run(AcceptAsync);
|
||||
}
|
||||
|
||||
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
|
||||
|
||||
/// <summary>The messages: sender, recipients, raw content.</summary>
|
||||
public ConcurrentQueue<(string From, IReadOnlyList<string> To, byte[] Content)> Messages { get; } = new();
|
||||
|
||||
/// <summary>When set, RCPT TO is refused with this reply.</summary>
|
||||
public string? RejectRecipient { get; set; }
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stop.CancelAsync();
|
||||
_listener.Stop();
|
||||
try
|
||||
{
|
||||
await _loop;
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task AcceptAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using (client)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ServeAsync(client.GetStream());
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ServeAsync(NetworkStream stream)
|
||||
{
|
||||
var reader = new LineReader(stream);
|
||||
async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token);
|
||||
await Send("220 fake.smtp ESMTP");
|
||||
string from = string.Empty;
|
||||
var to = new List<string>();
|
||||
while (true)
|
||||
{
|
||||
var line = await reader.LineAsync(_stop.Token);
|
||||
if (line is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var upper = line.ToUpperInvariant();
|
||||
if (upper.StartsWith("EHLO", StringComparison.Ordinal))
|
||||
{
|
||||
await Send("250-fake.smtp");
|
||||
await Send("250 AUTH PLAIN LOGIN");
|
||||
}
|
||||
else if (upper.StartsWith("AUTH PLAIN", StringComparison.Ordinal))
|
||||
{
|
||||
await Send("235 Authenticated");
|
||||
}
|
||||
else if (upper.StartsWith("MAIL FROM:", StringComparison.Ordinal))
|
||||
{
|
||||
from = line[10..].Trim('<', '>', ' ');
|
||||
to.Clear();
|
||||
await Send("250 OK");
|
||||
}
|
||||
else if (upper.StartsWith("RCPT TO:", StringComparison.Ordinal))
|
||||
{
|
||||
if (RejectRecipient is not null)
|
||||
{
|
||||
await Send(RejectRecipient);
|
||||
continue;
|
||||
}
|
||||
|
||||
to.Add(line[8..].Trim('<', '>', ' '));
|
||||
await Send("250 OK");
|
||||
}
|
||||
else if (upper == "DATA")
|
||||
{
|
||||
await Send("354 End data with <CR><LF>.<CR><LF>");
|
||||
var data = new StringBuilder();
|
||||
while (await reader.LineAsync(_stop.Token) is { } dataLine && dataLine != ".")
|
||||
{
|
||||
data.Append(dataLine.StartsWith("..", StringComparison.Ordinal) ? dataLine[1..] : dataLine).Append("\r\n");
|
||||
}
|
||||
|
||||
Messages.Enqueue((from, [.. to], Encoding.Latin1.GetBytes(data.ToString())));
|
||||
await Send("250 OK queued");
|
||||
}
|
||||
else if (upper == "QUIT")
|
||||
{
|
||||
await Send("221 Bye");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
await Send("502 Not implemented");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads CRLF lines and IMAP literals from a stream.</summary>
|
||||
internal sealed class LineReader(Stream stream)
|
||||
{
|
||||
private readonly byte[] _buffer = new byte[8192];
|
||||
private int _start;
|
||||
private int _end;
|
||||
|
||||
public async Task<string?> LineAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using var line = new MemoryStream();
|
||||
while (true)
|
||||
{
|
||||
if (_start == _end)
|
||||
{
|
||||
_start = 0;
|
||||
_end = await stream.ReadAsync(_buffer, cancellationToken);
|
||||
if (_end == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start);
|
||||
if (index < 0)
|
||||
{
|
||||
line.Write(_buffer, _start, _end - _start);
|
||||
_start = _end;
|
||||
continue;
|
||||
}
|
||||
|
||||
line.Write(_buffer, _start, index - _start);
|
||||
_start = index + 1;
|
||||
return Encoding.Latin1.GetString(line.ToArray()).TrimEnd('\r');
|
||||
}
|
||||
}
|
||||
|
||||
// A command line with its literals: after each {n} the server says "+" and reads n bytes.
|
||||
public async Task<(string? Line, Queue<byte[]> Literals)> CommandAsync(Func<Task> continuation, CancellationToken cancellationToken)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
var literals = new Queue<byte[]>();
|
||||
while (true)
|
||||
{
|
||||
var line = await LineAsync(cancellationToken);
|
||||
if (line is null)
|
||||
{
|
||||
return (null, literals);
|
||||
}
|
||||
|
||||
text.Append(line);
|
||||
var match = Regex.Match(line, @"\{(?<n>[0-9]+)\}$");
|
||||
if (!match.Success)
|
||||
{
|
||||
return (text.ToString(), literals);
|
||||
}
|
||||
|
||||
await continuation();
|
||||
var length = int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture);
|
||||
var bytes = new byte[length];
|
||||
var read = 0;
|
||||
while (read < length)
|
||||
{
|
||||
if (_start == _end)
|
||||
{
|
||||
_start = 0;
|
||||
_end = await stream.ReadAsync(_buffer, cancellationToken);
|
||||
if (_end == 0)
|
||||
{
|
||||
return (null, literals);
|
||||
}
|
||||
}
|
||||
|
||||
var take = Math.Min(length - read, _end - _start);
|
||||
Array.Copy(_buffer, _start, bytes, read, take);
|
||||
_start += take;
|
||||
read += take;
|
||||
}
|
||||
|
||||
literals.Enqueue(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Infrastructure.Mail;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Mail;
|
||||
|
||||
[TestClass]
|
||||
public sealed class MimeParserTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Certified_mail_gives_the_files_of_the_enclosed_message()
|
||||
{
|
||||
var receipt = Encoding.UTF8.GetBytes("<RicevutaConsegna/>");
|
||||
var message = MimeParser.Parse(PecSamples.Envelope("sdi07@pec.fatturapa.it", "Consegna", ("IT01234567897_00001_RC_001.xml", receipt)));
|
||||
|
||||
Assert.AreEqual("multipart/signed", message.MediaType);
|
||||
Assert.AreEqual("POSTA CERTIFICATA: Consegna", message.Header("Subject"));
|
||||
var envelope = message.Parts[0];
|
||||
var original = envelope.Parts.Single(p => p.MediaType == "message/rfc822");
|
||||
Assert.AreEqual("postacert.eml", original.FileName);
|
||||
Assert.IsNotNull(original.Enclosed);
|
||||
Assert.AreEqual("sdi07@pec.fatturapa.it", original.Enclosed.Header("from"));
|
||||
var file = original.Enclosed.Attachments().Single();
|
||||
Assert.AreEqual("IT01234567897_00001_RC_001.xml", file.FileName);
|
||||
CollectionAssert.AreEqual(receipt, file.Body);
|
||||
|
||||
var all = message.Attachments().Select(a => a.FileName).ToList();
|
||||
CollectionAssert.AreEqual(new[] { "daticert.xml", "IT01234567897_00001_RC_001.xml", "smime.p7s" }, all);
|
||||
StringAssert.Contains(envelope.Parts[0].Text(), "il messaggio originale è allegato");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encoded_words_are_decoded_and_joined()
|
||||
{
|
||||
Assert.AreEqual("Fattura n° 12", MimeParser.DecodeHeader("=?utf-8?Q?Fattura_n=C2=B0?= 12"));
|
||||
Assert.AreEqual("perché sì", MimeParser.DecodeHeader("=?iso-8859-1?Q?perch=E9?= =?iso-8859-1?Q?_s=EC?="));
|
||||
Assert.AreEqual("città", MimeParser.DecodeHeader("=?UTF-8?B?Y2l0dMOg?="));
|
||||
Assert.AreEqual("plain =? text", MimeParser.DecodeHeader("plain =? text"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void File_names_follow_rfc_2231()
|
||||
{
|
||||
var message = Encoding.ASCII.GetBytes(
|
||||
"Content-Type: multipart/mixed; boundary=b\r\n\r\n" +
|
||||
"--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment; filename*=utf-8''fattura%20citt%C3%A0.xml\r\n\r\n<a/>\r\n" +
|
||||
"--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment;\r\n filename*0=\"IT0123_\"; filename*1=\"00001.xml\"\r\n\r\n<b/>\r\n" +
|
||||
"--b\r\nContent-Type: application/xml; name=\"=?utf-8?Q?n=C2=B0.xml?=\"\r\n\r\n<c/>\r\n" +
|
||||
"--b--\r\n");
|
||||
|
||||
var names = MimeParser.Parse(message).Attachments().Select(a => a.FileName).ToList();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "fattura città.xml", "IT0123_00001.xml", "n°.xml" }, names);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Quoted_printable_and_broken_input_do_not_throw()
|
||||
{
|
||||
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("a=b c"), MimeParser.QuotedPrintable(Encoding.ASCII.GetBytes("a=3Db =\r\nc")));
|
||||
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("ab"), MimeParser.Base64(Encoding.ASCII.GetBytes("YW\r\nI=")));
|
||||
|
||||
var unclosed = MimeParser.Parse(Encoding.ASCII.GetBytes("Content-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/plain\r\n\r\nhello"));
|
||||
Assert.AreEqual("hello", unclosed.Parts.Single().Text());
|
||||
|
||||
var noHeaders = MimeParser.Parse(Encoding.ASCII.GetBytes("just text"));
|
||||
Assert.AreEqual("text/plain", noHeaders.MediaType);
|
||||
}
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class ImapClientTests
|
||||
{
|
||||
private static readonly byte[] First = PecSamples.Envelope("sdi01@pec.fatturapa.it", "Uno", ("IT01234567897_00001_RC_001.xml", [1]));
|
||||
private static readonly byte[] Second = PecSamples.Acceptance("Due");
|
||||
|
||||
[TestMethod]
|
||||
public async Task Search_fetch_flag_and_move()
|
||||
{
|
||||
await using var server = new FakeImapServer("fatture@pec.example.it", "segreto", First, Second);
|
||||
var token = TestContext.CancellationToken;
|
||||
await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "fatture@pec.example.it", "segreto"), token);
|
||||
await imap.LoginAsync("fatture@pec.example.it", "segreto", token);
|
||||
Assert.IsTrue(imap.Capabilities.Contains("MOVE"));
|
||||
|
||||
Assert.AreEqual(2, await imap.SelectAsync("INBOX", token));
|
||||
var uids = await imap.SearchAsync("UNSEEN FROM " + ImapClient.Quote("fatturapa.it"), token);
|
||||
Assert.AreEqual(1, uids.Count);
|
||||
|
||||
var message = await imap.FetchAsync(uids[0], token);
|
||||
Assert.IsNotNull(message);
|
||||
CollectionAssert.AreEqual(First, message.Content);
|
||||
Assert.IsFalse(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"), "BODY.PEEK must not mark the message.");
|
||||
|
||||
await imap.AddFlagsAsync(uids[0], @"\Seen", token);
|
||||
Assert.IsTrue(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"));
|
||||
Assert.AreEqual(0, (await imap.SearchAsync("UNSEEN FROM \"fatturapa.it\"", token)).Count);
|
||||
|
||||
await imap.MoveAsync(uids[0], "Khaemhat/SDI", token);
|
||||
Assert.AreEqual(1, server.Mailboxes["Khaemhat/SDI"].Count);
|
||||
Assert.AreEqual(1, server.Mailboxes["INBOX"].Count);
|
||||
Assert.IsNull(await imap.FetchAsync(uids[0], token));
|
||||
await imap.LogoutAsync(token);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Without_move_the_message_is_copied_and_expunged()
|
||||
{
|
||||
await using var server = new FakeImapServer("u", "p", First) { SupportsMove = false };
|
||||
server.Mailboxes["Archivio"] = [];
|
||||
var token = TestContext.CancellationToken;
|
||||
await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "p"), token);
|
||||
await imap.LoginAsync("u", "p", token);
|
||||
await imap.SelectAsync("INBOX", token);
|
||||
|
||||
await imap.MoveAsync((await imap.SearchAsync("ALL", token))[0], "Archivio", token);
|
||||
|
||||
Assert.AreEqual(0, server.Mailboxes["INBOX"].Count);
|
||||
Assert.AreEqual(1, server.Mailboxes["Archivio"].Count);
|
||||
Assert.IsTrue(server.Commands.Any(c => c.Contains("UID COPY", StringComparison.Ordinal)));
|
||||
Assert.IsTrue(server.Commands.Any(c => c.EndsWith("EXPUNGE", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Password_with_accents_goes_as_a_literal_and_wrong_password_fails()
|
||||
{
|
||||
await using var server = new FakeImapServer("u", "pàssword");
|
||||
var token = TestContext.CancellationToken;
|
||||
await using (var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "pàssword"), token))
|
||||
{
|
||||
await imap.LoginAsync("u", "pàssword", token);
|
||||
}
|
||||
|
||||
Assert.IsTrue(server.Commands.Any(c => c.StartsWith("K0002 LOGIN \"u\" {", StringComparison.Ordinal)));
|
||||
|
||||
await using var wrong = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "x"), token);
|
||||
var error = await Assert.ThrowsExactlyAsync<MailException>(() => wrong.LoginAsync("u", "x", token));
|
||||
StringAssert.Contains(error.Message, "LOGIN ***");
|
||||
Assert.IsFalse(error.Message.Contains("\"x\"", StringComparison.Ordinal), "The password must not appear in the error.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Unreachable_server_gives_a_mail_exception()
|
||||
{
|
||||
var settings = new ImapSettings("127.0.0.1", 1, false, "u", "p");
|
||||
await Assert.ThrowsExactlyAsync<MailException>(() => ImapClient.ConnectAsync(settings, TestContext.CancellationToken));
|
||||
Assert.AreEqual("127.0.0.1:1", settings.ToString());
|
||||
Assert.AreEqual("1-Nov-2026", ImapClient.SearchDate(new DateOnly(2026, 11, 1)));
|
||||
Assert.ThrowsExactly<MailException>(() => ImapClient.Quote("città"));
|
||||
}
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Mail;
|
||||
|
||||
/// <summary>
|
||||
/// Certified mail messages built in the test, shaped like the ones a PEC provider delivers: a <c>multipart/mixed</c>
|
||||
/// envelope with the text of the provider, <c>daticert.xml</c>, the original message as <c>postacert.eml</c>
|
||||
/// (<c>message/rfc822</c>) and the signature <c>smime.p7s</c>. Nothing is downloaded.
|
||||
/// </summary>
|
||||
internal static class PecSamples
|
||||
{
|
||||
/// <summary>A certified message whose original was sent by <paramref name="sender"/> with the given files.</summary>
|
||||
public static byte[] Envelope(string sender, string subject, params (string Name, byte[] Content)[] files)
|
||||
{
|
||||
var inner = new StringBuilder()
|
||||
.Append("From: ").Append(sender).Append("\r\n")
|
||||
.Append("To: fatture@pec.example.it\r\n")
|
||||
.Append("Subject: ").Append(subject).Append("\r\n")
|
||||
.Append("MIME-Version: 1.0\r\n")
|
||||
.Append("Content-Type: multipart/mixed; boundary=\"inner-b\"\r\n\r\n")
|
||||
.Append("--inner-b\r\n")
|
||||
.Append("Content-Type: text/plain; charset=utf-8\r\n\r\n")
|
||||
.Append("Messaggio del Sistema di Interscambio\r\n");
|
||||
foreach (var (name, content) in files)
|
||||
{
|
||||
inner.Append("--inner-b\r\n")
|
||||
.Append("Content-Type: application/octet-stream; name=\"").Append(name).Append("\"\r\n")
|
||||
.Append("Content-Transfer-Encoding: base64\r\n")
|
||||
.Append("Content-Disposition: attachment; filename=\"").Append(name).Append("\"\r\n\r\n")
|
||||
.Append(Wrap(Convert.ToBase64String(content))).Append("\r\n");
|
||||
}
|
||||
|
||||
inner.Append("--inner-b--\r\n");
|
||||
|
||||
var outer = new StringBuilder()
|
||||
.Append("From: \"Per conto di: ").Append(sender).Append("\" <posta-certificata@pec.provider.example>\r\n")
|
||||
.Append("To: fatture@pec.example.it\r\n")
|
||||
.Append("Subject: =?utf-8?B?").Append(Convert.ToBase64String(Encoding.UTF8.GetBytes("POSTA CERTIFICATA: " + subject))).Append("?=\r\n")
|
||||
.Append("X-Trasporto: posta-certificata\r\n")
|
||||
.Append("MIME-Version: 1.0\r\n")
|
||||
.Append("Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256;\r\n boundary=\"signed-b\"\r\n\r\n")
|
||||
.Append("--signed-b\r\n")
|
||||
.Append("Content-Type: multipart/mixed; boundary=\"outer-b\"\r\n\r\n")
|
||||
.Append("--outer-b\r\n")
|
||||
.Append("Content-Type: text/plain; charset=iso-8859-1\r\n")
|
||||
.Append("Content-Transfer-Encoding: quoted-printable\r\n\r\n")
|
||||
.Append("Messaggio di posta certificata: il messaggio originale =E8 allegato.\r\n")
|
||||
.Append("--outer-b\r\n")
|
||||
.Append("Content-Type: application/xml; name=daticert.xml\r\n")
|
||||
.Append("Content-Disposition: inline; filename=daticert.xml\r\n\r\n")
|
||||
.Append("<postacert tipo=\"posta-certificata\"/>\r\n")
|
||||
.Append("--outer-b\r\n")
|
||||
.Append("Content-Type: message/rfc822; name=postacert.eml\r\n")
|
||||
.Append("Content-Disposition: inline; filename=postacert.eml\r\n\r\n")
|
||||
.Append(inner)
|
||||
.Append("--outer-b--\r\n")
|
||||
.Append("--signed-b\r\n")
|
||||
.Append("Content-Type: application/pkcs7-signature; name=smime.p7s\r\n")
|
||||
.Append("Content-Transfer-Encoding: base64\r\n")
|
||||
.Append("Content-Disposition: attachment; filename=smime.p7s\r\n\r\n")
|
||||
.Append(Convert.ToBase64String([1, 2, 3, 4])).Append("\r\n")
|
||||
.Append("--signed-b--\r\n");
|
||||
return Encoding.UTF8.GetBytes(outer.ToString());
|
||||
}
|
||||
|
||||
/// <summary>The acceptance receipt of the provider: no original message, no files of the SDI.</summary>
|
||||
public static byte[] Acceptance(string subject) => Encoding.UTF8.GetBytes(
|
||||
"From: posta-certificata@pec.provider.example\r\n" +
|
||||
"Subject: ACCETTAZIONE: " + subject + "\r\n" +
|
||||
"X-Ricevuta: accettazione\r\n" +
|
||||
"Content-Type: multipart/mixed; boundary=\"a\"\r\n\r\n" +
|
||||
"--a\r\nContent-Type: text/plain\r\n\r\nIl messaggio e' stato accettato dal sistema.\r\n" +
|
||||
"--a\r\nContent-Type: application/xml; name=daticert.xml\r\nContent-Disposition: attachment; filename=daticert.xml\r\n\r\n<postacert tipo=\"accettazione\"/>\r\n" +
|
||||
"--a--\r\n");
|
||||
|
||||
private static string Wrap(string base64)
|
||||
{
|
||||
var lines = new StringBuilder();
|
||||
for (var i = 0; i < base64.Length; i += 76)
|
||||
{
|
||||
lines.Append(base64, i, Math.Min(76, base64.Length - i)).Append("\r\n");
|
||||
}
|
||||
|
||||
return lines.ToString().TrimEnd();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user