Skip to main content

Crate einvoice_validator

Crate einvoice_validator 

Source
Expand description

Validate EN 16931 and Peppol BIS Billing 3.0 e-invoices against the official validation artefacts, in pure Rust: no JVM, no C library, no FFI.

A Validator is built once from a rule set: the XML schema it names is loaded and its official compiled XSLT stylesheets are prepared. It then validates any number of documents, from any number of threads (Validator is Send + Sync). Each validation runs, in order:

  1. the XML check: an encoding the validator reads (UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 or windows-1252, as the byte order mark, the first bytes and the XML declaration say, decoded with einvoice_xml::decode), well-formed, namespace-well-formed, no document type declaration (Error::NotXml, Error::Unsupported), no element nested deeper than ValidateOptions::max_depth (Error::Limit);
  2. the XML schema of the rule set, if any (UBL 2.1 for the UBL rule sets, CII D16B for cen-cii, or the schema documents a bundle carries, such as the schema of a Factur-X profile), with einvoice_xsd: every validity error, with its line and column. The XML check and the schema run in one pass of the streaming reader of einvoice_xml over the text, which builds no tree;
  3. every stylesheet of the rule set, with einvoice_xslt_exec, which executes the official compiled Schematron with the behaviour of the reference engine (Saxon-HE 12.10) and writes its SVRL report. In a rule set that selects by scenario (RuleSet::selects_by_scenario, the XRechnung bundles), the match expressions of its scenarios are evaluated on the document first, as the KoSIT validator evaluates them: the one scenario that matches gives the stylesheets that run; a document that matches none, or more than one, is invalid (Report::no_scenario) and nothing runs on it.

The Report holds the schema errors, then, for each stylesheet, its raw SVRL report, its findings (failed asserts and successful reports, with their id, flag, location, rule context, test and message) and the canonical form of the SVRL. The verdict is Verdict::Valid when there is no schema error and no finding of severity Severity::Fatal: the flag fatal, or what the manifest of the rule set reads as fatal, as the reference validator of the rule set does (see Severities), and, in a rule set that selects by scenario, the document matched one.

use einvoice_validator::{Validator, Verdict};

let validator = Validator::cen_ubl()?;
let invoice = br#"<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"/>"#;
let report = validator.validate(invoice)?;
assert_eq!(report.verdict(), Verdict::Invalid);
// The schema wants the mandatory elements; the CEN rules report what is missing.
assert!(!report.schema_errors.is_empty());
assert!(report.findings().any(|f| f.id.as_deref() == Some("BR-01")));
assert_eq!(report.rule_set.version, "1.3.17");

§Rule sets and bundles

A rule set is described by a bundle: a manifest and the files it names. The manifest gives the rule set’s name, title and version, the XML schema to validate against first (an embedded one, or one whose documents the bundle carries), the stylesheets to run, and the resources they read with document() (code lists), 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 resources by their URI relative to its own (file: URIs in a directory, bundle:/<path> in memory), and nothing else: document() on any other URI is the error FODC0002.

  • Built in (BUILTIN_RULE_SETS, Validator::builtin), embedded unmodified, each behind a feature of its name, on by default (the artefacts are under the EUPL-1.2): cen-ubl, the CEN EN 16931 validation artefacts for UBL, release 1.3.17, with the UBL 2.1 schemas; cen-cii, the same release for UN/CEFACT CII D16B, with the UN/CEFACT CII D16B schemas. Syntax::detect tells from the root element which of the two a document is for.
  • From a directory (Validator::from_bundle_dir): the manifest is <dir>/bundle.toml (MANIFEST_FILE), and the paths it gives are relative to <dir>. This is how rule sets whose artefacts cannot be redistributed are used: fetch them into a directory, add the manifest.
  • From memory (Validator::from_bundle).
  • Fetched on demand from their publishers, and kept in a cache (RuleSetCache, Validator::from_cache): see the next section.

§Rule sets fetched on demand

