feat: read FatturaPA invoices and signed p7m files (#57)
The import of supplier e-invoices needs a reading layer that turns a received file into plain records, whatever form the file arrives in. - Fiscal.Abstractions: IIncomingInvoiceReader, an optional pack feature, with the IncomingInvoiceFile records and the incoming.* error codes the import service and screens build on. - Infrastructure: CmsSignedData, a minimal CMS SignedData (CAdES .p7m) reader on System.Formats.Asn1, since System.Security.Cryptography.Pkcs is a separate package. It accepts DER, BER with indefinite lengths and chunked content, base64 text and nested envelopes; it checks the message digest and the RSA (PKCS#1, PSS) or ECDSA signature with the embedded certificate and reports signer, tax code, validity and signing time. No trust chain or revocation check: no trusted list offline. - Fiscal.Italy: FatturaPaReader for FPR12/FPA12 v1.2.x and FSM10, matched by local name, DTD prohibited and no resolver, BOM/windows-1252/missing declaration tolerated, batches as one invoice per body, attachments decoded; registered in ItalyFiscalPack. - Tests build every sample and signed envelope in code (AsnWriter and self-signed certificates), nothing downloaded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2c56c0dff0
commit
9a40adecfe
8 files changed
+2516
No files matched your search
@@ -0,0 +1,586 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The reader of received FatturaPA files (issue #57). Every sample is written here with fictitious data: no file is
|
||||
/// downloaded and the identifiers are not checked by the reader.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class FatturaPaReaderTests
|
||||
{
|
||||
private const string FileName = "IT01234567890_00042.xml";
|
||||
private const string Namespace = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2";
|
||||
|
||||
private static readonly FatturaPaReader Reader = new();
|
||||
|
||||
private const string Header = """
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>00042</ProgressivoInvio>
|
||||
<FormatoTrasmissione>FPR12</FormatoTrasmissione>
|
||||
<CodiceDestinatario>ABC1234</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdFiscaleIVA>
|
||||
<CodiceFiscale>01234567890</CodiceFiscale>
|
||||
<Anagrafica><Denominazione>Ferramenta Piemontese S.r.l.</Denominazione></Anagrafica>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</DatiAnagrafici>
|
||||
<Sede>
|
||||
<Indirizzo>Via Roma</Indirizzo><NumeroCivico>12</NumeroCivico><CAP>10121</CAP>
|
||||
<Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione>
|
||||
</Sede>
|
||||
<IscrizioneREA><Ufficio>TO</Ufficio><NumeroREA>123456</NumeroREA><StatoLiquidazione>LN</StatoLiquidazione></IscrizioneREA>
|
||||
<Contatti><Telefono>011 1234567</Telefono><Email>amministrazione@ferramenta.example</Email></Contatti>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<DatiAnagrafici>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>09876543210</IdCodice></IdFiscaleIVA>
|
||||
<Anagrafica><Denominazione>Officine Esempio S.p.A.</Denominazione></Anagrafica>
|
||||
</DatiAnagrafici>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
""";
|
||||
|
||||
private const string OrdinaryBody = """
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>TD01</TipoDocumento>
|
||||
<Divisa>EUR</Divisa>
|
||||
<Data>2026-03-15</Data>
|
||||
<Numero>FT/2026/123</Numero>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>2.00</Percentuale></ScontoMaggiorazione>
|
||||
<ScontoMaggiorazione><Tipo>MG</Tipo><Importo>1.50</Importo></ScontoMaggiorazione>
|
||||
<ImportoTotaleDocumento>116.90</ImportoTotaleDocumento>
|
||||
<Causale>Fornitura di marzo</Causale>
|
||||
<Causale>Consegna in cantiere</Causale>
|
||||
</DatiGeneraliDocumento>
|
||||
<DatiOrdineAcquisto>
|
||||
<RiferimentoNumeroLinea>1</RiferimentoNumeroLinea>
|
||||
<RiferimentoNumeroLinea>2</RiferimentoNumeroLinea>
|
||||
<IdDocumento>ORD-77</IdDocumento>
|
||||
<Data>2026-03-01</Data>
|
||||
<CodiceCUP>J11B26000010001</CodiceCUP>
|
||||
<CodiceCIG>Z1234567AB</CodiceCIG>
|
||||
</DatiOrdineAcquisto>
|
||||
<DatiDDT>
|
||||
<NumeroDDT>DDT-501</NumeroDDT>
|
||||
<DataDDT>2026-03-10</DataDDT>
|
||||
<RiferimentoNumeroLinea>1</RiferimentoNumeroLinea>
|
||||
</DatiDDT>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>1</NumeroLinea>
|
||||
<CodiceArticolo><CodiceTipo>SKU</CodiceTipo><CodiceValore>B-M8-ZN</CodiceValore></CodiceArticolo>
|
||||
<CodiceArticolo><CodiceTipo>EAN</CodiceTipo><CodiceValore>8001234567895</CodiceValore></CodiceArticolo>
|
||||
<Descrizione>Bulloni M8 zincati</Descrizione>
|
||||
<Quantita>100.00</Quantita>
|
||||
<UnitaMisura>PZ</UnitaMisura>
|
||||
<PrezzoUnitario>0.500000</PrezzoUnitario>
|
||||
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>10.00</Percentuale></ScontoMaggiorazione>
|
||||
<PrezzoTotale>45.00</PrezzoTotale>
|
||||
<AliquotaIVA>22.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>2</NumeroLinea>
|
||||
<Descrizione>Manuale tecnico di carpenteria</Descrizione>
|
||||
<Quantita>2.00</Quantita>
|
||||
<PrezzoUnitario>25.00</PrezzoUnitario>
|
||||
<PrezzoTotale>50.00</PrezzoTotale>
|
||||
<AliquotaIVA>4.00</AliquotaIVA>
|
||||
</DettaglioLinee>
|
||||
<DettaglioLinee>
|
||||
<NumeroLinea>3</NumeroLinea>
|
||||
<TipoCessionePrestazione>AC</TipoCessionePrestazione>
|
||||
<Descrizione>Contributo ambientale imballi</Descrizione>
|
||||
<DataInizioPeriodo>2026-03-01</DataInizioPeriodo>
|
||||
<DataFinePeriodo>2026-03-31</DataFinePeriodo>
|
||||
<PrezzoUnitario>10.00</PrezzoUnitario>
|
||||
<PrezzoTotale>10.00</PrezzoTotale>
|
||||
<AliquotaIVA>0.00</AliquotaIVA>
|
||||
<Natura>N2.2</Natura>
|
||||
<RiferimentoAmministrazione>CC-12</RiferimentoAmministrazione>
|
||||
</DettaglioLinee>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>45.00</ImponibileImporto><Imposta>9.90</Imposta><EsigibilitaIVA>I</EsigibilitaIVA>
|
||||
</DatiRiepilogo>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>4.00</AliquotaIVA><ImponibileImporto>50.00</ImponibileImporto><Imposta>2.00</Imposta><EsigibilitaIVA>I</EsigibilitaIVA>
|
||||
</DatiRiepilogo>
|
||||
<DatiRiepilogo>
|
||||
<AliquotaIVA>0.00</AliquotaIVA><Natura>N2.2</Natura><ImponibileImporto>10.00</ImponibileImporto><Imposta>0.00</Imposta>
|
||||
<RiferimentoNormativo>Non soggetto art. 15 DPR 633/72</RiferimentoNormativo>
|
||||
</DatiRiepilogo>
|
||||
</DatiBeniServizi>
|
||||
<DatiPagamento>
|
||||
<CondizioniPagamento>TP01</CondizioniPagamento>
|
||||
<DettaglioPagamento>
|
||||
<ModalitaPagamento>MP05</ModalitaPagamento>
|
||||
<DataScadenzaPagamento>2026-04-30</DataScadenzaPagamento>
|
||||
<ImportoPagamento>58.45</ImportoPagamento>
|
||||
<IBAN>IT60X0542811101000000123456</IBAN>
|
||||
</DettaglioPagamento>
|
||||
<DettaglioPagamento>
|
||||
<Beneficiario>Ferramenta Piemontese S.r.l.</Beneficiario>
|
||||
<ModalitaPagamento>MP05</ModalitaPagamento>
|
||||
<DataScadenzaPagamento>2026-05-31</DataScadenzaPagamento>
|
||||
<ImportoPagamento>58.45</ImportoPagamento>
|
||||
<IBAN>IT60X0542811101000000123456</IBAN>
|
||||
<BIC>BPMOIT22XXX</BIC>
|
||||
</DettaglioPagamento>
|
||||
</DatiPagamento>
|
||||
</FatturaElettronicaBody>
|
||||
""";
|
||||
|
||||
private static string Prefixed(params string[] bodies) =>
|
||||
$"""<?xml version="1.0" encoding="UTF-8"?><p:FatturaElettronica versione="FPR12" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:p="{Namespace}">{Header}{string.Concat(bodies)}</p:FatturaElettronica>""";
|
||||
|
||||
private static string Body(string type, string number, string date, string generalExtra = "", string documentExtra = "", string goods = "", string extra = "") => $"""
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento>
|
||||
<TipoDocumento>{type}</TipoDocumento><Divisa>EUR</Divisa><Data>{date}</Data><Numero>{number}</Numero>{documentExtra}
|
||||
</DatiGeneraliDocumento>{generalExtra}
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi>{(goods.Length > 0 ? goods : SimpleGoods)}</DatiBeniServizi>{extra}
|
||||
</FatturaElettronicaBody>
|
||||
""";
|
||||
|
||||
private const string SimpleGoods = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Consulenza</Descrizione><PrezzoUnitario>100.00</PrezzoUnitario><PrezzoTotale>100.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA></DettaglioLinee>
|
||||
<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));
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission()
|
||||
{
|
||||
var file = Read(Prefixed(OrdinaryBody));
|
||||
|
||||
Assert.AreEqual(FileName, file.FileName);
|
||||
Assert.AreEqual("FPR12", file.TransmissionFormat);
|
||||
Assert.AreEqual("00042", file.ProgressiveNumber);
|
||||
Assert.AreEqual("ABC1234", file.RecipientCode);
|
||||
Assert.IsNull(file.Signature);
|
||||
Assert.HasCount(1, file.Invoices);
|
||||
|
||||
var supplier = file.Supplier;
|
||||
Assert.AreEqual("IT", supplier.CountryCode);
|
||||
Assert.AreEqual("01234567890", supplier.VatNumber);
|
||||
Assert.AreEqual("01234567890", supplier.TaxCode);
|
||||
Assert.AreEqual("Ferramenta Piemontese S.r.l.", supplier.DisplayName);
|
||||
Assert.AreEqual("Via Roma", supplier.Address);
|
||||
Assert.AreEqual("12", supplier.StreetNumber);
|
||||
Assert.AreEqual("10121", supplier.PostalCode);
|
||||
Assert.AreEqual("Torino", supplier.City);
|
||||
Assert.AreEqual("TO", supplier.Province);
|
||||
Assert.AreEqual("IT", supplier.Country);
|
||||
Assert.AreEqual("RF01", supplier.TaxRegime);
|
||||
Assert.AreEqual("amministrazione@ferramenta.example", supplier.Email);
|
||||
Assert.AreEqual("011 1234567", supplier.Phone);
|
||||
Assert.AreEqual("TO", supplier.ReaOffice);
|
||||
Assert.AreEqual("123456", supplier.ReaNumber);
|
||||
|
||||
Assert.AreEqual("09876543210", file.Customer.VatNumber);
|
||||
Assert.AreEqual("Officine Esempio S.p.A.", file.Customer.Name);
|
||||
Assert.AreEqual("Milano", file.Customer.City);
|
||||
Assert.IsNull(file.Customer.TaxRegime);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OrdinaryInvoice_ReadsDocumentLinesSummaryAndPayments()
|
||||
{
|
||||
var invoice = Read(Prefixed(OrdinaryBody)).Invoices[0];
|
||||
|
||||
Assert.AreEqual("TD01", invoice.DocumentType);
|
||||
Assert.AreEqual("EUR", invoice.Currency);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 15), invoice.Date);
|
||||
Assert.AreEqual("FT/2026/123", invoice.Number);
|
||||
Assert.AreEqual(116.90m, invoice.Total);
|
||||
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.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("Bulloni M8 zincati", bolts.Description);
|
||||
Assert.AreEqual(100m, bolts.Quantity);
|
||||
Assert.AreEqual("PZ", bolts.Unit);
|
||||
Assert.AreEqual(0.5m, bolts.UnitPrice);
|
||||
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.IsFalse(bolts.Withheld);
|
||||
|
||||
Assert.AreEqual(4m, invoice.Lines[1].TaxRate);
|
||||
var contribution = invoice.Lines[2];
|
||||
Assert.IsNull(contribution.Quantity);
|
||||
Assert.AreEqual(0m, contribution.TaxRate);
|
||||
Assert.AreEqual("N2.2", contribution.Nature);
|
||||
Assert.AreEqual("AC", contribution.LineType);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 1), contribution.PeriodStart);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 31), contribution.PeriodEnd);
|
||||
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(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("BPMOIT22XXX", invoice.Payments[1].Bic);
|
||||
Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary);
|
||||
Assert.IsEmpty(invoice.Attachments);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OrdinaryInvoice_ReadsOrdersAndDeliveryNotes()
|
||||
{
|
||||
var invoice = Read(Prefixed(OrdinaryBody)).Invoices[0];
|
||||
|
||||
var order = invoice.Orders.Single();
|
||||
Assert.AreEqual("ORD-77", order.Id);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 1), order.Date);
|
||||
CollectionAssert.AreEqual(new[] { 1, 2 }, order.LineNumbers.ToArray());
|
||||
Assert.AreEqual("Z1234567AB", order.Cig);
|
||||
Assert.AreEqual("J11B26000010001", order.Cup);
|
||||
|
||||
var note = invoice.DeliveryNotes.Single();
|
||||
Assert.AreEqual("DDT-501", note.Id);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 10), note.Date);
|
||||
CollectionAssert.AreEqual(new[] { 1 }, note.LineNumbers.ToArray());
|
||||
Assert.IsEmpty(invoice.Contracts);
|
||||
Assert.IsEmpty(invoice.RelatedInvoices);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_CreditNote_ReadsTheRelatedInvoice()
|
||||
{
|
||||
var related = """
|
||||
<DatiFattureCollegate><IdDocumento>FT/2026/123</IdDocumento><Data>2026-03-15</Data></DatiFattureCollegate>
|
||||
<DatiContratto><IdDocumento>CTR-2026-01</IdDocumento></DatiContratto>
|
||||
""";
|
||||
var invoice = Read(Prefixed(Body("TD04", "NC/2026/7", "2026-03-20", generalExtra: related))).Invoices[0];
|
||||
|
||||
Assert.AreEqual("TD04", invoice.DocumentType);
|
||||
Assert.AreEqual("NC/2026/7", invoice.Number);
|
||||
var original = invoice.RelatedInvoices.Single();
|
||||
Assert.AreEqual("FT/2026/123", original.Id);
|
||||
Assert.AreEqual(new DateOnly(2026, 3, 15), original.Date);
|
||||
Assert.IsEmpty(original.LineNumbers);
|
||||
Assert.AreEqual("CTR-2026-01", invoice.Contracts.Single().Id);
|
||||
Assert.IsNull(invoice.Contracts[0].Date);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Batch_ReturnsOneInvoicePerBody()
|
||||
{
|
||||
var file = Read(Prefixed(Body("TD01", "101", "2026-02-01"), Body("TD01", "102", "2026-02-02")));
|
||||
|
||||
Assert.HasCount(2, file.Invoices);
|
||||
Assert.AreEqual("101", file.Invoices[0].Number);
|
||||
Assert.AreEqual("102", file.Invoices[1].Number);
|
||||
Assert.AreEqual(new DateOnly(2026, 2, 2), file.Invoices[1].Date);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_IgnoresNamespacesAndPrefixes_AndToleratesBomAndWhitespace()
|
||||
{
|
||||
var prefixed = Prefixed(OrdinaryBody);
|
||||
var defaultNamespace = prefixed
|
||||
.Replace("<p:FatturaElettronica", "<FatturaElettronica", StringComparison.Ordinal)
|
||||
.Replace("</p:FatturaElettronica", "</FatturaElettronica", StringComparison.Ordinal)
|
||||
.Replace("xmlns:p=", "xmlns=", StringComparison.Ordinal);
|
||||
var everyElementPrefixed = System.Text.RegularExpressions.Regex
|
||||
.Replace(defaultNamespace, "<(/?)(?=[A-Za-z])", "<$1ns2:")
|
||||
.Replace("xmlns=", "xmlns:ns2=", StringComparison.Ordinal);
|
||||
var noDeclaration = defaultNamespace[defaultNamespace.IndexOf("?>", StringComparison.Ordinal)..][2..];
|
||||
|
||||
byte[] withBom = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("\r\n " + prefixed)];
|
||||
var variants = new List<byte[]>
|
||||
{
|
||||
Encoding.UTF8.GetBytes(prefixed),
|
||||
Encoding.UTF8.GetBytes(defaultNamespace),
|
||||
Encoding.UTF8.GetBytes(everyElementPrefixed),
|
||||
withBom,
|
||||
Encoding.UTF8.GetBytes("\n" + noDeclaration),
|
||||
};
|
||||
|
||||
foreach (var bytes in variants)
|
||||
{
|
||||
Assert.IsTrue(Reader.CanRead(FileName, bytes));
|
||||
var file = Reader.Read(FileName, bytes);
|
||||
Assert.AreEqual("Ferramenta Piemontese S.r.l.", file.Supplier.Name);
|
||||
Assert.AreEqual("FT/2026/123", file.Invoices[0].Number);
|
||||
Assert.HasCount(3, file.Invoices[0].Lines);
|
||||
Assert.HasCount(2, file.Invoices[0].Payments);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Windows1252Declaration_DecodesTheText()
|
||||
{
|
||||
var goods = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Caffè in grani € 1 al kg</Descrizione><PrezzoUnitario>10.00</PrezzoUnitario><PrezzoTotale>10.00</PrezzoTotale><AliquotaIVA>10.00</AliquotaIVA></DettaglioLinee>
|
||||
<DatiRiepilogo><AliquotaIVA>10.00</AliquotaIVA><ImponibileImporto>10.00</ImponibileImporto><Imposta>1.00</Imposta></DatiRiepilogo>
|
||||
""";
|
||||
var xml = Prefixed(Body("TD01", "5", "2026-01-10", goods: goods)).Replace("encoding=\"UTF-8\"", "encoding=\"windows-1252\"", StringComparison.Ordinal);
|
||||
var bytes = CodePagesEncodingProvider.Instance.GetEncoding(1252)!.GetBytes(xml);
|
||||
|
||||
var line = Reader.Read(FileName, bytes).Invoices[0].Lines[0];
|
||||
|
||||
Assert.AreEqual("Caffè in grani € 1 al kg", line.Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_WithholdingSocialSecurityAndVirtualStampDuty()
|
||||
{
|
||||
var document = """
|
||||
<DatiRitenuta><TipoRitenuta>RT01</TipoRitenuta><ImportoRitenuta>208.00</ImportoRitenuta><AliquotaRitenuta>20.00</AliquotaRitenuta><CausalePagamento>A</CausalePagamento></DatiRitenuta>
|
||||
<DatiBollo><BolloVirtuale>SI</BolloVirtuale><ImportoBollo>2.00</ImportoBollo></DatiBollo>
|
||||
<DatiCassaPrevidenziale>
|
||||
<TipoCassa>TC01</TipoCassa><AlCassa>4.00</AlCassa><ImportoContributoCassa>40.00</ImportoContributoCassa>
|
||||
<ImponibileCassa>1000.00</ImponibileCassa><AliquotaIVA>22.00</AliquotaIVA><Ritenuta>SI</Ritenuta>
|
||||
</DatiCassaPrevidenziale>
|
||||
<ImportoTotaleDocumento>1270.88</ImportoTotaleDocumento>
|
||||
<Arrotondamento>0.01</Arrotondamento>
|
||||
<Art73>SI</Art73>
|
||||
""";
|
||||
var goods = """
|
||||
<DettaglioLinee><NumeroLinea>1</NumeroLinea><Descrizione>Parere legale</Descrizione><PrezzoUnitario>1000.00</PrezzoUnitario><PrezzoTotale>1000.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA><Ritenuta>SI</Ritenuta></DettaglioLinee>
|
||||
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>1040.00</ImponibileImporto><Imposta>228.80</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
||||
""";
|
||||
var xml = Prefixed(Body("TD06", "12/2026", "2026-04-02", documentExtra: document, goods: goods))
|
||||
.Replace("<Denominazione>Ferramenta Piemontese S.r.l.</Denominazione>", "<Nome>Giulia</Nome><Cognome>Bianchi</Cognome>", StringComparison.Ordinal);
|
||||
|
||||
var file = Read(xml);
|
||||
var invoice = file.Invoices[0];
|
||||
|
||||
Assert.IsNull(file.Supplier.Name);
|
||||
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(1270.88m, invoice.Total);
|
||||
Assert.AreEqual(0.01m, invoice.Rounding);
|
||||
Assert.IsTrue(invoice.Art73);
|
||||
Assert.IsTrue(invoice.Lines[0].Withheld);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Attachment_IsDecoded()
|
||||
{
|
||||
var pdf = Encoding.ASCII.GetBytes("%PDF-1.4 copia di cortesia della fattura");
|
||||
var attachment = $"""
|
||||
<Allegati>
|
||||
<NomeAttachment>FT_2026_5.pdf</NomeAttachment>
|
||||
<FormatoAttachment>PDF</FormatoAttachment>
|
||||
<DescrizioneAttachment>Copia di cortesia</DescrizioneAttachment>
|
||||
<Attachment>{Convert.ToBase64String(pdf, Base64FormattingOptions.InsertLineBreaks)}
|
||||
</Attachment>
|
||||
</Allegati>
|
||||
""";
|
||||
|
||||
var found = Read(Prefixed(Body("TD01", "5", "2026-01-10", extra: attachment))).Invoices[0].Attachments.Single();
|
||||
|
||||
Assert.AreEqual("FT_2026_5.pdf", found.Name);
|
||||
Assert.AreEqual("PDF", found.Format);
|
||||
Assert.AreEqual("Copia di cortesia", found.Description);
|
||||
CollectionAssert.AreEqual(pdf, found.Content);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_SimplifiedInvoice_MapsTheGrossAmountsToNetLines()
|
||||
{
|
||||
var xml = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<p:FatturaElettronicaSemplificata versione="FSM10" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.0">
|
||||
<FatturaElettronicaHeader>
|
||||
<DatiTrasmissione>
|
||||
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdTrasmittente>
|
||||
<ProgressivoInvio>S0001</ProgressivoInvio>
|
||||
<FormatoTrasmissione>FSM10</FormatoTrasmissione>
|
||||
<CodiceDestinatario>0000000</CodiceDestinatario>
|
||||
</DatiTrasmissione>
|
||||
<CedentePrestatore>
|
||||
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567890</IdCodice></IdFiscaleIVA>
|
||||
<Denominazione>Bar Centrale di Rossi Mario</Denominazione>
|
||||
<Sede><Indirizzo>Piazza Castello</Indirizzo><CAP>10123</CAP><Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione></Sede>
|
||||
<RegimeFiscale>RF01</RegimeFiscale>
|
||||
</CedentePrestatore>
|
||||
<CessionarioCommittente>
|
||||
<IdentificativiFiscali><IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>09876543210</IdCodice></IdFiscaleIVA></IdentificativiFiscali>
|
||||
<AltriDatiIdentificativi>
|
||||
<Denominazione>Officine Esempio S.p.A.</Denominazione>
|
||||
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
||||
</AltriDatiIdentificativi>
|
||||
</CessionarioCommittente>
|
||||
</FatturaElettronicaHeader>
|
||||
<FatturaElettronicaBody>
|
||||
<DatiGenerali>
|
||||
<DatiGeneraliDocumento><TipoDocumento>TD08</TipoDocumento><Divisa>EUR</Divisa><Data>2026-05-04</Data><Numero>S/18</Numero></DatiGeneraliDocumento>
|
||||
<DatiFatturaRettificata><NumeroFR>S/12</NumeroFR><DataFR>2026-04-28</DataFR><ElementiRettificati>Importo</ElementiRettificati></DatiFatturaRettificata>
|
||||
</DatiGenerali>
|
||||
<DatiBeniServizi><Descrizione>Pranzo di lavoro</Descrizione><Importo>122.00</Importo><DatiIVA><Imposta>22.00</Imposta></DatiIVA></DatiBeniServizi>
|
||||
<DatiBeniServizi><Descrizione>Quotidiani e riviste</Descrizione><Importo>52.00</Importo><DatiIVA><Aliquota>4.00</Aliquota></DatiIVA></DatiBeniServizi>
|
||||
<DatiBeniServizi><Descrizione>Francobolli</Descrizione><Importo>30.00</Importo><DatiIVA><Imposta>0.00</Imposta></DatiIVA><Natura>N2.2</Natura></DatiBeniServizi>
|
||||
</FatturaElettronicaBody>
|
||||
</p:FatturaElettronicaSemplificata>
|
||||
""";
|
||||
|
||||
var file = Read(xml);
|
||||
var invoice = file.Invoices[0];
|
||||
|
||||
Assert.AreEqual("FSM10", file.TransmissionFormat);
|
||||
Assert.AreEqual("Bar Centrale di Rossi Mario", file.Supplier.Name);
|
||||
Assert.AreEqual("01234567890", file.Supplier.VatNumber);
|
||||
Assert.AreEqual("RF01", file.Supplier.TaxRegime);
|
||||
Assert.AreEqual("09876543210", file.Customer.VatNumber);
|
||||
Assert.AreEqual("Officine Esempio S.p.A.", file.Customer.Name);
|
||||
Assert.AreEqual("Milano", file.Customer.City);
|
||||
|
||||
Assert.AreEqual("TD08", invoice.DocumentType);
|
||||
Assert.AreEqual("S/18", invoice.Number);
|
||||
Assert.AreEqual(204m, invoice.Total);
|
||||
Assert.AreEqual("S/12", invoice.RelatedInvoices.Single().Id);
|
||||
Assert.AreEqual(new DateOnly(2026, 4, 28), invoice.RelatedInvoices[0].Date);
|
||||
|
||||
Assert.HasCount(3, invoice.Lines);
|
||||
var lunch = invoice.Lines[0];
|
||||
Assert.IsNull(lunch.Quantity);
|
||||
Assert.AreEqual(100m, lunch.UnitPrice);
|
||||
Assert.AreEqual(100m, lunch.TotalPrice);
|
||||
Assert.AreEqual(22m, lunch.TaxRate);
|
||||
Assert.AreEqual(50m, invoice.Lines[1].TotalPrice);
|
||||
Assert.AreEqual(4m, invoice.Lines[1].TaxRate);
|
||||
Assert.AreEqual("N2.2", invoice.Lines[2].Nature);
|
||||
Assert.AreEqual(0m, invoice.Lines[2].TaxRate);
|
||||
Assert.AreEqual(30m, invoice.Lines[2].TotalPrice);
|
||||
|
||||
Assert.HasCount(3, invoice.TaxSummary);
|
||||
Assert.AreEqual(22m, invoice.TaxSummary.Single(s => s.Rate == 22m).Tax);
|
||||
Assert.AreEqual(2m, invoice.TaxSummary.Single(s => s.Rate == 4m).Tax);
|
||||
Assert.AreEqual(30m, invoice.TaxSummary.Single(s => s.Nature == "N2.2").Taxable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_SignedP7m_ReturnsTheInvoiceAndTheSignature()
|
||||
{
|
||||
var xml = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody));
|
||||
var p7m = CmsTestSigner.Sign(xml, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true });
|
||||
var base64 = Encoding.ASCII.GetBytes(Convert.ToBase64String(p7m, Base64FormattingOptions.InsertLineBreaks));
|
||||
|
||||
foreach (var content in new[] { p7m, base64 })
|
||||
{
|
||||
Assert.IsTrue(Reader.CanRead(FileName + ".p7m", content));
|
||||
var file = Reader.Read(FileName + ".p7m", content);
|
||||
|
||||
CollectionAssert.AreEqual(xml, file.Xml);
|
||||
Assert.AreEqual("FT/2026/123", file.Invoices[0].Number);
|
||||
var signature = file.Signature!;
|
||||
Assert.IsTrue(signature.Verified, signature.Problem);
|
||||
Assert.AreEqual("Mario Rossi", signature.Signer);
|
||||
Assert.AreEqual("RSSMRA80A01H501U", signature.SignerTaxCode);
|
||||
Assert.AreEqual(CmsTestSigner.SigningTime, signature.SignedAt);
|
||||
Assert.AreEqual(new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero), signature.CertificateNotAfter);
|
||||
Assert.IsNull(signature.Problem);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_TamperedP7m_StillReadsTheInvoice_NotVerified()
|
||||
{
|
||||
var xml = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody));
|
||||
var tampered = Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody).Replace("116.90", "16.90", StringComparison.Ordinal));
|
||||
var p7m = CmsTestSigner.Sign(xml, CmsTestSigner.Rsa, new CmsTestOptions { TamperedContent = tampered });
|
||||
|
||||
var file = Reader.Read(FileName + ".p7m", p7m);
|
||||
|
||||
Assert.AreEqual(16.90m, file.Invoices[0].Total);
|
||||
Assert.IsFalse(file.Signature!.Verified);
|
||||
Assert.IsNotNull(file.Signature.Problem);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRead_SniffsTheContent()
|
||||
{
|
||||
Assert.IsTrue(Reader.CanRead("fattura.XML", Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody))));
|
||||
Assert.IsTrue(Reader.CanRead("senza-estensione", Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody))));
|
||||
Assert.IsFalse(Reader.CanRead("fattura.pdf", "%PDF-1.4"u8));
|
||||
Assert.IsFalse(Reader.CanRead("vuoto.xml", []));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_NotXml_IsNotReadable()
|
||||
{
|
||||
AssertError(IncomingInvoiceErrors.NotReadable, "%PDF-1.4 non è una fattura"u8.ToArray());
|
||||
AssertError(IncomingInvoiceErrors.NotReadable, []);
|
||||
AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes("<FatturaElettronica><Header></FatturaElettronica>"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Dtd_IsRefused()
|
||||
{
|
||||
var xml = """<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><FatturaElettronica>&e;</FatturaElettronica>""";
|
||||
|
||||
AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes(xml));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OtherXml_IsNotAnInvoice() =>
|
||||
AssertError(IncomingInvoiceErrors.NotInvoice, Encoding.UTF8.GetBytes("""<?xml version="1.0"?><Ordine><Numero>1</Numero></Ordine>"""));
|
||||
|
||||
[TestMethod]
|
||||
public void Read_MissingMandatoryData_IsInvalid()
|
||||
{
|
||||
var noNumber = Prefixed(Body("TD01", "", "2026-01-10"));
|
||||
var badDate = Prefixed(Body("TD01", "7", "10/01/2026"));
|
||||
var noHeader = $"""<FatturaElettronica xmlns="{Namespace}">{Body("TD01", "7", "2026-01-10")}</FatturaElettronica>""";
|
||||
var noBody = $"""<FatturaElettronica xmlns="{Namespace}">{Header}</FatturaElettronica>""";
|
||||
|
||||
foreach (var xml in new[] { noNumber, badDate, noHeader, noBody })
|
||||
{
|
||||
AssertError(IncomingInvoiceErrors.Invalid, Encoding.UTF8.GetBytes(xml));
|
||||
}
|
||||
|
||||
var ex = Assert.ThrowsExactly<IncomingInvoiceException>(() => Read(noNumber));
|
||||
StringAssert.Contains(ex.Message, "Numero");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_BrokenEnvelope_IsSignatureBroken()
|
||||
{
|
||||
var p7m = CmsTestSigner.Sign(Encoding.UTF8.GetBytes(Prefixed(OrdinaryBody)), CmsTestSigner.Rsa);
|
||||
|
||||
AssertError(IncomingInvoiceErrors.SignatureBroken, p7m[..(p7m.Length / 2)]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Pack_DeliversTheReader() =>
|
||||
Assert.IsInstanceOfType<FatturaPaReader>(new ItalyFiscalPack().GetFeature<IIncomingInvoiceReader>());
|
||||
|
||||
private static void AssertError(string code, byte[] content)
|
||||
{
|
||||
var ex = Assert.ThrowsExactly<IncomingInvoiceException>(() => Reader.Read(FileName, content));
|
||||
Assert.AreEqual(code, ex.Code, ex.Message);
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,9 @@
|
||||
<ProjectReference Include="../../src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- 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" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
/// <summary>The reader of CMS SignedData envelopes (.p7m) used for received e-invoices (issue #57).</summary>
|
||||
[TestClass]
|
||||
public sealed class CmsSignedDataTests
|
||||
{
|
||||
private static readonly byte[] Content = Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><FatturaElettronica>contenuto firmato</FatturaElettronica>");
|
||||
|
||||
[TestMethod]
|
||||
public void Read_RsaSignature_ReturnsTheContentVerified_WithTheSigner()
|
||||
{
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa);
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
CollectionAssert.AreEqual(Content, result.Content);
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
Assert.IsNull(result.Problem);
|
||||
Assert.AreEqual(1, result.Layers);
|
||||
var signer = result.Signer!;
|
||||
Assert.AreEqual("Mario Rossi", signer.Name);
|
||||
Assert.AreEqual("RSSMRA80A01H501U", signer.TaxCode);
|
||||
Assert.AreEqual(CmsTestSigner.SigningTime, signer.SigningTime);
|
||||
Assert.AreEqual(new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), signer.CertificateNotBefore);
|
||||
Assert.AreEqual(new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero), signer.CertificateNotAfter);
|
||||
CollectionAssert.AreEqual(CmsTestSigner.Rsa.RawData, signer.Certificate);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_EcdsaSignature_BySubjectKeyIdentifier_IsVerified()
|
||||
{
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Ecdsa, new CmsTestOptions { BySubjectKeyIdentifier = true });
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
Assert.AreEqual("RSSMRA80A01H501U", result.Signer!.TaxCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_WithoutSignedAttributes_VerifiesTheSignatureOverTheContent()
|
||||
{
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { SignedAttributes = false });
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
Assert.IsNull(result.Signer!.SigningTime);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_TamperedContent_ReturnsItNotVerified_WithTheProblem()
|
||||
{
|
||||
var tampered = Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><FatturaElettronica>contenuto alterato</FatturaElettronica>");
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { TamperedContent = tampered });
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
CollectionAssert.AreEqual(tampered, result.Content);
|
||||
Assert.IsFalse(result.Verified);
|
||||
StringAssert.Contains(result.Problem, "changed after signing");
|
||||
Assert.AreEqual("Mario Rossi", result.Signer!.Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_BrokenSignature_IsNotVerified()
|
||||
{
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { BreakSignature = true });
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
Assert.IsFalse(result.Verified);
|
||||
StringAssert.Contains(result.Problem, "does not match");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_BerWithIndefiniteLengthsAndChunkedContent_IsVerified()
|
||||
{
|
||||
var large = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("<Linea>Bulloni M8 zincati</Linea>", 40)));
|
||||
var envelope = CmsTestSigner.Sign(large, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true });
|
||||
Assert.AreEqual(0x80, envelope[1], "The outer SEQUENCE must have an indefinite length.");
|
||||
|
||||
var result = CmsSignedData.Read(envelope);
|
||||
|
||||
CollectionAssert.AreEqual(large, result.Content);
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Base64TextForm_WithLineBreaksAndArmour_IsVerified()
|
||||
{
|
||||
var envelope = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa);
|
||||
var plain = Encoding.ASCII.GetBytes(Convert.ToBase64String(envelope));
|
||||
var wrapped = Encoding.ASCII.GetBytes(
|
||||
"-----BEGIN PKCS7-----\r\n" + Convert.ToBase64String(envelope, Base64FormattingOptions.InsertLineBreaks) + "\r\n-----END PKCS7-----\r\n");
|
||||
|
||||
Assert.IsTrue(CmsSignedData.LooksLikeCms(plain));
|
||||
Assert.IsTrue(CmsSignedData.LooksLikeCms(wrapped));
|
||||
foreach (var text in new[] { plain, wrapped })
|
||||
{
|
||||
var result = CmsSignedData.Read(text);
|
||||
CollectionAssert.AreEqual(Content, result.Content);
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_NestedEnvelopes_AreOpenedUntilTheContent()
|
||||
{
|
||||
var inner = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa);
|
||||
var outer = CmsTestSigner.Sign(inner, CmsTestSigner.Ecdsa, new CmsTestOptions { Ber = true });
|
||||
|
||||
var result = CmsSignedData.Read(outer);
|
||||
|
||||
CollectionAssert.AreEqual(Content, result.Content);
|
||||
Assert.AreEqual(2, result.Layers);
|
||||
Assert.HasCount(2, result.Signers);
|
||||
Assert.IsTrue(result.Verified, result.Problem);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_NestedEnvelope_WithABrokenInnerSignature_IsNotVerified()
|
||||
{
|
||||
var inner = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { BreakSignature = true });
|
||||
var outer = CmsTestSigner.Sign(inner, CmsTestSigner.Rsa);
|
||||
|
||||
var result = CmsSignedData.Read(outer);
|
||||
|
||||
Assert.IsTrue(result.Signers[0].Verified);
|
||||
Assert.IsFalse(result.Signers[1].Verified);
|
||||
Assert.IsFalse(result.Verified);
|
||||
Assert.IsNotNull(result.Problem);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Garbage_Throws()
|
||||
{
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => CmsSignedData.Read(Encoding.UTF8.GetBytes("questo non è un file firmato")));
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => CmsSignedData.Read([]));
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => CmsSignedData.Read(Content));
|
||||
|
||||
// The right start and nothing after it.
|
||||
var truncated = CmsTestSigner.Sign(Content, CmsTestSigner.Rsa)[..40];
|
||||
Assert.IsTrue(CmsSignedData.LooksLikeCms(truncated));
|
||||
Assert.ThrowsExactly<CmsFormatException>(() => CmsSignedData.Read(truncated));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LooksLikeCms_SniffsTheContent()
|
||||
{
|
||||
Assert.IsTrue(CmsSignedData.LooksLikeCms(CmsTestSigner.Sign(Content, CmsTestSigner.Rsa)));
|
||||
Assert.IsTrue(CmsSignedData.LooksLikeCms(CmsTestSigner.Sign(Content, CmsTestSigner.Rsa, new CmsTestOptions { Ber = true })));
|
||||
Assert.IsFalse(CmsSignedData.LooksLikeCms(Content));
|
||||
Assert.IsFalse(CmsSignedData.LooksLikeCms("QUJDRA=="u8));
|
||||
Assert.IsFalse(CmsSignedData.LooksLikeCms([]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DecodeBase64Text_RejectsWhatIsNotBase64()
|
||||
{
|
||||
Assert.IsNull(CmsSignedData.DecodeBase64Text("non è base64!"u8));
|
||||
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, CmsSignedData.DecodeBase64Text("AQID\r\n"u8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using System.Formats.Asn1;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Security;
|
||||
|
||||
/// <summary>How <see cref="CmsTestSigner.Sign"/> builds the envelope.</summary>
|
||||
internal sealed record CmsTestOptions
|
||||
{
|
||||
/// <summary>BER with indefinite lengths and the content split in chunks, as many signing programs write.</summary>
|
||||
public bool Ber { get; init; }
|
||||
|
||||
/// <summary>Identify the signer by subject key identifier instead of issuer and serial number.</summary>
|
||||
public bool BySubjectKeyIdentifier { get; init; }
|
||||
|
||||
/// <summary>Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly.</summary>
|
||||
public bool SignedAttributes { get; init; } = true;
|
||||
|
||||
/// <summary>Content put in the envelope instead of the signed one (to simulate tampering).</summary>
|
||||
public byte[]? TamperedContent { get; init; }
|
||||
|
||||
/// <summary>Flip a bit of the signature.</summary>
|
||||
public bool BreakSignature { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with <see cref="AsnWriter"/> and self-signed certificates:
|
||||
/// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader.
|
||||
/// </summary>
|
||||
internal static class CmsTestSigner
|
||||
{
|
||||
public static readonly DateTimeOffset SigningTime = new(2026, 3, 15, 10, 30, 0, TimeSpan.Zero);
|
||||
|
||||
private const string DataOid = "1.2.840.113549.1.7.1";
|
||||
private const string SignedDataOid = "1.2.840.113549.1.7.2";
|
||||
private const string Sha256Oid = "2.16.840.1.101.3.4.2.1";
|
||||
|
||||
private static readonly Lazy<X509Certificate2> RsaCertificate = new(() => Create(ecdsa: false));
|
||||
private static readonly Lazy<X509Certificate2> EcdsaCertificate = new(() => Create(ecdsa: true));
|
||||
|
||||
/// <summary>A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U.</summary>
|
||||
public static X509Certificate2 Rsa => RsaCertificate.Value;
|
||||
|
||||
/// <summary>A self-signed ECDSA P-256 certificate of the same person.</summary>
|
||||
public static X509Certificate2 Ecdsa => EcdsaCertificate.Value;
|
||||
|
||||
public static byte[] Sign(byte[] content, X509Certificate2 certificate, CmsTestOptions? options = null)
|
||||
{
|
||||
options ??= new CmsTestOptions();
|
||||
var isEcdsa = certificate.GetECDsaPrivateKey() is not null;
|
||||
|
||||
byte[]? signedAttributes = null;
|
||||
byte[] toSign = content;
|
||||
if (options.SignedAttributes)
|
||||
{
|
||||
var writer = new AsnWriter(AsnEncodingRules.DER);
|
||||
using (writer.PushSetOf())
|
||||
{
|
||||
WriteAttribute(writer, "1.2.840.113549.1.9.3", w => w.WriteObjectIdentifier(DataOid));
|
||||
WriteAttribute(writer, "1.2.840.113549.1.9.4", w => w.WriteOctetString(SHA256.HashData(content)));
|
||||
WriteAttribute(writer, "1.2.840.113549.1.9.5", w => w.WriteUtcTime(SigningTime));
|
||||
}
|
||||
|
||||
toSign = writer.Encode();
|
||||
signedAttributes = (byte[])toSign.Clone();
|
||||
signedAttributes[0] = 0xA0;
|
||||
}
|
||||
|
||||
byte[] signature;
|
||||
if (isEcdsa)
|
||||
{
|
||||
using var key = certificate.GetECDsaPrivateKey()!;
|
||||
signature = key.SignData(toSign, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
|
||||
}
|
||||
else
|
||||
{
|
||||
using var key = certificate.GetRSAPrivateKey()!;
|
||||
signature = key.SignData(toSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
}
|
||||
|
||||
if (options.BreakSignature)
|
||||
{
|
||||
signature[^5] ^= 0x01;
|
||||
}
|
||||
|
||||
var signerInfo = new AsnWriter(AsnEncodingRules.DER);
|
||||
using (signerInfo.PushSequence())
|
||||
{
|
||||
if (options.BySubjectKeyIdentifier)
|
||||
{
|
||||
signerInfo.WriteInteger(3);
|
||||
var ski = certificate.Extensions.OfType<X509SubjectKeyIdentifierExtension>().Single();
|
||||
signerInfo.WriteOctetString(ski.SubjectKeyIdentifierBytes.Span, new Asn1Tag(TagClass.ContextSpecific, 0));
|
||||
}
|
||||
else
|
||||
{
|
||||
signerInfo.WriteInteger(1);
|
||||
using (signerInfo.PushSequence())
|
||||
{
|
||||
signerInfo.WriteEncodedValue(certificate.IssuerName.RawData);
|
||||
signerInfo.WriteInteger(certificate.SerialNumberBytes.Span);
|
||||
}
|
||||
}
|
||||
|
||||
WriteAlgorithm(signerInfo, Sha256Oid, withNull: true);
|
||||
if (signedAttributes is not null)
|
||||
{
|
||||
signerInfo.WriteEncodedValue(signedAttributes);
|
||||
}
|
||||
|
||||
WriteAlgorithm(signerInfo, isEcdsa ? "1.2.840.10045.4.3.2" : "1.2.840.113549.1.1.11", withNull: !isEcdsa);
|
||||
signerInfo.WriteOctetString(signature);
|
||||
}
|
||||
|
||||
var version = Der(w => w.WriteInteger(1));
|
||||
var digestAlgorithms = Der(w =>
|
||||
{
|
||||
using (w.PushSetOf())
|
||||
{
|
||||
WriteAlgorithm(w, Sha256Oid, withNull: true);
|
||||
}
|
||||
});
|
||||
var certificates = Tlv(0xA0, certificate.RawData);
|
||||
var signerInfos = Tlv(0x31, signerInfo.Encode());
|
||||
var signedDataOid = Der(w => w.WriteObjectIdentifier(SignedDataOid));
|
||||
var dataOid = Der(w => w.WriteObjectIdentifier(DataOid));
|
||||
var envelopeContent = options.TamperedContent ?? content;
|
||||
|
||||
if (!options.Ber)
|
||||
{
|
||||
return Tlv(0x30, signedDataOid, Tlv(0xA0, Tlv(0x30,
|
||||
version, digestAlgorithms, Tlv(0x30, dataOid, Tlv(0xA0, Tlv(0x04, envelopeContent))), certificates, signerInfos)));
|
||||
}
|
||||
|
||||
// BER: indefinite lengths everywhere around the content, which is a constructed OCTET STRING of small chunks.
|
||||
var chunks = envelopeContent.Chunk(100).Select(c => Tlv(0x04, c)).ToArray();
|
||||
return Indefinite(0x30, signedDataOid, Indefinite(0xA0, Indefinite(0x30,
|
||||
version, digestAlgorithms, Indefinite(0x30, dataOid, Indefinite(0xA0, Indefinite(0x24, chunks))), certificates, signerInfos)));
|
||||
}
|
||||
|
||||
private static X509Certificate2 Create(bool ecdsa)
|
||||
{
|
||||
var name = new X500DistinguishedNameBuilder();
|
||||
name.AddCountryOrRegion("IT");
|
||||
name.Add("2.5.4.42", "Mario");
|
||||
name.Add("2.5.4.4", "Rossi");
|
||||
name.Add("2.5.4.5", "TINIT-RSSMRA80A01H501U", UniversalTagNumber.PrintableString);
|
||||
name.AddCommonName("Mario Rossi");
|
||||
var subject = name.Build();
|
||||
var notBefore = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
var notAfter = new DateTimeOffset(2028, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
if (ecdsa)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256);
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
|
||||
return request.CreateSelfSigned(notBefore, notAfter);
|
||||
}
|
||||
else
|
||||
{
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
|
||||
return request.CreateSelfSigned(notBefore, notAfter);
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteAttribute(AsnWriter writer, string oid, Action<AsnWriter> value)
|
||||
{
|
||||
using (writer.PushSequence())
|
||||
{
|
||||
writer.WriteObjectIdentifier(oid);
|
||||
using (writer.PushSetOf())
|
||||
{
|
||||
value(writer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteAlgorithm(AsnWriter writer, string oid, bool withNull)
|
||||
{
|
||||
using (writer.PushSequence())
|
||||
{
|
||||
writer.WriteObjectIdentifier(oid);
|
||||
if (withNull)
|
||||
{
|
||||
writer.WriteNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Der(Action<AsnWriter> write)
|
||||
{
|
||||
var writer = new AsnWriter(AsnEncodingRules.DER);
|
||||
write(writer);
|
||||
return writer.Encode();
|
||||
}
|
||||
|
||||
private static byte[] Tlv(byte tag, params byte[][] children)
|
||||
{
|
||||
var body = children.SelectMany(c => c).ToArray();
|
||||
var length = body.Length;
|
||||
byte[] lengthBytes = length switch
|
||||
{
|
||||
< 0x80 => [(byte)length],
|
||||
<= 0xFF => [0x81, (byte)length],
|
||||
<= 0xFFFF => [0x82, (byte)(length >> 8), (byte)length],
|
||||
_ => [0x83, (byte)(length >> 16), (byte)(length >> 8), (byte)length],
|
||||
};
|
||||
return [tag, .. lengthBytes, .. body];
|
||||
}
|
||||
|
||||
private static byte[] Indefinite(byte tag, params byte[][] children) =>
|
||||
[tag, 0x80, .. children.SelectMany(c => c), 0x00, 0x00];
|
||||
}
|
||||
Reference in new issue
Block a user