1use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use einvoice_xpath_eval::{
8 Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DynamicContext, ErrorCode, Item,
9 LimitExceeded, NoHost, SimpleStaticContext,
10};
11use einvoice_xslt::LoadErrorKind;
12use einvoice_xslt_exec::{
13 DEFAULT_MAX_STACK, Executable, TransformError, TransformOptions, max_nesting_for_depth,
14};
15use sha2::{Digest, Sha256};
16
17use crate::manifest::{
18 CII, MANIFEST_FILE, RuleSet, Scenario, SchemaDocumentEntry, SchemaId, StylesheetEntry,
19 UBL_CREDIT_NOTE, UBL_INVOICE, namespace_map,
20};
21use crate::report::{
22 NoScenario, Report, RuleSetVersion, SchemaError, Severities, StylesheetFailure,
23 StylesheetReport, SvrlReader,
24};
25use crate::resources::{BUNDLE_URI, Resources};
26use crate::{Error, builtin};
27
28#[derive(Debug, Clone, Copy)]
30pub struct ValidateOptions<'a> {
31 document_uri: Option<&'a str>,
32 clock: Option<Clock>,
33 max_depth: u32,
34 max_stack: u32,
35 fail_closed: bool,
36}
37
38impl Default for ValidateOptions<'_> {
39 fn default() -> Self {
40 Self::new()
41 }
42}
43
44impl<'a> ValidateOptions<'a> {
45 #[must_use]
49 pub const fn new() -> Self {
50 Self {
51 document_uri: None,
52 clock: None,
53 max_depth: DEFAULT_MAX_DEPTH,
54 max_stack: DEFAULT_MAX_STACK,
55 fail_closed: false,
56 }
57 }
58
59 #[must_use]
66 pub const fn fail_closed(mut self, fail_closed: bool) -> Self {
67 self.fail_closed = fail_closed;
68 self
69 }
70
71 #[must_use]
88 pub const fn max_depth(mut self, max_depth: u32) -> Self {
89 self.max_depth = max_depth;
90 self
91 }
92
93 #[must_use]
105 pub const fn max_stack(mut self, bytes: u32) -> Self {
106 self.max_stack = bytes;
107 self
108 }
109
110 #[must_use]
116 pub const fn clock(mut self, clock: Clock) -> Self {
117 self.clock = Some(clock);
118 self
119 }
120
121 #[must_use]
125 pub const fn document_uri(mut self, uri: &'a str) -> Self {
126 self.document_uri = Some(uri);
127 self
128 }
129}
130
131pub const WASM_MAX_DEPTH: u32 = 400;
149
150pub const WASM_MAX_STACK: u32 = 256 << 10;
173
174#[cfg(target_family = "wasm")]
177const CAPS: Option<(u32, u32)> = Some((WASM_MAX_DEPTH, WASM_MAX_STACK));
178#[cfg(not(target_family = "wasm"))]
179const CAPS: Option<(u32, u32)> = None;
180
181#[cfg(target_family = "wasm")]
183const _: () = assert!(DEFAULT_MAX_STACK <= WASM_MAX_STACK && DEFAULT_MAX_DEPTH <= WASM_MAX_DEPTH);
184
185impl ValidateOptions<'_> {
186 const fn check(&self, caps: Option<(u32, u32)>) -> Result<(), Error> {
189 let Some((max_depth, max_stack)) = caps else {
190 return Ok(());
191 };
192 if self.max_depth > max_depth {
193 return Err(Error::OptionOutOfRange {
194 option: "max_depth",
195 value: self.max_depth,
196 max: max_depth,
197 });
198 }
199 if self.max_stack > max_stack {
200 return Err(Error::OptionOutOfRange {
201 option: "max_stack",
202 value: self.max_stack,
203 max: max_stack,
204 });
205 }
206 Ok(())
207 }
208}
209
210#[must_use]
213pub fn file_uri(path: &Path) -> Option<String> {
214 einvoice_xpath_eval::file_uri(path)
215}
216
217#[derive(Debug, Clone)]
223pub struct Validator {
224 rule_set: RuleSet,
225 schema: Option<Arc<einvoice_xsd::Schema>>,
226 stylesheets: Arc<[Executable]>,
228 resources: Arc<Resources>,
230 selections: Arc<[Selection]>,
233 all: Arc<[usize]>,
235}
236
237#[derive(Debug)]
240struct Selection {
241 matches: CompiledExpr,
242 stylesheets: Vec<usize>,
244}
245
246impl Validator {
247 pub fn builtin(name: &str) -> Result<Self, Error> {
254 let (manifest, files) = builtin::get(name)?;
255 Self::from_bundle(manifest, files)
256 }
257
258 #[cfg(feature = "cen-ubl")]
265 pub fn cen_ubl() -> Result<Self, Error> {
266 Self::builtin("cen-ubl")
267 }
268
269 #[cfg(feature = "cen-cii")]
277 pub fn cen_cii() -> Result<Self, Error> {
278 Self::builtin("cen-cii")
279 }
280
281 pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
291 let rule_set = RuleSet::parse(manifest)?;
292 let file = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, b)| *b);
293 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
294 for entry in rule_set.stylesheets() {
295 let Some(bytes) = file(entry.path()) else {
296 return Err(Error::bundle(format!(
297 "stylesheet {}: file {} missing from the bundle",
298 entry.name(),
299 entry.path()
300 )));
301 };
302 let base_uri = format!("{BUNDLE_URI}{}", entry.path());
304 stylesheets.push(prepare(entry, bytes, Some(base_uri))?);
305 }
306 let mut resources = Resources::default();
307 for entry in rule_set.resources() {
308 let Some(bytes) = file(entry.path()) else {
309 return Err(Error::bundle(format!(
310 "resource {}: file missing from the bundle",
311 entry.path()
312 )));
313 };
314 resources.add(entry, bytes, format!("{BUNDLE_URI}{}", entry.path()))?;
315 }
316 let mut schema_documents = Vec::with_capacity(rule_set.schema_documents().len());
317 for entry in rule_set.schema_documents() {
318 let Some(bytes) = file(entry.path()) else {
319 return Err(Error::bundle(format!(
320 "schema document {}: file missing from the bundle",
321 entry.path()
322 )));
323 };
324 schema_documents.push(schema_document(entry, bytes)?);
325 }
326 Self::with(rule_set, stylesheets, resources, &schema_documents)
327 }
328
329 pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
337 let dir = dir.as_ref();
338 let manifest_path = dir.join(MANIFEST_FILE);
339 let manifest = read(&manifest_path)?;
340 let manifest = std::str::from_utf8(&manifest)
341 .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
342 let rule_set = RuleSet::parse(manifest)?;
343 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
344 for entry in rule_set.stylesheets() {
345 let mut path = dir.to_path_buf();
346 path.extend(entry.path().split('/'));
347 let bytes = read(&path)?;
348 let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
349 stylesheets.push(prepare(entry, &bytes, base_uri)?);
350 }
351 let mut resources = Resources::default();
352 for entry in rule_set.resources() {
353 let mut path = dir.to_path_buf();
354 path.extend(entry.path().split('/'));
355 let bytes = read(&path)?;
356 let uri = std::path::absolute(&path)
357 .ok()
358 .and_then(|p| file_uri(&p))
359 .ok_or_else(|| {
360 Error::bundle(format!(
361 "resource {}: no file URI for {}",
362 entry.path(),
363 path.display()
364 ))
365 })?;
366 resources.add(entry, &bytes, uri)?;
367 }
368 let mut schema_documents = Vec::with_capacity(rule_set.schema_documents().len());
369 for entry in rule_set.schema_documents() {
370 let mut path = dir.to_path_buf();
371 path.extend(entry.path().split('/'));
372 schema_documents.push(schema_document(entry, &read(&path)?)?);
373 }
374 Self::with(rule_set, stylesheets, resources, &schema_documents)
375 }
376
377 fn with(
380 rule_set: RuleSet,
381 stylesheets: Vec<Executable>,
382 resources: Resources,
383 schema_documents: &[(String, String)],
384 ) -> Result<Self, Error> {
385 let schema = match rule_set.schema() {
386 None => None,
387 Some(id) => Some(load_schema(id, schema_documents)?),
388 };
389 let selections = if rule_set.selects_by_scenario() {
390 rule_set
391 .scenarios()
392 .iter()
393 .map(|scenario| selection(&rule_set, scenario))
394 .collect::<Result<Vec<_>, Error>>()?
395 } else {
396 Vec::new()
397 };
398 Ok(Self {
399 rule_set,
400 schema: schema.map(Arc::new),
401 all: (0..stylesheets.len()).collect(),
402 stylesheets: stylesheets.into(),
403 resources: Arc::new(resources),
404 selections: selections.into(),
405 })
406 }
407
408 #[must_use]
410 pub const fn rule_set(&self) -> &RuleSet {
411 &self.rule_set
412 }
413
414 pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
420 self.validate_with(document, &ValidateOptions::new())
421 }
422
423 pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
430 self.validate_owned_with(document, &ValidateOptions::new())
431 }
432
433 pub fn validate_owned_with(
444 &self,
445 document: Vec<u8>,
446 options: &ValidateOptions<'_>,
447 ) -> Result<Report, Error> {
448 options.check(CAPS)?;
449 self.validate_text(Cow::Owned(decode_owned(document)?), options)
450 }
451
452 pub fn validate_with(
484 &self,
485 document: &[u8],
486 options: &ValidateOptions<'_>,
487 ) -> Result<Report, Error> {
488 options.check(CAPS)?;
489 self.validate_text(decode(document)?, options)
490 }
491
492 fn validate_text(
495 &self,
496 text: Cow<'_, str>,
497 options: &ValidateOptions<'_>,
498 ) -> Result<Report, Error> {
499 let selects = self.rule_set.selects_by_scenario();
500 let identify = !selects && !self.rule_set.scenarios().is_empty();
501 let checked = check(&text, options.max_depth, self.schema.as_deref(), identify)?;
502 let schema_errors = checked.schema_errors;
503 let (scenario, run) = if selects {
504 match self.select(&text, options)? {
505 Ok(index) => (
506 self.rule_set.scenarios().get(index),
507 self.selections
508 .get(index)
509 .map(|s| s.stylesheets.as_slice())
510 .unwrap_or_default(),
511 ),
512 Err(no_scenario) => return Ok(self.without_scenario(no_scenario, options)),
515 }
516 } else {
517 (
518 checked.identification.scenario(self.rule_set.scenarios()),
519 self.all.as_ref(),
520 )
521 };
522 let transform_options = TransformOptions {
523 implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
524 current_date_time: options.clock.map(|c| c.current_date_time()),
525 max_depth: options.max_depth,
526 max_nesting: max_nesting_for_depth(options.max_depth),
527 max_stack: options.max_stack,
528 resolver: Some(&*self.resources),
529 ..TransformOptions::default()
530 };
531 let mut stylesheets = Vec::with_capacity(run.len());
532 let count = run.len();
533 let mut text = Some(text);
535 for (index, &stylesheet) in run.iter().enumerate() {
536 let (Some(entry), Some(executable)) = (
537 self.rule_set.stylesheets().get(stylesheet),
538 self.stylesheets.get(stylesheet),
539 ) else {
540 return Err(Error::internal(
541 "a scenario names no stylesheet of the rule set",
542 ));
543 };
544 let source = if index + 1 == count {
545 text.take()
546 } else {
547 text.as_deref().map(Cow::Borrowed)
548 }
549 .ok_or_else(|| Error::internal("the document text was given away early"))?;
550 let mut reader = SvrlReader::new(Severities {
552 fail_closed: options.fail_closed,
553 unflagged_assert: entry.unflagged_assert(),
554 scenario,
555 });
556 let result = executable.transform_compact(
557 source,
558 options.document_uri,
559 &transform_options,
560 &mut reader,
561 );
562 let report = match result {
563 Ok(result) => StylesheetReport::new(
564 entry,
565 result.output,
566 reader,
567 result.warnings,
568 options.document_uri,
569 )?,
570 Err(e) => match transform_error(entry, &e) {
571 Error::Transform {
574 code,
575 line,
576 message,
577 ..
578 } if !schema_errors.is_empty() => StylesheetReport::failed(
579 entry,
580 StylesheetFailure {
581 code,
582 line,
583 message,
584 },
585 options.document_uri,
586 ),
587 other => return Err(other),
588 },
589 };
590 stylesheets.push(report);
591 }
592 Ok(Report {
593 rule_set: self.version(),
594 document_uri: options.document_uri.map(str::to_owned),
595 scenario: scenario.map(|s| s.name().to_owned()),
596 no_scenario: None,
597 schema_errors,
598 stylesheets,
599 })
600 }
601
602 fn without_scenario(&self, no_scenario: NoScenario, options: &ValidateOptions<'_>) -> Report {
605 Report {
606 rule_set: self.version(),
607 document_uri: options.document_uri.map(str::to_owned),
608 scenario: None,
609 no_scenario: Some(no_scenario),
610 schema_errors: Vec::new(),
611 stylesheets: Vec::new(),
612 }
613 }
614
615 fn version(&self) -> RuleSetVersion {
617 RuleSetVersion {
618 name: self.rule_set.name().to_owned(),
619 title: self.rule_set.title().to_owned(),
620 version: self.rule_set.version().to_owned(),
621 schema: self.rule_set.schema().cloned(),
622 unchecked_schema: self.rule_set.unchecked_schema().map(str::to_owned),
623 }
624 }
625
626 fn select(
634 &self,
635 text: &str,
636 options: &ValidateOptions<'_>,
637 ) -> Result<Result<usize, NoScenario>, Error> {
638 let document =
639 Document::parse_with_max_depth(text, None, options.max_depth).map_err(|e| {
640 Error::internal(format!("the document for the scenarios: {}", e.message()))
642 })?;
643 let clock = match options.clock {
644 Some(clock) => clock,
645 None => system_clock()?,
646 };
647 let dc = DynamicContext::new(&NoHost, clock);
648 let context = Context::for_item(Item::Node(document.root()));
649 let mut matched = Vec::new();
650 for (index, (scenario, selection)) in self
651 .rule_set
652 .scenarios()
653 .iter()
654 .zip(self.selections.iter())
655 .enumerate()
656 {
657 match selection.matches.effective_boolean_value(&dc, &context) {
658 Ok(true) => matched.push(index),
659 Ok(false) => {}
660 Err(e) => {
661 let what = format!("scenario {:?}: match: {}", scenario.name(), e.message());
662 if let Some(limit) = e.limit() {
663 return Err(Error::Limit {
664 limit,
665 message: what,
666 });
667 }
668 match e.code() {
669 ErrorCode::Unsupported => return Err(Error::unsupported(what)),
670 ErrorCode::Internal => return Err(Error::internal(what)),
671 _ => {}
674 }
675 }
676 }
677 }
678 Ok(match matched[..] {
679 [index] => Ok(index),
680 [] => Err(NoScenario::NoneMatches),
681 _ => Err(NoScenario::SeveralMatch(
682 matched
683 .iter()
684 .filter_map(|&i| self.rule_set.scenarios().get(i))
685 .map(|s| s.name().to_owned())
686 .collect(),
687 )),
688 })
689 }
690}
691
692#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
695fn system_clock() -> Result<Clock, Error> {
696 Clock::system(0).map_err(|e| Error::internal(format!("the system clock: {}", e.message())))
697}
698
699#[cfg(all(target_family = "wasm", target_os = "unknown"))]
701fn system_clock() -> Result<Clock, Error> {
702 Err(Error::unsupported(
703 "no system clock on this target: give ValidateOptions::clock",
704 ))
705}
706
707fn selection(rule_set: &RuleSet, scenario: &Scenario) -> Result<Selection, Error> {
711 let what = format!("scenario {:?}: match", scenario.name());
712 let Some(text) = scenario.match_expression() else {
713 return Err(Error::internal(format!("{what}: none")));
714 };
715 let expr = einvoice_xpath::parse_expr(text, &namespace_map(scenario.namespaces()))
716 .map_err(|e| Error::bundle(format!("{what}: {e}")))?;
717 let matches = einvoice_xpath_eval::compile(&expr, &SimpleStaticContext::new())
720 .map_err(|e| Error::unsupported(format!("{what}: {}", e.message())))?;
721 let stylesheets = match scenario.stylesheets() {
722 None => (0..rule_set.stylesheets().len()).collect(),
723 Some(names) => names
724 .iter()
725 .map(|name| {
726 rule_set
727 .stylesheets()
728 .iter()
729 .position(|s| s.name() == name)
730 .ok_or_else(|| Error::internal(format!("{what}: no stylesheet {name}")))
731 })
732 .collect::<Result<_, Error>>()?,
733 };
734 Ok(Selection {
735 matches,
736 stylesheets,
737 })
738}
739
740fn read(path: &Path) -> Result<Vec<u8>, Error> {
741 std::fs::read(path).map_err(|source| Error::Io {
742 path: PathBuf::from(path),
743 source,
744 })
745}
746
747fn schema_document(entry: &SchemaDocumentEntry, bytes: &[u8]) -> Result<(String, String), Error> {
750 let actual = sha256_hex(bytes);
751 if actual != entry.sha256() {
752 return Err(Error::Checksum {
753 path: entry.path().to_owned(),
754 expected: entry.sha256().to_owned(),
755 actual,
756 });
757 }
758 let text = decode(bytes)
759 .map_err(|e| Error::bundle(format!("schema document {}: {e}", entry.path())))?;
760 Ok((entry.path().to_owned(), text.into_owned()))
761}
762
763fn load_schema(
766 id: &SchemaId,
767 documents: &[(String, String)],
768) -> Result<einvoice_xsd::Schema, Error> {
769 let loaded = match id {
770 SchemaId::Ubl21 => einvoice_xsd::Schema::ubl_2_1(),
771 SchemaId::CiiD16b => einvoice_xsd::Schema::cii_d16b(),
772 SchemaId::Bundle(entry_point) => {
773 let files: Vec<(&str, &str)> = documents
774 .iter()
775 .map(|(path, text)| (path.as_str(), text.as_str()))
776 .collect();
777 einvoice_xsd::Schema::load(&files, &[entry_point.as_str()])
778 }
779 };
780 loaded.map_err(|e| {
781 if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
782 Error::unsupported(format!("schema {id}: {e}"))
783 } else if matches!(id, SchemaId::Bundle(_)) {
784 Error::bundle(format!("schema {id}: {e}"))
785 } else {
786 Error::internal(format!("the embedded schema {id} does not load: {e}"))
787 }
788 })
789}
790
791pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
793 const HEX: &[u8; 16] = b"0123456789abcdef";
794 let digest = Sha256::digest(bytes);
795 let mut hex = String::with_capacity(64);
796 for byte in digest {
797 hex.push(char::from(HEX[usize::from(byte >> 4)]));
798 hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
799 }
800 hex
801}
802
803fn prepare(
805 entry: &StylesheetEntry,
806 bytes: &[u8],
807 base_uri: Option<String>,
808) -> Result<Executable, Error> {
809 let actual = sha256_hex(bytes);
810 if actual != entry.sha256() {
811 return Err(Error::Checksum {
812 path: entry.path().to_owned(),
813 expected: entry.sha256().to_owned(),
814 actual,
815 });
816 }
817 let what = format!("stylesheet {} ({})", entry.name(), entry.path());
818 let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
819 let sheet = einvoice_xslt::load(&text).map_err(|errors| {
820 let unsupported = errors.0.iter().any(|e| {
821 matches!(
822 e.kind,
823 LoadErrorKind::UnsupportedElement { .. }
824 | LoadErrorKind::UnsupportedAttribute { .. }
825 | LoadErrorKind::UnsupportedValue { .. }
826 | LoadErrorKind::XPath { .. }
827 | LoadErrorKind::TooDeep { .. }
828 )
829 });
830 let message = format!("{what}: {}", first_lines(&errors.to_string()));
831 if unsupported {
832 Error::unsupported(message)
833 } else {
834 Error::bundle(message)
835 }
836 })?;
837 let executable = Executable::new(&sheet).map_err(|errors| {
838 Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
839 })?;
840 Ok(match base_uri {
841 Some(uri) => executable.with_base_uri(uri),
842 None => executable,
843 })
844}
845
846fn first_lines(text: &str) -> String {
848 const MAX: usize = 10;
849 let lines: Vec<&str> = text.lines().collect();
850 if lines.len() <= MAX {
851 return lines.join("; ");
852 }
853 format!(
854 "{}; and {} more",
855 lines[..MAX].join("; "),
856 lines.len() - MAX
857 )
858}
859
860fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
861 let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
862 if let Some(limit) = e.limit() {
863 return Error::Limit {
864 limit,
865 message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
866 };
867 }
868 match e.code() {
869 "UNSUPPORTED" => {
870 Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
871 }
872 "INTERNAL" | "SXXP0003" => Error::internal(format!(
875 "stylesheet {}{at}: {}: {}",
876 entry.name(),
877 e.code(),
878 e.message()
879 )),
880 code => Error::Transform {
881 stylesheet: entry.name().to_owned(),
882 code: code.to_owned(),
883 line: e.line(),
884 message: e.message().to_owned(),
885 },
886 }
887}
888
889pub(crate) fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, Error> {
893 einvoice_xml::decode(bytes).map_err(decoding_error)
894}
895
896fn decode_owned(bytes: Vec<u8>) -> Result<String, Error> {
899 einvoice_xml::decode_owned(bytes).map_err(decoding_error)
900}
901
902fn decoding_error(e: einvoice_xml::Error) -> Error {
907 match e {
908 einvoice_xml::Error::UnsupportedEncoding(name) => Error::unsupported(format!(
909 "the {name} encoding: the encodings read are UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 and windows-1252"
910 )),
911 e => Error::NotXml {
912 line: e.pos().row,
913 column: e.pos().col,
914 message: e.to_string(),
915 },
916 }
917}
918
919const UBL_CBC: &str = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
921const CII_RAM: &str =
923 "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
924
925fn identifier_path(namespace: &str, local: &str) -> &'static [(&'static str, &'static str)] {
928 match (namespace, local) {
929 (UBL_INVOICE, "Invoice") | (UBL_CREDIT_NOTE, "CreditNote") => {
930 &[(UBL_CBC, "CustomizationID")]
931 }
932 (CII, "CrossIndustryInvoice") => &[
933 (CII, "ExchangedDocumentContext"),
934 (CII_RAM, "GuidelineSpecifiedDocumentContextParameter"),
935 (CII_RAM, "ID"),
936 ],
937 _ => &[],
938 }
939}
940
941#[derive(Debug, Default)]
944struct Identification {
945 root: Option<(String, String)>,
947 path: &'static [(&'static str, &'static str)],
949 matched: usize,
951 text: Option<String>,
953 identifiers: Vec<String>,
955}
956
957impl Identification {
958 fn start(&mut self, name: &einvoice_xml::Name<'_, '_>, depth: u32) {
960 let Ok(depth) = usize::try_from(depth) else {
961 return;
962 };
963 let namespace = name.namespace.unwrap_or("");
964 if depth == 1 {
965 self.path = identifier_path(namespace, name.local);
966 self.root = Some((namespace.to_owned(), name.local.to_owned()));
967 return;
968 }
969 if self.matched + 2 == depth
971 && self
972 .path
973 .get(self.matched)
974 .is_some_and(|&(ns, local)| ns == namespace && local == name.local)
975 {
976 self.matched += 1;
977 if self.matched == self.path.len() {
978 self.text = Some(String::new());
979 }
980 }
981 }
982
983 fn end(&mut self, depth: u32) {
985 let Ok(depth) = usize::try_from(depth) else {
986 return;
987 };
988 if depth >= 2 && self.matched + 1 == depth {
989 if self.matched == self.path.len()
990 && let Some(text) = self.text.take()
991 {
992 self.identifiers.push(text);
993 }
994 self.matched -= 1;
995 }
996 }
997
998 fn text(&mut self, text: &str) {
1000 if let Some(value) = &mut self.text {
1001 value.push_str(text);
1002 }
1003 }
1004
1005 fn scenario<'s>(&self, scenarios: &'s [Scenario]) -> Option<&'s Scenario> {
1007 let (namespace, local) = self.root.as_ref()?;
1008 scenarios.iter().find(|s| {
1009 s.namespace() == Some(namespace.as_str())
1010 && s.root() == Some(local.as_str())
1011 && self
1012 .identifiers
1013 .iter()
1014 .any(|i| Some(i.as_str()) == s.identifier())
1015 })
1016 }
1017}
1018
1019#[derive(Debug)]
1021struct Checked {
1022 schema_errors: Vec<SchemaError>,
1024 identification: Identification,
1026}
1027
1028fn check(
1039 text: &str,
1040 max_depth: u32,
1041 schema: Option<&einvoice_xsd::Schema>,
1042 identify: bool,
1043) -> Result<Checked, Error> {
1044 let mut reader = einvoice_xml::Reader::new(text);
1045 let mut validation = schema.map(|schema| schema.validation(text));
1046 let mut identification = Identification::default();
1047 let mut depth = 0u32;
1048 let mut too_deep = None;
1049 loop {
1050 let event = match reader.next_event() {
1051 Ok(Some(event)) => event,
1052 Ok(None) => break,
1053 Err(einvoice_xml::Error::DtdDetected) => {
1054 return Err(Error::unsupported(
1055 "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
1056 ));
1057 }
1058 Err(e) => {
1059 return Err(Error::NotXml {
1060 line: e.pos().row,
1061 column: e.pos().col,
1062 message: e.to_string(),
1063 });
1064 }
1065 };
1066 match &event {
1067 einvoice_xml::Event::Start(start) => {
1068 depth = depth.saturating_add(1);
1069 if identify {
1070 identification.start(&start.name(), depth);
1071 }
1072 if depth > max_depth && too_deep.is_none() {
1073 let at = einvoice_xml::TextPos::at(text, start.range().start);
1074 too_deep = Some(LimitExceeded::Depth {
1075 max: max_depth,
1076 line: at.row,
1077 column: at.col,
1078 });
1079 validation = None;
1081 }
1082 }
1083 einvoice_xml::Event::End(_) => {
1084 if identify {
1085 identification.end(depth);
1086 }
1087 depth = depth.saturating_sub(1);
1088 }
1089 einvoice_xml::Event::Text(t) if identify => identification.text(&t.value),
1090 _ => {}
1091 }
1092 if let Some(validation) = &mut validation {
1093 validation.event(event);
1094 }
1095 }
1096 if let Some(limit) = too_deep {
1097 return Err(Error::Limit {
1098 limit,
1099 message: format!("document, {limit}"),
1100 });
1101 }
1102 let schema_errors = match validation {
1103 None => Vec::new(),
1104 Some(validation) => schema_errors(validation)?,
1105 };
1106 Ok(Checked {
1107 schema_errors,
1108 identification,
1109 })
1110}
1111
1112fn schema_errors(validation: einvoice_xsd::Validation<'_, '_>) -> Result<Vec<SchemaError>, Error> {
1114 match validation.finish() {
1115 Ok(report) => Ok(report.errors),
1116 Err(einvoice_xsd::DocumentError::Malformed {
1117 line,
1118 column,
1119 message,
1120 }) => Err(Error::NotXml {
1121 line,
1122 column,
1123 message,
1124 }),
1125 Err(einvoice_xsd::DocumentError::Unsupported {
1126 line,
1127 column,
1128 message,
1129 }) => Err(Error::unsupported(format!(
1130 "document, line {line}, column {column}: {message}"
1131 ))),
1132 }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use super::*;
1138
1139 fn check(
1141 text: &str,
1142 max_depth: u32,
1143 schema: Option<&einvoice_xsd::Schema>,
1144 ) -> Result<Vec<SchemaError>, Error> {
1145 super::check(text, max_depth, schema, false).map(|c| c.schema_errors)
1146 }
1147
1148 fn identify(text: &str) -> (Option<(String, String)>, Vec<String>) {
1150 let checked = super::check(text, DEFAULT_MAX_DEPTH, None, true).unwrap();
1151 (
1152 checked.identification.root,
1153 checked.identification.identifiers,
1154 )
1155 }
1156
1157 #[test]
1158 fn specification_identifiers() {
1159 let root = |ns: &str, local: &str| Some((ns.to_owned(), local.to_owned()));
1160 let ubl = format!(
1161 "<Invoice xmlns='{UBL_INVOICE}' xmlns:cbc='{UBL_CBC}'><cbc:CustomizationID> urn:a</cbc:CustomizationID>\
1162 <x><cbc:CustomizationID>no</cbc:CustomizationID></x>\
1163 <cbc:CustomizationID>u<!-- c -->rn:<![CDATA[b]]><i>c</i></cbc:CustomizationID><CustomizationID>no</CustomizationID></Invoice>"
1164 );
1165 assert_eq!(
1166 identify(&ubl),
1167 (
1168 root(UBL_INVOICE, "Invoice"),
1169 vec![" urn:a".to_owned(), "urn:bc".to_owned()]
1170 )
1171 );
1172 let credit_note = format!(
1173 "<c:CreditNote xmlns:c='{UBL_CREDIT_NOTE}'><b:CustomizationID xmlns:b='{UBL_CBC}'>urn:x</b:CustomizationID></c:CreditNote>"
1174 );
1175 assert_eq!(
1176 identify(&credit_note),
1177 (
1178 root(UBL_CREDIT_NOTE, "CreditNote"),
1179 vec!["urn:x".to_owned()]
1180 )
1181 );
1182 let cii = format!(
1183 "<rsm:CrossIndustryInvoice xmlns:rsm='{CII}' xmlns:ram='{CII_RAM}'>\
1184 <rsm:ExchangedDocumentContext><ram:ID>no</ram:ID>\
1185 <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:y</ram:ID><ram:Other>no</ram:Other></ram:GuidelineSpecifiedDocumentContextParameter>\
1186 <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:z</ram:ID></ram:GuidelineSpecifiedDocumentContextParameter>\
1187 </rsm:ExchangedDocumentContext><ram:ID>no</ram:ID></rsm:CrossIndustryInvoice>"
1188 );
1189 assert_eq!(
1190 identify(&cii),
1191 (
1192 root(CII, "CrossIndustryInvoice"),
1193 vec!["urn:y".to_owned(), "urn:z".to_owned()]
1194 )
1195 );
1196 assert_eq!(
1198 identify(&format!(
1199 "<Order xmlns='{UBL_INVOICE}'><CustomizationID xmlns='{UBL_CBC}'>x</CustomizationID></Order>"
1200 )),
1201 (root(UBL_INVOICE, "Order"), vec![])
1202 );
1203 assert_eq!(identify("<a/>"), (root("", "a"), vec![]));
1204 }
1205
1206 #[test]
1208 fn options_within_the_caps_of_webassembly() {
1209 let caps = Some((WASM_MAX_DEPTH, WASM_MAX_STACK));
1210 let within = ValidateOptions::new()
1211 .max_depth(WASM_MAX_DEPTH)
1212 .max_stack(WASM_MAX_STACK);
1213 assert!(within.check(caps).is_ok());
1214 assert!(
1215 ValidateOptions::new()
1216 .max_stack(WASM_MAX_STACK)
1217 .check(caps)
1218 .is_ok()
1219 );
1220 let error = within
1221 .max_depth(WASM_MAX_DEPTH + 1)
1222 .check(caps)
1223 .unwrap_err();
1224 assert!(matches!(
1225 error,
1226 Error::OptionOutOfRange {
1227 option: "max_depth",
1228 value: 401,
1229 max: 400
1230 }
1231 ));
1232 assert_eq!(error.kind(), crate::ErrorKind::Unsupported);
1233 assert_eq!(
1234 error.to_string(),
1235 "option max_depth is 401, more than 400, the most this target allows"
1236 );
1237 let error = within
1238 .max_stack(WASM_MAX_STACK + 1)
1239 .check(caps)
1240 .unwrap_err();
1241 assert!(matches!(
1242 error,
1243 Error::OptionOutOfRange {
1244 option: "max_stack",
1245 value: 262_145,
1246 max: 262_144
1247 }
1248 ));
1249 let anything = ValidateOptions::new()
1251 .max_depth(u32::MAX)
1252 .max_stack(u32::MAX);
1253 assert!(anything.check(None).is_ok());
1254 assert_eq!(CAPS, None);
1255 }
1256
1257 #[test]
1258 fn decoding_a_buffer_gives_the_same_result() {
1259 for bytes in [
1260 &b"<a/>"[..],
1261 b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
1262 b"<?xml version='1.0' encoding='UTF-8'?><a/>",
1263 b"\xFF\xFE<\0a\0/\0>\0",
1264 b"\xFE\xFF\0<\0a\0/\0>",
1265 b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
1266 b"<a>\n \xC3\xA9\xFF</a>",
1267 b"\xEF\xBB\xBF<a>\n\xFF</a>",
1268 b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
1269 b"<?xml version='1.0' encoding='Shift_JIS'?><a/>",
1270 b"\xEF\xBB\xBF\xEF\xBB\xBF<a/>",
1271 b"\xEF\xBB\xBF",
1272 b"",
1273 ] {
1274 let borrowed = decode(bytes)
1275 .map(Cow::into_owned)
1276 .map_err(|e| e.to_string());
1277 let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
1278 assert_eq!(owned, borrowed, "{bytes:?}");
1279 }
1280 }
1281
1282 #[test]
1283 fn decoding() {
1284 assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
1285 assert_eq!(
1286 decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
1287 "<?xml version='1.0' encoding='UTF-8'?><a/>"
1288 );
1289 assert!(matches!(decode(b"<a/>").unwrap(), Cow::Borrowed("<a/>")));
1290 assert_eq!(decode(b"\xFF\xFE<\0a\0/\0>\0").unwrap(), "<a/>");
1291 assert_eq!(
1292 decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a>\xE9</a>").unwrap(),
1293 "<?xml version='1.0' encoding='ISO-8859-1'?><a>\u{e9}</a>"
1294 );
1295 match decode(b"<?xml version='1.0' encoding='Shift_JIS'?><a/>") {
1296 Err(Error::Unsupported { message }) => assert_eq!(
1297 message,
1298 "the Shift_JIS encoding: the encodings read are UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 and windows-1252"
1299 ),
1300 other => panic!("{other:?}"),
1301 }
1302 match decode(b"<?xml version='1.0' encoding='UTF-16'?><a/>") {
1303 Err(Error::NotXml {
1304 line: 1,
1305 column: 1,
1306 message,
1307 }) => assert_eq!(
1308 message,
1309 "UTF-8 (no byte order mark), but the XML declaration names the encoding 'UTF-16'"
1310 ),
1311 other => panic!("{other:?}"),
1312 }
1313 match decode(b"<a>\n \xC3\xA9\xFF</a>") {
1314 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
1315 other => panic!("{other:?}"),
1316 }
1317 match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
1318 Err(Error::NotXml {
1319 line,
1320 column,
1321 message,
1322 }) => {
1323 assert_eq!((line, column), (2, 4));
1324 assert_eq!(message, "bytes that are not US-ASCII at 2:4");
1325 }
1326 other => panic!("{other:?}"),
1327 }
1328 assert!(decode(b"<?xml-stylesheet encoding='x'?><a/>").is_ok());
1330 }
1331
1332 #[test]
1333 fn well_formedness() {
1334 assert!(check("<a/>", 1, None).is_ok());
1335 match check("<a>\n<b></a>", DEFAULT_MAX_DEPTH, None) {
1336 Err(Error::NotXml {
1337 line,
1338 column,
1339 message,
1340 }) => assert_eq!(
1341 (line, column, message.as_str()),
1342 (2, 4, "expected 'b' tag, not 'a' at 2:4")
1343 ),
1344 other => panic!("{other:?}"),
1345 }
1346 assert!(matches!(
1347 check(
1348 "<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
1349 DEFAULT_MAX_DEPTH,
1350 None
1351 ),
1352 Err(Error::Unsupported { .. })
1353 ));
1354 assert!(matches!(
1355 check("<p:a/>", DEFAULT_MAX_DEPTH, None),
1356 Err(Error::NotXml { .. })
1357 ));
1358 }
1359
1360 #[test]
1361 fn one_pass_order_of_errors() {
1362 let schema = einvoice_xsd::Schema::ubl_2_1().unwrap();
1363 let invoice = "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' \
1364 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1365 let depth = |text: &str, max| match check(text, max, Some(&schema)) {
1366 Err(Error::Limit {
1367 limit: LimitExceeded::Depth { line, column, .. },
1368 ..
1369 }) => Some((line, column)),
1370 _ => None,
1371 };
1372 let errors = check(&format!("{invoice}</Invoice>"), 3, Some(&schema)).unwrap();
1374 assert_eq!(errors.len(), 1);
1375 assert_eq!(errors[0].kind.as_str(), "missing-element");
1376 let deep = format!("{invoice}\n<a><b><c/></b></a><d><e><f/></e></d></Invoice>");
1378 assert_eq!(depth(&deep, 2), Some((2, 4)));
1379 assert_eq!(depth(&deep, 3), Some((2, 7)));
1380 assert_eq!(depth(&deep, 4), None);
1381 let malformed = format!("{deep}<");
1383 assert!(matches!(
1384 check(&malformed, 2, Some(&schema)),
1385 Err(Error::NotXml { .. })
1386 ));
1387 assert!(matches!(
1388 check(&malformed, 2, None),
1389 Err(Error::NotXml { .. })
1390 ));
1391 let retyped = invoice.replace(
1394 "<Invoice ",
1395 "<Invoice xsi:type='xs:IDREF' xmlns:xs='http://www.w3.org/2001/XMLSchema' ",
1396 );
1397 let errors = check(&format!("{retyped}</Invoice>"), 3, Some(&schema)).unwrap();
1398 assert!(
1399 errors
1400 .iter()
1401 .any(|e| e.kind == einvoice_xsd::ErrorKind::InvalidXsiType),
1402 "{errors:?}"
1403 );
1404 assert!(matches!(
1405 check(&format!("{retyped}<b><c/></b></Invoice>"), 2, Some(&schema)),
1406 Err(Error::Limit { .. })
1407 ));
1408 assert!(matches!(
1409 check(&format!("{retyped}</Invoice><"), 3, Some(&schema)),
1410 Err(Error::NotXml { .. })
1411 ));
1412 assert!(matches!(
1414 check("<!DOCTYPE Invoice><Invoice/>", 3, Some(&schema)),
1415 Err(Error::Unsupported { .. })
1416 ));
1417 }
1418
1419 #[test]
1420 fn checksums() {
1421 assert_eq!(
1422 sha256_hex(b"abc"),
1423 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1424 );
1425 }
1426
1427 #[test]
1428 fn errors_are_summarised() {
1429 let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
1430 let text = first_lines(&many.join("\n"));
1431 assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
1432 }
1433}