Factur-X (the five profiles), XRechnung (UBL and CII), the French rules (the fourteen bundles of the FNFE-MPE package) and Peppol BIS Billing 3.0 may not be redistributed, so the crate does not embed them: fetched_rule_sets is their catalogue, which gives, for each, the files of its family at their publishers (pinned URL and SHA-256, the pins of the fetch scripts of the repository) and the manifest of its bundle. Not on WebAssembly.

  • With the feature fetch (off by default; on in einvoice-cli), RuleSetCache::fetch downloads the files of a family (or takes them from a local directory, FetchOptions::from_dir), checks each against its pinned digest, assembles the bundles exactly as the fetch scripts do (a test checks they are the same, byte for byte) and installs them in the cache in one rename. Peppol BIS Billing publishes its rules as Schematron only: its bundle is built by compiling them as ph-schematron compiles them for the reference validators, in Rust (einvoice-schematron, with the ISO Schematron skeleton of the pinned jar of ph-schematron-isosch): no Java. The HTTP client is minimal and pure Rust, its cryptography included (rustls, with a provider on the RustCrypto crates, and the Mozilla roots of webpki-roots): HTTPS only (plain HTTP only to a loopback address, for a local mirror), at most five redirects, never from HTTPS to HTTP, five attempts with a doubling delay on an I/O error and on HTTP 408, 429 and 5xx (honouring Retry-After), an interrupted download resumed where it stopped, a size limit (DEFAULT_MAX_SIZE, 64 MiB); the archives (ZIP, gzip, tar) are read in memory, refusing absolute paths, .., links and sizes beyond their limits.
  • Nothing is downloaded otherwise: RuleSetCache::load and Validator::from_cache read the cache only, and fail with Error::NotCached for a rule set that has not been fetched. On every load the cached manifest must be, byte for byte, the catalogue’s, and every file must have its SHA-256, so a cache works offline and is never trusted.
use einvoice_validator::{FetchOptions, RuleSetCache, Validator};

// The platform's cache directory, or EINVOICE_VALIDATOR_CACHE.
let cache = RuleSetCache::new()?;
// Downloads and builds xrechnung-ubl and xrechnung-cii (once: then from the cache).
cache.fetch("xrechnung", &FetchOptions::new())?;
let validator = cache.load("xrechnung-ubl")?;
// The same, from the default cache, never downloading.
let same = Validator::from_cache("xrechnung-ubl")?;
assert_eq!(validator.rule_set(), same.rule_set());

The manifest is TOML, restricted to the subset below; anything else is refused with the line concerned (unknown keys included).

format = 2                   # the manifest format: 1, or MANIFEST_FORMAT for what says format 2
name = "cen-ubl"             # ASCII letters, digits, '-', '.', '_'
title = "CEN EN 16931 UBL"
version = "1.3.17"           # the version of the official artefacts
schema = "ubl-2.1"           # optional: the XML schema validated first, ubl-2.1 or cii-d16b,
#                            # or (format 2) the path of the entry point of the schema
#                            # documents of the bundle ([[schema-document]])
# unchecked-schema = "..."   # format 2, optional: an XML schema the reference
#                            # validator also checks and this rule set does not

[[stylesheet]]               # one or more, run in this order
name = "EN16931-UBL"         # unique in the bundle
path = "ubl/xslt/EN16931-UBL-validation.xslt"   # relative, '/'-separated, no '..'
sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
# version = "..."            # optional: when it differs from the bundle's
# unflagged-assert = "fatal" # format 2, optional: the severity of a failed assert
#                            # without a flag (fatal, warning or other; default other)

[[resource]]                 # format 2: zero or more files read with document()
path = "ubl/xslt/codes.xml"  # relative, '/'-separated, no '..'
sha256 = "0000000000000000000000000000000000000000000000000000000000000000"

[[schema-document]]          # format 2: the documents of the schema of the bundle, when
path = "xsd/main.xsd"        # `schema` is the path of one of them, its entry point: it
sha256 = "1111111111111111111111111111111111111111111111111111111111111111"
#                            # and every document it imports or includes, each a table

[[scenario]]                 # format 2: zero or more, tried in this order
name = "EN16931 XRechnung (UBL Invoice)"        # unique in the bundle
# A scenario of a KoSIT configuration: its namespaces (prefix=uri, separated by
# spaces), its match expression (XPath, as written) and the stylesheets it runs.
namespaces = "cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 invoice=urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
match = "exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0'])"
stylesheets = "EN16931-UBL XRechnung-UBL"    # optional: by default all, in order
fatal = "UBL-CR-646"         # optional: rule ids and the severity the scenario
warning = "BR-CL-23 BR-CL-21"   # gives them, separated by spaces, each in one list
# Or, instead of namespaces, match and stylesheets: the root element and the
# specification identifier (BT-24) of the documents it gives severities to (at least
# one of fatal, warning and other then), every stylesheet running.
# namespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
# root = "Invoice"           # with namespace: a UBL Invoice or CreditNote, a CII CrossIndustryInvoice
# identifier = "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0"

