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: UTF-8, well-formed, namespace-well-formed, no document type
10//! declaration ([`Error::NotXml`], [`Error::Unsupported`]), no element nested deeper
11//! than [`ValidateOptions::max_depth`] ([`Error::Limit`]);
12//! 2. the XML schema of the rule set, if any (UBL 2.1 for the UBL rule sets), with
13//! [`einvoice_xsd`]: every validity error, with its line and column;
14//! 3. every stylesheet of the rule set, with [`einvoice_xslt_exec`], which executes the
15//! official compiled Schematron with the behaviour of the reference engine
16//! (Saxon-HE 12.10) and writes its SVRL report.
17//!
18//! The [`Report`] holds the schema errors, then, for each stylesheet, its raw SVRL
19//! report, its findings (failed asserts and successful reports, with their id, flag,
20//! location, rule context, test and message) and the canonical form of the SVRL. The
21//! verdict is [`Verdict::Valid`] when there is no schema error and no finding with flag
22//! `fatal`.
23//!
24//! ```
25//! # #[cfg(feature = "cen-ubl")] {
26//! use einvoice_validator::{Validator, Verdict};
27//!
28//! let validator = Validator::cen_ubl()?;
29//! let invoice = br#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#;
30//! let report = validator.validate(invoice)?;
31//! assert_eq!(report.verdict(), Verdict::Invalid);
32//! // The schema wants the mandatory elements; the CEN rules report what is missing.
33//! assert!(!report.schema_errors.is_empty());
34//! assert!(report.findings().any(|f| f.id.as_deref() == Some("BR-01")));
35//! assert_eq!(report.rule_set.version, "1.3.17");
36//! # }
37//! # Ok::<(), einvoice_validator::Error>(())
38//! ```
39//!
40//! # Rule sets and bundles
41//!
42//! A rule set is described by a bundle: a manifest and the files it names. The
43//! manifest gives the rule set's name, title and version, the XML schema to validate
44//! against first, and the stylesheets to run, each with the SHA-256 of its file, which
45//! is checked when the bundle is loaded. [`RuleSet`] is the manifest, parsed.
46//!
47//! - Built in ([`BUILTIN_RULE_SETS`], [`Validator::builtin`]), embedded unmodified, each
48//! behind a feature of its name, on by default (the artefacts are under the EUPL-1.2):
49//! `cen-ubl`, the CEN EN 16931 validation artefacts for UBL, release 1.3.17, with the
50//! UBL 2.1 schemas; `cen-cii`, the same release for UN/CEFACT CII D16B, without an XML
51//! schema (the CII D16B schemas are not embedded: documents are checked for
52//! well-formedness, then by the stylesheet). [`Syntax::detect`] tells from the root
53//! element which of the two a document is for.
54//! - From a directory ([`Validator::from_bundle_dir`]): the manifest is
55//! `<dir>/bundle.toml` ([`MANIFEST_FILE`]), and the paths it gives are relative to
56//! `<dir>`. This is how rule sets whose artefacts cannot be redistributed are used:
57//! fetch them into a directory, add the manifest.
58//! - From memory ([`Validator::from_bundle`]).
59//!
60//! The manifest is TOML, restricted to the subset below; anything else is refused with
61//! the line concerned (unknown keys included).
62//!
63//! ```toml
64//! format = 1 # the manifest format, MANIFEST_FORMAT
65//! name = "cen-ubl" # ASCII letters, digits, '-', '.', '_'
66//! title = "CEN EN 16931 UBL"
67//! version = "1.3.17" # the version of the official artefacts
68//! schema = "ubl-2.1" # optional: the XML schema validated first
69//!
70//! [[stylesheet]] # one or more, run in this order
71//! name = "EN16931-UBL" # unique in the bundle
72//! path = "ubl/xslt/EN16931-UBL-validation.xslt" # relative, '/'-separated, no '..'
73//! sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
74//! # version = "..." # optional: when it differs from the bundle's
75//! ```
76//!
77//! Accepted syntax: comments, `key = value` lines with a bare key, values that are
78//! basic strings (escapes `\"` and `\\` only), literal strings or non-negative integers,
79//! and `[[stylesheet]]` headers.
80//!
81//! # WebAssembly
82//!
83//! The crate builds for `wasm32-unknown-unknown` and needs nothing from the host there:
84//! the built-in rule set is embedded, and a bundle can be given from memory. That target
85//! has no system clock, so the caller gives the one the stylesheets read with
86//! [`ValidateOptions::clock`] (for instance [`Clock::from_unix_millis`] with
87//! JavaScript's `Date.now()`); without it, a validation fails with
88//! [`Error::Unsupported`]. The `wasm-validate` example validates two embedded documents
89//! that way and runs under wasmtime.
90//!
91//! # Licences
92//!
93//! The code is MIT. The built-in rule sets `cen-ubl` and `cen-cii` embed the CEN
94//! stylesheets, under the EUPL-1.2, and [`einvoice_xsd`] embeds the OASIS UBL 2.1 schemas, which keep their own
95//! terms (OASIS, UN/CEFACT, W3C). [`licences()`] returns the full text of every licence
96//! of what this build embeds, for programs that must show them to their users.
97//!
98//! # Errors
99//!
100//! A schema error or a failed assert is not an error: it is in the [`Report`]. An
101//! [`Error`] means no complete verdict could be given: a bundle that cannot be loaded,
102//! a document that is not XML, a construct the engine refuses rather than evaluating it
103//! differently from the reference engine, a document beyond a limit, a dynamic error
104//! raised by a stylesheet, or a bug.
105//!
106//! # Limits
107//!
108//! The stylesheets walk the document with template rules applied one element level
109//! inside another, so the stack a validation needs grows with the depth of the document.
110//! A document with an element nested deeper than [`ValidateOptions::max_depth`]
111//! ([`DEFAULT_MAX_DEPTH`], 256, libxml2's default) is therefore refused before its schema
112//! is checked, with [`Error::Limit`] and the line and column of that element, rather
113//! than overflowing the stack of the thread, which would abort the process. At the
114//! default maximum, a validation with the built-in rule sets or the Peppol bundle runs on
115//! a thread with the default 2 MiB stack of a spawned thread, debug builds included. The
116//! template and function invocations of the stylesheets are bounded too: in nesting
117//! ([`max_nesting_for_depth`] of the maximum depth) and in the stack they use
118//! ([`ValidateOptions::max_stack`], [`DEFAULT_MAX_STACK`]), so that a stylesheet that
119//! recurses without end fails with [`Error::Limit`] as well.
120
121mod builtin;
122mod detect;
123mod error;
124mod licences;
125mod manifest;
126mod report;
127mod validator;
128
129pub use builtin::BUILTIN_RULE_SETS;
130pub use detect::Syntax;
131pub use error::{Error, ErrorKind};
132pub use licences::{Licence, licences};
133pub use manifest::{MANIFEST_FILE, MANIFEST_FORMAT, RuleSet, SchemaId, StylesheetEntry};
134pub use report::{
135 Finding, FindingKind, Report, RuleSetVersion, SchemaError, SchemaErrorKind, Severity,
136 StylesheetFailure, StylesheetReport, Verdict,
137};
138pub use validator::{ValidateOptions, Validator, file_uri};
139
140/// The clock of a validation ([`ValidateOptions::clock`]): the implicit timezone and the
141/// value of `fn:current-dateTime()`.
142pub use einvoice_xpath_eval::Clock;
143
144/// The default maximum element depth of a document ([`ValidateOptions::max_depth`]), and
145/// the limits [`Error::Limit`] reports.
146pub use einvoice_xpath_eval::{DEFAULT_MAX_DEPTH, LimitExceeded};
147
148/// The nesting of template and function invocations the stylesheets are allowed on a
149/// document at most `max_depth` deep ([`ValidateOptions::max_depth`]): twice the depth,
150/// plus 64. Each level needs less than 3 KiB of stack (debug builds included), which is
151/// what a caller raising the maximum depth must give the validating thread.
152pub use einvoice_xslt_exec::max_nesting_for_depth;
153
154/// The default stack the stylesheets may use ([`ValidateOptions::max_stack`]).
155pub use einvoice_xslt_exec::DEFAULT_MAX_STACK;
156
157/// The version of this crate, as published.
158pub const VERSION: &str = env!("CARGO_PKG_VERSION");
159
160#[cfg(test)]
161mod tests {
162 use super::VERSION;
163
164 #[test]
165 fn version_is_major_minor_patch() {
166 let parts: Vec<&str> = VERSION.split('.').collect();
167 assert_eq!(parts.len(), 3, "{VERSION}");
168 for part in parts {
169 assert!(
170 !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()),
171 "{VERSION}"
172 );
173 }
174 }
175}