Skip to main content

einvoice_validator/
manifest.rs

1//! The manifest of a rule-set bundle (`bundle.toml`): what the rule set is, which XML
2//! schema and which stylesheets it runs, and the SHA-256 of each stylesheet.
3
4use std::fmt;
5
6use crate::Error;
7
8/// The file name of the manifest in a bundle directory.
9pub const MANIFEST_FILE: &str = "bundle.toml";
10
11/// The manifest format this crate reads (the `format` key).
12pub const MANIFEST_FORMAT: u32 = 1;
13
14/// The XML schema a rule set validates documents against before running its
15/// stylesheets.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum SchemaId {
19    /// The OASIS UBL 2.1 schemas for Invoice and `CreditNote`, embedded in
20    /// [`einvoice_xsd`].
21    Ubl21,
22}
23
24impl SchemaId {
25    /// The name used in manifests: `ubl-2.1`.
26    #[must_use]
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Ubl21 => "ubl-2.1",
30        }
31    }
32
33    /// The schema named `name` in a manifest.
34    #[must_use]
35    pub fn from_name(name: &str) -> Option<Self> {
36        match name {
37            "ubl-2.1" => Some(Self::Ubl21),
38            _ => None,
39        }
40    }
41}
42
43impl fmt::Display for SchemaId {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str(self.as_str())
46    }
47}
48
49/// One stylesheet of a rule set, as its manifest describes it.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct StylesheetEntry {
52    name: String,
53    version: String,
54    path: String,
55    sha256: String,
56}
57
58impl StylesheetEntry {
59    /// Its name, unique within the rule set (`EN16931-UBL`, ...).
60    #[must_use]
61    pub fn name(&self) -> &str {
62        &self.name
63    }
64
65    /// The version of the rule set it implements: the manifest's `version` of the
66    /// stylesheet, else the version of the bundle.
67    #[must_use]
68    pub fn version(&self) -> &str {
69        &self.version
70    }
71
72    /// Its path in the bundle: relative, `/`-separated.
73    #[must_use]
74    pub fn path(&self) -> &str {
75        &self.path
76    }
77
78    /// The SHA-256 of the file, lower-case hexadecimal.
79    #[must_use]
80    pub fn sha256(&self) -> &str {
81        &self.sha256
82    }
83}
84
85/// A rule set, as described by the manifest of its bundle: its name and version, the
86/// XML schema to validate against first, and the stylesheets to run, in order, with
87/// their checksums.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct RuleSet {
90    name: String,
91    title: String,
92    version: String,
93    schema: Option<SchemaId>,
94    stylesheets: Vec<StylesheetEntry>,
95}
96
97impl RuleSet {
98    /// Parses a bundle manifest (see the crate documentation for the format).
99    ///
100    /// # Errors
101    ///
102    /// [`Error::Bundle`] naming the line: a syntax outside the accepted TOML subset, an
103    /// unknown or repeated key, a missing key, a value that is not valid for its key, an
104    /// unknown schema, a format other than [`MANIFEST_FORMAT`].
105    pub fn parse(manifest: &str) -> Result<Self, Error> {
106        let tables = parse_tables(manifest)?;
107        let mut tables = tables.into_iter();
108        let Some(top) = tables.next() else {
109            return Err(Error::bundle(format!("{MANIFEST_FILE}: empty")));
110        };
111        let mut top = Table::new(top);
112        let format_line = top.line_of("format");
113        top.allow(&["format", "name", "title", "version", "schema"])?;
114        match top.take("format") {
115            Some(Value::Integer(f)) if f == u64::from(MANIFEST_FORMAT) => {}
116            Some(Value::Integer(f)) => {
117                return Err(Error::bundle(format!(
118                    "{MANIFEST_FILE}:{format_line}: format {f}: only format {MANIFEST_FORMAT} is supported"
119                )));
120            }
121            Some(Value::String(_)) => {
122                return Err(Error::bundle(format!(
123                    "{MANIFEST_FILE}:{format_line}: `format` must be an integer"
124                )));
125            }
126            None => {
127                return Err(Error::bundle(format!(
128                    "{MANIFEST_FILE}: the `format` key is missing (format = {MANIFEST_FORMAT})"
129                )));
130            }
131        }
132        let name = top.required_string("name")?;
133        check_name(&name).map_err(|m| top.error("name", &m))?;
134        let title = top.required_string("title")?;
135        if title.trim().is_empty() || title.chars().any(char::is_control) {
136            return Err(top.error("title", "must be non-empty text on one line"));
137        }
138        let version = top.required_string("version")?;
139        check_version(&version).map_err(|m| top.error("version", &m))?;
140        let schema = match top.optional_string("schema")? {
141            None => None,
142            Some(s) => Some(SchemaId::from_name(&s).ok_or_else(|| {
143                top.error("schema", &format!("unknown schema {s:?} (known: ubl-2.1)"))
144            })?),
145        };
146        top.finish()?;
147
148        let mut stylesheets: Vec<StylesheetEntry> = Vec::new();
149        for raw in tables {
150            let mut table = Table::new(raw);
151            table.allow(&["name", "version", "path", "sha256"])?;
152            let entry_name = table.required_string("name")?;
153            check_name(&entry_name).map_err(|m| table.error("name", &m))?;
154            if stylesheets.iter().any(|s| s.name == entry_name) {
155                return Err(table.error("name", &format!("stylesheet {entry_name:?} twice")));
156            }
157            let entry_version = match table.optional_string("version")? {
158                Some(v) => {
159                    check_version(&v).map_err(|m| table.error("version", &m))?;
160                    v
161                }
162                None => version.clone(),
163            };
164            let path = table.required_string("path")?;
165            check_path(&path).map_err(|m| table.error("path", &m))?;
166            let sha256 = table.required_string("sha256")?;
167            if sha256.len() != 64
168                || !sha256
169                    .bytes()
170                    .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
171            {
172                return Err(table.error("sha256", "must be 64 lower-case hexadecimal digits"));
173            }
174            table.finish()?;
175            stylesheets.push(StylesheetEntry {
176                name: entry_name,
177                version: entry_version,
178                path,
179                sha256,
180            });
181        }
182        if stylesheets.is_empty() {
183            return Err(Error::bundle(format!(
184                "{MANIFEST_FILE}: no [[stylesheet]]: a rule set runs at least one"
185            )));
186        }
187        Ok(Self {
188            name,
189            title,
190            version,
191            schema,
192            stylesheets,
193        })
194    }
195
196    /// The manifest of the built-in rule set `name` (see
197    /// [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)), without loading it.
198    ///
199    /// # Errors
200    ///
201    /// [`Error::Bundle`] for an unknown name.
202    pub fn builtin(name: &str) -> Result<Self, Error> {
203        Self::parse(crate::builtin::get(name)?.0)
204    }
205
206    /// Its short name (`cen-ubl`): ASCII letters, digits, `-`, `.` and `_`.
207    #[must_use]
208    pub fn name(&self) -> &str {
209        &self.name
210    }
211
212    /// Its title (`CEN EN 16931 UBL`).
213    #[must_use]
214    pub fn title(&self) -> &str {
215        &self.title
216    }
217
218    /// The version of the official artefacts (`1.3.17`).
219    #[must_use]
220    pub fn version(&self) -> &str {
221        &self.version
222    }
223
224    /// The XML schema documents are validated against first, if any.
225    #[must_use]
226    pub const fn schema(&self) -> Option<SchemaId> {
227        self.schema
228    }
229
230    /// The stylesheets, in the order they run.
231    #[must_use]
232    pub fn stylesheets(&self) -> &[StylesheetEntry] {
233        &self.stylesheets
234    }
235}
236
237fn check_name(name: &str) -> Result<(), String> {
238    let mut bytes = name.bytes();
239    let first_ok = bytes.next().is_some_and(|b| b.is_ascii_alphanumeric());
240    if first_ok && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_')) {
241        Ok(())
242    } else {
243        Err(format!(
244            "{name:?}: ASCII letters, digits, `-`, `.` and `_` only, starting with a letter or digit"
245        ))
246    }
247}
248
249fn check_version(version: &str) -> Result<(), String> {
250    if !version.is_empty()
251        && version
252            .chars()
253            .all(|c| !c.is_whitespace() && !c.is_control())
254    {
255        Ok(())
256    } else {
257        Err(format!("{version:?}: must be non-empty, without spaces"))
258    }
259}
260
261/// A path inside the bundle: relative, `/`-separated, no empty, `.` or `..` segment, no
262/// backslash or colon, so that it can never designate a file outside the bundle.
263fn check_path(path: &str) -> Result<(), String> {
264    let bad = path.is_empty()
265        || path.contains(['\\', ':'])
266        || path.chars().any(char::is_control)
267        || path
268            .split('/')
269            .any(|segment| segment.is_empty() || segment == "." || segment == "..");
270    if bad {
271        Err(format!(
272            "{path:?}: must be a relative `/`-separated path inside the bundle (no empty, `.` or `..` segment, no `\\` or `:`)"
273        ))
274    } else {
275        Ok(())
276    }
277}
278
279/// A value of the accepted TOML subset.
280#[derive(Debug, Clone, PartialEq, Eq)]
281enum Value {
282    String(String),
283    Integer(u64),
284}
285
286/// The keys of one table, in order, with their lines. The top-level table has header
287/// line 0.
288#[derive(Debug)]
289struct RawTable {
290    header_line: u32,
291    entries: Vec<(String, Value, u32)>,
292}
293
294/// Reads the accepted TOML subset: comments, blank lines, `key = value` lines with a
295/// bare key and a basic string (escapes `\"` and `\\` only), a literal string or a
296/// non-negative integer, and `[[stylesheet]]` headers.
297fn parse_tables(text: &str) -> Result<Vec<RawTable>, Error> {
298    let mut tables = vec![RawTable {
299        header_line: 0,
300        entries: Vec::new(),
301    }];
302    for (index, line) in text.split('\n').enumerate() {
303        let number = u32::try_from(index + 1).unwrap_or(u32::MAX);
304        let fail = |message: &str| Error::bundle(format!("{MANIFEST_FILE}:{number}: {message}"));
305        let line = line.strip_suffix('\r').unwrap_or(line);
306        let content = line.trim_matches([' ', '\t']);
307        if content.is_empty() || content.starts_with('#') {
308            continue;
309        }
310        if let Some(rest) = content.strip_prefix('[') {
311            let header = rest.strip_prefix("[stylesheet]]").map(after_value);
312            match header {
313                Some(Ok(())) => {
314                    tables.push(RawTable {
315                        header_line: number,
316                        entries: Vec::new(),
317                    });
318                    continue;
319                }
320                Some(Err(m)) => return Err(fail(&m)),
321                None => return Err(fail("the only table allowed is [[stylesheet]]")),
322            }
323        }
324        let Some((key, value)) = content.split_once('=') else {
325            return Err(fail("expected `key = value`"));
326        };
327        let key = key.trim_matches([' ', '\t']);
328        if key.is_empty()
329            || !key
330                .bytes()
331                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
332        {
333            return Err(fail(&format!("{key:?}: expected a bare key")));
334        }
335        let value = parse_value(value.trim_start_matches([' ', '\t'])).map_err(|m| fail(&m))?;
336        let Some(table) = tables.last_mut() else {
337            return Err(Error::internal("manifest: no table"));
338        };
339        if table.entries.iter().any(|(k, _, _)| k == key) {
340            return Err(fail(&format!("key `{key}` repeated")));
341        }
342        table.entries.push((key.to_owned(), value, number));
343    }
344    Ok(tables)
345}
346
347fn parse_value(text: &str) -> Result<Value, String> {
348    if let Some(rest) = text.strip_prefix('"') {
349        let mut value = String::new();
350        let mut chars = rest.char_indices();
351        while let Some((i, c)) = chars.next() {
352            match c {
353                '"' => {
354                    after_value(&rest[i + 1..])?;
355                    return Ok(Value::String(value));
356                }
357                '\\' => match chars.next() {
358                    Some((_, '"')) => value.push('"'),
359                    Some((_, '\\')) => value.push('\\'),
360                    _ => return Err("only the escapes \\\" and \\\\ are accepted".to_owned()),
361                },
362                c if c.is_control() && c != '\t' => {
363                    return Err("control character in a string".to_owned());
364                }
365                c => value.push(c),
366            }
367        }
368        Err("unterminated string".to_owned())
369    } else if let Some(rest) = text.strip_prefix('\'') {
370        let end = rest
371            .find('\'')
372            .ok_or_else(|| "unterminated string".to_owned())?;
373        let value = &rest[..end];
374        if value.chars().any(|c| c.is_control() && c != '\t') {
375            return Err("control character in a string".to_owned());
376        }
377        after_value(&rest[end + 1..])?;
378        Ok(Value::String(value.to_owned()))
379    } else {
380        let end = text
381            .find(|c: char| !c.is_ascii_digit())
382            .unwrap_or(text.len());
383        let digits = &text[..end];
384        if digits.is_empty() || (digits.len() > 1 && digits.starts_with('0')) {
385            return Err("expected a string or a non-negative integer".to_owned());
386        }
387        let value = digits
388            .parse()
389            .map_err(|_| "integer out of range".to_owned())?;
390        after_value(&text[end..])?;
391        Ok(Value::Integer(value))
392    }
393}
394
395/// What may follow a value or a header on its line: blanks and a comment.
396fn after_value(rest: &str) -> Result<(), String> {
397    let rest = rest.trim_start_matches([' ', '\t']);
398    if rest.is_empty() || rest.starts_with('#') {
399        Ok(())
400    } else {
401        Err(format!("unexpected {rest:?} after the value"))
402    }
403}
404
405/// A table whose keys are taken one by one; [`Table::finish`] fails on any left.
406struct Table {
407    header_line: u32,
408    /// Key, value (`None` once taken) and line.
409    entries: Vec<(String, Option<Value>, u32)>,
410}
411
412impl Table {
413    fn new(raw: RawTable) -> Self {
414        Self {
415            header_line: raw.header_line,
416            entries: raw
417                .entries
418                .into_iter()
419                .map(|(k, v, l)| (k, Some(v), l))
420                .collect(),
421        }
422    }
423
424    fn where_(&self) -> String {
425        if self.header_line == 0 {
426            MANIFEST_FILE.to_owned()
427        } else {
428            format!(
429                "{MANIFEST_FILE}: [[stylesheet]] of line {}",
430                self.header_line
431            )
432        }
433    }
434
435    /// The line of `key`, taken or not; the header's line when absent.
436    fn line_of(&self, key: &str) -> u32 {
437        self.entries
438            .iter()
439            .find(|(k, _, _)| k == key)
440            .map_or(self.header_line, |(_, _, l)| *l)
441    }
442
443    fn error(&self, key: &str, message: &str) -> Error {
444        Error::bundle(format!(
445            "{MANIFEST_FILE}:{}: `{key}`: {message}",
446            self.line_of(key)
447        ))
448    }
449
450    /// Fails on a key outside `allowed`.
451    fn allow(&self, allowed: &[&str]) -> Result<(), Error> {
452        match self
453            .entries
454            .iter()
455            .find(|(k, _, _)| !allowed.contains(&k.as_str()))
456        {
457            Some((key, _, line)) => Err(Error::bundle(format!(
458                "{MANIFEST_FILE}:{line}: unknown key `{key}` (expected one of: {})",
459                allowed.join(", ")
460            ))),
461            None => Ok(()),
462        }
463    }
464
465    fn take(&mut self, key: &str) -> Option<Value> {
466        self.entries
467            .iter_mut()
468            .find(|(k, _, _)| k == key)
469            .and_then(|(_, v, _)| v.take())
470    }
471
472    fn optional_string(&mut self, key: &str) -> Result<Option<String>, Error> {
473        match self.take(key) {
474            None => Ok(None),
475            Some(Value::String(s)) => Ok(Some(s)),
476            Some(Value::Integer(_)) => Err(self.error(key, "must be a string")),
477        }
478    }
479
480    fn required_string(&mut self, key: &str) -> Result<String, Error> {
481        let where_ = self.where_();
482        self.optional_string(key)?
483            .ok_or_else(|| Error::bundle(format!("{where_}: the `{key}` key is missing")))
484    }
485
486    fn finish(self) -> Result<(), Error> {
487        match self.entries.iter().find(|(_, v, _)| v.is_some()) {
488            Some((key, _, line)) => Err(Error::bundle(format!(
489                "{MANIFEST_FILE}:{line}: unexpected key `{key}`"
490            ))),
491            None => Ok(()),
492        }
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499
500    const GOOD: &str = r#"# comment
501format = 1
502name = "cen-ubl"   # trailing comment
503title = 'CEN EN 16931 UBL'
504version = "1.3.17"
505schema = "ubl-2.1"
506
507[[stylesheet]]
508name = "EN16931-UBL"
509path = "ubl/xslt/EN16931-UBL-validation.xslt"
510sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
511
512[[stylesheet]]  # second
513name = "other"
514version = "3.0.22"
515path = "x.xsl"
516sha256 = "0000000000000000000000000000000000000000000000000000000000000000"
517"#;
518
519    #[test]
520    fn parses_a_manifest() {
521        let rule_set = RuleSet::parse(GOOD).unwrap();
522        assert_eq!(rule_set.name(), "cen-ubl");
523        assert_eq!(rule_set.title(), "CEN EN 16931 UBL");
524        assert_eq!(rule_set.version(), "1.3.17");
525        assert_eq!(rule_set.schema(), Some(SchemaId::Ubl21));
526        let s = rule_set.stylesheets();
527        assert_eq!(s.len(), 2);
528        assert_eq!(s[0].name(), "EN16931-UBL");
529        assert_eq!(s[0].version(), "1.3.17");
530        assert_eq!(s[0].path(), "ubl/xslt/EN16931-UBL-validation.xslt");
531        assert_eq!(s[1].version(), "3.0.22");
532    }
533
534    #[test]
535    fn the_embedded_manifest_parses() {
536        let rule_set = RuleSet::parse(include_str!("../bundles/cen-ubl/bundle.toml")).unwrap();
537        assert_eq!(rule_set.name(), "cen-ubl");
538    }
539
540    #[test]
541    fn schema_is_optional() {
542        let text = GOOD.replace("schema = \"ubl-2.1\"\n", "");
543        assert_eq!(RuleSet::parse(&text).unwrap().schema(), None);
544    }
545
546    fn error(text: &str) -> String {
547        RuleSet::parse(text).unwrap_err().to_string()
548    }
549
550    #[test]
551    fn refusals_name_the_line() {
552        let cases = [
553            (
554                GOOD.replace("format = 1", "format = 2"),
555                "bundle.toml:2: format 2",
556            ),
557            (
558                GOOD.replace("format = 1", "format = \"1\""),
559                "bundle.toml:2:",
560            ),
561            (
562                GOOD.replace("format = 1\n", ""),
563                "the `format` key is missing",
564            ),
565            (
566                GOOD.replace("ubl-2.1", "ubl-2.2"),
567                "bundle.toml:6: `schema`: unknown schema",
568            ),
569            (
570                GOOD.replace("title =", "titel ="),
571                "bundle.toml:4: unknown key `titel`",
572            ),
573            (
574                GOOD.replace("name = \"other\"", "name = \"EN16931-UBL\""),
575                "twice",
576            ),
577            (GOOD.replace("x.xsl", "../x.xsl"), "`path`"),
578            (GOOD.replace("x.xsl", "/x.xsl"), "`path`"),
579            (GOOD.replace("x.xsl", "C:/x.xsl"), "`path`"),
580            (GOOD.replace("x.xsl", "a//x.xsl"), "`path`"),
581            (GOOD.replace("x.xsl", "a\\\\x.xsl"), "`path`"),
582            (GOOD.replace("\"0000", "\"A000"), "`sha256`"),
583            (
584                GOOD.replace("version = \"1.3.17\"", "version = \"1 3\""),
585                "`version`",
586            ),
587            (
588                GOOD.replace("[[stylesheet]]  #", "[stylesheet] #"),
589                "bundle.toml:13: the only table",
590            ),
591            (
592                GOOD.replace("name = \"cen-ubl\"", "name = \"cen\\nubl\""),
593                "bundle.toml:3: only the escapes",
594            ),
595            (
596                GOOD.replace("name = \"cen-ubl\"", "name = \"cen-ubl"),
597                "unterminated",
598            ),
599            (
600                GOOD.replace("version = \"1.3.17\"", "version = \"1.3.17\" x"),
601                "after the value",
602            ),
603            (
604                GOOD.replace("format = 1", "format = 1\nformat = 1"),
605                "repeated",
606            ),
607            (
608                GOOD.replace("format = 1", "format = 01"),
609                "bundle.toml:2: expected a string",
610            ),
611            (
612                GOOD.replace("path = \"x.xsl\"\n", ""),
613                "the `path` key is missing",
614            ),
615            (
616                GOOD.split("[[stylesheet]]").next().unwrap().to_owned(),
617                "no [[stylesheet]]",
618            ),
619            (String::new(), "the `format` key is missing"),
620            (
621                "format\n".to_owned(),
622                "bundle.toml:1: expected `key = value`",
623            ),
624        ];
625        for (text, expected) in cases {
626            let message = error(&text);
627            assert!(
628                message.contains(expected),
629                "{expected:?} not in {message:?}"
630            );
631        }
632    }
633}