From 9a40adecfea9658916836f7cce868a06a20fe904 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 12 Nov 2026 21:08:29 +0100 Subject: [PATCH] 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 --- .../IncomingInvoices.cs | 269 +++++++ src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs | 517 ++++++++++++ src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 1 + .../Security/CmsSignedData.cs | 756 ++++++++++++++++++ .../FatturaPaReaderTests.cs | 586 ++++++++++++++ .../Khaemhat.Fiscal.Italy.Tests.csproj | 5 + .../Security/CmsSignedDataTests.cs | 167 ++++ .../Security/CmsTestSigner.cs | 215 +++++ 8 files changed, 2516 insertions(+) create mode 100644 src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs create mode 100644 src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs create mode 100644 src/Khaemhat.Infrastructure/Security/CmsSignedData.cs create mode 100644 tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs diff --git a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs new file mode 100644 index 0000000..1c8c3e4 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs @@ -0,0 +1,269 @@ +namespace Khaemhat.Fiscal.Abstractions; + +// The supplier invoices received as files of the country's e-invoice format (Italy: FatturaPA, also signed .p7m). +// The records keep the file as it is, with the codes of the format; the import service maps them to documents. + +/// +/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like +/// . The reader only reads: it never contacts a service and never resolves external +/// references. +/// +public interface IIncomingInvoiceReader +{ + /// + /// Whether the file looks like one the reader understands (Italy: .xml, .p7m in DER or as base64 + /// text). The content is sniffed, not only the name. + /// + /// The name of the file, extension included. + /// The content, or at least its first bytes. + /// when is worth trying. + bool CanRead(string fileName, ReadOnlySpan content); + + /// Reads a file. + /// The name of the file, extension included. + /// The whole content. + /// The file with its invoices. + /// The file is not readable, not an invoice, or misses mandatory data; + /// is one of . + IncomingInvoiceFile Read(string fileName, byte[] content); +} + +/// A received e-invoice file that cannot be read; is one of . +public sealed class IncomingInvoiceException : Exception +{ + /// Creates the exception. + public IncomingInvoiceException() + : this(IncomingInvoiceErrors.NotReadable, "The file is not readable.") + { + } + + /// Creates the exception. + /// What went wrong. + public IncomingInvoiceException(string message) + : this(IncomingInvoiceErrors.NotReadable, message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public IncomingInvoiceException(string message, Exception innerException) + : this(IncomingInvoiceErrors.NotReadable, message, innerException) + { + } + + /// Creates the exception with a code. + /// One of . + /// What went wrong. + public IncomingInvoiceException(string code, string message) + : base(message) => Code = code; + + /// Creates the exception with a code and its cause. + /// One of . + /// What went wrong. + /// The cause. + public IncomingInvoiceException(string code, string message, Exception? innerException) + : base(message, innerException) => Code = code; + + /// The text code of the error, one of . + public string Code { get; } +} + +/// The codes of . +public static class IncomingInvoiceErrors +{ + /// Neither XML nor a signed envelope: garbage, an empty file, a truncated download. + public const string NotReadable = "incoming.not-readable"; + + /// A well-formed XML document that is not an e-invoice. + public const string NotInvoice = "incoming.not-invoice"; + + /// A signed envelope whose content cannot be extracted. + public const string SignatureBroken = "incoming.signature-broken"; + + /// An e-invoice that misses mandatory data (date, number, document type...). + public const string Invalid = "incoming.invalid"; +} + +/// A received e-invoice file: the transmission header, the two parties and one or more invoices. +/// The name of the file as received. +/// The transmission format (Italy: FPR12, FPA12, FSM10). +/// The progressive number of the transmission given by the sender. +/// The recipient code of the transmission. +/// The supplier who issued the invoices. +/// The customer the invoices are addressed to (normally the company). +/// The invoices, one per body of the file (a batch has more than one). +/// The signature of the envelope, or for an unsigned file. +/// The XML of the invoice, taken out of the envelope when the file was signed. +public sealed record IncomingInvoiceFile( + string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode, + IncomingParty Supplier, IncomingParty Customer, IReadOnlyList Invoices, + IncomingSignature? Signature, byte[] Xml); + +/// +/// The signature of a signed file. says only that the content is intact and signed by the key +/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no +/// trusted list is available offline. +/// +/// Whether the digest and the signature match the content. +/// The name of the signer, from the certificate. +/// The tax code of the signer, when the certificate carries it. +/// The signing time declared by the signer, if any (not a trusted timestamp). +/// The start of validity of the certificate. +/// The end of validity of the certificate. +/// Why the signature is not verified, or . +public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt, + DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem); + +/// A party of the invoice (supplier or customer) as written in the file. +/// The country of the VAT number. +/// The VAT number without the country prefix. +/// The tax code. +/// The company name, when the party is a company. +/// The first name, when the party is a person. +/// The last name, when the party is a person. +/// The street of the registered office. +/// The street number. +/// The postal code. +/// The city. +/// The province. +/// The country of the registered office. +/// The tax regime (supplier only). +/// The e-mail address (supplier only). +/// The phone number (supplier only). +/// The office of the companies register. +/// The number in the companies register. +public sealed record IncomingParty( + string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName, + string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country, + string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber) +{ + /// The company name, or first and last name of a person. + public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s))); +} + +/// An invoice of the file (one body). +/// The document type (Italy: TD01, TD04...). +/// The currency code. +/// The date of the document. +/// The number of the document. +/// The total amount declared by the supplier, if any. +/// The rounding on the total, if any. +/// The free-text causals. +/// Whether the document is issued under the rule that allows several documents with the same +/// number in a year (Italy: art. 73 DPR 633/72). +/// The withholding taxes. +/// The stamp duty, if any. +/// The social security contributions. +/// The discounts and surcharges on the whole document. +/// The purchase orders referred to. +/// The contracts referred to. +/// The invoices referred to (the invoice a credit note corrects). +/// The delivery notes referred to. +/// The lines. +/// The tax summary, one row per rate or nature. +/// The payment installments. +/// The attached files. +public sealed record IncomingInvoice( + string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding, + IReadOnlyList Causals, bool Art73, + IReadOnlyList Withholdings, IncomingStampDuty? StampDuty, + IReadOnlyList SocialSecurity, IReadOnlyList Discounts, + IReadOnlyList Orders, IReadOnlyList Contracts, + IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes, + IReadOnlyList Lines, IReadOnlyList TaxSummary, + IReadOnlyList Payments, IReadOnlyList Attachments); + +/// A line of an invoice. +/// The line number. +/// The item codes (type and value). +/// The description. +/// The quantity, if given. +/// The unit of measure, if given. +/// The unit price. +/// The total of the line, net of tax. +/// The tax rate in percent (zero with a nature). +/// The reason of a zero rate (Italy: N2.2...). +/// The discounts and surcharges of the line. +/// Whether the line is subject to withholding tax. +/// The kind of line (Italy: SC discount, PR premium, AB rebate, +/// AC ancillary cost). +/// The start of the period the line refers to. +/// The end of the period the line refers to. +/// The administrative reference (cost centre, internal code). +public sealed record IncomingLine( + int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit, + decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts, + bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference); + +/// A code of the item of a line. +/// The kind of code (EAN, SKU, the supplier's code...). +/// The code. +public sealed record IncomingItemCode(string Type, string Value); + +/// A discount or surcharge. +/// Whether it is a surcharge (Italy: MG) instead of a discount (SC). +/// The percentage, if given. +/// The amount, if given. +public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount); + +/// A row of the tax summary. +/// The tax rate in percent. +/// The reason of a zero rate. +/// The taxable amount. +/// The tax. +/// When the tax is due (Italy: I immediate, D deferred, S split payment). +/// The law that justifies the nature. +/// Ancillary expenses, if any. +/// The rounding, if any. +public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility, + string? LegalReference, decimal? ExpensesAmount, decimal? Rounding); + +/// A payment installment. +/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance). +/// The payment method (Italy: MP05 bank transfer...). +/// The due date, if given. +/// The amount. +/// The IBAN to pay to, if given. +/// The BIC, if given. +/// The beneficiary, if different from the supplier. +public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount, + string? Iban, string? Bic, string? Beneficiary); + +/// A reference to another document (order, contract, invoice, delivery note). +/// The number of the document. +/// The date of the document. +/// The lines of the invoice the reference applies to; empty when it applies to all. +/// The tender code, if any (public administration). +/// The project code, if any (public administration). +public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup); + +/// A withholding tax. +/// The kind of withholding (Italy: RT01...). +/// The amount withheld. +/// The rate in percent. +/// The payment reason (Italy: A...), if given. +public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason); + +/// The stamp duty of an invoice. +/// Whether it is paid virtually by the issuer. +/// The amount. +public sealed record IncomingStampDuty(bool Virtual, decimal Amount); + +/// A social security contribution added to the invoice. +/// The fund (Italy: TC01...). +/// The rate of the contribution in percent. +/// The amount of the contribution. +/// The amount the contribution is computed on, if given. +/// The tax rate applied to the contribution. +/// Whether the contribution is subject to withholding tax. +/// The reason of a zero tax rate. +public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate, + bool Withheld, string? Nature); + +/// A file attached to the invoice. +/// The name of the attachment. +/// The format declared by the supplier (such as PDF), if any. +/// The description, if any. +/// The decoded content. +public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content); diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs new file mode 100644 index 0000000..9775730 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs @@ -0,0 +1,517 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x +/// (FPR12, FPA12), simplified invoices (FSM10), plain .xml or signed CAdES .p7m +/// (binary or base64 text, also nested). +/// +/// +/// Elements are matched by local name, whatever the namespace or prefix (p:, ns2:, none). The XML +/// is read with DTDs prohibited and no resolver, so nothing external is ever loaded. A UTF-8 byte order mark, a +/// missing XML declaration, an ISO-8859-1 or windows-1252 declaration and leading whitespace are tolerated. +/// Amounts use the invariant culture (. separator) and dates yyyy-MM-dd. The reader does not +/// validate the file against the XSD nor recompute totals: it reports what the supplier wrote and rejects only files +/// without the data an import cannot do without (document type, date, number, prices and rates of the lines, the +/// rows of the tax summary, the amounts of withholdings and payments). A missing Divisa is read as +/// EUR; an attachment whose content is not valid base64 is kept with an empty content. +/// For signed files the signature is checked for integrity only (see ): no trust chain +/// and no revocation check. +/// Simplified invoices (FSM10): each DatiBeniServizi becomes a line with no quantity whose unit and +/// total price are Importo minus the tax, because there Importo includes the tax. The tax is +/// DatiIVA/Imposta or, when only the rate is given, the tax included in Importo at that rate; the rate is +/// DatiIVA/Aliquota or, when only the tax is given, derived from it. The tax summary groups the lines by rate and +/// nature, the total is the sum of Importo and DatiFatturaRettificata becomes the related invoice. +/// +public sealed class FatturaPaReader : IIncomingInvoiceReader +{ + /// The largest file read, as for signed envelopes (50 MB). + public const int MaxSize = CmsSignedData.MaxSize; + + /// + public bool CanRead(string fileName, ReadOnlySpan content) => + !content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content)); + + /// + public IncomingInvoiceFile Read(string fileName, byte[] content) + { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(content); + if (content.Length == 0) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is empty."); + } + + if (content.Length > MaxSize) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB."); + } + + IncomingSignature? signature = null; + var xml = content; + if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content)) + { + CmsContent envelope; + try + { + envelope = CmsSignedData.Read(content); + } + catch (CmsFormatException ex) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.SignatureBroken, "The content of the signed file cannot be extracted: " + ex.Message, ex); + } + + xml = envelope.Content; + var signer = envelope.Signer; + signature = new IncomingSignature( + envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime, + signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem); + } + + if (!LooksLikeXml(xml)) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is neither XML nor a signed envelope."); + } + + var root = Parse(xml).Root + ?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML has no root element."); + return root.Name.LocalName switch + { + "FatturaElettronica" => ReadOrdinary(fileName, root, signature, xml), + "FatturaElettronicaSemplificata" => ReadSimplified(fileName, root, signature, xml), + _ => throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not an electronic invoice."), + }; + } + + // --- XML ------------------------------------------------------------------------------------------------------- + + private static bool LooksLikeXml(ReadOnlySpan content) + { + if (content.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + content = content[3..]; + } + else if (content.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + return true; + } + + var trimmed = content.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']); + return !trimmed.IsEmpty && trimmed[0] == (byte)'<'; + } + + private static XDocument Parse(byte[] xml) + { + var text = Decode(xml).TrimStart('', ' ', '\t', '\r', '\n'); + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + }; + try + { + using var reader = XmlReader.Create(new StringReader(text), settings); + return XDocument.Load(reader); + } + catch (XmlException ex) + { + throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML is not well formed: " + ex.Message, ex); + } + } + + // The text is decoded here, then read from a string: the encoding of the declaration is honoured without the + // reader having to know code pages (windows-1252 is common in files written by older programs). + private static string Decode(byte[] xml) + { + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3); + } + + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xFF, 0xFE])) + { + return Encoding.Unicode.GetString(xml, 2, xml.Length - 2); + } + + if (xml.AsSpan().StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + return Encoding.BigEndianUnicode.GetString(xml, 2, xml.Length - 2); + } + + return EncodingOfDeclaration(xml).GetString(xml); + } + + private static Encoding EncodingOfDeclaration(byte[] xml) + { + var head = Encoding.ASCII.GetString(xml, 0, Math.Min(xml.Length, 256)); + var start = head.IndexOf("", start, StringComparison.Ordinal); + if (end < 0) + { + return new UTF8Encoding(false); + } + + var declaration = head[start..end]; + var at = declaration.IndexOf("encoding", StringComparison.OrdinalIgnoreCase); + if (at < 0) + { + return new UTF8Encoding(false); + } + + var quote = declaration.IndexOfAny(['"', '\''], at); + var close = quote < 0 ? -1 : declaration.IndexOf(declaration[quote], quote + 1); + if (close < 0) + { + return new UTF8Encoding(false); + } + + var name = declaration[(quote + 1)..close].Trim().ToUpperInvariant(); + return name switch + { + "UTF-8" or "UTF8" => new UTF8Encoding(false), + "ISO-8859-1" or "LATIN1" or "ISO8859-1" => Encoding.Latin1, + "WINDOWS-1252" or "CP1252" => CodePage(1252), + "ISO-8859-15" => CodePage(28605), + _ => new UTF8Encoding(false), + }; + } + + private static Encoding CodePage(int codePage) => + CodePagesEncodingProvider.Instance.GetEncoding(codePage) ?? Encoding.Latin1; + + // --- Ordinary invoice -------------------------------------------------------------------------------------------- + + private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + { + var header = El(root, "FatturaElettronicaHeader") + ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); + var transmission = El(header, "DatiTrasmissione"); + var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore."); + var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente."); + var bodies = Els(root, "FatturaElettronicaBody").ToList(); + if (bodies.Count == 0) + { + throw Invalid("The invoice has no FatturaElettronicaBody."); + } + + return new IncomingInvoiceFile( + fileName, + Text(transmission, "FormatoTrasmissione"), + Text(transmission, "ProgressivoInvio"), + Text(transmission, "CodiceDestinatario"), + ReadParty(supplier), + ReadParty(customer), + bodies.Select(ReadBody).ToList(), + signature, + xml); + } + + private static IncomingParty ReadParty(XElement party) + { + var personal = El(party, "DatiAnagrafici"); + var identifiers = El(party, "IdentificativiFiscali"); + var others = El(party, "AltriDatiIdentificativi"); + var vat = El(personal, "IdFiscaleIVA") ?? El(identifiers, "IdFiscaleIVA") ?? El(party, "IdFiscaleIVA"); + var names = El(personal, "Anagrafica") ?? others ?? party; + var office = El(party, "Sede") ?? El(others, "Sede"); + var register = El(party, "IscrizioneREA"); + var contacts = El(party, "Contatti"); + return new IncomingParty( + Text(vat, "IdPaese"), + Text(vat, "IdCodice"), + Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"), + Text(names, "Denominazione"), + Text(names, "Nome"), + Text(names, "Cognome"), + Text(office, "Indirizzo"), + Text(office, "NumeroCivico"), + Text(office, "CAP"), + Text(office, "Comune"), + Text(office, "Provincia"), + Text(office, "Nazione"), + Text(personal, "RegimeFiscale") ?? Text(party, "RegimeFiscale"), + Text(contacts, "Email"), + Text(contacts, "Telefono"), + Text(register, "Ufficio"), + Text(register, "NumeroREA")); + } + + private static IncomingInvoice ReadBody(XElement body, int index) + { + var general = El(body, "DatiGenerali"); + var document = El(general, "DatiGeneraliDocumento") + ?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento."); + var goods = El(body, "DatiBeniServizi"); + var stamp = El(document, "DatiBollo"); + + return new IncomingInvoice( + Required(document, "TipoDocumento", index), + Text(document, "Divisa") ?? "EUR", + RequiredDate(document, "Data", index), + Required(document, "Numero", index), + OptionalDecimal(document, "ImportoTotaleDocumento"), + OptionalDecimal(document, "Arrotondamento"), + Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(), + Flag(document, "Art73"), + Els(document, "DatiRitenuta").Select(w => new IncomingWithholding( + Required(w, "TipoRitenuta", index), + RequiredDecimal(w, "ImportoRitenuta", index), + RequiredDecimal(w, "AliquotaRitenuta", index), + Text(w, "CausalePagamento"))).ToList(), + stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m), + Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity( + Required(s, "TipoCassa", index), + RequiredDecimal(s, "AlCassa", index), + RequiredDecimal(s, "ImportoContributoCassa", index), + OptionalDecimal(s, "ImponibileCassa"), + RequiredDecimal(s, "AliquotaIVA", index), + Flag(s, "Ritenuta"), + Text(s, "Natura"))).ToList(), + ReadDiscounts(document), + ReadReferences(general, "DatiOrdineAcquisto"), + ReadReferences(general, "DatiContratto"), + ReadReferences(general, "DatiFattureCollegate"), + Els(general, "DatiDDT").Select(d => new IncomingReference( + Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(), + Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(), + Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary( + RequiredDecimal(r, "AliquotaIVA", index), + Text(r, "Natura"), + RequiredDecimal(r, "ImponibileImporto", index), + RequiredDecimal(r, "Imposta", index), + Text(r, "EsigibilitaIVA"), + Text(r, "RiferimentoNormativo"), + OptionalDecimal(r, "SpeseAccessorie"), + OptionalDecimal(r, "Arrotondamento"))).ToList(), + ReadPayments(body, index), + ReadAttachments(body)); + } + + private static IncomingLine ReadLine(XElement line, int position, int index) => new( + OptionalInt(line, "NumeroLinea") ?? position + 1, + Els(line, "CodiceArticolo") + .Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty)) + .Where(c => c.Value.Length > 0) + .ToList(), + Text(line, "Descrizione") ?? string.Empty, + OptionalDecimal(line, "Quantita"), + Text(line, "UnitaMisura"), + RequiredDecimal(line, "PrezzoUnitario", index), + RequiredDecimal(line, "PrezzoTotale", index), + RequiredDecimal(line, "AliquotaIVA", index), + Text(line, "Natura"), + ReadDiscounts(line), + Flag(line, "Ritenuta"), + Text(line, "TipoCessionePrestazione"), + OptionalDate(line, "DataInizioPeriodo"), + OptionalDate(line, "DataFinePeriodo"), + Text(line, "RiferimentoAmministrazione")); + + private static List ReadDiscounts(XElement? parent) => + Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount( + string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase), + OptionalDecimal(d, "Percentuale"), + OptionalDecimal(d, "Importo"))).ToList(); + + private static List ReadReferences(XElement? general, string name) => + Els(general, name).Select(r => new IncomingReference( + Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList(); + + private static List LineNumbers(XElement reference) => + Els(reference, "RiferimentoNumeroLinea") + .Select(n => int.TryParse(n.Value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : 0) + .Where(n => n > 0) + .ToList(); + + private static List ReadPayments(XElement body, int index) => + Els(body, "DatiPagamento").SelectMany(p => + { + var conditions = Text(p, "CondizioniPagamento"); + return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment( + conditions, + Text(d, "ModalitaPagamento"), + OptionalDate(d, "DataScadenzaPagamento"), + RequiredDecimal(d, "ImportoPagamento", index), + Text(d, "IBAN"), + Text(d, "BIC"), + Text(d, "Beneficiario"))); + }).ToList(); + + private static List ReadAttachments(XElement body) => + Els(body, "Allegati").Select(a => new IncomingAttachment( + Text(a, "NomeAttachment") ?? "allegato", + Text(a, "FormatoAttachment"), + Text(a, "DescrizioneAttachment"), + DecodeAttachment(El(a, "Attachment")?.Value))).ToList(); + + private static byte[] DecodeAttachment(string? base64) + { + if (string.IsNullOrWhiteSpace(base64)) + { + return []; + } + + var compact = new StringBuilder(base64.Length); + foreach (var c in base64) + { + if (!char.IsWhiteSpace(c)) + { + compact.Append(c); + } + } + + var text = compact.ToString(); + var buffer = new byte[text.Length / 4 * 3 + 3]; + return Convert.TryFromBase64String(text, buffer, out var written) ? buffer[..written] : []; + } + + // --- Simplified invoice ------------------------------------------------------------------------------------------ + + private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml) + { + var header = El(root, "FatturaElettronicaHeader") + ?? throw Invalid("The invoice has no FatturaElettronicaHeader."); + var transmission = El(header, "DatiTrasmissione"); + var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore."); + var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente."); + var bodies = Els(root, "FatturaElettronicaBody").ToList(); + if (bodies.Count == 0) + { + throw Invalid("The invoice has no FatturaElettronicaBody."); + } + + return new IncomingInvoiceFile( + fileName, + Text(transmission, "FormatoTrasmissione"), + Text(transmission, "ProgressivoInvio"), + Text(transmission, "CodiceDestinatario"), + ReadParty(supplier), + ReadParty(customer), + bodies.Select(ReadSimplifiedBody).ToList(), + signature, + xml); + } + + private static IncomingInvoice ReadSimplifiedBody(XElement body, int index) + { + var general = El(body, "DatiGenerali"); + var document = El(general, "DatiGeneraliDocumento") + ?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento."); + var lines = Els(body, "DatiBeniServizi").Select((l, i) => ReadSimplifiedLine(l, i, index)).ToList(); + var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index)); + var summary = lines + .GroupBy(l => (l.TaxRate, l.Nature)) + .Select(g => new IncomingTaxSummary( + g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null, + g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null)) + .ToList(); + var corrected = Els(general, "DatiFatturaRettificata") + .Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null)) + .ToList(); + + return new IncomingInvoice( + Required(document, "TipoDocumento", index), + Text(document, "Divisa") ?? "EUR", + RequiredDate(document, "Data", index), + Required(document, "Numero", index), + gross, + null, + [], + false, + [], + Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null, + [], + [], + [], + [], + corrected, + [], + lines.Select(l => l.Line).ToList(), + summary, + [], + ReadAttachments(body)); + } + + private static SimplifiedLine ReadSimplifiedLine(XElement line, int position, int index) + { + var gross = RequiredDecimal(line, "Importo", index); + var vat = El(line, "DatiIVA"); + var tax = OptionalDecimal(vat, "Imposta"); + var rate = OptionalDecimal(vat, "Aliquota"); + tax ??= rate is { } r && r != 0m ? Math.Round(gross * r / (100m + r), 2, MidpointRounding.AwayFromZero) : 0m; + var net = gross - tax.Value; + rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m; + var nature = Text(line, "Natura"); + return new SimplifiedLine( + new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature, + [], false, null, null, null, null), + tax.Value, + Text(line, "RiferimentoNormativo")); + } + + private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference) + { + public decimal TaxRate => Line.TaxRate; + + public string? Nature => Line.Nature; + + public decimal TotalPrice => Line.TotalPrice; + } + + // --- Helpers ----------------------------------------------------------------------------------------------------- + + private static XElement? El(XElement? parent, string localName) => + parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName); + + private static IEnumerable Els(XElement? parent, string localName) => + parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName); + + private static string? Text(XElement? parent, string localName) + { + var value = El(parent, localName)?.Value.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } + + private static bool Flag(XElement? parent, string localName) => + string.Equals(Text(parent, localName), "SI", StringComparison.OrdinalIgnoreCase); + + private static string Required(XElement parent, string localName, int index) => + Text(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing."); + + private static decimal? OptionalDecimal(XElement? parent, string localName) => + Text(parent, localName) is { } text && decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value) + ? value + : null; + + private static decimal RequiredDecimal(XElement parent, string localName, int index) => + OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number."); + + private static int? OptionalInt(XElement parent, string localName) => + Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null; + + private static DateOnly? OptionalDate(XElement? parent, string localName) + { + var text = Text(parent, localName); + if (text is null) + { + return null; + } + + // xs:date may carry a time zone (2026-03-15+01:00): the day is what counts. + var day = text.Length > 10 ? text[..10] : text; + return DateOnly.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? date : null; + } + + private static DateOnly RequiredDate(XElement parent, string localName, int index) => + OptionalDate(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a date."); + + private static IncomingInvoiceException Invalid(string message) => new(IncomingInvoiceErrors.Invalid, message); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index ab9137c..34498e2 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -15,6 +15,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase public ItalyFiscalPack() { AddFeature(new FatturaPaFormat()); + AddFeature(new FatturaPaReader()); AddFeature(new WithholdingRulesIt()); AddFeature(new FixedAssetRulesIt()); AddFeature(new F24Exporter()); diff --git a/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs b/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs new file mode 100644 index 0000000..aed701b --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/CmsSignedData.cs @@ -0,0 +1,756 @@ +using System.Buffers.Text; +using System.Formats.Asn1; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Khaemhat.Infrastructure.Security; + +/// A structure that is not a readable CMS SignedData, or whose content cannot be extracted. +public sealed class CmsFormatException : Exception +{ + /// Creates the exception. + public CmsFormatException() + : base("Not a CMS SignedData structure.") + { + } + + /// Creates the exception. + /// What went wrong. + public CmsFormatException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public CmsFormatException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// A signer of a CMS SignedData with what its certificate says and the result of the check. +/// The name of the signer: common name, else given name and surname, else organization, else +/// serial number of the subject. +/// The tax code of the signer, from the subject's SERIALNUMBER (OID 2.5.4.5) without +/// the TINIT- or IT: prefix, when present. +/// The subject of the certificate, or when it was not found. +/// The issuer of the certificate, or when it was not found. +/// The start of validity of the certificate. +/// The end of validity of the certificate. +/// The signingTime signed attribute: what the signer's clock said, not a trusted timestamp. +/// Whether the digest of the content and the signature match. +/// Why the signature is not verified, or . +/// The DER of the signer certificate, or when it was not found. +public sealed record CmsSigner( + string? Name, string? TaxCode, string? Subject, string? Issuer, + DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime, + bool Verified, string? Problem, byte[]? Certificate); + +/// The content of one or more nested CMS SignedData envelopes and their signers. +/// The content of the innermost envelope. +/// The signers, outermost envelope first. +/// How many envelopes were opened (two for .xml.p7m.p7m). +public sealed record CmsContent(byte[] Content, IReadOnlyList Signers, int Layers) +{ + /// Whether there is at least one signer and every signer of every envelope is verified. + public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified); + + /// The first problem found, or when . + public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem; + + /// The signer of the outermost envelope, or when there is none. + public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null; +} + +/// +/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as .p7m, +/// written on System.Formats.Asn1 because System.Security.Cryptography.Pkcs is a separate package +/// (SPEC §1.2). +/// +/// +/// It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the +/// binary with or without line breaks and -----BEGIN armour, and nested envelopes (.p7m.p7m), opened +/// until the content is no longer CMS. +/// It checks integrity only: the messageDigest attribute against the content (SHA-1, SHA-256, SHA-384, +/// SHA-512) and the signature with the public key of the embedded signer certificate (RSA PKCS #1 v1.5, RSA-PSS with +/// the salt as long as the hash, ECDSA). It does not check the trust chain, the qualified status of the +/// certificate or its revocation, because no trusted list is available offline; it never follows external +/// references. A broken signature still returns the content, with false and the +/// problem; only unreadable structures throw . Detached signatures (no content) are +/// not supported. +/// +public static class CmsSignedData +{ + /// The largest envelope read, 50 MB. + public const int MaxSize = 50 * 1024 * 1024; + + /// The most nested envelopes opened. + public const int MaxLayers = 8; + + private const string SignedDataOid = "1.2.840.113549.1.7.2"; + private const string ContentTypeAttributeOid = "1.2.840.113549.1.9.3"; + private const string MessageDigestAttributeOid = "1.2.840.113549.1.9.4"; + private const string SigningTimeAttributeOid = "1.2.840.113549.1.9.5"; + private const string RsaEncryptionOid = "1.2.840.113549.1.1.1"; + private const string RsaPssOid = "1.2.840.113549.1.1.10"; + private const string EcPublicKeyOid = "1.2.840.10045.2.1"; + + // DER of OBJECT IDENTIFIER 1.2.840.113549.1.7.2 (signedData): what follows the header of the outer SEQUENCE. + private static readonly byte[] SignedDataOidDer = [0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02]; + + private static readonly Asn1Tag Context0 = new(TagClass.ContextSpecific, 0); + private static readonly Asn1Tag Context0Constructed = new(TagClass.ContextSpecific, 0, isConstructed: true); + private static readonly Asn1Tag Context1 = new(TagClass.ContextSpecific, 1); + + /// Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at. + /// The content, or at least its first hundred bytes. + /// when is worth trying. + public static bool LooksLikeCms(ReadOnlySpan data) + { + if (LooksLikeBinaryCms(data)) + { + return true; + } + + // Base64 text: decode the first characters and look again. + Span chars = stackalloc byte[96]; + var count = 0; + foreach (var b in SkipArmour(SkipBom(data))) + { + if (IsBase64Whitespace(b)) + { + continue; + } + + if (!IsBase64Char(b)) + { + break; + } + + chars[count++] = b; + if (count == chars.Length) + { + break; + } + } + + count -= count % 4; + if (count < 24) + { + return false; + } + + Span decoded = stackalloc byte[72]; + var status = Base64.DecodeFromUtf8(chars[..count], decoded, out _, out var written, isFinalBlock: false); + return status is System.Buffers.OperationStatus.Done or System.Buffers.OperationStatus.NeedMoreData + && LooksLikeBinaryCms(decoded[..written]); + } + + /// + /// Opens a CMS SignedData and every envelope nested inside it, and checks the signatures. Accepts DER, BER and + /// base64 text (see the remarks of the class). + /// + /// The envelope. + /// The content of the innermost envelope and the signers. + /// The data is not a CMS SignedData, is too large, nests too deep, has no + /// content, or cannot be decoded. + public static CmsContent Read(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + var current = data; + var signers = new List(); + var layers = 0; + while (true) + { + if (current.Length > MaxSize) + { + throw new CmsFormatException($"The envelope is larger than {MaxSize / (1024 * 1024)} MB."); + } + + var binary = ToBinary(current); + if (binary is null) + { + if (layers == 0) + { + throw new CmsFormatException("Not a CMS SignedData structure."); + } + + return new CmsContent(current, signers, layers); + } + + if (++layers > MaxLayers) + { + throw new CmsFormatException($"More than {MaxLayers} nested envelopes."); + } + + current = ReadLayer(binary, signers); + } + } + + /// + /// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, -----BEGIN + /// and -----END lines dropped, a UTF-8 byte order mark ignored. + /// + /// The text, as bytes. + /// The decoded bytes, or when the text is not base64. + public static byte[]? DecodeBase64Text(ReadOnlySpan text) + { + var body = SkipBom(text); + var filtered = new byte[body.Length]; + var count = 0; + var lineStart = true; + var skippingLine = false; + foreach (var b in body) + { + if (b is (byte)'\n' or (byte)'\r') + { + lineStart = true; + skippingLine = false; + continue; + } + + if (lineStart && b == (byte)'-') + { + skippingLine = true; + } + + lineStart = false; + if (skippingLine || IsBase64Whitespace(b)) + { + continue; + } + + if (!IsBase64Char(b) && b != (byte)'=') + { + return null; + } + + filtered[count++] = b; + } + + if (count == 0 || count % 4 != 0) + { + return null; + } + + var output = new byte[Base64.GetMaxDecodedFromUtf8Length(count)]; + var status = Base64.DecodeFromUtf8(filtered.AsSpan(0, count), output, out _, out var written); + return status == System.Buffers.OperationStatus.Done ? output[..written] : null; + } + + private static byte[]? ToBinary(byte[] data) + { + if (LooksLikeBinaryCms(data)) + { + return data; + } + + if (!LooksLikeCms(data)) + { + return null; + } + + var decoded = DecodeBase64Text(data); + return decoded is not null && LooksLikeBinaryCms(decoded) ? decoded : null; + } + + private static bool LooksLikeBinaryCms(ReadOnlySpan data) + { + if (data.Length < 2 || data[0] != 0x30) + { + return false; + } + + int header; + if (data[1] <= 0x80) + { + header = 2; + } + else + { + var lengthBytes = data[1] & 0x7F; + if (lengthBytes > 4) + { + return false; + } + + header = 2 + lengthBytes; + } + + return data.Length >= header + SignedDataOidDer.Length && data.Slice(header, SignedDataOidDer.Length).SequenceEqual(SignedDataOidDer); + } + + private static byte[] ReadLayer(byte[] data, List signers) + { + try + { + var outer = new AsnReader(data, AsnEncodingRules.BER); + var contentInfo = outer.ReadSequence(); + if (contentInfo.ReadObjectIdentifier() != SignedDataOid) + { + throw new CmsFormatException("The envelope is not SignedData."); + } + + var signedData = contentInfo.ReadSequence(Context0Constructed).ReadSequence(); + signedData.ReadInteger(); + signedData.ReadSetOf(skipSortOrderValidation: true); + + var encapsulated = signedData.ReadSequence(); + encapsulated.ReadObjectIdentifier(); + if (!encapsulated.HasData) + { + throw new CmsFormatException("The signature is detached: the envelope has no content."); + } + + var content = encapsulated.ReadSequence(Context0Constructed).ReadOctetString(); + + var certificates = new List(); + if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context0)) + { + var set = signedData.ReadSetOf(skipSortOrderValidation: true, Context0); + while (set.HasData) + { + var tag = set.PeekTag(); + var encoded = set.ReadEncodedValue(); + if (tag.HasSameClassAndValue(Asn1Tag.Sequence)) + { + certificates.Add(encoded.ToArray()); + } + } + } + + if (signedData.HasData && signedData.PeekTag().HasSameClassAndValue(Context1)) + { + signedData.ReadEncodedValue(); + } + + var signerInfos = signedData.ReadSetOf(skipSortOrderValidation: true); + var found = 0; + while (signerInfos.HasData) + { + signers.Add(ReadSigner(signerInfos.ReadSequence(), content, certificates)); + found++; + } + + if (found == 0) + { + signers.Add(new CmsSigner(null, null, null, null, null, null, null, false, "The envelope has no signer.", null)); + } + + return content; + } + catch (AsnContentException ex) + { + throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex); + } + catch (CryptographicException ex) + { + throw new CmsFormatException("The envelope cannot be decoded: " + ex.Message, ex); + } + } + + private static CmsSigner ReadSigner(AsnReader signerInfo, byte[] content, List certificates) + { + signerInfo.ReadInteger(); + byte[]? issuer = null; + byte[]? serial = null; + byte[]? keyIdentifier = null; + if (signerInfo.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence)) + { + var issuerAndSerial = signerInfo.ReadSequence(); + issuer = issuerAndSerial.ReadEncodedValue().ToArray(); + serial = issuerAndSerial.ReadIntegerBytes().ToArray(); + } + else + { + keyIdentifier = signerInfo.ReadOctetString(Context0); + } + + var (digestOid, _) = ReadAlgorithm(signerInfo); + byte[]? signedAttributes = null; + if (signerInfo.PeekTag().HasSameClassAndValue(Context0)) + { + signedAttributes = signerInfo.ReadEncodedValue().ToArray(); + } + + var (signatureOid, signatureParameters) = ReadAlgorithm(signerInfo); + var signature = signerInfo.ReadOctetString(); + + DateTimeOffset? signingTime = null; + byte[]? messageDigest = null; + if (signedAttributes is not null) + { + ReadAttributes(signedAttributes, out messageDigest, out signingTime); + } + + using var certificate = FindCertificate(certificates, issuer, serial, keyIdentifier); + var problem = Verify(certificate, content, digestOid, signedAttributes, messageDigest, signatureOid, signatureParameters, signature); + return Describe(certificate, signingTime, problem); + } + + private static (string Oid, byte[]? Parameters) ReadAlgorithm(AsnReader reader) + { + var algorithm = reader.ReadSequence(); + var oid = algorithm.ReadObjectIdentifier(); + var parameters = algorithm.HasData ? algorithm.ReadEncodedValue().ToArray() : null; + return (oid, parameters); + } + + private static void ReadAttributes(byte[] signedAttributes, out byte[]? messageDigest, out DateTimeOffset? signingTime) + { + messageDigest = null; + signingTime = null; + var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0); + while (set.HasData) + { + var attribute = set.ReadSequence(); + var type = attribute.ReadObjectIdentifier(); + var values = attribute.ReadSetOf(skipSortOrderValidation: true); + if (!values.HasData) + { + continue; + } + + switch (type) + { + case MessageDigestAttributeOid: + messageDigest = values.ReadOctetString(); + break; + case SigningTimeAttributeOid: + signingTime = values.PeekTag().HasSameClassAndValue(Asn1Tag.UtcTime) ? values.ReadUtcTime() : values.ReadGeneralizedTime(); + break; + case ContentTypeAttributeOid: + default: + break; + } + } + } + + private static X509Certificate2? FindCertificate(List certificates, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier) + { + foreach (var der in certificates) + { + X509Certificate2 certificate; + try + { + certificate = X509CertificateLoader.LoadCertificate(der); + } + catch (CryptographicException) + { + continue; + } + + if (Matches(certificate, issuer, serial, keyIdentifier)) + { + return certificate; + } + + certificate.Dispose(); + } + + return null; + } + + private static bool Matches(X509Certificate2 certificate, byte[]? issuer, byte[]? serial, byte[]? keyIdentifier) + { + if (issuer is not null && serial is not null) + { + return certificate.IssuerName.RawData.AsSpan().SequenceEqual(issuer) + && certificate.SerialNumberBytes.Span.SequenceEqual(serial); + } + + return keyIdentifier is not null + && certificate.Extensions.OfType().FirstOrDefault() is { } extension + && extension.SubjectKeyIdentifierBytes.Span.SequenceEqual(keyIdentifier); + } + + private static string? Verify( + X509Certificate2? certificate, byte[] content, string digestOid, byte[]? signedAttributes, byte[]? messageDigest, + string signatureOid, byte[]? signatureParameters, byte[] signature) + { + if (certificate is null) + { + return "The signer certificate is not in the envelope."; + } + + if (HashOf(digestOid) is not { } digest) + { + return $"Unsupported digest algorithm {digestOid}."; + } + + List signedForms; + if (signedAttributes is null) + { + signedForms = [content]; + } + else + { + if (messageDigest is null) + { + return "The signed attributes have no message digest."; + } + + if (!CryptographicOperations.FixedTimeEquals(CryptographicOperations.HashData(digest, content), messageDigest)) + { + return "The content does not match the signed digest: it was changed after signing."; + } + + signedForms = SignedAttributesAsSet(signedAttributes); + } + + try + { + foreach (var signed in signedForms) + { + var result = VerifySignature(certificate, signed, digest, signatureOid, signatureParameters, signature); + if (result is null) + { + return null; + } + + if (result.Length > 0) + { + return result; + } + } + } + catch (CryptographicException ex) + { + return "The signature cannot be checked: " + ex.Message; + } + + return "The signature does not match the signer certificate."; + } + + // The signature covers the DER of the attributes as a SET (tag 0x31), not the [0] implicit tag of the file. The + // bytes of the file are tried first (they are DER in every well-formed signature); a DER re-encoding after. + private static List SignedAttributesAsSet(byte[] signedAttributes) + { + var forms = new List(); + if (signedAttributes.Length > 1 && signedAttributes[1] != 0x80) + { + var asSet = (byte[])signedAttributes.Clone(); + asSet[0] = 0x31; + forms.Add(asSet); + } + + try + { + var set = new AsnReader(signedAttributes, AsnEncodingRules.BER).ReadSetOf(skipSortOrderValidation: true, Context0); + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSetOf()) + { + while (set.HasData) + { + writer.WriteEncodedValue(set.ReadEncodedValue().Span); + } + } + + var der = writer.Encode(); + if (!forms.Exists(f => f.AsSpan().SequenceEqual(der))) + { + forms.Add(der); + } + } + catch (ArgumentException) + { + // Attributes that are not DER inside cannot be re-encoded; the bytes of the file are all there is. + } + catch (AsnContentException) + { + // Same as above. + } + + return forms; + } + + // Null when verified, an empty string when the signature does not match, a message for an unsupported algorithm. + private static string? VerifySignature( + X509Certificate2 certificate, byte[] signed, HashAlgorithmName digest, string signatureOid, byte[]? signatureParameters, byte[] signature) + { + switch (signatureOid) + { + case RsaPssOid: + { + using var rsa = certificate.GetRSAPublicKey(); + if (rsa is null) + { + return "The signer certificate has no RSA key."; + } + + var pssHash = PssHash(signatureParameters) ?? digest; + return rsa.VerifyData(signed, signature, pssHash, RSASignaturePadding.Pss) ? null : string.Empty; + } + + case EcPublicKeyOid: + case "1.2.840.10045.4.1": + case "1.2.840.10045.4.3.2": + case "1.2.840.10045.4.3.3": + case "1.2.840.10045.4.3.4": + { + using var ecdsa = certificate.GetECDsaPublicKey(); + if (ecdsa is null) + { + return "The signer certificate has no ECDSA key."; + } + + var hash = signatureOid == EcPublicKeyOid ? digest : HashOfSignature(signatureOid) ?? digest; + return ecdsa.VerifyData(signed, signature, hash, DSASignatureFormat.Rfc3279DerSequence) ? null : string.Empty; + } + + case RsaEncryptionOid: + case "1.2.840.113549.1.1.5": + case "1.2.840.113549.1.1.11": + case "1.2.840.113549.1.1.12": + case "1.2.840.113549.1.1.13": + { + using var rsa = certificate.GetRSAPublicKey(); + if (rsa is null) + { + return "The signer certificate has no RSA key."; + } + + var hash = signatureOid == RsaEncryptionOid ? digest : HashOfSignature(signatureOid) ?? digest; + return rsa.VerifyData(signed, signature, hash, RSASignaturePadding.Pkcs1) ? null : string.Empty; + } + + default: + return $"Unsupported signature algorithm {signatureOid}."; + } + } + + private static HashAlgorithmName? HashOf(string digestOid) => digestOid switch + { + "1.3.14.3.2.26" => HashAlgorithmName.SHA1, + "2.16.840.1.101.3.4.2.1" => HashAlgorithmName.SHA256, + "2.16.840.1.101.3.4.2.2" => HashAlgorithmName.SHA384, + "2.16.840.1.101.3.4.2.3" => HashAlgorithmName.SHA512, + _ => null, + }; + + private static HashAlgorithmName? HashOfSignature(string signatureOid) => signatureOid switch + { + "1.2.840.113549.1.1.5" or "1.2.840.10045.4.1" => HashAlgorithmName.SHA1, + "1.2.840.113549.1.1.11" or "1.2.840.10045.4.3.2" => HashAlgorithmName.SHA256, + "1.2.840.113549.1.1.12" or "1.2.840.10045.4.3.3" => HashAlgorithmName.SHA384, + "1.2.840.113549.1.1.13" or "1.2.840.10045.4.3.4" => HashAlgorithmName.SHA512, + _ => null, + }; + + // RSASSA-PSS-params: hashAlgorithm [0] (default SHA-1), maskGenAlgorithm [1], saltLength [2], trailerField [3]. + private static HashAlgorithmName? PssHash(byte[]? parameters) + { + if (parameters is null) + { + return null; + } + + var sequence = new AsnReader(parameters, AsnEncodingRules.BER).ReadSequence(); + if (!sequence.HasData || !sequence.PeekTag().HasSameClassAndValue(Context0)) + { + return HashAlgorithmName.SHA1; + } + + var (oid, _) = ReadAlgorithm(sequence.ReadSequence(Context0Constructed)); + return HashOf(oid); + } + + private static CmsSigner Describe(X509Certificate2? certificate, DateTimeOffset? signingTime, string? problem) + { + if (certificate is null) + { + return new CmsSigner(null, null, null, null, null, null, signingTime, false, problem, null); + } + + string? commonName = null, givenName = null, surname = null, organization = null, serialNumber = null; + foreach (var rdn in certificate.SubjectName.EnumerateRelativeDistinguishedNames()) + { + if (rdn.HasMultipleElements) + { + continue; + } + + var value = rdn.GetSingleElementValue(); + switch (rdn.GetSingleElementType().Value) + { + case "2.5.4.3": + commonName ??= value; + break; + case "2.5.4.42": + givenName ??= value; + break; + case "2.5.4.4": + surname ??= value; + break; + case "2.5.4.10": + organization ??= value; + break; + case "2.5.4.5": + serialNumber ??= value; + break; + default: + break; + } + } + + var personName = string.Join(' ', new[] { givenName, surname }.Where(s => !string.IsNullOrWhiteSpace(s))); + var name = NullIfBlank(commonName) ?? NullIfBlank(personName) ?? NullIfBlank(organization) ?? NullIfBlank(serialNumber); + return new CmsSigner( + name, + TaxCodeOf(serialNumber), + certificate.Subject, + certificate.Issuer, + new DateTimeOffset(certificate.NotBefore.ToUniversalTime(), TimeSpan.Zero), + new DateTimeOffset(certificate.NotAfter.ToUniversalTime(), TimeSpan.Zero), + signingTime, + problem is null, + problem, + certificate.RawData); + } + + // ETSI EN 319 412-1: SERIALNUMBER = TINIT-; older Italian certificates use IT:. + private static string? TaxCodeOf(string? serialNumber) + { + if (string.IsNullOrWhiteSpace(serialNumber)) + { + return null; + } + + var value = serialNumber.Trim(); + if (value.StartsWith("TINIT-", StringComparison.OrdinalIgnoreCase)) + { + return NullIfBlank(value["TINIT-".Length..].Trim()); + } + + if (value.StartsWith("IT:", StringComparison.OrdinalIgnoreCase)) + { + return NullIfBlank(value["IT:".Length..].Trim()); + } + + return value.Length is 11 or 16 && value.All(char.IsAsciiLetterOrDigit) ? value.ToUpperInvariant() : null; + } + + private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value; + + private static ReadOnlySpan SkipBom(ReadOnlySpan data) => + data.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF]) ? data[3..] : data; + + private static ReadOnlySpan SkipArmour(ReadOnlySpan data) + { + var trimmed = data.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']); + if (!trimmed.StartsWith("-----"u8)) + { + return trimmed; + } + + var end = trimmed.IndexOf((byte)'\n'); + return end < 0 ? [] : trimmed[(end + 1)..]; + } + + private static bool IsBase64Char(byte b) => + b is (>= (byte)'A' and <= (byte)'Z') or (>= (byte)'a' and <= (byte)'z') or (>= (byte)'0' and <= (byte)'9') or (byte)'+' or (byte)'/'; + + private static bool IsBase64Whitespace(byte b) => b is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n'; +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs new file mode 100644 index 0000000..96fc5f6 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs @@ -0,0 +1,586 @@ +using System.Text; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Tests.Security; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// +/// 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. +/// +[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 = """ + + + IT01234567890 + 00042 + FPR12 + ABC1234 + + + + IT01234567890 + 01234567890 + Ferramenta Piemontese S.r.l. + RF01 + + + Via Roma1210121 + TorinoTOIT + + TO123456LN + 011 1234567amministrazione@ferramenta.example + + + + IT09876543210 + Officine Esempio S.p.A. + + Corso Milano20121MilanoMIIT + + + """; + + private const string OrdinaryBody = """ + + + + TD01 + EUR + 2026-03-15 + FT/2026/123 + SC2.00 + MG1.50 + 116.90 + Fornitura di marzo + Consegna in cantiere + + + 1 + 2 + ORD-77 + 2026-03-01 + J11B26000010001 + Z1234567AB + + + DDT-501 + 2026-03-10 + 1 + + + + + 1 + SKUB-M8-ZN + EAN8001234567895 + Bulloni M8 zincati + 100.00 + PZ + 0.500000 + SC10.00 + 45.00 + 22.00 + + + 2 + Manuale tecnico di carpenteria + 2.00 + 25.00 + 50.00 + 4.00 + + + 3 + AC + Contributo ambientale imballi + 2026-03-01 + 2026-03-31 + 10.00 + 10.00 + 0.00 + N2.2 + CC-12 + + + 22.0045.009.90I + + + 4.0050.002.00I + + + 0.00N2.210.000.00 + Non soggetto art. 15 DPR 633/72 + + + + TP01 + + MP05 + 2026-04-30 + 58.45 + IT60X0542811101000000123456 + + + Ferramenta Piemontese S.r.l. + MP05 + 2026-05-31 + 58.45 + IT60X0542811101000000123456 + BPMOIT22XXX + + + + """; + + private static string Prefixed(params string[] bodies) => + $"""{Header}{string.Concat(bodies)}"""; + + private static string Body(string type, string number, string date, string generalExtra = "", string documentExtra = "", string goods = "", string extra = "") => $""" + + + + {type}EUR{date}{number}{documentExtra} + {generalExtra} + + {(goods.Length > 0 ? goods : SimpleGoods)}{extra} + + """; + + private const string SimpleGoods = """ + 1Consulenza100.00100.0022.00 + 22.00100.0022.00I + """; + + 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 = """ + FT/2026/1232026-03-15 + CTR-2026-01 + """; + 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("", StringComparison.Ordinal)..][2..]; + + byte[] withBom = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes("\r\n " + prefixed)]; + var variants = new List + { + 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 = """ + 1Caffè in grani € 1 al kg10.0010.0010.00 + 10.0010.001.00 + """; + 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 = """ + RT01208.0020.00A + SI2.00 + + TC014.0040.00 + 1000.0022.00SI + + 1270.88 + 0.01 + SI + """; + var goods = """ + 1Parere legale1000.001000.0022.00SI + 22.001040.00228.80I + """; + var xml = Prefixed(Body("TD06", "12/2026", "2026-04-02", documentExtra: document, goods: goods)) + .Replace("Ferramenta Piemontese S.r.l.", "GiuliaBianchi", 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 = $""" + + FT_2026_5.pdf + PDF + Copia di cortesia + {Convert.ToBase64String(pdf, Base64FormattingOptions.InsertLineBreaks)} + + + """; + + 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 = """ + + + + + IT01234567890 + S0001 + FSM10 + 0000000 + + + IT01234567890 + Bar Centrale di Rossi Mario + Piazza Castello10123TorinoTOIT + RF01 + + + IT09876543210 + + Officine Esempio S.p.A. + Corso Milano20121MilanoMIIT + + + + + + TD08EUR2026-05-04S/18 + S/122026-04-28Importo + + Pranzo di lavoro122.0022.00 + Quotidiani e riviste52.004.00 + Francobolli30.000.00N2.2 + + + """; + + 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("
")); + } + + [TestMethod] + public void Read_Dtd_IsRefused() + { + var xml = """]>&e;"""; + + AssertError(IncomingInvoiceErrors.NotReadable, Encoding.UTF8.GetBytes(xml)); + } + + [TestMethod] + public void Read_OtherXml_IsNotAnInvoice() => + AssertError(IncomingInvoiceErrors.NotInvoice, Encoding.UTF8.GetBytes("""1""")); + + [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 = $"""{Body("TD01", "7", "2026-01-10")}"""; + var noBody = $"""{Header}"""; + + foreach (var xml in new[] { noNumber, badDate, noHeader, noBody }) + { + AssertError(IncomingInvoiceErrors.Invalid, Encoding.UTF8.GetBytes(xml)); + } + + var ex = Assert.ThrowsExactly(() => 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(new ItalyFiscalPack().GetFeature()); + + private static void AssertError(string code, byte[] content) + { + var ex = Assert.ThrowsExactly(() => Reader.Read(FileName, content)); + Assert.AreEqual(code, ex.Code, ex.Message); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj b/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj index ac3cce5..fb03430 100644 --- a/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj +++ b/tests/Khaemhat.Fiscal.Italy.Tests/Khaemhat.Fiscal.Italy.Tests.csproj @@ -8,4 +8,9 @@ + + + + + diff --git a/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs b/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs new file mode 100644 index 0000000..3bcd86b --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Security/CmsSignedDataTests.cs @@ -0,0 +1,167 @@ +using System.Text; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Infrastructure.Tests.Security; + +/// The reader of CMS SignedData envelopes (.p7m) used for received e-invoices (issue #57). +[TestClass] +public sealed class CmsSignedDataTests +{ + private static readonly byte[] Content = Encoding.UTF8.GetBytes("contenuto firmato"); + + [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("contenuto alterato"); + 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("Bulloni M8 zincati", 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(() => CmsSignedData.Read(Encoding.UTF8.GetBytes("questo non è un file firmato"))); + Assert.ThrowsExactly(() => CmsSignedData.Read([])); + Assert.ThrowsExactly(() => 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(() => 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)); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs b/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs new file mode 100644 index 0000000..8940eb4 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs @@ -0,0 +1,215 @@ +using System.Formats.Asn1; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Khaemhat.Infrastructure.Tests.Security; + +/// How builds the envelope. +internal sealed record CmsTestOptions +{ + /// BER with indefinite lengths and the content split in chunks, as many signing programs write. + public bool Ber { get; init; } + + /// Identify the signer by subject key identifier instead of issuer and serial number. + public bool BySubjectKeyIdentifier { get; init; } + + /// Whether to sign attributes (contentType, messageDigest, signingTime) or the content directly. + public bool SignedAttributes { get; init; } = true; + + /// Content put in the envelope instead of the signed one (to simulate tampering). + public byte[]? TamperedContent { get; init; } + + /// Flip a bit of the signature. + public bool BreakSignature { get; init; } +} + +/// +/// Builds CMS SignedData envelopes (CAdES .p7m) in the tests with and self-signed certificates: +/// no fixture is downloaded and no package is needed. Shared with the tests of the FatturaPA reader. +/// +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 RsaCertificate = new(() => Create(ecdsa: false)); + private static readonly Lazy EcdsaCertificate = new(() => Create(ecdsa: true)); + + /// A self-signed RSA certificate of "Mario Rossi" with SERIALNUMBER=TINIT-RSSMRA80A01H501U. + public static X509Certificate2 Rsa => RsaCertificate.Value; + + /// A self-signed ECDSA P-256 certificate of the same person. + 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().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 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 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]; +}