Skip to main content

einvoice_validator/
lib.rs

1//! Validate EN 16931 and Peppol BIS Billing 3.0 e-invoices against the official
2//! validation artefacts, in pure Rust: no JVM, no C library, no FFI.
3//!
4//! A [`Validator`] is built once from a rule set: the XML schema it names is loaded and
5//! its official compiled XSLT stylesheets are prepared. It then validates any number of
6//! documents, from any number of threads ([`Validator`] is `Send + Sync`). Each
7//! validation runs, in order:
8//!
9//! 1. the XML check: an encoding the validator reads (UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 or windows-1252,
10//!    as the byte order mark, the first bytes and the XML declaration say, decoded with
11//!    [`einvoice_xml::decode`]), well-formed, namespace-well-formed, no document type
12//!    declaration ([`Error::NotXml`], [`Error::Unsupported`]), no element nested deeper
13//!    than [`ValidateOptions::max_depth`] ([`Error::Limit`]);
14//! 2. the XML schema of the rule set, if any (UBL 2.1 for the UBL rule sets, CII D16B
15//!    for `cen-cii`, or the schema documents a bundle carries, such as the schema of a
16//!    Factur-X profile), with [`einvoice_xsd`]: every validity error, with its line and
17//!    column. The XML check and the schema run in one pass of the streaming reader of
18//!    [`einvoice_xml`] over the text, which builds no tree;
19//! 3. every stylesheet of the rule set, with [`einvoice_xslt_exec`], which executes the
20//!    official compiled Schematron with the behaviour of the reference engine
21//!    (Saxon-HE 12.10) and writes its SVRL report. In a rule set that selects by
22//!    scenario ([`RuleSet::selects_by_scenario`], the XRechnung bundles), the `match`
23//!    expressions of its scenarios are evaluated on the document first, as the KoSIT
24//!    validator evaluates them: the one scenario that matches gives the stylesheets that
25//!    run; a document that matches none, or more than one, is invalid
26//!    ([`Report::no_scenario`]) and nothing runs on it.
27//!
28//! The [`Report`] holds the schema errors, then, for each stylesheet, its raw SVRL
29//! report, its findings (failed asserts and successful reports, with their id, flag,
30//! location, rule context, test and message) and the canonical form of the SVRL. The
31//! verdict is [`Verdict::Valid`] when there is no schema error and no finding of severity
32//! [`Severity::Fatal`]: the flag `fatal`, or what the manifest of the rule set reads as
33//! fatal, as the reference validator of the rule set does (see [Severities](#severities)),
34//! and, in a rule set that selects by scenario, the document matched one.
35//!
36//! ```
37//! # #[cfg(feature = "cen-ubl")] {
38//! use einvoice_validator::{Validator, Verdict};
39//!
40//! let validator = Validator::cen_ubl()?;
41//! let invoice = br#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#;
42//! let report = validator.validate(invoice)?;
43//! assert_eq!(report.verdict(), Verdict::Invalid);
44//! // The schema wants the mandatory elements; the CEN rules report what is missing.
45//! assert!(!report.schema_errors.is_empty());
46//! assert!(report.findings().any(|f| f.id.as_deref() == Some("BR-01")));
47//! assert_eq!(report.rule_set.version, "1.3.17");
48//! # }
49//! # Ok::<(), einvoice_validator::Error>(())
50//! ```
51//!
52//! # Rule sets and bundles
53//!
54//! A rule set is described by a bundle: a manifest and the files it names. The
55//! manifest gives the rule set's name, title and version, the XML schema to validate
56//! against first (an embedded one, or one whose documents the bundle carries), the
57//! stylesheets to run, and the resources they read with `document()` (code lists),
58//! each with the SHA-256 of its file, which is checked when the bundle is loaded. [`RuleSet`] is the manifest, parsed. A stylesheet reads the
59//! resources by their URI relative to its own (`file:` URIs in a directory,
60//! `bundle:/<path>` in memory), and nothing else: `document()` on any other URI is the
61//! error `FODC0002`.
62//!
63//! - Built in ([`BUILTIN_RULE_SETS`], [`Validator::builtin`]), embedded unmodified, each
64//!   behind a feature of its name, on by default (the artefacts are under the EUPL-1.2):
65//!   `cen-ubl`, the CEN EN 16931 validation artefacts for UBL, release 1.3.17, with the
66//!   UBL 2.1 schemas; `cen-cii`, the same release for UN/CEFACT CII D16B, with the
67//!   UN/CEFACT CII D16B schemas. [`Syntax::detect`] tells from the root element which of
68//!   the two a document is for.
69//! - From a directory ([`Validator::from_bundle_dir`]): the manifest is
70//!   `<dir>/bundle.toml` ([`MANIFEST_FILE`]), and the paths it gives are relative to
71//!   `<dir>`. This is how rule sets whose artefacts cannot be redistributed are used:
72//!   fetch them into a directory, add the manifest.
73//! - From memory ([`Validator::from_bundle`]).
74//! - Fetched on demand from their publishers, and kept in a cache
75//!   ([`RuleSetCache`], [`Validator::from_cache`]): see the next section.
76//!
77//! # Rule sets fetched on demand
78//!
79//! Factur-X (the five profiles), XRechnung (UBL and CII), the French rules (the
80//! fourteen bundles of the FNFE-MPE package) and Peppol BIS Billing 3.0 may not be
81//! redistributed, so the crate does not embed them: [`fetched_rule_sets`] is their
82//! catalogue, which gives, for each, the files of its family at their publishers (pinned
83//! URL and SHA-256, the pins of the fetch scripts of the repository) and the
84//! manifest of its bundle. Not on WebAssembly.
85//!
86//! - With the feature `fetch` (off by default; on in `einvoice-cli`),
87//!   `RuleSetCache::fetch` downloads the files of a family (or takes them from a
88//!   local directory, `FetchOptions::from_dir`), checks each against its pinned
89//!   digest, assembles the bundles exactly as the fetch scripts do (a test checks they
90//!   are the same, byte for byte) and installs them in the cache in one rename. Peppol
91//!   BIS Billing publishes its rules as Schematron only: its bundle is built by
92//!   compiling them as ph-schematron compiles them for the reference validators, in
93//!   Rust (`einvoice-schematron`, with the ISO Schematron skeleton of the pinned jar of
94//!   ph-schematron-isosch): no Java. The HTTP client is
95//!   minimal and pure Rust, its cryptography included (rustls, with a provider on the
96//!   `RustCrypto` crates, and the Mozilla roots of webpki-roots): HTTPS only (plain
97//!   HTTP only to a loopback address, for a local mirror), at most five redirects,
98//!   never from HTTPS to HTTP, five attempts with a doubling delay on an I/O error and
99//!   on HTTP 408, 429 and 5xx (honouring `Retry-After`), an interrupted download resumed
100//!   where it stopped, a size limit (`DEFAULT_MAX_SIZE`, 64 MiB); the archives (ZIP,
101//!   gzip, tar) are read in memory, refusing absolute paths, `..`, links and sizes
102//!   beyond their limits.
103//! - Nothing is downloaded otherwise: [`RuleSetCache::load`] and
104//!   [`Validator::from_cache`] read the cache only, and fail with
105//!   [`Error::NotCached`] for a rule set that has not been fetched. On every load the
106//!   cached manifest must be, byte for byte, the catalogue's, and every file must have
107//!   its SHA-256, so a cache works offline and is never trusted.
108//!
109//! ```no_run
110//! # #[cfg(feature = "fetch")] {
111//! use einvoice_validator::{FetchOptions, RuleSetCache, Validator};
112//!
113//! // The platform's cache directory, or EINVOICE_VALIDATOR_CACHE.
114//! let cache = RuleSetCache::new()?;
115//! // Downloads and builds xrechnung-ubl and xrechnung-cii (once: then from the cache).
116//! cache.fetch("xrechnung", &FetchOptions::new())?;
117//! let validator = cache.load("xrechnung-ubl")?;
118//! // The same, from the default cache, never downloading.
119//! let same = Validator::from_cache("xrechnung-ubl")?;
120//! assert_eq!(validator.rule_set(), same.rule_set());
121//! # }
122//! # Ok::<(), einvoice_validator::Error>(())
123//! ```
124//!
125//! The manifest is TOML, restricted to the subset below; anything else is refused with
126//! the line concerned (unknown keys included).
127//!
128//! ```toml
129//! format = 2                   # the manifest format: 1, or MANIFEST_FORMAT for what says format 2
130//! name = "cen-ubl"             # ASCII letters, digits, '-', '.', '_'
131//! title = "CEN EN 16931 UBL"
132//! version = "1.3.17"           # the version of the official artefacts
133//! schema = "ubl-2.1"           # optional: the XML schema validated first, ubl-2.1 or cii-d16b,
134//! #                            # or (format 2) the path of the entry point of the schema
135//! #                            # documents of the bundle ([[schema-document]])
136//! # unchecked-schema = "..."   # format 2, optional: an XML schema the reference
137//! #                            # validator also checks and this rule set does not
138//!
139//! [[stylesheet]]               # one or more, run in this order
140//! name = "EN16931-UBL"         # unique in the bundle
141//! path = "ubl/xslt/EN16931-UBL-validation.xslt"   # relative, '/'-separated, no '..'
142//! sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
143//! # version = "..."            # optional: when it differs from the bundle's
144//! # unflagged-assert = "fatal" # format 2, optional: the severity of a failed assert
145//! #                            # without a flag (fatal, warning or other; default other)
146//!
147//! [[resource]]                 # format 2: zero or more files read with document()
148//! path = "ubl/xslt/codes.xml"  # relative, '/'-separated, no '..'
149//! sha256 = "0000000000000000000000000000000000000000000000000000000000000000"
150//!
151//! [[schema-document]]          # format 2: the documents of the schema of the bundle, when
152//! path = "xsd/main.xsd"        # `schema` is the path of one of them, its entry point: it
153//! sha256 = "1111111111111111111111111111111111111111111111111111111111111111"
154//! #                            # and every document it imports or includes, each a table
155//!
156//! [[scenario]]                 # format 2: zero or more, tried in this order
157//! name = "EN16931 XRechnung (UBL Invoice)"        # unique in the bundle
158//! # A scenario of a KoSIT configuration: its namespaces (prefix=uri, separated by
159//! # spaces), its match expression (XPath, as written) and the stylesheets it runs.
160//! namespaces = "cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 invoice=urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
161//! match = "exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0'])"
162//! stylesheets = "EN16931-UBL XRechnung-UBL"    # optional: by default all, in order
163//! fatal = "UBL-CR-646"         # optional: rule ids and the severity the scenario
164//! warning = "BR-CL-23 BR-CL-21"   # gives them, separated by spaces, each in one list
165//! # Or, instead of namespaces, match and stylesheets: the root element and the
166//! # specification identifier (BT-24) of the documents it gives severities to (at least
167//! # one of fatal, warning and other then), every stylesheet running.
168//! # namespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
169//! # root = "Invoice"           # with namespace: a UBL Invoice or CreditNote, a CII CrossIndustryInvoice
170//! # identifier = "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0"
171//! ```
172//!
173//! The scenarios of a manifest all have a `match` expression, or none has. With them, the
174//! rule set selects by scenario ([`Scenario`]): a document must match exactly one, whose
175//! stylesheets run, in its order, and whose severities apply; a document that matches none,
176//! or several, is invalid, with no schema error reported and no stylesheet run, as the
177//! KoSIT validator rejects it with its fallback scenario (which has no schema). The expressions are evaluated
178//! with [`einvoice_xpath_eval`], with the document node as the context item, their
179//! effective boolean value; one that raises a dynamic error is false, as for the KoSIT
180//! validator; one outside the engine's subset is refused when the bundle is loaded.
181//!
182//! Accepted syntax: comments, `key = value` lines with a bare key, values that are
183//! basic strings (escapes `\"` and `\\` only), literal strings or non-negative integers,
184//! and `[[stylesheet]]`, `[[resource]]`, `[[schema-document]]` and `[[scenario]]`
185//! headers.
186//!
187//! # Severities
188//!
189//! Each finding has a [`Severity`], and a fatal finding makes the document invalid. By
190//! default it is the one its Schematron flag stands for ([`Severity::from_flag`]: `fatal`,
191//! `warning`, any other flag or none [`Severity::Other`]), which is how the reference
192//! validators read the CEN and Peppol rules, which flag every assert. The manifest gives
193//! the others what their reference validators read:
194//!
195//! - `unflagged-assert`, for a stylesheet whose failed asserts may have no flag: the
196//!   Factur-X stylesheets leave it out of most of their asserts, which the Mustang validator
197//!   reads as errors, so the Factur-X bundles (and those of the French rules that run a
198//!   Factur-X profile) say `unflagged-assert = "fatal"`, as do the XRechnung bundles, the
199//!   KoSIT validator reading a missing flag as an error too. A successful report without a
200//!   flag stays [`Severity::Other`].
201//! - `[[scenario]]` ([`Scenario`]): the levels a scenario of a KoSIT validator
202//!   configuration gives rule ids (`customLevel`), whatever their flags, in the documents
203//!   it matches; the XRechnung bundles have the scenarios of their configuration, each
204//!   with its `match` expression and its stylesheets (`error` is [`Severity::Fatal`],
205//!   `information` [`Severity::Other`]). The [`Report`] names the scenario the document
206//!   matched, or says why it has none.
207//!
208//! The KoSIT validator also validates each document against the XML schema of its
209//! scenario: the UBL 2.1 schema, which the XRechnung UBL bundle runs, or the UN/CEFACT
210//! CII D16B schema, which the XRechnung CII bundle runs ([`SchemaId::CiiD16b`]). The
211//! Mustang validator validates a Factur-X document against the XML schema of its
212//! profile, and the documentation of the French rules has a document validated against
213//! the schema of its syntax or profile first: their bundles carry those schemas
214//! ([`SchemaId::Bundle`]); a schema error makes the document invalid, and the
215//! stylesheets run all the same. A bundle whose reference validator checks a schema
216//! it does not run names it in `unchecked-schema` ([`RuleSet::unchecked_schema`],
217//! [`RuleSetVersion::unchecked_schema`] in the report): a document it would reject for a
218//! schema error alone is valid here.
219//!
220//! [`ValidateOptions::fail_closed`] then makes every finding that is still
221//! [`Severity::Other`] fatal, for rule sets whose flags the caller does not know.
222//!
223//! # PDF files
224//!
225//! With the feature `pdf` (on by default), the module `pdf` extracts the invoice XML that
226//! a Factur-X, `ZUGFeRD` or Order-X PDF/A-3 file embeds, with its `/AFRelationship` and
227//! the document's XMP metadata, in pure Rust (the crate einvoice-pdf); the XML is then
228//! validated as any other document, with the rule set [`Syntax::detect`] names for it.
229//!
230//! # WebAssembly
231//!
232//! The crate builds for `wasm32-unknown-unknown` and needs nothing from the host there:
233//! the built-in rule set is embedded, and a bundle can be given from memory. That target
234//! has no system clock, so the caller gives the one the stylesheets read with
235//! [`ValidateOptions::clock`] (for instance [`Clock::from_unix_millis`] with
236//! JavaScript's `Date.now()`); without it, a validation fails with
237//! [`Error::Unsupported`]. The `wasm-validate` example validates two embedded documents
238//! that way and runs under wasmtime.
239//!
240//! # Licences
241//!
242//! The code is MIT. The built-in rule sets `cen-ubl` and `cen-cii` embed the CEN
243//! stylesheets, under the EUPL-1.2, and [`einvoice_xsd`] embeds the OASIS UBL 2.1 schemas
244//! and the UN/CEFACT CII D16B schemas, which keep their own terms (OASIS, UN/CEFACT, W3C).
245//! [`licences()`] returns the full text of every licence of what this build embeds, for
246//! programs that must show them to their users.
247//!
248//! # Errors
249//!
250//! A schema error or a failed assert is not an error: it is in the [`Report`]. An
251//! [`Error`] means no complete verdict could be given: a bundle that cannot be loaded,
252//! a document that is not XML, a construct the engine refuses rather than evaluating it
253//! differently from the reference engine, a document beyond a limit, a dynamic error
254//! raised by a stylesheet, or a bug.
255//!
256//! # Limits
257//!
258//! The stylesheets walk the document with template rules applied one element level
259//! inside another, so the stack a validation needs grows with the depth of the document.
260//! A document with an element nested deeper than [`ValidateOptions::max_depth`]
261//! ([`DEFAULT_MAX_DEPTH`], 256, libxml2's default) is therefore refused before its schema
262//! is checked, with [`Error::Limit`] and the line and column of that element, rather
263//! than overflowing the stack of the thread, which would abort the process. At the
264//! default maximum, a validation with the built-in rule sets or the Peppol bundle runs on
265//! a thread with the default 2 MiB stack of a spawned thread, debug builds included. The
266//! template and function invocations of the stylesheets are bounded too: in nesting
267//! ([`max_nesting_for_depth`] of the maximum depth) and in the stack they use
268//! ([`ValidateOptions::max_stack`], [`DEFAULT_MAX_STACK`]), so that a stylesheet that
269//! recurses without end fails with [`Error::Limit`] as well.
270//!
271//! On WebAssembly, the engine running the module has a native stack of its own, which
272//! the module cannot measure and which runs out before the module's stack in some
273//! JavaScript engines, leaving the module unusable. There, the stack the stylesheets may
274//! use is 256 KiB, and at most [`WASM_MAX_STACK`], the same; the maximum depth is at
275//! most [`WASM_MAX_DEPTH`], 400: a validation asking for more fails with
276//! [`Error::OptionOutOfRange`]. Within 256 KiB, the stylesheets validate a document up
277//! to 487 levels deep when no rule fires on its deepest elements, and up to 243 when a
278//! rule reports on every level (measured with the official stylesheets); deeper, the
279//! validation fails with [`Error::Limit`].
280
281mod builtin;
282mod detect;
283mod error;
284mod licences;
285mod manifest;
286#[cfg(feature = "pdf")]
287pub mod pdf;
288mod report;
289mod resources;
290#[cfg(not(target_family = "wasm"))]
291mod rulesets;
292mod validator;
293
294pub use builtin::BUILTIN_RULE_SETS;
295pub use detect::Syntax;
296pub use error::{Error, ErrorKind};
297pub use licences::{Licence, licences};
298pub use manifest::{
299    MANIFEST_FILE, MANIFEST_FORMAT, ResourceEntry, RuleSet, Scenario, SchemaDocumentEntry,
300    SchemaId, StylesheetEntry,
301};
302pub use report::{
303    Finding, FindingKind, NoScenario, Report, RuleSetVersion, SchemaError, SchemaErrorKind,
304    Severity, StylesheetFailure, StylesheetReport, Verdict,
305};
306pub use validator::{ValidateOptions, Validator, WASM_MAX_DEPTH, WASM_MAX_STACK, file_uri};
307
308#[cfg(not(target_family = "wasm"))]
309pub use rulesets::{
310    CACHE_ENV, CacheStatus, FetchedRuleSet, RuleSetCache, Source, fetched_rule_set,
311    fetched_rule_set_aliases, fetched_rule_sets,
312};
313#[cfg(all(feature = "fetch", not(target_family = "wasm")))]
314pub use rulesets::{DEFAULT_MAX_SIZE, FetchOptions, Fetched, Progress};
315
316/// The clock of a validation ([`ValidateOptions::clock`]): the implicit timezone and the
317/// value of `fn:current-dateTime()`.
318pub use einvoice_xpath_eval::Clock;
319
320/// The default maximum element depth of a document ([`ValidateOptions::max_depth`]), and
321/// the limits [`Error::Limit`] reports.
322pub use einvoice_xpath_eval::{DEFAULT_MAX_DEPTH, LimitExceeded};
323
324/// The nesting of template and function invocations the stylesheets are allowed on a
325/// document at most `max_depth` deep ([`ValidateOptions::max_depth`]): twice the depth,
326/// plus 64. Each level needs less than 3 KiB of stack (debug builds included), which is
327/// what a caller raising the maximum depth must give the validating thread.
328pub use einvoice_xslt_exec::max_nesting_for_depth;
329
330/// The default stack the stylesheets may use ([`ValidateOptions::max_stack`]).
331pub use einvoice_xslt_exec::DEFAULT_MAX_STACK;
332
333/// An SVRL report as the stylesheet wrote it, kept compactly
334/// ([`StylesheetReport::svrl`]).
335pub use einvoice_xslt_exec::CompactOutput;
336
337/// The version of this crate, as published.
338pub const VERSION: &str = env!("CARGO_PKG_VERSION");
339
340#[cfg(test)]
341mod tests {
342    use super::VERSION;
343
344    #[test]
345    fn version_is_major_minor_patch() {
346        let parts: Vec<&str> = VERSION.split('.').collect();
347        assert_eq!(parts.len(), 3, "{VERSION}");
348        for part in parts {
349            assert!(
350                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()),
351                "{VERSION}"
352            );
353        }
354    }
355}