feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)

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:
Alby96andClaude Opus 5.5 committed 2026-11-13 11:51:31 +01:00
1 parent 0debd82983
commit 709bb13532
26 files changed
+5916 -243

No files matched your search

@@ -159,7 +159,7 @@ public sealed class FatturaPaReaderTests
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>100.00</ImponibileImporto><Imposta>22.00</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
""";
private static IncomingInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml));
private static EInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml));
[TestMethod]
public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission()
@@ -209,14 +209,14 @@ public sealed class FatturaPaReaderTests
Assert.IsNull(invoice.Rounding);
CollectionAssert.AreEqual(new[] { "Fornitura di marzo", "Consegna in cantiere" }, invoice.Causals.ToArray());
Assert.IsFalse(invoice.Art73);
Assert.AreEqual(new IncomingDiscount(false, 2.00m, null), invoice.Discounts[0]);
Assert.AreEqual(new IncomingDiscount(true, null, 1.50m), invoice.Discounts[1]);
Assert.AreEqual(new EInvoiceDiscount(false, 2.00m, null), invoice.Discounts[0]);
Assert.AreEqual(new EInvoiceDiscount(true, null, 1.50m), invoice.Discounts[1]);
Assert.HasCount(3, invoice.Lines);
var bolts = invoice.Lines[0];
Assert.AreEqual(1, bolts.Number);
Assert.AreEqual(new IncomingItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]);
Assert.AreEqual(new IncomingItemCode("EAN", "8001234567895"), bolts.Codes[1]);
Assert.AreEqual(new EInvoiceItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]);
Assert.AreEqual(new EInvoiceItemCode("EAN", "8001234567895"), bolts.Codes[1]);
Assert.AreEqual("Bulloni M8 zincati", bolts.Description);
Assert.AreEqual(100m, bolts.Quantity);
Assert.AreEqual("PZ", bolts.Unit);
@@ -224,7 +224,7 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual(45m, bolts.TotalPrice);
Assert.AreEqual(22m, bolts.TaxRate);
Assert.IsNull(bolts.Nature);
Assert.AreEqual(new IncomingDiscount(false, 10m, null), bolts.Discounts.Single());
Assert.AreEqual(new EInvoiceDiscount(false, 10m, null), bolts.Discounts.Single());
Assert.IsFalse(bolts.Withheld);
Assert.AreEqual(4m, invoice.Lines[1].TaxRate);
@@ -238,13 +238,13 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual("CC-12", contribution.AdministrativeReference);
Assert.HasCount(3, invoice.TaxSummary);
Assert.AreEqual(new IncomingTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]);
Assert.AreEqual(new EInvoiceTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]);
Assert.AreEqual(4m, invoice.TaxSummary[1].Rate);
Assert.AreEqual("N2.2", invoice.TaxSummary[2].Nature);
Assert.AreEqual("Non soggetto art. 15 DPR 633/72", invoice.TaxSummary[2].LegalReference);
Assert.HasCount(2, invoice.Payments);
Assert.AreEqual(new IncomingPayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]);
Assert.AreEqual(new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]);
Assert.AreEqual("BPMOIT22XXX", invoice.Payments[1].Bic);
Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary);
Assert.IsEmpty(invoice.Attachments);
@@ -377,9 +377,9 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual("Giulia", file.Supplier.FirstName);
Assert.AreEqual("Bianchi", file.Supplier.LastName);
Assert.AreEqual("Giulia Bianchi", file.Supplier.DisplayName);
Assert.AreEqual(new IncomingWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single());
Assert.AreEqual(new IncomingStampDuty(true, 2m), invoice.StampDuty);
Assert.AreEqual(new IncomingSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single());
Assert.AreEqual(new EInvoiceWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single());
Assert.AreEqual(new EInvoiceStampDuty(true, 2m), invoice.StampDuty);
Assert.AreEqual(new EInvoiceSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single());
Assert.AreEqual(1270.88m, invoice.Total);
Assert.AreEqual(0.01m, invoice.Rounding);
Assert.IsTrue(invoice.Art73);
@@ -0,0 +1,335 @@
using System.Text;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>
/// The writer and the validator of FatturaPA (issue #74): every file written is valid against the schema, reads back to
/// the same content and passes the checks of the exchange system; each check is shown failing on a broken invoice.
/// The parties are fictitious, with VAT numbers that only pass the check digit.
/// </summary>
[TestClass]
public sealed class FatturaPaWriterTests
{
private static readonly FatturaPaWriter Writer = new();
private static readonly FatturaPaValidator Validator = new();
private static readonly FatturaPaReader Reader = new();
/// <summary>The company: an Italian limited company in the companies register.</summary>
public static EInvoiceParty Company { get; } = new(
"IT", "01234567897", "01234567897", "Khaemhat Demo S.r.l.", null, null,
"Via dei Granai", "57", "10121", "Torino", "TO", "IT", "RF01", "amministrazione@demo.example", "011 555 1234", "TO", "123456")
{
ShareCapital = 10_000m,
Shareholders = "SU",
LiquidationStatus = "LN",
};
/// <summary>A business customer.</summary>
public static EInvoiceParty Customer { get; } = new(
"IT", "09876543217", null, "Officine Esempio S.p.A.", null, null,
"Corso Milano", "4", "20121", "Milano", "MI", "IT", null, null, null, null, null);
/// <summary>An invoice with two rates, a discount, a delivery note and two installments.</summary>
/// <returns>The file.</returns>
public static EInvoiceFile Invoice() => new(
"IT01234567897_00001.xml", "FPR12", "00001", "ABC1234", Company, Customer,
[
new EInvoiceBody(
"TD01", "EUR", new DateOnly(2026, 10, 9), "FT/2026/000414", 1_311.62m, null,
["Fornitura di ottobre"], false, [], null, [], [],
[new EInvoiceReference("ORD-77", new DateOnly(2026, 9, 30), [], null, null)], [], [],
[new EInvoiceReference("DDT/2026/88", new DateOnly(2026, 10, 2), [1, 2], null, null)],
[
new EInvoiceLine(1, [new EInvoiceItemCode("INTERNO", "VIT-08")], "Viti autofilettanti 8 mm", 100m, "PZ", 0.85m, 80.75m, 22m, null,
[new EInvoiceDiscount(false, 5m, null)], false, null, null, null, null),
new EInvoiceLine(2, [], "Trapano a percussione", 2m, "PZ", 489.50m, 979m, 22m, null, [], false, null, null, null, null),
new EInvoiceLine(3, [], "Manuale tecnico", 1m, "PZ", 18m, 18m, 4m, null, [], false, null, null, null, null),
],
[
new EInvoiceTaxSummary(22m, null, 1_059.75m, 233.15m, "I", null, null, null),
new EInvoiceTaxSummary(4m, null, 18m, 0.72m, "I", null, null, null),
],
[
new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 11, 30), 655.81m, "IT60X0542811101000000123456", null, null),
new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 12, 31), 655.81m, "IT60X0542811101000000123456", null, null),
],
[]),
],
null, [])
{
TransmitterCountry = "IT",
TransmitterId = "01234567897",
};
[TestMethod]
public void FileName_UsesTheTransmitterAndAFiveCharacterBase36Progressive()
{
Assert.AreEqual("IT01234567897_00001.xml", Writer.FileName("IT", "01234567897", 1));
Assert.AreEqual("00010", Writer.Progressive(36));
Assert.AreEqual("0000Z", Writer.Progressive(35));
Assert.AreEqual("ZZZZZ", Writer.Progressive(60_466_175));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => Writer.Progressive(0));
}
[TestMethod]
public void Write_Invoice_IsValidAgainstTheSchemaAndPassesTheChecks()
{
var file = Invoice();
Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var xml = Writer.Write(file);
var problems = Validator.ValidateXml(xml);
Assert.IsEmpty(problems, string.Join("\n", problems.Select(p => p.Path + ": " + p.Message)));
}
[TestMethod]
public void Write_Invoice_ReadsBackToTheSameContent()
{
var file = Invoice();
var read = Reader.Read(file.FileName, Writer.Write(file));
Assert.AreEqual("FPR12", read.TransmissionFormat);
Assert.AreEqual("ABC1234", read.RecipientCode);
Assert.AreEqual("01234567897", read.TransmitterId);
Assert.AreEqual("Khaemhat Demo S.r.l.", read.Supplier.Name);
Assert.AreEqual(10_000m, read.Supplier.ShareCapital);
Assert.AreEqual("SU", read.Supplier.Shareholders);
Assert.AreEqual("0115551234", read.Supplier.Phone);
var body = read.Invoices.Single();
Assert.AreEqual("FT/2026/000414", body.Number);
Assert.AreEqual(1_311.62m, body.Total);
Assert.HasCount(3, body.Lines);
Assert.AreEqual(80.75m, body.Lines[0].TotalPrice);
Assert.AreEqual(5m, body.Lines[0].Discounts.Single().Percent);
Assert.AreEqual("VIT-08", body.Lines[0].Codes.Single().Value);
Assert.HasCount(2, body.TaxSummary);
Assert.AreEqual("DDT/2026/88", body.DeliveryNotes.Single().Id);
CollectionAssert.AreEqual(new[] { 1, 2 }, body.DeliveryNotes.Single().LineNumbers.ToArray());
Assert.AreEqual("ORD-77", body.Orders.Single().Id);
Assert.HasCount(2, body.Payments);
Assert.AreEqual("TP01", body.PaymentConditions);
}
[TestMethod]
public void Write_RootIsQualifiedAndChildrenAreNot()
{
var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice()))).Root!;
Assert.AreEqual(FatturaPaWriter.Namespace, root.Name.NamespaceName);
Assert.AreEqual("FPR12", root.Attribute("versione")!.Value);
Assert.IsTrue(root.Elements().All(e => e.Name.NamespaceName.Length == 0));
}
[TestMethod]
public void Write_ProfessionalFee_WithWithholdingFundStampAndNature()
{
var professional = Company with { TaxRegime = "RF19" };
var body = new EInvoiceBody(
"TD06", "EUR", new DateOnly(2026, 10, 12), "P/2026/7", 1_286.80m, null, [], false,
[new EInvoiceWithholding("RT01", 200m, 20m, "A")], new EInvoiceStampDuty(true, 2m),
[new EInvoiceSocialSecurity("TC04", 4m, 40m, 1_000m, 22m, false, null)], [], [], [], [], [],
[
new EInvoiceLine(1, [], "Consulenza tecnica di ottobre", null, null, 1_000m, 1_000m, 22m, null, [], true, null, null, null, null),
new EInvoiceLine(2, [], "Diritti di segreteria anticipati", null, null, 16m, 16m, 0m, "N1", [], false, null, null, null, null),
],
[
new EInvoiceTaxSummary(22m, null, 1_040m, 228.80m, "I", null, null, null),
new EInvoiceTaxSummary(0m, "N1", 16m, 0m, null, "Art. 15 DPR 633/72", null, null),
],
[new EInvoicePayment("TP02", "MP05", null, 1_086.80m, null, null, null)],
[new EInvoiceAttachment("cortesia.pdf", "PDF", "Copia di cortesia", Encoding.ASCII.GetBytes("%PDF-1.4"))]);
var file = Invoice() with { Supplier = professional, Invoices = [body] };
var errors = Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList();
Assert.IsEmpty(errors, string.Join("\n", errors));
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml).Invoices.Single();
Assert.AreEqual(200m, read.Withholdings.Single().Amount);
Assert.AreEqual("TC04", read.SocialSecurity.Single().Fund);
Assert.AreEqual(2m, read.StampDuty!.Amount);
Assert.IsTrue(read.Lines[0].Withheld);
Assert.AreEqual("N1", read.Lines[1].Nature);
Assert.AreEqual("%PDF-1.4", Encoding.ASCII.GetString(read.Attachments.Single().Content));
}
[TestMethod]
public void Write_PublicAdministration_SplitPaymentWithCigCupAndIntentData()
{
var administration = Customer with { VatNumber = null, TaxCode = "80012345676", Name = "Comune di Esempio" };
var line = new EInvoiceLine(1, [], "Manutenzione impianto", 1m, null, 1_000m, 1_000m, 22m, null, [], false, null, null, null, "UFF-12")
{
OtherData = [new EInvoiceOtherData("INTENTO", "26012345678901-000001", null, new DateOnly(2026, 1, 8))],
};
var body = new EInvoiceBody(
"TD01", "EUR", new DateOnly(2026, 9, 30), "FT/2026/390", 1_220m, null, [], false, [], null, [], [],
[new EInvoiceReference("DET-2026-15", new DateOnly(2026, 6, 1), [], "ZAB1234567", "J51B26000010007")], [], [], [],
[line],
[new EInvoiceTaxSummary(22m, null, 1_000m, 220m, "S", null, null, null)],
[new EInvoicePayment("TP02", "MP05", new DateOnly(2026, 10, 30), 1_000m, "IT60X0542811101000000123456", null, null)],
[]);
var file = Invoice() with { TransmissionFormat = "FPA12", RecipientCode = "UFE7GH", Customer = administration, Invoices = [body] };
Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml);
Assert.AreEqual("FPA12", read.TransmissionFormat);
Assert.AreEqual("ZAB1234567", read.Invoices[0].Orders.Single().Cig);
Assert.AreEqual("J51B26000010007", read.Invoices[0].Orders.Single().Cup);
Assert.AreEqual("S", read.Invoices[0].TaxSummary.Single().Exigibility);
Assert.AreEqual("INTENTO", read.Invoices[0].Lines[0].OtherData.Single().Type);
Assert.AreEqual("UFF-12", read.Invoices[0].Lines[0].AdministrativeReference);
}
[TestMethod]
public void Write_ForeignCustomerAndConsumerWithPec()
{
var foreign = Customer with { CountryCode = "DE", VatNumber = "DE123456789", Country = "DE", PostalCode = "80331", Province = null, City = "München", Name = "Alpenbau GmbH" };
var file = Invoice() with { RecipientCode = "XXXXXXX", Customer = foreign };
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml);
Assert.AreEqual("00000", read.Customer.PostalCode);
Assert.IsNull(read.Customer.Province);
Assert.AreEqual("München", read.Customer.City);
var consumer = new EInvoiceParty("IT", null, "RSSMRA80A01H501U", null, "Mario", "Rossi", "Via Po", "1", "10124", "Torino", "TO", "IT", null, null, null, null, null);
var toConsumer = Invoice() with { RecipientCode = "0000000", RecipientPec = "mario.rossi@pec.example.it", Customer = consumer };
Assert.IsEmpty(Validator.Validate(toConsumer).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var consumerXml = Writer.Write(toConsumer);
Assert.IsEmpty(Validator.ValidateXml(consumerXml));
Assert.AreEqual("mario.rossi@pec.example.it", Reader.Read(toConsumer.FileName, consumerXml).RecipientPec);
}
[TestMethod]
public void Write_TextOutsideLatin1_IsReplacedAndCut()
{
Assert.AreEqual("Viti 'speciali' - EUR 5...", FatturaPaWriter.Text("Viti ‘speciali’ — € 5…", 100));
Assert.AreEqual("abc", FatturaPaWriter.Text("abcdef", 3));
Assert.AreEqual("a ? b", FatturaPaWriter.Text("a 漢 b", 10));
var line = Invoice().Invoices[0].Lines[2] with { Description = "Manuale “tecnico” – ed. 2026 ✓" };
var body = Invoice().Invoices[0] with { Lines = [.. Invoice().Invoices[0].Lines.Take(2), line] };
Assert.IsEmpty(Validator.ValidateXml(Writer.Write(Invoice() with { Invoices = [body] })));
}
[TestMethod]
public void Write_LongCausal_IsSplitIntoFieldsOf200Characters()
{
var note = string.Join(' ', Enumerable.Repeat("Consegna al magazzino di via dei Granai.", 12));
var body = Invoice().Invoices[0] with { Causals = [note] };
var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice() with { Invoices = [body] }))).Root!;
var causals = root.Descendants("Causale").Select(c => c.Value).ToList();
Assert.IsGreaterThan(1, causals.Count);
Assert.IsTrue(causals.All(c => c.Length <= 200));
Assert.AreEqual(note.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(causals).Replace(" ", string.Empty, StringComparison.Ordinal));
}
[TestMethod]
public void Validate_WrongLineTotal_Gives00423()
{
var body = Invoice().Invoices[0];
var wrong = body with { Lines = [body.Lines[0] with { TotalPrice = 85m }, body.Lines[1], body.Lines[2]] };
var problems = Validator.Validate(Invoice() with { Invoices = [wrong] });
Assert.IsTrue(problems.Any(p => p.Code == "00423" && p.Path.Contains("DettaglioLinee[1]", StringComparison.Ordinal)));
}
[TestMethod]
public void Validate_NatureRules_Give00400_00401_00445_00429()
{
var body = Invoice().Invoices[0];
var noNature = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m }] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [noNature] }).Any(p => p.Code == "00400"));
var natureWithRate = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { Nature = "N4" }] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [natureWithRate] }).Any(p => p.Code == "00401"));
var generic = body with
{
Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m, Nature = "N2" }],
TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, "N2", 18m, 0m, null, "Art. 7", null, null)],
};
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [generic] }).Any(p => p.Code == "00445"));
var summaryWithout = body with { TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, null, 18m, 0m, null, null, null, null)] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [summaryWithout] }).Any(p => p.Code == "00429"));
}
[TestMethod]
public void Validate_SummaryRules_Give00419_00421_00422()
{
var body = Invoice().Invoices[0];
var missing = body with { TaxSummary = [body.TaxSummary[0]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [missing] }).Any(p => p.Code == "00419"));
var wrongTax = body with { TaxSummary = [body.TaxSummary[0] with { Tax = 230m }, body.TaxSummary[1]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTax] }).Any(p => p.Code == "00421"));
var wrongTaxable = body with { TaxSummary = [body.TaxSummary[0] with { Taxable = 1_070m, Tax = 235.40m }, body.TaxSummary[1]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTaxable] }).Any(p => p.Code == "00422"));
}
[TestMethod]
public void Validate_RecipientAndCustomerRules()
{
Assert.IsTrue(Validator.Validate(Invoice() with { RecipientCode = "ABC123" }).Any(p => p.Code == "00427"));
Assert.IsTrue(Validator.Validate(Invoice() with { TransmissionFormat = "FPA12" }).Any(p => p.Code == "00427"));
Assert.IsTrue(Validator.Validate(Invoice() with { RecipientPec = "a@pec.example.it" }).Any(p => p.Code == "00426"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = null, TaxCode = null } }).Any(p => p.Code == "00417"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = "09876543210" } }).Any(p => p.Code == "00305"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { TaxCode = "RSSMRA80A01H501X" } }).Any(p => p.Code == "00306"));
Assert.IsTrue(Validator.Validate(Invoice() with { TransmitterId = null }).Any(p => p.Code == "einvoice.transmitter"));
}
[TestMethod]
public void Validate_SelfInvoiceRules_Give00471_00472_00473()
{
var body = Invoice().Invoices[0];
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Company }).Any(p => p.Code == "00471"));
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD27" }] }).Any(p => p.Code == "00472"));
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD17" }] }).Any(p => p.Code == "00473"));
}
[TestMethod]
public void Validate_WithholdingLinesWithoutData_Give00411()
{
var body = Invoice().Invoices[0];
var withheld = body with { Lines = [body.Lines[0] with { Withheld = true }, body.Lines[1], body.Lines[2]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [withheld] }).Any(p => p.Code == "00411"));
}
[TestMethod]
public void Validate_ExemptOverThresholdWithoutStamp_IsAWarning()
{
var body = Invoice().Invoices[0] with
{
Lines = [new EInvoiceLine(1, [], "Servizio esente", 1m, null, 100m, 100m, 0m, "N4", [], false, null, null, null, null)],
TaxSummary = [new EInvoiceTaxSummary(0m, "N4", 100m, 0m, null, "Art. 10 DPR 633/72", null, null)],
};
var problem = Validator.Validate(Invoice() with { Invoices = [body] }).Single(p => p.Code == "einvoice.stamp-duty");
Assert.AreEqual(EInvoiceProblemSeverity.Warning, problem.Severity);
}
[TestMethod]
public void ValidateXml_BrokenFile_ReportsSchemaErrors()
{
var xml = Encoding.UTF8.GetString(Writer.Write(Invoice())).Replace("<Divisa>EUR</Divisa>", "<Divisa>EURO</Divisa>", StringComparison.Ordinal);
var problems = Validator.ValidateXml(Encoding.UTF8.GetBytes(xml));
Assert.IsTrue(problems.Any(p => p.Code == "einvoice.xml.schema"));
Assert.AreEqual("einvoice.xml.malformed", Validator.ValidateXml(Encoding.UTF8.GetBytes("<p:FatturaElettronica")).Single().Code);
}
}
@@ -11,6 +11,8 @@
<!-- The builder of signed envelopes is shared with the CMS tests: the p7m files are made in the test, never downloaded. -->
<ItemGroup>
<Compile Include="../Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs" Link="Shared/CmsTestSigner.cs" />
<Compile Include="../Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs" Link="Shared/FakeMailServers.cs" />
<Compile Include="../Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs" Link="Shared/PecSamples.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,102 @@
using System.Text;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>The notifications of the SDI (issue #75), written here in the layout of <c>MessaggiTypes</c> v1.0.</summary>
[TestClass]
public sealed class SdiReceiptReaderTests
{
private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0";
private static readonly SdiReceiptReader Reader = new();
/// <summary>A notification as the SDI writes it.</summary>
/// <param name="root">The root element.</param>
/// <param name="body">The children.</param>
/// <returns>The file.</returns>
public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes(
$"""<?xml version="1.0" encoding="UTF-8"?><types:{root} xmlns:types="{Ns}" versione="1.0">{body}<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"/></types:{root}>""");
[TestMethod]
public void Read_DeliveryReceipt()
{
var content = Notification("RicevutaConsegna", """
<IdentificativoSdI>111222333</IdentificativoSdI><NomeFile>IT01234567897_00001.xml</NomeFile><Hash>abc</Hash>
<DataOraRicezione>2026-10-12T15:40:10.000+02:00</DataOraRicezione><DataOraConsegna>2026-10-12T15:41:00.000+02:00</DataOraConsegna>
<Destinatario><Codice>ABC1234</Codice><Descrizione>Officine</Descrizione></Destinatario><MessageId>9001</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00001_RC_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Delivered, receipt.Kind);
Assert.AreEqual("RC", receipt.Code);
Assert.AreEqual("IT01234567897_00001.xml", receipt.InvoiceFileName);
Assert.AreEqual("111222333", receipt.ExchangeId);
Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 15, 41, 0, TimeSpan.FromHours(2)), receipt.DeliveredAt);
Assert.AreEqual("9001", receipt.MessageId);
}
[TestMethod]
public void Read_Rejection_ListsTheErrors()
{
var content = Notification("NotificaScarto", """
<IdentificativoSdI>111222334</IdentificativoSdI><NomeFile>IT01234567897_00002.xml</NomeFile>
<DataOraRicezione>2026-10-09T10:00:00</DataOraRicezione>
<ListaErrori>
<Errore><Codice>00311</Codice><Descrizione>1.1.4 CodiceDestinatario non valido</Descrizione></Errore>
<Errore><Codice>00423</Codice><Descrizione>2.2.1.11 PrezzoTotale non calcolato correttamente</Descrizione><Suggerimento>Verificare</Suggerimento></Errore>
</ListaErrori><MessageId>9002</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00002_NS_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Rejected, receipt.Kind);
Assert.HasCount(2, receipt.Errors);
Assert.AreEqual("00311", receipt.Errors[0].Code);
Assert.AreEqual("Verificare", receipt.Errors[1].Hint);
}
[TestMethod]
public void Read_OutcomeOfAnAdministration()
{
var content = Notification("NotificaEsito", """
<IdentificativoSdI>555</IdentificativoSdI><NomeFile>IT01234567897_00003.xml</NomeFile>
<EsitoCommittente><IdentificativoSdI>555</IdentificativoSdI><Esito>EC02</Esito><Descrizione>CIG errato</Descrizione></EsitoCommittente>
<MessageId>9003</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00003_NE_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Outcome, receipt.Kind);
Assert.AreEqual("EC02", receipt.Outcome);
Assert.IsTrue(receipt.Refused);
Assert.AreEqual("CIG errato", receipt.Description);
}
[TestMethod]
[DataRow("NotificaMancataConsegna", "MC", EInvoiceReceiptKind.NotDelivered)]
[DataRow("NotificaDecorrenzaTermini", "DT", EInvoiceReceiptKind.TermsElapsed)]
[DataRow("AttestazioneTrasmissioneFattura", "AT", EInvoiceReceiptKind.Undeliverable)]
[DataRow("FileMetadati", "MT", EInvoiceReceiptKind.Metadata)]
public void Read_OtherNotifications(string root, string code, EInvoiceReceiptKind kind)
{
var content = Notification(root, "<IdentificativoSdI>777</IdentificativoSdI><NomeFile>IT09876543217_0A1B2.xml.p7m</NomeFile><CodiceDestinatario>ABC1234</CodiceDestinatario><MessageId>1</MessageId>");
var receipt = Reader.Read("anything.xml", content);
Assert.AreEqual(kind, receipt.Kind);
Assert.AreEqual(code, receipt.Code);
Assert.AreEqual("777", receipt.ExchangeId);
Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", receipt.InvoiceFileName);
}
[TestMethod]
public void IsReceipt_ByNameOrRoot_AndNotForInvoices()
{
Assert.IsTrue(Reader.IsReceipt("IT01234567897_00001_NS_001.xml", []));
Assert.IsTrue(Reader.IsReceipt("x.xml", Notification("RicevutaConsegna", string.Empty)));
Assert.IsFalse(Reader.IsReceipt("IT01234567897_00001.xml", Encoding.UTF8.GetBytes("<p:FatturaElettronica/>")));
Assert.AreEqual("MT", SdiReceiptReader.CodeOfName("IT09876543217_0A1B2_MT_001.xml"));
Assert.ThrowsExactly<IncomingInvoiceException>(() => Reader.Read("a.xml", Encoding.UTF8.GetBytes("<FatturaElettronica/>")));
}
}
@@ -0,0 +1,345 @@
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("<p:FatturaElettronica/>"), "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("<ns:RicevutaConsegna xmlns:ns=\"x\"/>");
var invoice = Encoding.UTF8.GetBytes("<p:FatturaElettronica/>");
var metadata = Encoding.UTF8.GetBytes("<ns:FileMetadati xmlns:ns=\"x\"/>");
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\" <posta-certificata@x.it>"));
Assert.IsNull(PecSdiTransport.SdiAddress("info@fatturapa.it"));
}
}
/// <summary>An HTTP handler that answers from a function and keeps the requests (with their bodies).</summary>
internal sealed class StubHandler(Func<HttpRequestMessage, byte[], HttpResponseMessage> answer, ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)> log) : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> 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(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body>" + body + "</soapenv:Body></soapenv:Envelope>",
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(
"<ns2:rispostaSdIRiceviFile xmlns:ns2=\"http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types\"><IdentificativoSdI>111222333</IdentificativoSdI><DataOraRicezione>2026-11-13T10:00:00.000+01:00</DataOraRicezione></ns2:rispostaSdIRiceviFile>"), log));
var content = Encoding.UTF8.GetBytes("<p:FatturaElettronica versione=\"FPR12\"/>");
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("<r><Errore>EI03</Errore></r>"), log));
var fault = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("<soapenv:Fault><faultcode>x</faultcode><faultstring>Bad request</faultstring></soapenv:Fault>"), 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("<NotificaScarto/>"));
var inline = Encoding.UTF8.GetBytes(
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><t:fileSdI xmlns:t=\"http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types\">" +
"<IdentificativoSdI>42</IdentificativoSdI><NomeFile>IT01234567897_00001_NS_001.xml</NomeFile><File>" + receipt + "</File></t:fileSdI></s:Body></s:Envelope>");
var notification = SdiCoopMessages.Read("text/xml; charset=utf-8", inline)!;
Assert.AreEqual("Notifica", notification.Operation);
Assert.AreEqual("42", notification.ExchangeId);
Assert.AreEqual("<NotificaScarto/>", 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: <root>\r\n\r\n" +
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><t:fileSdIConMetadati xmlns:t=\"http://www.fatturapa.gov.it/sdi/ws/ricezione/v1.0/types\">" +
"<IdentificativoSdI>77</IdentificativoSdI><NomeFile>IT09876543217_0A1B2.xml.p7m</NomeFile><File><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"cid:f1\"/></File>" +
"<NomeFileMetadati>IT09876543217_0A1B2_MT_001.xml</NomeFileMetadati><Metadati><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"cid:f2\"/></Metadati>" +
"</t:fileSdIConMetadati></s:Body></s:Envelope>\r\n" +
"--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <f1>\r\n\r\nP7M\r\n" +
"--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-ID: <f2>\r\n\r\n<FileMetadati/>\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("<FileMetadati/>", Encoding.UTF8.GetString(invoice.Files[1].Content));
StringAssert.Contains(SdiCoopMessages.Answer(invoice), "<Esito>ER01</Esito>");
Assert.IsNull(SdiCoopMessages.Read("text/xml", Encoding.UTF8.GetBytes("<not-soap/>")));
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("<RicevutaConsegna/>"));
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("<RicevutaConsegna/>", 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<IEInvoiceChannels>()!;
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"));
}
}
@@ -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();
}
}