using System.Collections.Concurrent; using System.Net; using System.Text; using System.Text.Json; using Khaemhat.Fiscal.Abstractions; using Khaemhat.Fiscal.Italy.Sdi; using Khaemhat.Infrastructure.Mail; using Khaemhat.Infrastructure.Tests.Mail; namespace Khaemhat.Fiscal.Italy.Tests; [TestClass] public sealed class PecSdiTransportTests { private const string Mailbox = "fatture@pec.example.it"; private const string Secret = "test-secret"; public TestContext TestContext { get; set; } = null!; private static EInvoiceChannelSettings Settings(FakeSmtpServer? smtp, FakeImapServer? imap, string? archive = null, string? exchange = null) => new() { Code = PecSdiTransport.ChannelCode, Mailbox = Mailbox, SmtpHost = "127.0.0.1", SmtpPort = smtp?.Port ?? 1, ImapHost = "127.0.0.1", ImapPort = imap?.Port ?? 1, Tls = false, User = Mailbox, Password = Secret, ArchiveFolder = archive, ExchangeAddress = exchange, }; [TestMethod] public async Task First_file_goes_to_sdi01_then_to_the_assigned_address() { await using var smtp = new FakeSmtpServer(); var transport = new PecSdiTransport(); var file = new EInvoiceOutgoing("IT01234567897_00001.xml", Encoding.UTF8.GetBytes(""), "FT 1/2026"); var first = await transport.SendAsync(Settings(smtp, null), file, TestContext.CancellationToken); var next = await transport.SendAsync(Settings(smtp, null, exchange: "sdi23@pec.fatturapa.it"), file, TestContext.CancellationToken); Assert.IsTrue(first.Accepted, first.Error); Assert.IsTrue(next.Accepted, next.Error); var messages = smtp.Messages.ToList(); Assert.AreEqual("sdi01@pec.fatturapa.it", messages[0].To.Single()); Assert.AreEqual("sdi23@pec.fatturapa.it", messages[1].To.Single()); Assert.AreEqual(Mailbox, messages[0].From); var sent = MimeParser.Parse(messages[0].Content); var attachment = sent.Attachments().Single(); Assert.AreEqual("IT01234567897_00001.xml", attachment.FileName); CollectionAssert.AreEqual(file.Content, attachment.Body); } [TestMethod] public async Task Refused_recipient_is_reported_not_thrown() { await using var smtp = new FakeSmtpServer { RejectRecipient = "550 Mailbox unavailable" }; var result = await new PecSdiTransport().SendAsync(Settings(smtp, null), new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); Assert.IsFalse(result.Accepted); StringAssert.Contains(result.Error, "550"); } [TestMethod] public async Task Fetch_reads_only_the_sdi_and_learns_its_address() { var receipt = Encoding.UTF8.GetBytes(""); var invoice = Encoding.UTF8.GetBytes(""); var metadata = Encoding.UTF8.GetBytes(""); await using var imap = new FakeImapServer(Mailbox, Secret, PecSamples.Envelope("sdi07@pec.fatturapa.it", "Ricevuta di consegna", ("IT01234567897_00001_RC_001.xml", receipt)), PecSamples.Acceptance("Invio file IT01234567897_00002.xml"), PecSamples.Envelope("sdi07@pec.fatturapa.it", "Invio File 99", ("IT09876543217_0A1B2.xml", invoice), ("IT09876543217_0A1B2_MT_001.xml", metadata))); var transport = new PecSdiTransport(); var settings = Settings(null, imap, archive: "Khaemhat/SDI"); var result = await transport.FetchAsync(settings, TestContext.CancellationToken); Assert.AreEqual(2, result.MessagesRead, "The acceptance of the provider is not a message of the SDI."); CollectionAssert.AreEqual( new[] { "IT01234567897_00001_RC_001.xml", "IT09876543217_0A1B2.xml", "IT09876543217_0A1B2_MT_001.xml" }, result.Files.Select(f => f.FileName).ToList()); Assert.AreEqual("sdi07@pec.fatturapa.it", result.ExchangeAddress); Assert.AreEqual("sdi07@pec.fatturapa.it", result.Files[0].Sender); CollectionAssert.AreEqual(receipt, result.Files[0].Content); await transport.AcknowledgeAsync(settings, result.Files.Select(f => f.MessageKey).ToList(), TestContext.CancellationToken); Assert.AreEqual(2, imap.Mailboxes["Khaemhat/SDI"].Count); Assert.AreEqual(1, imap.Mailboxes["INBOX"].Count, "Only the acceptance of the provider is left."); var again = await transport.FetchAsync(settings with { ExchangeAddress = "sdi07@pec.fatturapa.it" }, TestContext.CancellationToken); Assert.AreEqual(0, again.Files.Count); Assert.IsNull(again.ExchangeAddress, "The address did not change."); } [TestMethod] public async Task Without_archive_messages_are_marked_as_read() { await using var imap = new FakeImapServer(Mailbox, Secret, PecSamples.Envelope("sdi01@pec.fatturapa.it", "Scarto", ("IT01234567897_00003_NS_001.xml", [1, 2]))); var transport = new PecSdiTransport(); var settings = Settings(null, imap); var first = await transport.FetchAsync(settings, TestContext.CancellationToken); Assert.AreEqual(1, first.Files.Count); Assert.AreEqual(1, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count, "Not acknowledged: read again."); await transport.AcknowledgeAsync(settings, [first.Files[0].MessageKey], TestContext.CancellationToken); Assert.AreEqual(0, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count); Assert.IsTrue(imap.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen")); } [TestMethod] public async Task Check_reports_login_and_missing_settings() { await using var smtp = new FakeSmtpServer(); await using var imap = new FakeImapServer(Mailbox, Secret); var transport = new PecSdiTransport(); var ok = await transport.CheckAsync(Settings(smtp, imap), TestContext.CancellationToken); var wrong = await transport.CheckAsync(Settings(smtp, imap) with { Password = "other" }, TestContext.CancellationToken); var missing = await transport.CheckAsync(new EInvoiceChannelSettings { Code = "PEC" }, TestContext.CancellationToken); Assert.IsTrue(ok.Success, ok.Message); Assert.IsFalse(wrong.Success); Assert.IsFalse(wrong.Message.Contains("other", StringComparison.Ordinal), "The password must not appear."); Assert.IsFalse(missing.Success); } [TestMethod] public void Sdi_addresses_are_recognised() { Assert.AreEqual("sdi07@pec.fatturapa.it", PecSdiTransport.SdiAddress("\"Per conto di: SDI07@pec.fatturapa.it\" ")); Assert.IsNull(PecSdiTransport.SdiAddress("info@fatturapa.it")); } } /// An HTTP handler that answers from a function and keeps the requests (with their bodies). internal sealed class StubHandler(Func answer, ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)> log) : HttpMessageHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var body = request.Content is null ? [] : await request.Content.ReadAsByteArrayAsync(cancellationToken); log.Enqueue((request, body)); return answer(request, body); } } [TestClass] public sealed class SdiCoopTransportTests { public TestContext TestContext { get; set; } = null!; private static HttpResponseMessage Soap(string body) => new(HttpStatusCode.OK) { Content = new StringContent( "" + body + "", Encoding.UTF8, "text/xml"), }; [TestMethod] public async Task Send_posts_mtom_and_reads_the_identifier() { var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); var transport = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap( "1112223332026-11-13T10:00:00.000+01:00"), log)); var content = Encoding.UTF8.GetBytes(""); var settings = new EInvoiceChannelSettings { Code = "SDICOOP", TestEnvironment = true }; var result = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", content, null), TestContext.CancellationToken); Assert.IsTrue(result.Accepted, result.Error); Assert.AreEqual("111222333", result.ExchangeId); var (request, body) = log.Single(); Assert.AreEqual(SdiCoopTransport.TestEndpoint, request.RequestUri!.ToString()); Assert.AreEqual("multipart/related", request.Content!.Headers.ContentType!.MediaType); Assert.AreEqual("\"" + SdiCoopTransport.RiceviFileAction + "\"", request.Headers.GetValues("SOAPAction").Single()); // What the SDI would read: the envelope with the file put back in place of the reference. var envelope = SdiCoopMessages.Envelope(request.Content.Headers.ContentType.ToString(), body)!; Assert.AreEqual("IT01234567897_00001.xml", envelope.Descendants().Single(e => e.Name.LocalName == "NomeFile").Value); CollectionAssert.AreEqual(content, Convert.FromBase64String(envelope.Descendants().Single(e => e.Name.LocalName == "File").Value)); } [TestMethod] public async Task Errors_of_the_service_are_reported() { var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); var error = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("EI03"), log)); var fault = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("xBad request"), log)); var settings = new EInvoiceChannelSettings { Code = "SDICOOP" }; var file = new EInvoiceOutgoing("a.xml", [1], null); var refused = await error.SendAsync(settings, file, TestContext.CancellationToken); var faulted = await fault.SendAsync(settings, file, TestContext.CancellationToken); var noCertificate = await new SdiCoopTransport().SendAsync(settings, file, TestContext.CancellationToken); StringAssert.Contains(refused.Error, "EI03"); StringAssert.Contains(faulted.Error, "Bad request"); Assert.IsFalse(noCertificate.Accepted); Assert.AreEqual(SdiCoopTransport.ProductionEndpoint, SdiCoopTransport.EndpointOf(settings)); } [TestMethod] public void Inbound_messages_are_read_inline_and_mtom() { var receipt = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); var inline = Encoding.UTF8.GetBytes( "" + "42IT01234567897_00001_NS_001.xml" + receipt + ""); var notification = SdiCoopMessages.Read("text/xml; charset=utf-8", inline)!; Assert.AreEqual("Notifica", notification.Operation); Assert.AreEqual("42", notification.ExchangeId); Assert.AreEqual("", Encoding.UTF8.GetString(notification.Files.Single().Content)); Assert.IsFalse(SdiCoopMessages.Answer(notification).Contains("ER01", StringComparison.Ordinal)); const string Boundary = "uuid:b1"; var mtom = Encoding.UTF8.GetBytes( "--" + Boundary + "\r\nContent-Type: application/xop+xml; type=\"text/xml\"\r\nContent-ID: \r\n\r\n" + "" + "77IT09876543217_0A1B2.xml.p7m" + "IT09876543217_0A1B2_MT_001.xml" + "\r\n" + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: \r\n\r\nP7M\r\n" + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-ID: \r\n\r\n\r\n" + "--" + Boundary + "--\r\n"); var invoice = SdiCoopMessages.Read("multipart/related; type=\"application/xop+xml\"; boundary=\"" + Boundary + "\"", mtom)!; Assert.AreEqual("RiceviFatture", invoice.Operation); Assert.AreEqual("77", invoice.ExchangeId); Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", invoice.Files[0].FileName); Assert.AreEqual("P7M", Encoding.UTF8.GetString(invoice.Files[0].Content)); Assert.AreEqual("", Encoding.UTF8.GetString(invoice.Files[1].Content)); StringAssert.Contains(SdiCoopMessages.Answer(invoice), "ER01"); Assert.IsNull(SdiCoopMessages.Read("text/xml", Encoding.UTF8.GetBytes(""))); StringAssert.Contains(SdiCoopMessages.Answer(null), "Fault"); } } [TestClass] public sealed class IntermediaryTransportTests { public TestContext TestContext { get; set; } = null!; private static HttpResponseMessage Json(object value, HttpStatusCode status = HttpStatusCode.OK) => new(status) { Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json") }; [TestMethod] public async Task Intermediary_a_sends_lists_and_acknowledges() { var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); var waiting = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); var transport = new IntermediaryATransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch { ("POST", "/v1/invoices") => Json(new { id = "up-1", sdiId = (string?)null }), ("GET", "/v1/files") => Json(new[] { new { id = "f-9", fileName = "IT01234567897_00001_RC_001.xml", content = waiting, receivedAt = "2026-11-13T09:00:00Z" } }), ("POST", "/v1/files/f-9/ack") => new HttpResponseMessage(HttpStatusCode.NoContent), ("GET", "/v1/status") => Json(new { ok = true }), _ => new HttpResponseMessage(HttpStatusCode.NotFound), }, log)); var settings = new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://int-a.example/v1/", ApiKey = "test-key" }; var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", [1, 2, 3], null), TestContext.CancellationToken); var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); await transport.AcknowledgeAsync(settings, [fetched.Files[0].MessageKey], TestContext.CancellationToken); var check = await transport.CheckAsync(settings, TestContext.CancellationToken); Assert.IsTrue(sent.Accepted, sent.Error); Assert.AreEqual("up-1", sent.MessageId); var post = log.First(); Assert.AreEqual("Bearer", post.Request.Headers.Authorization!.Scheme); Assert.AreEqual("IT01234567897_00001.xml", post.Request.Headers.GetValues("X-File-Name").Single()); CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, post.Body); Assert.AreEqual("IT01234567897_00001_RC_001.xml", fetched.Files.Single().FileName); Assert.AreEqual("", Encoding.UTF8.GetString(fetched.Files[0].Content)); Assert.IsTrue(log.Any(l => l.Request.RequestUri!.AbsolutePath == "/v1/files/f-9/ack")); Assert.IsTrue(check.Success, check.Message); } [TestMethod] public async Task Intermediary_b_uses_basic_authentication_and_json() { var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); var transport = new IntermediaryBTransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch { ("POST", "/api/v1/send") => Json(new { uploadId = "u-5", identificativoSdi = "998877" }), ("GET", "/api/v1/inbox") => Json(new { items = new[] { new { key = "k1", name = "IT09876543217_0A1B2.xml", data = Convert.ToBase64String([9]), date = "2026-11-12" } } }), ("DELETE", "/api/v1/inbox/k1") => new HttpResponseMessage(HttpStatusCode.OK), ("GET", "/api/v1/ping") => new HttpResponseMessage(HttpStatusCode.Unauthorized), _ => new HttpResponseMessage(HttpStatusCode.NotFound), }, log)); var settings = new EInvoiceChannelSettings { Code = "INTB", Endpoint = "https://int-b.example", User = "azienda", Password = "test-secret" }; var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00002.xml", [7], null), TestContext.CancellationToken); var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); await transport.AcknowledgeAsync(settings, ["k1"], TestContext.CancellationToken); var check = await transport.CheckAsync(settings, TestContext.CancellationToken); var missing = await transport.SendAsync(settings with { Password = null }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); Assert.AreEqual("998877", sent.ExchangeId); Assert.AreEqual("Basic", log.First().Request.Headers.Authorization!.Scheme); using (var body = JsonDocument.Parse(log.First().Body)) { Assert.AreEqual("IT01234567897_00002.xml", body.RootElement.GetProperty("fileName").GetString()); } Assert.AreEqual("k1", fetched.Files.Single().MessageKey); Assert.IsTrue(log.Any(l => l.Request.Method == HttpMethod.Delete)); Assert.IsFalse(check.Success); Assert.IsFalse(missing.Accepted); } [TestMethod] public async Task Refused_file_is_reported_with_the_message_of_the_api() { var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); var transport = new IntermediaryATransport(_ => new StubHandler((_, _) => Json(new { error = "Invalid XML" }, HttpStatusCode.UnprocessableEntity), log)); var result = await transport.SendAsync( new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://a.example", ApiKey = "k" }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); Assert.IsFalse(result.Accepted); Assert.AreEqual("422: Invalid XML", result.Error); } [TestMethod] public void The_pack_offers_the_four_channels() { var channels = new ItalyFiscalPack().GetFeature()!; CollectionAssert.AreEqual(new[] { "PEC", "SDICOOP", "INTA", "INTB" }, channels.All.Select(c => c.Code).ToList()); Assert.IsFalse(channels.Find("sdicoop")!.Transport.Polls); Assert.IsNull(channels.Find("X")); } }