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,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.
|
||||
|
||||
/// <summary>
|
||||
/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like
|
||||
/// <see cref="IEInvoiceFormat"/>. The reader only reads: it never contacts a service and never resolves external
|
||||
/// references.
|
||||
/// </summary>
|
||||
public interface IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the file looks like one the reader understands (Italy: <c>.xml</c>, <c>.p7m</c> in DER or as base64
|
||||
/// text). The content is sniffed, not only the name.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The content, or at least its first bytes.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
bool CanRead(string fileName, ReadOnlySpan<byte> content);
|
||||
|
||||
/// <summary>Reads a file.</summary>
|
||||
/// <param name="fileName">The name of the file, extension included.</param>
|
||||
/// <param name="content">The whole content.</param>
|
||||
/// <returns>The file with its invoices.</returns>
|
||||
/// <exception cref="IncomingInvoiceException">The file is not readable, not an invoice, or misses mandatory data;
|
||||
/// <see cref="IncomingInvoiceException.Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</exception>
|
||||
IncomingInvoiceFile Read(string fileName, byte[] content);
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file that cannot be read; <see cref="Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public sealed class IncomingInvoiceException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public IncomingInvoiceException()
|
||||
: this(IncomingInvoiceErrors.NotReadable, "The file is not readable.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string message)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string message, Exception innerException)
|
||||
: this(IncomingInvoiceErrors.NotReadable, message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a code.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public IncomingInvoiceException(string code, string message)
|
||||
: base(message) => Code = code;
|
||||
|
||||
/// <summary>Creates the exception with a code and its cause.</summary>
|
||||
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public IncomingInvoiceException(string code, string message, Exception? innerException)
|
||||
: base(message, innerException) => Code = code;
|
||||
|
||||
/// <summary>The text code of the error, one of <see cref="IncomingInvoiceErrors"/>.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>The codes of <see cref="IncomingInvoiceException"/>.</summary>
|
||||
public static class IncomingInvoiceErrors
|
||||
{
|
||||
/// <summary>Neither XML nor a signed envelope: garbage, an empty file, a truncated download.</summary>
|
||||
public const string NotReadable = "incoming.not-readable";
|
||||
|
||||
/// <summary>A well-formed XML document that is not an e-invoice.</summary>
|
||||
public const string NotInvoice = "incoming.not-invoice";
|
||||
|
||||
/// <summary>A signed envelope whose content cannot be extracted.</summary>
|
||||
public const string SignatureBroken = "incoming.signature-broken";
|
||||
|
||||
/// <summary>An e-invoice that misses mandatory data (date, number, document type...).</summary>
|
||||
public const string Invalid = "incoming.invalid";
|
||||
}
|
||||
|
||||
/// <summary>A received e-invoice file: the transmission header, the two parties and one or more invoices.</summary>
|
||||
/// <param name="FileName">The name of the file as received.</param>
|
||||
/// <param name="TransmissionFormat">The transmission format (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</param>
|
||||
/// <param name="ProgressiveNumber">The progressive number of the transmission given by the sender.</param>
|
||||
/// <param name="RecipientCode">The recipient code of the transmission.</param>
|
||||
/// <param name="Supplier">The supplier who issued the invoices.</param>
|
||||
/// <param name="Customer">The customer the invoices are addressed to (normally the company).</param>
|
||||
/// <param name="Invoices">The invoices, one per body of the file (a batch has more than one).</param>
|
||||
/// <param name="Signature">The signature of the envelope, or <see langword="null"/> for an unsigned file.</param>
|
||||
/// <param name="Xml">The XML of the invoice, taken out of the envelope when the file was signed.</param>
|
||||
public sealed record IncomingInvoiceFile(
|
||||
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
|
||||
IncomingParty Supplier, IncomingParty Customer, IReadOnlyList<IncomingInvoice> Invoices,
|
||||
IncomingSignature? Signature, byte[] Xml);
|
||||
|
||||
/// <summary>
|
||||
/// The signature of a signed file. <see cref="Verified"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="Verified">Whether the digest and the signature match the content.</param>
|
||||
/// <param name="Signer">The name of the signer, from the certificate.</param>
|
||||
/// <param name="SignerTaxCode">The tax code of the signer, when the certificate carries it.</param>
|
||||
/// <param name="SignedAt">The signing time declared by the signer, if any (not a trusted timestamp).</param>
|
||||
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
||||
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
||||
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
|
||||
|
||||
/// <summary>A party of the invoice (supplier or customer) as written in the file.</summary>
|
||||
/// <param name="CountryCode">The country of the VAT number.</param>
|
||||
/// <param name="VatNumber">The VAT number without the country prefix.</param>
|
||||
/// <param name="TaxCode">The tax code.</param>
|
||||
/// <param name="Name">The company name, when the party is a company.</param>
|
||||
/// <param name="FirstName">The first name, when the party is a person.</param>
|
||||
/// <param name="LastName">The last name, when the party is a person.</param>
|
||||
/// <param name="Address">The street of the registered office.</param>
|
||||
/// <param name="StreetNumber">The street number.</param>
|
||||
/// <param name="PostalCode">The postal code.</param>
|
||||
/// <param name="City">The city.</param>
|
||||
/// <param name="Province">The province.</param>
|
||||
/// <param name="Country">The country of the registered office.</param>
|
||||
/// <param name="TaxRegime">The tax regime (supplier only).</param>
|
||||
/// <param name="Email">The e-mail address (supplier only).</param>
|
||||
/// <param name="Phone">The phone number (supplier only).</param>
|
||||
/// <param name="ReaOffice">The office of the companies register.</param>
|
||||
/// <param name="ReaNumber">The number in the companies register.</param>
|
||||
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)
|
||||
{
|
||||
/// <summary>The company name, or first and last name of a person.</summary>
|
||||
public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
}
|
||||
|
||||
/// <summary>An invoice of the file (one body).</summary>
|
||||
/// <param name="DocumentType">The document type (Italy: <c>TD01</c>, <c>TD04</c>...).</param>
|
||||
/// <param name="Currency">The currency code.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="Number">The number of the document.</param>
|
||||
/// <param name="Total">The total amount declared by the supplier, if any.</param>
|
||||
/// <param name="Rounding">The rounding on the total, if any.</param>
|
||||
/// <param name="Causals">The free-text causals.</param>
|
||||
/// <param name="Art73">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).</param>
|
||||
/// <param name="Withholdings">The withholding taxes.</param>
|
||||
/// <param name="StampDuty">The stamp duty, if any.</param>
|
||||
/// <param name="SocialSecurity">The social security contributions.</param>
|
||||
/// <param name="Discounts">The discounts and surcharges on the whole document.</param>
|
||||
/// <param name="Orders">The purchase orders referred to.</param>
|
||||
/// <param name="Contracts">The contracts referred to.</param>
|
||||
/// <param name="RelatedInvoices">The invoices referred to (the invoice a credit note corrects).</param>
|
||||
/// <param name="DeliveryNotes">The delivery notes referred to.</param>
|
||||
/// <param name="Lines">The lines.</param>
|
||||
/// <param name="TaxSummary">The tax summary, one row per rate or nature.</param>
|
||||
/// <param name="Payments">The payment installments.</param>
|
||||
/// <param name="Attachments">The attached files.</param>
|
||||
public sealed record IncomingInvoice(
|
||||
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
|
||||
IReadOnlyList<string> Causals, bool Art73,
|
||||
IReadOnlyList<IncomingWithholding> Withholdings, IncomingStampDuty? StampDuty,
|
||||
IReadOnlyList<IncomingSocialSecurity> SocialSecurity, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
IReadOnlyList<IncomingReference> Orders, IReadOnlyList<IncomingReference> Contracts,
|
||||
IReadOnlyList<IncomingReference> RelatedInvoices, IReadOnlyList<IncomingReference> DeliveryNotes,
|
||||
IReadOnlyList<IncomingLine> Lines, IReadOnlyList<IncomingTaxSummary> TaxSummary,
|
||||
IReadOnlyList<IncomingPayment> Payments, IReadOnlyList<IncomingAttachment> Attachments);
|
||||
|
||||
/// <summary>A line of an invoice.</summary>
|
||||
/// <param name="Number">The line number.</param>
|
||||
/// <param name="Codes">The item codes (type and value).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Quantity">The quantity, if given.</param>
|
||||
/// <param name="Unit">The unit of measure, if given.</param>
|
||||
/// <param name="UnitPrice">The unit price.</param>
|
||||
/// <param name="TotalPrice">The total of the line, net of tax.</param>
|
||||
/// <param name="TaxRate">The tax rate in percent (zero with a nature).</param>
|
||||
/// <param name="Nature">The reason of a zero rate (Italy: <c>N2.2</c>...).</param>
|
||||
/// <param name="Discounts">The discounts and surcharges of the line.</param>
|
||||
/// <param name="Withheld">Whether the line is subject to withholding tax.</param>
|
||||
/// <param name="LineType">The kind of line (Italy: <c>SC</c> discount, <c>PR</c> premium, <c>AB</c> rebate,
|
||||
/// <c>AC</c> ancillary cost).</param>
|
||||
/// <param name="PeriodStart">The start of the period the line refers to.</param>
|
||||
/// <param name="PeriodEnd">The end of the period the line refers to.</param>
|
||||
/// <param name="AdministrativeReference">The administrative reference (cost centre, internal code).</param>
|
||||
public sealed record IncomingLine(
|
||||
int Number, IReadOnlyList<IncomingItemCode> Codes, string Description, decimal? Quantity, string? Unit,
|
||||
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<IncomingDiscount> Discounts,
|
||||
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
|
||||
|
||||
/// <summary>A code of the item of a line.</summary>
|
||||
/// <param name="Type">The kind of code (<c>EAN</c>, <c>SKU</c>, the supplier's code...).</param>
|
||||
/// <param name="Value">The code.</param>
|
||||
public sealed record IncomingItemCode(string Type, string Value);
|
||||
|
||||
/// <summary>A discount or surcharge.</summary>
|
||||
/// <param name="IsSurcharge">Whether it is a surcharge (Italy: <c>MG</c>) instead of a discount (<c>SC</c>).</param>
|
||||
/// <param name="Percent">The percentage, if given.</param>
|
||||
/// <param name="Amount">The amount, if given.</param>
|
||||
public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
|
||||
|
||||
/// <summary>A row of the tax summary.</summary>
|
||||
/// <param name="Rate">The tax rate in percent.</param>
|
||||
/// <param name="Nature">The reason of a zero rate.</param>
|
||||
/// <param name="Taxable">The taxable amount.</param>
|
||||
/// <param name="Tax">The tax.</param>
|
||||
/// <param name="Exigibility">When the tax is due (Italy: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment).</param>
|
||||
/// <param name="LegalReference">The law that justifies the nature.</param>
|
||||
/// <param name="ExpensesAmount">Ancillary expenses, if any.</param>
|
||||
/// <param name="Rounding">The rounding, if any.</param>
|
||||
public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
|
||||
string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
|
||||
|
||||
/// <summary>A payment installment.</summary>
|
||||
/// <param name="Conditions">The payment conditions (Italy: <c>TP01</c> installments, <c>TP02</c> full, <c>TP03</c> advance).</param>
|
||||
/// <param name="Method">The payment method (Italy: <c>MP05</c> bank transfer...).</param>
|
||||
/// <param name="DueDate">The due date, if given.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
/// <param name="Iban">The IBAN to pay to, if given.</param>
|
||||
/// <param name="Bic">The BIC, if given.</param>
|
||||
/// <param name="Beneficiary">The beneficiary, if different from the supplier.</param>
|
||||
public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
|
||||
string? Iban, string? Bic, string? Beneficiary);
|
||||
|
||||
/// <summary>A reference to another document (order, contract, invoice, delivery note).</summary>
|
||||
/// <param name="Id">The number of the document.</param>
|
||||
/// <param name="Date">The date of the document.</param>
|
||||
/// <param name="LineNumbers">The lines of the invoice the reference applies to; empty when it applies to all.</param>
|
||||
/// <param name="Cig">The tender code, if any (public administration).</param>
|
||||
/// <param name="Cup">The project code, if any (public administration).</param>
|
||||
public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList<int> LineNumbers, string? Cig, string? Cup);
|
||||
|
||||
/// <summary>A withholding tax.</summary>
|
||||
/// <param name="Type">The kind of withholding (Italy: <c>RT01</c>...).</param>
|
||||
/// <param name="Amount">The amount withheld.</param>
|
||||
/// <param name="Rate">The rate in percent.</param>
|
||||
/// <param name="Reason">The payment reason (Italy: <c>A</c>...), if given.</param>
|
||||
public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
|
||||
|
||||
/// <summary>The stamp duty of an invoice.</summary>
|
||||
/// <param name="Virtual">Whether it is paid virtually by the issuer.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
public sealed record IncomingStampDuty(bool Virtual, decimal Amount);
|
||||
|
||||
/// <summary>A social security contribution added to the invoice.</summary>
|
||||
/// <param name="Fund">The fund (Italy: <c>TC01</c>...).</param>
|
||||
/// <param name="Rate">The rate of the contribution in percent.</param>
|
||||
/// <param name="Amount">The amount of the contribution.</param>
|
||||
/// <param name="Taxable">The amount the contribution is computed on, if given.</param>
|
||||
/// <param name="TaxRate">The tax rate applied to the contribution.</param>
|
||||
/// <param name="Withheld">Whether the contribution is subject to withholding tax.</param>
|
||||
/// <param name="Nature">The reason of a zero tax rate.</param>
|
||||
public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
|
||||
bool Withheld, string? Nature);
|
||||
|
||||
/// <summary>A file attached to the invoice.</summary>
|
||||
/// <param name="Name">The name of the attachment.</param>
|
||||
/// <param name="Format">The format declared by the supplier (such as <c>PDF</c>), if any.</param>
|
||||
/// <param name="Description">The description, if any.</param>
|
||||
/// <param name="Content">The decoded content.</param>
|
||||
public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x
|
||||
/// (<c>FPR12</c>, <c>FPA12</c>), simplified invoices (<c>FSM10</c>), plain <c>.xml</c> or signed CAdES <c>.p7m</c>
|
||||
/// (binary or base64 text, also nested).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Elements are matched by local name, whatever the namespace or prefix (<c>p:</c>, <c>ns2:</c>, 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.</para>
|
||||
/// <para>Amounts use the invariant culture (<c>.</c> separator) and dates <c>yyyy-MM-dd</c>. 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 <c>Divisa</c> is read as
|
||||
/// <c>EUR</c>; an attachment whose content is not valid base64 is kept with an empty content.</para>
|
||||
/// <para>For signed files the signature is checked for integrity only (see <see cref="CmsSignedData"/>): no trust chain
|
||||
/// and no revocation check.</para>
|
||||
/// <para>Simplified invoices (<c>FSM10</c>): each <c>DatiBeniServizi</c> becomes a line with no quantity whose unit and
|
||||
/// total price are <c>Importo</c> minus the tax, because there <c>Importo</c> includes the tax. The tax is
|
||||
/// <c>DatiIVA/Imposta</c> or, when only the rate is given, the tax included in <c>Importo</c> at that rate; the rate is
|
||||
/// <c>DatiIVA/Aliquota</c> 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 <c>Importo</c> and <c>DatiFatturaRettificata</c> becomes the related invoice.</para>
|
||||
/// </remarks>
|
||||
public sealed class FatturaPaReader : IIncomingInvoiceReader
|
||||
{
|
||||
/// <summary>The largest file read, as for signed envelopes (50 MB).</summary>
|
||||
public const int MaxSize = CmsSignedData.MaxSize;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanRead(string fileName, ReadOnlySpan<byte> content) =>
|
||||
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
|
||||
|
||||
/// <inheritdoc />
|
||||
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<byte> content)
|
||||
{
|
||||
if (content.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
content = content[3..];
|
||||
}
|
||||
else if (content.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var trimmed = content.TrimStart((ReadOnlySpan<byte>)[(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<byte>)[0xEF, 0xBB, 0xBF]))
|
||||
{
|
||||
return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]))
|
||||
{
|
||||
return Encoding.Unicode.GetString(xml, 2, xml.Length - 2);
|
||||
}
|
||||
|
||||
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[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("<?xml", StringComparison.Ordinal);
|
||||
var end = start < 0 ? -1 : 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<IncomingDiscount> 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<IncomingReference> 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<int> 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<IncomingPayment> 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<IncomingAttachment> 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<XElement> 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);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A structure that is not a readable CMS SignedData, or whose content cannot be extracted.</summary>
|
||||
public sealed class CmsFormatException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public CmsFormatException()
|
||||
: base("Not a CMS SignedData structure.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public CmsFormatException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public CmsFormatException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A signer of a CMS SignedData with what its certificate says and the result of the check.</summary>
|
||||
/// <param name="Name">The name of the signer: common name, else given name and surname, else organization, else
|
||||
/// serial number of the subject.</param>
|
||||
/// <param name="TaxCode">The tax code of the signer, from the subject's <c>SERIALNUMBER</c> (OID 2.5.4.5) without
|
||||
/// the <c>TINIT-</c> or <c>IT:</c> prefix, when present.</param>
|
||||
/// <param name="Subject">The subject of the certificate, or <see langword="null"/> when it was not found.</param>
|
||||
/// <param name="Issuer">The issuer of the certificate, or <see langword="null"/> when it was not found.</param>
|
||||
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
|
||||
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
|
||||
/// <param name="SigningTime">The <c>signingTime</c> signed attribute: what the signer's clock said, not a trusted timestamp.</param>
|
||||
/// <param name="Verified">Whether the digest of the content and the signature match.</param>
|
||||
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
|
||||
/// <param name="Certificate">The DER of the signer certificate, or <see langword="null"/> when it was not found.</param>
|
||||
public sealed record CmsSigner(
|
||||
string? Name, string? TaxCode, string? Subject, string? Issuer,
|
||||
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, DateTimeOffset? SigningTime,
|
||||
bool Verified, string? Problem, byte[]? Certificate);
|
||||
|
||||
/// <summary>The content of one or more nested CMS SignedData envelopes and their signers.</summary>
|
||||
/// <param name="Content">The content of the innermost envelope.</param>
|
||||
/// <param name="Signers">The signers, outermost envelope first.</param>
|
||||
/// <param name="Layers">How many envelopes were opened (two for <c>.xml.p7m.p7m</c>).</param>
|
||||
public sealed record CmsContent(byte[] Content, IReadOnlyList<CmsSigner> Signers, int Layers)
|
||||
{
|
||||
/// <summary>Whether there is at least one signer and every signer of every envelope is verified.</summary>
|
||||
public bool Verified => Signers.Count > 0 && Signers.All(s => s.Verified);
|
||||
|
||||
/// <summary>The first problem found, or <see langword="null"/> when <see cref="Verified"/>.</summary>
|
||||
public string? Problem => Signers.Count == 0 ? "The envelope has no signer." : Signers.FirstOrDefault(s => s.Problem is not null)?.Problem;
|
||||
|
||||
/// <summary>The signer of the outermost envelope, or <see langword="null"/> when there is none.</summary>
|
||||
public CmsSigner? Signer => Signers.Count > 0 ? Signers[0] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A minimal reader of CMS SignedData (RFC 5652, PKCS #7), the envelope of CAdES signed files such as <c>.p7m</c>,
|
||||
/// written on <c>System.Formats.Asn1</c> because <c>System.Security.Cryptography.Pkcs</c> is a separate package
|
||||
/// (SPEC §1.2).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>It accepts DER and BER (indefinite lengths, content split in constructed chunks), the base64 text of the
|
||||
/// binary with or without line breaks and <c>-----BEGIN</c> armour, and nested envelopes (<c>.p7m.p7m</c>), opened
|
||||
/// until the content is no longer CMS.</para>
|
||||
/// <para>It checks integrity only: the <c>messageDigest</c> 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 <b>not</b> 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 <see cref="CmsSigner.Verified"/> false and the
|
||||
/// problem; only unreadable structures throw <see cref="CmsFormatException"/>. Detached signatures (no content) are
|
||||
/// not supported.</para>
|
||||
/// </remarks>
|
||||
public static class CmsSignedData
|
||||
{
|
||||
/// <summary>The largest envelope read, 50 MB.</summary>
|
||||
public const int MaxSize = 50 * 1024 * 1024;
|
||||
|
||||
/// <summary>The most nested envelopes opened.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Whether the bytes look like a CMS SignedData, in binary or as base64 text. Only the start is looked at.</summary>
|
||||
/// <param name="data">The content, or at least its first hundred bytes.</param>
|
||||
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
|
||||
public static bool LooksLikeCms(ReadOnlySpan<byte> data)
|
||||
{
|
||||
if (LooksLikeBinaryCms(data))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Base64 text: decode the first characters and look again.
|
||||
Span<byte> 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<byte> 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]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="data">The envelope.</param>
|
||||
/// <returns>The content of the innermost envelope and the signers.</returns>
|
||||
/// <exception cref="CmsFormatException">The data is not a CMS SignedData, is too large, nests too deep, has no
|
||||
/// content, or cannot be decoded.</exception>
|
||||
public static CmsContent Read(byte[] data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var current = data;
|
||||
var signers = new List<CmsSigner>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the base64 text form of a binary structure: whitespace and line breaks are skipped, <c>-----BEGIN</c>
|
||||
/// and <c>-----END</c> lines dropped, a UTF-8 byte order mark ignored.
|
||||
/// </summary>
|
||||
/// <param name="text">The text, as bytes.</param>
|
||||
/// <returns>The decoded bytes, or <see langword="null"/> when the text is not base64.</returns>
|
||||
public static byte[]? DecodeBase64Text(ReadOnlySpan<byte> 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<byte> 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<CmsSigner> 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<byte[]>();
|
||||
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<byte[]> 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<byte[]> 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<X509SubjectKeyIdentifierExtension>().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<byte[]> 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<byte[]> SignedAttributesAsSet(byte[] signedAttributes)
|
||||
{
|
||||
var forms = new List<byte[]>();
|
||||
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-<tax code>; older Italian certificates use IT:<tax code>.
|
||||
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<byte> SkipBom(ReadOnlySpan<byte> data) =>
|
||||
data.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]) ? data[3..] : data;
|
||||
|
||||
private static ReadOnlySpan<byte> SkipArmour(ReadOnlySpan<byte> data)
|
||||
{
|
||||
var trimmed = data.TrimStart((ReadOnlySpan<byte>)[(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';
|
||||
}
|
||||
@@ -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