The scenarios of a manifest all have a match expression, or none has. With them, the rule set selects by scenario (Scenario): a document must match exactly one, whose stylesheets run, in its order, and whose severities apply; a document that matches none, or several, is invalid, with no schema error reported and no stylesheet run, as the KoSIT validator rejects it with its fallback scenario (which has no schema). The expressions are evaluated with einvoice_xpath_eval, with the document node as the context item, their effective boolean value; one that raises a dynamic error is false, as for the KoSIT validator; one outside the engine’s subset is refused when the bundle is loaded.

Accepted syntax: comments, key = value lines with a bare key, values that are basic strings (escapes \" and \\ only), literal strings or non-negative integers, and [[stylesheet]], [[resource]], [[schema-document]] and [[scenario]] headers.

§Severities

Each finding has a Severity, and a fatal finding makes the document invalid. By default it is the one its Schematron flag stands for (Severity::from_flag: fatal, warning, any other flag or none Severity::Other), which is how the reference validators read the CEN and Peppol rules, which flag every assert. The manifest gives the others what their reference validators read:

  • unflagged-assert, for a stylesheet whose failed asserts may have no flag: the Factur-X stylesheets leave it out of most of their asserts, which the Mustang validator reads as errors, so the Factur-X bundles (and those of the French rules that run a Factur-X profile) say unflagged-assert = "fatal", as do the XRechnung bundles, the KoSIT validator reading a missing flag as an error too. A successful report without a flag stays Severity::Other.
  • [[scenario]] (Scenario): the levels a scenario of a KoSIT validator configuration gives rule ids (customLevel), whatever their flags, in the documents it matches; the XRechnung bundles have the scenarios of their configuration, each with its match expression and its stylesheets (error is Severity::Fatal, information Severity::Other). The Report names the scenario the document matched, or says why it has none.

The KoSIT validator also validates each document against the XML schema of its scenario: the UBL 2.1 schema, which the XRechnung UBL bundle runs, or the UN/CEFACT CII D16B schema, which the XRechnung CII bundle runs (SchemaId::CiiD16b). The Mustang validator validates a Factur-X document against the XML schema of its profile, and the documentation of the French rules has a document validated against the schema of its syntax or profile first: their bundles carry those schemas (SchemaId::Bundle); a schema error makes the document invalid, and the stylesheets run all the same. A bundle whose reference validator checks a schema it does not run names it in unchecked-schema (RuleSet::unchecked_schema, RuleSetVersion::unchecked_schema in the report): a document it would reject for a schema error alone is valid here.

ValidateOptions::fail_closed then makes every finding that is still Severity::Other fatal, for rule sets whose flags the caller does not know.

§PDF files

With the feature pdf (on by default), the module pdf extracts the invoice XML that a Factur-X, ZUGFeRD or Order-X PDF/A-3 file embeds, with its /AFRelationship and the document’s XMP metadata, in pure Rust (the crate einvoice-pdf); the XML is then validated as any other document, with the rule set Syntax::detect names for it.

§WebAssembly

The crate builds for wasm32-unknown-unknown and needs nothing from the host there: the built-in rule set is embedded, and a bundle can be given from memory. That target has no system clock, so the caller gives the one the stylesheets read with ValidateOptions::clock (for instance Clock::from_unix_millis with JavaScript’s Date.now()); without it, a validation fails with Error::Unsupported. The wasm-validate example validates two embedded documents that way and runs under wasmtime.

§Licences

The code is MIT. The built-in rule sets cen-ubl and cen-cii embed the CEN stylesheets, under the EUPL-1.2, and einvoice_xsd embeds the OASIS UBL 2.1 schemas and the UN/CEFACT CII D16B schemas, which keep their own terms (OASIS, UN/CEFACT, W3C). licences() returns the full text of every licence of what this build embeds, for programs that must show them to their users.

§Errors

A schema error or a failed assert is not an error: it is in the Report. An Error means no complete verdict could be given: a bundle that cannot be loaded, a document that is not XML, a construct the engine refuses rather than evaluating it differently from the reference engine, a document beyond a limit, a dynamic error raised by a stylesheet, or a bug.

§Limits

The stylesheets walk the document with template rules applied one element level inside another, so the stack a validation needs grows with the depth of the document. A document with an element nested deeper than ValidateOptions::max_depth (DEFAULT_MAX_DEPTH, 256, libxml2’s default) is therefore refused before its schema is checked, with Error::Limit and the line and column of that element, rather than overflowing the stack of the thread, which would abort the process. At the default maximum, a validation with the built-in rule sets or the Peppol bundle runs on a thread with the default 2 MiB stack of a spawned thread, debug builds included. The template and function invocations of the stylesheets are bounded too: in nesting (max_nesting_for_depth of the maximum depth) and in the stack they use (ValidateOptions::max_stack, DEFAULT_MAX_STACK), so that a stylesheet that recurses without end fails with Error::Limit as well.

On WebAssembly, the engine running the module has a native stack of its own, which the module cannot measure and which runs out before the module’s stack in some JavaScript engines, leaving the module unusable. There, the stack the stylesheets may use is 256 KiB, and at most WASM_MAX_STACK, the same; the maximum depth is at most WASM_MAX_DEPTH, 400: a validation asking for more fails with Error::OptionOutOfRange. Within 256 KiB, the stylesheets validate a document up to 487 levels deep when no rule fires on its deepest elements, and up to 243 when a rule reports on every level (measured with the official stylesheets); deeper, the validation fails with Error::Limit.

Modules§

pdf
Factur-X, ZUGFeRD and Order-X PDF files (feature pdf, on by default): the invoice XML a PDF/A-3 file embeds, extracted with einvoice_pdf, to be validated as any other document.

Structs§

Clock
The clock of a validation (ValidateOptions::clock): the implicit timezone and the value of fn:current-dateTime(). The clock of an evaluation: the implicit timezone and the value of fn:current-dateTime(). Both are inputs: the evaluator never reads a clock itself, and the current date and time stays the same for every evaluation made with the clock, as Saxon reads its clock once per transformation.
CompactOutput
An SVRL report as the stylesheet wrote it, kept compactly (StylesheetReport::svrl). The serialized result document of Executable::transform_compact, kept as a sequence of pieces, each distinct piece stored once. A piece is what the serializer writes from one tag to the next written in full: an element with its indentation, a start tag, or text with the end tag that follows.
FetchedRuleSet
A rule set this crate fetches from its publisher on demand (RuleSetCache): its files are not redistributed by the project. Each is one bundle of a family; the rule sets of a family come from the same downloads and are fetched together.
Finding
A failed assert or a successful report of a stylesheet, as the SVRL report states it.
Licence
A licence under which part of a crate is distributed: one term of the crate’s licence expression, what it covers, and its full text, as shipped in the crate’s LICENSES/ directory.
Report
The result of validating one document: the schema errors, then what each stylesheet of the rule set reported.
ResourceEntry
A file of the bundle that the stylesheets read with document() (a code list, …), as the manifest describes it (format 2, [[resource]]).
RuleSet
A rule set, as described by the manifest of its bundle: its name and version, the XML schema to validate against first, the stylesheets to run, in order, and the resources they read and the schema documents, with their checksums.
RuleSetCache
The cache of the rule sets fetched from their publishers (fetched_rule_sets): a directory holding, under rules/, the bundle of each fetched rule set, laid out as the fetch scripts of the repository lay them out (FetchedRuleSet::bundle_path).
RuleSetVersion
The rule set a report was produced with.
Scenario
A scenario of the rule set (format 2, [[scenario]]): which documents it matches, the severities it gives rule ids, whatever their flags, in them (the customLevel elements of a scenario of a KoSIT validator configuration), and, for a scenario with a match expression, the stylesheets that run on them.
SchemaDocumentEntry
A document of the XML schema of the bundle (format 2, [[schema-document]]): the entry point the manifest’s schema names, or a document it imports or includes, as the manifest describes it.
SchemaError
One validity error of a document.
Source
A pinned download, resolved.
StylesheetEntry
One stylesheet of a rule set, as its manifest describes it.
StylesheetFailure
A dynamic error raised by a stylesheet on a document (the reference engine raises it as well), which stopped the stylesheet.
StylesheetReport
What one stylesheet of the rule set reported on a document.
ValidateOptions
Options of one validation.
Validator
A rule set ready to validate documents: its schema loaded and its stylesheets prepared, once. Validating a document only reads it, so one Validator serves any number of documents, from any number of threads at once (Send + Sync); nothing of the rule set is copied per document. A clone shares the loaded rule set (it is reference-counted): cloning is cheap, and the clones can be moved to other threads.

Enums§

CacheStatus
What the cache holds of a fetched rule set.
Error
Why a rule set could not be loaded, or a document could not be validated.
ErrorKind
The kind of an Error, for callers that only need to classify it (the exit code of a command-line tool, …).
FindingKind
What a finding is in the SVRL report.
LimitExceeded
The default maximum element depth of a document (ValidateOptions::max_depth), and the limits Error::Limit reports. A limit that a document or a transformation exceeded: the input is refused rather than processed with an unbounded call stack.
NoScenario
Why a document has no scenario, in a rule set that selects by scenario (RuleSet::selects_by_scenario): the document is then invalid and no stylesheet runs on it, as the KoSIT validator rejects a document with its fallback scenario.
SchemaErrorKind
The kind of a ValidationError. The set and the names of ErrorKind::as_str are stable.
SchemaId
The XML schema a rule set validates documents against before running its stylesheets.
Severity
The severity of a finding, from its Schematron flag, as the official rule sets use it, and from the manifest of the rule set: a failed assert without a flag has the severity of its stylesheet’s unflagged-assert (StylesheetEntry::unflagged_assert), and the scenario a document matches gives the rule ids it lists their severities, whatever their flags (Scenario).
Syntax
The syntax of an e-invoice, as its root element names it.
Verdict
The overall verdict on a document.

Constants§

BUILTIN_RULE_SETS
The names of the built-in rule sets of this build (each is a cargo feature of the same name, cen-ubl and cen-cii on by default).
CACHE_ENV
The environment variable that sets the cache directory, overriding the platform’s.
DEFAULT_MAX_DEPTH
The default maximum element depth of a document (ValidateOptions::max_depth), and the limits Error::Limit reports. The maximum element depth of a parsed document, unless the caller sets another one: the document element is at depth 1, its child elements at depth 2, and so on.
DEFAULT_MAX_STACK
The default stack the stylesheets may use (ValidateOptions::max_stack). The default of TransformOptions::max_stack: 1.5 MiB, for a thread with the default 2 MiB stack of a spawned thread; 256 KiB on WebAssembly. With it, the official stylesheets run on a document DEFAULT_MAX_DEPTH deep, in a debug build too, and the 512 KiB left are more than the caller and one level of invocation need.
MANIFEST_FILE
The file name of the manifest in a bundle directory.
MANIFEST_FORMAT
The newest manifest format this crate reads (the format key): format 2 adds to format 1, which is read too, the [[resource]], [[schema-document]] and [[scenario]] tables, the unflagged-assert key of [[stylesheet]] and the unchecked-schema key.
VERSION
The version of this crate, as published.
WASM_MAX_DEPTH
The largest ValidateOptions::max_depth on WebAssembly: 400.
WASM_MAX_STACK
The largest ValidateOptions::max_stack on WebAssembly, and its default there (DEFAULT_MAX_STACK): 256 KiB.

Functions§

fetched_rule_set
The fetched rule set named name, or the one an alias names for a document of syntax (peppol; xrechnung, which is xrechnung-ubl or xrechnung-cii).
fetched_rule_set_aliases
The aliases fetched_rule_set takes besides the names of the rule sets: peppol (peppol-bis-billing-ubl) and xrechnung (xrechnung-ubl or xrechnung-cii, by syntax).
fetched_rule_sets
Every rule set fetched on demand, in the order of the catalogue: the five Factur-X profiles, XRechnung UBL and CII, the fourteen bundles of the French rules, Peppol BIS Billing 3.0.
file_uri
The file: URI that the reference engine (Saxon-HE) gives a document read from the file at path (absolute). None for a relative path or one that is not Unicode.
licences
Every licence of what this build of the crate embeds in a program, with its full text: the MIT licence of the code (of this crate and of the crates of the project it depends on, which share that licence), the EUPL-1.2 of the CEN stylesheets when the feature cen-ubl or cen-cii is on, then the terms of the UBL 2.1 and CII D16B schemas embedded by einvoice_xsd (OASIS, UN/CEFACT, W3C).
max_nesting_for_depth
The nesting of template and function invocations the stylesheets are allowed on a document at most max_depth deep (ValidateOptions::max_depth): twice the depth, plus 64. Each level needs less than 3 KiB of stack (debug builds included), which is what a caller raising the maximum depth must give the validating thread. The nesting of invocations that the official stylesheets need on a document max_depth deep, with room to spare: twice the depth, plus 64.