1use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5
6use einvoice_xpath_eval::{Clock, DEFAULT_MAX_DEPTH, LimitExceeded};
7use einvoice_xslt::LoadErrorKind;
8use einvoice_xslt_exec::{
9 DEFAULT_MAX_STACK, Executable, TransformError, TransformOptions, max_nesting_for_depth,
10};
11use roxmltree::ParsingOptions;
12use sha2::{Digest, Sha256};
13
14use crate::manifest::{MANIFEST_FILE, RuleSet, SchemaId, StylesheetEntry};
15use crate::report::{Report, RuleSetVersion, StylesheetFailure, StylesheetReport};
16use crate::{Error, builtin};
17
18#[derive(Debug, Clone, Copy)]
20pub struct ValidateOptions<'a> {
21 document_uri: Option<&'a str>,
22 clock: Option<Clock>,
23 max_depth: u32,
24 max_stack: u32,
25}
26
27impl Default for ValidateOptions<'_> {
28 fn default() -> Self {
29 Self::new()
30 }
31}
32
33impl<'a> ValidateOptions<'a> {
34 #[must_use]
38 pub const fn new() -> Self {
39 Self {
40 document_uri: None,
41 clock: None,
42 max_depth: DEFAULT_MAX_DEPTH,
43 max_stack: DEFAULT_MAX_STACK,
44 }
45 }
46
47 #[must_use]
61 pub const fn max_depth(mut self, max_depth: u32) -> Self {
62 self.max_depth = max_depth;
63 self
64 }
65
66 #[must_use]
74 pub const fn max_stack(mut self, bytes: u32) -> Self {
75 self.max_stack = bytes;
76 self
77 }
78
79 #[must_use]
85 pub const fn clock(mut self, clock: Clock) -> Self {
86 self.clock = Some(clock);
87 self
88 }
89
90 #[must_use]
94 pub const fn document_uri(mut self, uri: &'a str) -> Self {
95 self.document_uri = Some(uri);
96 self
97 }
98}
99
100#[must_use]
103pub fn file_uri(path: &Path) -> Option<String> {
104 einvoice_xpath_eval::file_uri(path)
105}
106
107#[derive(Debug)]
112pub struct Validator {
113 rule_set: RuleSet,
114 schema: Option<einvoice_xsd::Schema>,
115 stylesheets: Vec<Executable>,
117}
118
119impl Validator {
120 pub fn builtin(name: &str) -> Result<Self, Error> {
127 let (manifest, files) = builtin::get(name)?;
128 Self::from_bundle(manifest, files)
129 }
130
131 #[cfg(feature = "cen-ubl")]
138 pub fn cen_ubl() -> Result<Self, Error> {
139 Self::builtin("cen-ubl")
140 }
141
142 #[cfg(feature = "cen-cii")]
150 pub fn cen_cii() -> Result<Self, Error> {
151 Self::builtin("cen-cii")
152 }
153
154 pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
164 let rule_set = RuleSet::parse(manifest)?;
165 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
166 for entry in rule_set.stylesheets() {
167 let Some((_, bytes)) = files.iter().find(|(path, _)| *path == entry.path()) else {
168 return Err(Error::bundle(format!(
169 "stylesheet {}: file {} missing from the bundle",
170 entry.name(),
171 entry.path()
172 )));
173 };
174 stylesheets.push(prepare(entry, bytes, None)?);
175 }
176 Self::with(rule_set, stylesheets)
177 }
178
179 pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
187 let dir = dir.as_ref();
188 let manifest_path = dir.join(MANIFEST_FILE);
189 let manifest = read(&manifest_path)?;
190 let manifest = std::str::from_utf8(&manifest)
191 .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
192 let rule_set = RuleSet::parse(manifest)?;
193 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
194 for entry in rule_set.stylesheets() {
195 let mut path = dir.to_path_buf();
196 path.extend(entry.path().split('/'));
197 let bytes = read(&path)?;
198 let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
199 stylesheets.push(prepare(entry, &bytes, base_uri)?);
200 }
201 Self::with(rule_set, stylesheets)
202 }
203
204 fn with(rule_set: RuleSet, stylesheets: Vec<Executable>) -> Result<Self, Error> {
205 let schema = match rule_set.schema() {
206 None => None,
207 Some(SchemaId::Ubl21) => Some(einvoice_xsd::Schema::ubl_2_1().map_err(|e| {
208 if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
209 Error::unsupported(format!("schema ubl-2.1: {e}"))
210 } else {
211 Error::internal(format!("the embedded schema ubl-2.1 does not load: {e}"))
212 }
213 })?),
214 };
215 Ok(Self {
216 rule_set,
217 schema,
218 stylesheets,
219 })
220 }
221
222 #[must_use]
224 pub const fn rule_set(&self) -> &RuleSet {
225 &self.rule_set
226 }
227
228 pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
234 self.validate_with(document, &ValidateOptions::new())
235 }
236
237 pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
244 self.validate_owned_with(document, &ValidateOptions::new())
245 }
246
247 pub fn validate_owned_with(
258 &self,
259 document: Vec<u8>,
260 options: &ValidateOptions<'_>,
261 ) -> Result<Report, Error> {
262 self.validate_text(Cow::Owned(decode_owned(document)?), options)
263 }
264
265 pub fn validate_with(
284 &self,
285 document: &[u8],
286 options: &ValidateOptions<'_>,
287 ) -> Result<Report, Error> {
288 self.validate_text(Cow::Borrowed(decode(document)?), options)
289 }
290
291 fn validate_text(
294 &self,
295 text: Cow<'_, str>,
296 options: &ValidateOptions<'_>,
297 ) -> Result<Report, Error> {
298 check_well_formed(&text, options.max_depth)?;
299 let schema_errors = match &self.schema {
300 None => Vec::new(),
301 Some(schema) => {
302 schema
303 .validate(&text)
304 .map_err(|e| match e {
305 einvoice_xsd::DocumentError::Malformed {
306 line,
307 column,
308 message,
309 } => Error::NotXml {
310 line,
311 column,
312 message,
313 },
314 einvoice_xsd::DocumentError::Unsupported {
315 line,
316 column,
317 message,
318 } => Error::unsupported(format!(
319 "document, line {line}, column {column}: {message}"
320 )),
321 })?
322 .errors
323 }
324 };
325 let transform_options = TransformOptions {
326 implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
327 current_date_time: options.clock.map(|c| c.current_date_time()),
328 max_depth: options.max_depth,
329 max_nesting: max_nesting_for_depth(options.max_depth),
330 max_stack: options.max_stack,
331 ..TransformOptions::default()
332 };
333 let mut stylesheets = Vec::with_capacity(self.stylesheets.len());
334 let count = self.stylesheets.len();
335 let mut text = Some(text);
337 for (index, (entry, executable)) in self
338 .rule_set
339 .stylesheets()
340 .iter()
341 .zip(&self.stylesheets)
342 .enumerate()
343 {
344 let source = if index + 1 == count {
345 text.take()
346 } else {
347 text.as_deref().map(Cow::Borrowed)
348 }
349 .ok_or_else(|| Error::internal("the document text was given away early"))?;
350 let result =
351 executable.transform_with(source, options.document_uri, &transform_options);
352 let report = match result {
353 Ok(result) => StylesheetReport::new(
354 entry,
355 result.output,
356 result.warnings,
357 options.document_uri,
358 )?,
359 Err(e) => match transform_error(entry, &e) {
360 Error::Transform {
363 code,
364 line,
365 message,
366 ..
367 } if !schema_errors.is_empty() => StylesheetReport::failed(
368 entry,
369 StylesheetFailure {
370 code,
371 line,
372 message,
373 },
374 options.document_uri,
375 ),
376 other => return Err(other),
377 },
378 };
379 stylesheets.push(report);
380 }
381 Ok(Report {
382 rule_set: RuleSetVersion {
383 name: self.rule_set.name().to_owned(),
384 title: self.rule_set.title().to_owned(),
385 version: self.rule_set.version().to_owned(),
386 schema: self.rule_set.schema(),
387 },
388 document_uri: options.document_uri.map(str::to_owned),
389 schema_errors,
390 stylesheets,
391 })
392 }
393}
394
395fn read(path: &Path) -> Result<Vec<u8>, Error> {
396 std::fs::read(path).map_err(|source| Error::Io {
397 path: PathBuf::from(path),
398 source,
399 })
400}
401
402pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
404 const HEX: &[u8; 16] = b"0123456789abcdef";
405 let digest = Sha256::digest(bytes);
406 let mut hex = String::with_capacity(64);
407 for byte in digest {
408 hex.push(char::from(HEX[usize::from(byte >> 4)]));
409 hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
410 }
411 hex
412}
413
414fn prepare(
416 entry: &StylesheetEntry,
417 bytes: &[u8],
418 base_uri: Option<String>,
419) -> Result<Executable, Error> {
420 let actual = sha256_hex(bytes);
421 if actual != entry.sha256() {
422 return Err(Error::Checksum {
423 path: entry.path().to_owned(),
424 expected: entry.sha256().to_owned(),
425 actual,
426 });
427 }
428 let what = format!("stylesheet {} ({})", entry.name(), entry.path());
429 let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
430 let sheet = einvoice_xslt::load(text).map_err(|errors| {
431 let unsupported = errors.0.iter().any(|e| {
432 matches!(
433 e.kind,
434 LoadErrorKind::UnsupportedElement { .. }
435 | LoadErrorKind::UnsupportedAttribute { .. }
436 | LoadErrorKind::UnsupportedValue { .. }
437 | LoadErrorKind::XPath { .. }
438 )
439 });
440 let message = format!("{what}: {}", first_lines(&errors.to_string()));
441 if unsupported {
442 Error::unsupported(message)
443 } else {
444 Error::bundle(message)
445 }
446 })?;
447 let executable = Executable::new(&sheet).map_err(|errors| {
448 Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
449 })?;
450 Ok(match base_uri {
451 Some(uri) => executable.with_base_uri(uri),
452 None => executable,
453 })
454}
455
456fn first_lines(text: &str) -> String {
458 const MAX: usize = 10;
459 let lines: Vec<&str> = text.lines().collect();
460 if lines.len() <= MAX {
461 return lines.join("; ");
462 }
463 format!(
464 "{}; and {} more",
465 lines[..MAX].join("; "),
466 lines.len() - MAX
467 )
468}
469
470fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
471 let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
472 if let Some(limit) = e.limit() {
473 return Error::Limit {
474 limit,
475 message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
476 };
477 }
478 match e.code() {
479 "UNSUPPORTED" => {
480 Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
481 }
482 "INTERNAL" | "SXXP0003" => Error::internal(format!(
485 "stylesheet {}{at}: {}: {}",
486 entry.name(),
487 e.code(),
488 e.message()
489 )),
490 code => Error::Transform {
491 stylesheet: entry.name().to_owned(),
492 code: code.to_owned(),
493 line: e.line(),
494 message: e.message().to_owned(),
495 },
496 }
497}
498
499const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
501
502fn decode(bytes: &[u8]) -> Result<&str, Error> {
505 refuse_utf16(bytes)?;
506 let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
507 check_encoding(bytes)?;
508 std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
509}
510
511fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
514 refuse_utf16(&bytes)?;
515 if bytes.starts_with(BOM) {
516 bytes.drain(..BOM.len());
517 }
518 check_encoding(&bytes)?;
519 String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
520}
521
522fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
524 bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
525}
526
527fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
529 let before = &bytes[..valid_up_to];
530 let line_start = before
531 .iter()
532 .rposition(|&b| b == b'\n')
533 .map_or(0, |i| i + 1);
534 let line = before.split(|&b| b == b'\n').count();
535 let column = String::from_utf8_lossy(&before[line_start..])
536 .chars()
537 .count()
538 + 1;
539 Error::NotXml {
540 line: u32::try_from(line).unwrap_or(u32::MAX),
541 column: u32::try_from(column).unwrap_or(u32::MAX),
542 message,
543 }
544}
545
546fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
548 if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
549 return Err(Error::unsupported(
550 "a UTF-16 document: only UTF-8 is supported",
551 ));
552 }
553 Ok(())
554}
555
556fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
560 let ascii = match declared_encoding(bytes) {
561 None => false,
562 Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
563 Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
564 Some(e) => {
565 return Err(Error::unsupported(format!(
566 "the {e} encoding: only UTF-8 is supported"
567 )));
568 }
569 };
570 if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
571 return Err(bad_at(
572 bytes,
573 i,
574 "a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
575 ));
576 }
577 Ok(())
578}
579
580fn declared_encoding(bytes: &[u8]) -> Option<&str> {
582 let declaration = bytes.strip_prefix(b"<?xml")?;
583 if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
584 return None;
585 }
586 let end = declaration.windows(2).position(|w| w == b"?>")?;
587 let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
588 let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
589 let rest = rest.trim_start().strip_prefix('=')?.trim_start();
590 let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
591 let value = &rest[1..];
592 value.find(quote).map(|end| &value[..end])
593}
594
595fn check_well_formed(text: &str, max_depth: u32) -> Result<(), Error> {
599 let options = ParsingOptions {
600 allow_dtd: false,
601 nodes_limit: u32::MAX,
602 ..ParsingOptions::default()
603 };
604 match roxmltree::Document::parse_with_options(text, options) {
605 Ok(document) => check_depth(&document, max_depth),
606 Err(roxmltree::Error::DtdDetected) => Err(Error::unsupported(
607 "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
608 )),
609 Err(e) => Err(Error::NotXml {
610 line: e.pos().row,
611 column: e.pos().col,
612 message: e.to_string(),
613 }),
614 }
615}
616
617fn check_depth(document: &roxmltree::Document<'_>, max_depth: u32) -> Result<(), Error> {
620 let mut open: Vec<roxmltree::NodeId> = Vec::new();
623 for node in document
624 .root()
625 .descendants()
626 .filter(roxmltree::Node::is_element)
627 {
628 let parent = node.parent().map(|p| p.id());
629 while open.last().is_some_and(|&id| Some(id) != parent) {
630 open.pop();
631 }
632 if u32::try_from(open.len()).map_or(true, |depth| depth >= max_depth) {
633 let at = document.text_pos_at(node.range().start);
634 let limit = LimitExceeded::Depth {
635 max: max_depth,
636 line: at.row,
637 column: at.col,
638 };
639 return Err(Error::Limit {
640 limit,
641 message: format!("document, {limit}"),
642 });
643 }
644 open.push(node.id());
645 }
646 Ok(())
647}
648
649#[cfg(test)]
650mod tests {
651 use super::*;
652
653 #[test]
654 fn decoding_a_buffer_gives_the_same_result() {
655 for bytes in [
656 &b"<a/>"[..],
657 b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
658 b"<?xml version='1.0' encoding='UTF-8'?><a/>",
659 b"\xFF\xFE<\0a\0/\0>\0",
660 b"\xFE\xFF\0<\0a\0/\0>",
661 b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
662 b"<a>\n \xC3\xA9\xFF</a>",
663 b"\xEF\xBB\xBF<a>\n\xFF</a>",
664 b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
665 b"\xEF\xBB\xBF",
666 b"",
667 ] {
668 let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
669 let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
670 assert_eq!(owned, borrowed, "{bytes:?}");
671 }
672 }
673
674 #[test]
675 fn decoding() {
676 assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
677 assert_eq!(
678 decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
679 "<?xml version='1.0' encoding='UTF-8'?><a/>"
680 );
681 assert!(matches!(
682 decode(b"\xFF\xFE<\0a\0/\0>\0"),
683 Err(Error::Unsupported { .. })
684 ));
685 assert!(matches!(
686 decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
687 Err(Error::Unsupported { .. })
688 ));
689 match decode(b"<a>\n \xC3\xA9\xFF</a>") {
690 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
691 other => panic!("{other:?}"),
692 }
693 match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
694 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
695 other => panic!("{other:?}"),
696 }
697 assert_eq!(
698 declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
699 None
700 );
701 }
702
703 #[test]
704 fn well_formedness() {
705 assert!(check_well_formed("<a/>", 1).is_ok());
706 match check_well_formed("<a>\n<b></a>", DEFAULT_MAX_DEPTH) {
707 Err(Error::NotXml { line, .. }) => assert_eq!(line, 2),
708 other => panic!("{other:?}"),
709 }
710 assert!(matches!(
711 check_well_formed(
712 "<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
713 DEFAULT_MAX_DEPTH
714 ),
715 Err(Error::Unsupported { .. })
716 ));
717 assert!(matches!(
718 check_well_formed("<p:a/>", DEFAULT_MAX_DEPTH),
719 Err(Error::NotXml { .. })
720 ));
721 }
722
723 #[test]
724 fn checksums() {
725 assert_eq!(
726 sha256_hex(b"abc"),
727 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
728 );
729 }
730
731 #[test]
732 fn errors_are_summarised() {
733 let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
734 let text = first_lines(&many.join("\n"));
735 assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
736 }
737}