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, SchemaId, StylesheetEntry, UBL_CREDIT_NOTE, UBL_INVOICE,
19 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]
85 pub const fn max_depth(mut self, max_depth: u32) -> Self {
86 self.max_depth = max_depth;
87 self
88 }
89
90 #[must_use]
98 pub const fn max_stack(mut self, bytes: u32) -> Self {
99 self.max_stack = bytes;
100 self
101 }
102
103 #[must_use]
109 pub const fn clock(mut self, clock: Clock) -> Self {
110 self.clock = Some(clock);
111 self
112 }
113
114 #[must_use]
118 pub const fn document_uri(mut self, uri: &'a str) -> Self {
119 self.document_uri = Some(uri);
120 self
121 }
122}
123
124#[must_use]
127pub fn file_uri(path: &Path) -> Option<String> {
128 einvoice_xpath_eval::file_uri(path)
129}
130
131#[derive(Debug, Clone)]
137pub struct Validator {
138 rule_set: RuleSet,
139 schema: Option<Arc<einvoice_xsd::Schema>>,
140 stylesheets: Arc<[Executable]>,
142 resources: Arc<Resources>,
144 selections: Arc<[Selection]>,
147 all: Arc<[usize]>,
149}
150
151#[derive(Debug)]
154struct Selection {
155 matches: CompiledExpr,
156 stylesheets: Vec<usize>,
158}
159
160impl Validator {
161 pub fn builtin(name: &str) -> Result<Self, Error> {
168 let (manifest, files) = builtin::get(name)?;
169 Self::from_bundle(manifest, files)
170 }
171
172 #[cfg(feature = "cen-ubl")]
179 pub fn cen_ubl() -> Result<Self, Error> {
180 Self::builtin("cen-ubl")
181 }
182
183 #[cfg(feature = "cen-cii")]
191 pub fn cen_cii() -> Result<Self, Error> {
192 Self::builtin("cen-cii")
193 }
194
195 pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
205 let rule_set = RuleSet::parse(manifest)?;
206 let file = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, b)| *b);
207 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
208 for entry in rule_set.stylesheets() {
209 let Some(bytes) = file(entry.path()) else {
210 return Err(Error::bundle(format!(
211 "stylesheet {}: file {} missing from the bundle",
212 entry.name(),
213 entry.path()
214 )));
215 };
216 let base_uri = format!("{BUNDLE_URI}{}", entry.path());
218 stylesheets.push(prepare(entry, bytes, Some(base_uri))?);
219 }
220 let mut resources = Resources::default();
221 for entry in rule_set.resources() {
222 let Some(bytes) = file(entry.path()) else {
223 return Err(Error::bundle(format!(
224 "resource {}: file missing from the bundle",
225 entry.path()
226 )));
227 };
228 resources.add(entry, bytes, format!("{BUNDLE_URI}{}", entry.path()))?;
229 }
230 Self::with(rule_set, stylesheets, resources)
231 }
232
233 pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
241 let dir = dir.as_ref();
242 let manifest_path = dir.join(MANIFEST_FILE);
243 let manifest = read(&manifest_path)?;
244 let manifest = std::str::from_utf8(&manifest)
245 .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
246 let rule_set = RuleSet::parse(manifest)?;
247 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
248 for entry in rule_set.stylesheets() {
249 let mut path = dir.to_path_buf();
250 path.extend(entry.path().split('/'));
251 let bytes = read(&path)?;
252 let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
253 stylesheets.push(prepare(entry, &bytes, base_uri)?);
254 }
255 let mut resources = Resources::default();
256 for entry in rule_set.resources() {
257 let mut path = dir.to_path_buf();
258 path.extend(entry.path().split('/'));
259 let bytes = read(&path)?;
260 let uri = std::path::absolute(&path)
261 .ok()
262 .and_then(|p| file_uri(&p))
263 .ok_or_else(|| {
264 Error::bundle(format!(
265 "resource {}: no file URI for {}",
266 entry.path(),
267 path.display()
268 ))
269 })?;
270 resources.add(entry, &bytes, uri)?;
271 }
272 Self::with(rule_set, stylesheets, resources)
273 }
274
275 fn with(
276 rule_set: RuleSet,
277 stylesheets: Vec<Executable>,
278 resources: Resources,
279 ) -> Result<Self, Error> {
280 let schema = match rule_set.schema() {
281 None => None,
282 Some(id) => {
283 let loaded = match id {
284 SchemaId::Ubl21 => einvoice_xsd::Schema::ubl_2_1(),
285 SchemaId::CiiD16b => einvoice_xsd::Schema::cii_d16b(),
286 };
287 Some(loaded.map_err(|e| {
288 if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
289 Error::unsupported(format!("schema {id}: {e}"))
290 } else {
291 Error::internal(format!("the embedded schema {id} does not load: {e}"))
292 }
293 })?)
294 }
295 };
296 let selections = if rule_set.selects_by_scenario() {
297 rule_set
298 .scenarios()
299 .iter()
300 .map(|scenario| selection(&rule_set, scenario))
301 .collect::<Result<Vec<_>, Error>>()?
302 } else {
303 Vec::new()
304 };
305 Ok(Self {
306 rule_set,
307 schema: schema.map(Arc::new),
308 all: (0..stylesheets.len()).collect(),
309 stylesheets: stylesheets.into(),
310 resources: Arc::new(resources),
311 selections: selections.into(),
312 })
313 }
314
315 #[must_use]
317 pub const fn rule_set(&self) -> &RuleSet {
318 &self.rule_set
319 }
320
321 pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
327 self.validate_with(document, &ValidateOptions::new())
328 }
329
330 pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
337 self.validate_owned_with(document, &ValidateOptions::new())
338 }
339
340 pub fn validate_owned_with(
351 &self,
352 document: Vec<u8>,
353 options: &ValidateOptions<'_>,
354 ) -> Result<Report, Error> {
355 self.validate_text(Cow::Owned(decode_owned(document)?), options)
356 }
357
358 pub fn validate_with(
387 &self,
388 document: &[u8],
389 options: &ValidateOptions<'_>,
390 ) -> Result<Report, Error> {
391 self.validate_text(Cow::Borrowed(decode(document)?), options)
392 }
393
394 fn validate_text(
397 &self,
398 text: Cow<'_, str>,
399 options: &ValidateOptions<'_>,
400 ) -> Result<Report, Error> {
401 let selects = self.rule_set.selects_by_scenario();
402 let identify = !selects && !self.rule_set.scenarios().is_empty();
403 let checked = check(&text, options.max_depth, self.schema.as_deref(), identify)?;
404 let schema_errors = checked.schema_errors;
405 let (scenario, run) = if selects {
406 match self.select(&text, options)? {
407 Ok(index) => (
408 self.rule_set.scenarios().get(index),
409 self.selections
410 .get(index)
411 .map(|s| s.stylesheets.as_slice())
412 .unwrap_or_default(),
413 ),
414 Err(no_scenario) => return Ok(self.without_scenario(no_scenario, options)),
417 }
418 } else {
419 (
420 checked.identification.scenario(self.rule_set.scenarios()),
421 self.all.as_ref(),
422 )
423 };
424 let transform_options = TransformOptions {
425 implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
426 current_date_time: options.clock.map(|c| c.current_date_time()),
427 max_depth: options.max_depth,
428 max_nesting: max_nesting_for_depth(options.max_depth),
429 max_stack: options.max_stack,
430 resolver: Some(&*self.resources),
431 ..TransformOptions::default()
432 };
433 let mut stylesheets = Vec::with_capacity(run.len());
434 let count = run.len();
435 let mut text = Some(text);
437 for (index, &stylesheet) in run.iter().enumerate() {
438 let (Some(entry), Some(executable)) = (
439 self.rule_set.stylesheets().get(stylesheet),
440 self.stylesheets.get(stylesheet),
441 ) else {
442 return Err(Error::internal(
443 "a scenario names no stylesheet of the rule set",
444 ));
445 };
446 let source = if index + 1 == count {
447 text.take()
448 } else {
449 text.as_deref().map(Cow::Borrowed)
450 }
451 .ok_or_else(|| Error::internal("the document text was given away early"))?;
452 let mut reader = SvrlReader::new(Severities {
454 fail_closed: options.fail_closed,
455 unflagged_assert: entry.unflagged_assert(),
456 scenario,
457 });
458 let result = executable.transform_compact(
459 source,
460 options.document_uri,
461 &transform_options,
462 &mut reader,
463 );
464 let report = match result {
465 Ok(result) => StylesheetReport::new(
466 entry,
467 result.output,
468 reader,
469 result.warnings,
470 options.document_uri,
471 )?,
472 Err(e) => match transform_error(entry, &e) {
473 Error::Transform {
476 code,
477 line,
478 message,
479 ..
480 } if !schema_errors.is_empty() => StylesheetReport::failed(
481 entry,
482 StylesheetFailure {
483 code,
484 line,
485 message,
486 },
487 options.document_uri,
488 ),
489 other => return Err(other),
490 },
491 };
492 stylesheets.push(report);
493 }
494 Ok(Report {
495 rule_set: self.version(),
496 document_uri: options.document_uri.map(str::to_owned),
497 scenario: scenario.map(|s| s.name().to_owned()),
498 no_scenario: None,
499 schema_errors,
500 stylesheets,
501 })
502 }
503
504 fn without_scenario(&self, no_scenario: NoScenario, options: &ValidateOptions<'_>) -> Report {
507 Report {
508 rule_set: self.version(),
509 document_uri: options.document_uri.map(str::to_owned),
510 scenario: None,
511 no_scenario: Some(no_scenario),
512 schema_errors: Vec::new(),
513 stylesheets: Vec::new(),
514 }
515 }
516
517 fn version(&self) -> RuleSetVersion {
519 RuleSetVersion {
520 name: self.rule_set.name().to_owned(),
521 title: self.rule_set.title().to_owned(),
522 version: self.rule_set.version().to_owned(),
523 schema: self.rule_set.schema(),
524 unchecked_schema: self.rule_set.unchecked_schema().map(str::to_owned),
525 }
526 }
527
528 fn select(
536 &self,
537 text: &str,
538 options: &ValidateOptions<'_>,
539 ) -> Result<Result<usize, NoScenario>, Error> {
540 let document =
541 Document::parse_with_max_depth(text, None, options.max_depth).map_err(|e| {
542 Error::internal(format!("the document for the scenarios: {}", e.message()))
544 })?;
545 let clock = match options.clock {
546 Some(clock) => clock,
547 None => system_clock()?,
548 };
549 let dc = DynamicContext::new(&NoHost, clock);
550 let context = Context::for_item(Item::Node(document.root()));
551 let mut matched = Vec::new();
552 for (index, (scenario, selection)) in self
553 .rule_set
554 .scenarios()
555 .iter()
556 .zip(self.selections.iter())
557 .enumerate()
558 {
559 match selection.matches.effective_boolean_value(&dc, &context) {
560 Ok(true) => matched.push(index),
561 Ok(false) => {}
562 Err(e) => {
563 let what = format!("scenario {:?}: match: {}", scenario.name(), e.message());
564 if let Some(limit) = e.limit() {
565 return Err(Error::Limit {
566 limit,
567 message: what,
568 });
569 }
570 match e.code() {
571 ErrorCode::Unsupported => return Err(Error::unsupported(what)),
572 ErrorCode::Internal => return Err(Error::internal(what)),
573 _ => {}
576 }
577 }
578 }
579 }
580 Ok(match matched[..] {
581 [index] => Ok(index),
582 [] => Err(NoScenario::NoneMatches),
583 _ => Err(NoScenario::SeveralMatch(
584 matched
585 .iter()
586 .filter_map(|&i| self.rule_set.scenarios().get(i))
587 .map(|s| s.name().to_owned())
588 .collect(),
589 )),
590 })
591 }
592}
593
594#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
597fn system_clock() -> Result<Clock, Error> {
598 Clock::system(0).map_err(|e| Error::internal(format!("the system clock: {}", e.message())))
599}
600
601#[cfg(all(target_family = "wasm", target_os = "unknown"))]
603fn system_clock() -> Result<Clock, Error> {
604 Err(Error::unsupported(
605 "no system clock on this target: give ValidateOptions::clock",
606 ))
607}
608
609fn selection(rule_set: &RuleSet, scenario: &Scenario) -> Result<Selection, Error> {
613 let what = format!("scenario {:?}: match", scenario.name());
614 let Some(text) = scenario.match_expression() else {
615 return Err(Error::internal(format!("{what}: none")));
616 };
617 let expr = einvoice_xpath::parse_expr(text, &namespace_map(scenario.namespaces()))
618 .map_err(|e| Error::bundle(format!("{what}: {e}")))?;
619 let matches = einvoice_xpath_eval::compile(&expr, &SimpleStaticContext::new())
622 .map_err(|e| Error::unsupported(format!("{what}: {}", e.message())))?;
623 let stylesheets = match scenario.stylesheets() {
624 None => (0..rule_set.stylesheets().len()).collect(),
625 Some(names) => names
626 .iter()
627 .map(|name| {
628 rule_set
629 .stylesheets()
630 .iter()
631 .position(|s| s.name() == name)
632 .ok_or_else(|| Error::internal(format!("{what}: no stylesheet {name}")))
633 })
634 .collect::<Result<_, Error>>()?,
635 };
636 Ok(Selection {
637 matches,
638 stylesheets,
639 })
640}
641
642fn read(path: &Path) -> Result<Vec<u8>, Error> {
643 std::fs::read(path).map_err(|source| Error::Io {
644 path: PathBuf::from(path),
645 source,
646 })
647}
648
649pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
651 const HEX: &[u8; 16] = b"0123456789abcdef";
652 let digest = Sha256::digest(bytes);
653 let mut hex = String::with_capacity(64);
654 for byte in digest {
655 hex.push(char::from(HEX[usize::from(byte >> 4)]));
656 hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
657 }
658 hex
659}
660
661fn prepare(
663 entry: &StylesheetEntry,
664 bytes: &[u8],
665 base_uri: Option<String>,
666) -> Result<Executable, Error> {
667 let actual = sha256_hex(bytes);
668 if actual != entry.sha256() {
669 return Err(Error::Checksum {
670 path: entry.path().to_owned(),
671 expected: entry.sha256().to_owned(),
672 actual,
673 });
674 }
675 let what = format!("stylesheet {} ({})", entry.name(), entry.path());
676 let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
677 let sheet = einvoice_xslt::load(text).map_err(|errors| {
678 let unsupported = errors.0.iter().any(|e| {
679 matches!(
680 e.kind,
681 LoadErrorKind::UnsupportedElement { .. }
682 | LoadErrorKind::UnsupportedAttribute { .. }
683 | LoadErrorKind::UnsupportedValue { .. }
684 | LoadErrorKind::XPath { .. }
685 | LoadErrorKind::TooDeep { .. }
686 )
687 });
688 let message = format!("{what}: {}", first_lines(&errors.to_string()));
689 if unsupported {
690 Error::unsupported(message)
691 } else {
692 Error::bundle(message)
693 }
694 })?;
695 let executable = Executable::new(&sheet).map_err(|errors| {
696 Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
697 })?;
698 Ok(match base_uri {
699 Some(uri) => executable.with_base_uri(uri),
700 None => executable,
701 })
702}
703
704fn first_lines(text: &str) -> String {
706 const MAX: usize = 10;
707 let lines: Vec<&str> = text.lines().collect();
708 if lines.len() <= MAX {
709 return lines.join("; ");
710 }
711 format!(
712 "{}; and {} more",
713 lines[..MAX].join("; "),
714 lines.len() - MAX
715 )
716}
717
718fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
719 let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
720 if let Some(limit) = e.limit() {
721 return Error::Limit {
722 limit,
723 message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
724 };
725 }
726 match e.code() {
727 "UNSUPPORTED" => {
728 Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
729 }
730 "INTERNAL" | "SXXP0003" => Error::internal(format!(
733 "stylesheet {}{at}: {}: {}",
734 entry.name(),
735 e.code(),
736 e.message()
737 )),
738 code => Error::Transform {
739 stylesheet: entry.name().to_owned(),
740 code: code.to_owned(),
741 line: e.line(),
742 message: e.message().to_owned(),
743 },
744 }
745}
746
747const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
749
750pub(crate) fn decode(bytes: &[u8]) -> Result<&str, Error> {
753 refuse_utf16(bytes)?;
754 let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
755 check_encoding(bytes)?;
756 std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
757}
758
759fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
762 refuse_utf16(&bytes)?;
763 if bytes.starts_with(BOM) {
764 bytes.drain(..BOM.len());
765 }
766 check_encoding(&bytes)?;
767 String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
768}
769
770fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
772 bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
773}
774
775fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
777 let before = &bytes[..valid_up_to];
778 let line_start = before
779 .iter()
780 .rposition(|&b| b == b'\n')
781 .map_or(0, |i| i + 1);
782 let line = before.split(|&b| b == b'\n').count();
783 let column = String::from_utf8_lossy(&before[line_start..])
784 .chars()
785 .count()
786 + 1;
787 Error::NotXml {
788 line: u32::try_from(line).unwrap_or(u32::MAX),
789 column: u32::try_from(column).unwrap_or(u32::MAX),
790 message,
791 }
792}
793
794fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
796 if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
797 return Err(Error::unsupported(
798 "a UTF-16 document: only UTF-8 is supported",
799 ));
800 }
801 Ok(())
802}
803
804fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
808 let ascii = match declared_encoding(bytes) {
809 None => false,
810 Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
811 Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
812 Some(e) => {
813 return Err(Error::unsupported(format!(
814 "the {e} encoding: only UTF-8 is supported"
815 )));
816 }
817 };
818 if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
819 return Err(bad_at(
820 bytes,
821 i,
822 "a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
823 ));
824 }
825 Ok(())
826}
827
828fn declared_encoding(bytes: &[u8]) -> Option<&str> {
830 let declaration = bytes.strip_prefix(b"<?xml")?;
831 if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
832 return None;
833 }
834 let end = declaration.windows(2).position(|w| w == b"?>")?;
835 let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
836 let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
837 let rest = rest.trim_start().strip_prefix('=')?.trim_start();
838 let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
839 let value = &rest[1..];
840 value.find(quote).map(|end| &value[..end])
841}
842
843const UBL_CBC: &str = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
845const CII_RAM: &str =
847 "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
848
849fn identifier_path(namespace: &str, local: &str) -> &'static [(&'static str, &'static str)] {
852 match (namespace, local) {
853 (UBL_INVOICE, "Invoice") | (UBL_CREDIT_NOTE, "CreditNote") => {
854 &[(UBL_CBC, "CustomizationID")]
855 }
856 (CII, "CrossIndustryInvoice") => &[
857 (CII, "ExchangedDocumentContext"),
858 (CII_RAM, "GuidelineSpecifiedDocumentContextParameter"),
859 (CII_RAM, "ID"),
860 ],
861 _ => &[],
862 }
863}
864
865#[derive(Debug, Default)]
868struct Identification {
869 root: Option<(String, String)>,
871 path: &'static [(&'static str, &'static str)],
873 matched: usize,
875 text: Option<String>,
877 identifiers: Vec<String>,
879}
880
881impl Identification {
882 fn start(&mut self, name: &einvoice_xml::Name<'_, '_>, depth: u32) {
884 let Ok(depth) = usize::try_from(depth) else {
885 return;
886 };
887 let namespace = name.namespace.unwrap_or("");
888 if depth == 1 {
889 self.path = identifier_path(namespace, name.local);
890 self.root = Some((namespace.to_owned(), name.local.to_owned()));
891 return;
892 }
893 if self.matched + 2 == depth
895 && self
896 .path
897 .get(self.matched)
898 .is_some_and(|&(ns, local)| ns == namespace && local == name.local)
899 {
900 self.matched += 1;
901 if self.matched == self.path.len() {
902 self.text = Some(String::new());
903 }
904 }
905 }
906
907 fn end(&mut self, depth: u32) {
909 let Ok(depth) = usize::try_from(depth) else {
910 return;
911 };
912 if depth >= 2 && self.matched + 1 == depth {
913 if self.matched == self.path.len()
914 && let Some(text) = self.text.take()
915 {
916 self.identifiers.push(text);
917 }
918 self.matched -= 1;
919 }
920 }
921
922 fn text(&mut self, text: &str) {
924 if let Some(value) = &mut self.text {
925 value.push_str(text);
926 }
927 }
928
929 fn scenario<'s>(&self, scenarios: &'s [Scenario]) -> Option<&'s Scenario> {
931 let (namespace, local) = self.root.as_ref()?;
932 scenarios.iter().find(|s| {
933 s.namespace() == Some(namespace.as_str())
934 && s.root() == Some(local.as_str())
935 && self
936 .identifiers
937 .iter()
938 .any(|i| Some(i.as_str()) == s.identifier())
939 })
940 }
941}
942
943#[derive(Debug)]
945struct Checked {
946 schema_errors: Vec<SchemaError>,
948 identification: Identification,
950}
951
952fn check(
963 text: &str,
964 max_depth: u32,
965 schema: Option<&einvoice_xsd::Schema>,
966 identify: bool,
967) -> Result<Checked, Error> {
968 let mut reader = einvoice_xml::Reader::new(text);
969 let mut validation = schema.map(|schema| schema.validation(text));
970 let mut identification = Identification::default();
971 let mut depth = 0u32;
972 let mut too_deep = None;
973 loop {
974 let event = match reader.next_event() {
975 Ok(Some(event)) => event,
976 Ok(None) => break,
977 Err(einvoice_xml::Error::DtdDetected) => {
978 return Err(Error::unsupported(
979 "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
980 ));
981 }
982 Err(e) => {
983 return Err(Error::NotXml {
984 line: e.pos().row,
985 column: e.pos().col,
986 message: e.to_string(),
987 });
988 }
989 };
990 match &event {
991 einvoice_xml::Event::Start(start) => {
992 depth = depth.saturating_add(1);
993 if identify {
994 identification.start(&start.name(), depth);
995 }
996 if depth > max_depth && too_deep.is_none() {
997 let at = einvoice_xml::TextPos::at(text, start.range().start);
998 too_deep = Some(LimitExceeded::Depth {
999 max: max_depth,
1000 line: at.row,
1001 column: at.col,
1002 });
1003 validation = None;
1005 }
1006 }
1007 einvoice_xml::Event::End(_) => {
1008 if identify {
1009 identification.end(depth);
1010 }
1011 depth = depth.saturating_sub(1);
1012 }
1013 einvoice_xml::Event::Text(t) if identify => identification.text(&t.value),
1014 _ => {}
1015 }
1016 if let Some(validation) = &mut validation {
1017 validation.event(event);
1018 }
1019 }
1020 if let Some(limit) = too_deep {
1021 return Err(Error::Limit {
1022 limit,
1023 message: format!("document, {limit}"),
1024 });
1025 }
1026 let schema_errors = match validation {
1027 None => Vec::new(),
1028 Some(validation) => schema_errors(validation)?,
1029 };
1030 Ok(Checked {
1031 schema_errors,
1032 identification,
1033 })
1034}
1035
1036fn schema_errors(validation: einvoice_xsd::Validation<'_, '_>) -> Result<Vec<SchemaError>, Error> {
1038 match validation.finish() {
1039 Ok(report) => Ok(report.errors),
1040 Err(einvoice_xsd::DocumentError::Malformed {
1041 line,
1042 column,
1043 message,
1044 }) => Err(Error::NotXml {
1045 line,
1046 column,
1047 message,
1048 }),
1049 Err(einvoice_xsd::DocumentError::Unsupported {
1050 line,
1051 column,
1052 message,
1053 }) => Err(Error::unsupported(format!(
1054 "document, line {line}, column {column}: {message}"
1055 ))),
1056 }
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061 use super::*;
1062
1063 fn check(
1065 text: &str,
1066 max_depth: u32,
1067 schema: Option<&einvoice_xsd::Schema>,
1068 ) -> Result<Vec<SchemaError>, Error> {
1069 super::check(text, max_depth, schema, false).map(|c| c.schema_errors)
1070 }
1071
1072 fn identify(text: &str) -> (Option<(String, String)>, Vec<String>) {
1074 let checked = super::check(text, DEFAULT_MAX_DEPTH, None, true).unwrap();
1075 (
1076 checked.identification.root,
1077 checked.identification.identifiers,
1078 )
1079 }
1080
1081 #[test]
1082 fn specification_identifiers() {
1083 let root = |ns: &str, local: &str| Some((ns.to_owned(), local.to_owned()));
1084 let ubl = format!(
1085 "<Invoice xmlns='{UBL_INVOICE}' xmlns:cbc='{UBL_CBC}'><cbc:CustomizationID> urn:a</cbc:CustomizationID>\
1086 <x><cbc:CustomizationID>no</cbc:CustomizationID></x>\
1087 <cbc:CustomizationID>u<!-- c -->rn:<![CDATA[b]]><i>c</i></cbc:CustomizationID><CustomizationID>no</CustomizationID></Invoice>"
1088 );
1089 assert_eq!(
1090 identify(&ubl),
1091 (
1092 root(UBL_INVOICE, "Invoice"),
1093 vec![" urn:a".to_owned(), "urn:bc".to_owned()]
1094 )
1095 );
1096 let credit_note = format!(
1097 "<c:CreditNote xmlns:c='{UBL_CREDIT_NOTE}'><b:CustomizationID xmlns:b='{UBL_CBC}'>urn:x</b:CustomizationID></c:CreditNote>"
1098 );
1099 assert_eq!(
1100 identify(&credit_note),
1101 (
1102 root(UBL_CREDIT_NOTE, "CreditNote"),
1103 vec!["urn:x".to_owned()]
1104 )
1105 );
1106 let cii = format!(
1107 "<rsm:CrossIndustryInvoice xmlns:rsm='{CII}' xmlns:ram='{CII_RAM}'>\
1108 <rsm:ExchangedDocumentContext><ram:ID>no</ram:ID>\
1109 <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:y</ram:ID><ram:Other>no</ram:Other></ram:GuidelineSpecifiedDocumentContextParameter>\
1110 <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:z</ram:ID></ram:GuidelineSpecifiedDocumentContextParameter>\
1111 </rsm:ExchangedDocumentContext><ram:ID>no</ram:ID></rsm:CrossIndustryInvoice>"
1112 );
1113 assert_eq!(
1114 identify(&cii),
1115 (
1116 root(CII, "CrossIndustryInvoice"),
1117 vec!["urn:y".to_owned(), "urn:z".to_owned()]
1118 )
1119 );
1120 assert_eq!(
1122 identify(&format!(
1123 "<Order xmlns='{UBL_INVOICE}'><CustomizationID xmlns='{UBL_CBC}'>x</CustomizationID></Order>"
1124 )),
1125 (root(UBL_INVOICE, "Order"), vec![])
1126 );
1127 assert_eq!(identify("<a/>"), (root("", "a"), vec![]));
1128 }
1129
1130 #[test]
1131 fn decoding_a_buffer_gives_the_same_result() {
1132 for bytes in [
1133 &b"<a/>"[..],
1134 b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
1135 b"<?xml version='1.0' encoding='UTF-8'?><a/>",
1136 b"\xFF\xFE<\0a\0/\0>\0",
1137 b"\xFE\xFF\0<\0a\0/\0>",
1138 b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
1139 b"<a>\n \xC3\xA9\xFF</a>",
1140 b"\xEF\xBB\xBF<a>\n\xFF</a>",
1141 b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
1142 b"\xEF\xBB\xBF",
1143 b"",
1144 ] {
1145 let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
1146 let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
1147 assert_eq!(owned, borrowed, "{bytes:?}");
1148 }
1149 }
1150
1151 #[test]
1152 fn decoding() {
1153 assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
1154 assert_eq!(
1155 decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
1156 "<?xml version='1.0' encoding='UTF-8'?><a/>"
1157 );
1158 assert!(matches!(
1159 decode(b"\xFF\xFE<\0a\0/\0>\0"),
1160 Err(Error::Unsupported { .. })
1161 ));
1162 assert!(matches!(
1163 decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
1164 Err(Error::Unsupported { .. })
1165 ));
1166 match decode(b"<a>\n \xC3\xA9\xFF</a>") {
1167 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
1168 other => panic!("{other:?}"),
1169 }
1170 match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
1171 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
1172 other => panic!("{other:?}"),
1173 }
1174 assert_eq!(
1175 declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
1176 None
1177 );
1178 }
1179
1180 #[test]
1181 fn well_formedness() {
1182 assert!(check("<a/>", 1, None).is_ok());
1183 match check("<a>\n<b></a>", DEFAULT_MAX_DEPTH, None) {
1184 Err(Error::NotXml {
1185 line,
1186 column,
1187 message,
1188 }) => assert_eq!(
1189 (line, column, message.as_str()),
1190 (2, 4, "expected 'b' tag, not 'a' at 2:4")
1191 ),
1192 other => panic!("{other:?}"),
1193 }
1194 assert!(matches!(
1195 check(
1196 "<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
1197 DEFAULT_MAX_DEPTH,
1198 None
1199 ),
1200 Err(Error::Unsupported { .. })
1201 ));
1202 assert!(matches!(
1203 check("<p:a/>", DEFAULT_MAX_DEPTH, None),
1204 Err(Error::NotXml { .. })
1205 ));
1206 }
1207
1208 #[test]
1209 fn one_pass_order_of_errors() {
1210 let schema = einvoice_xsd::Schema::ubl_2_1().unwrap();
1211 let invoice = "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' \
1212 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1213 let depth = |text: &str, max| match check(text, max, Some(&schema)) {
1214 Err(Error::Limit {
1215 limit: LimitExceeded::Depth { line, column, .. },
1216 ..
1217 }) => Some((line, column)),
1218 _ => None,
1219 };
1220 let errors = check(&format!("{invoice}</Invoice>"), 3, Some(&schema)).unwrap();
1222 assert_eq!(errors.len(), 1);
1223 assert_eq!(errors[0].kind.as_str(), "missing-element");
1224 let deep = format!("{invoice}\n<a><b><c/></b></a><d><e><f/></e></d></Invoice>");
1226 assert_eq!(depth(&deep, 2), Some((2, 4)));
1227 assert_eq!(depth(&deep, 3), Some((2, 7)));
1228 assert_eq!(depth(&deep, 4), None);
1229 let malformed = format!("{deep}<");
1231 assert!(matches!(
1232 check(&malformed, 2, Some(&schema)),
1233 Err(Error::NotXml { .. })
1234 ));
1235 assert!(matches!(
1236 check(&malformed, 2, None),
1237 Err(Error::NotXml { .. })
1238 ));
1239 let unsupported = invoice.replace(
1242 "<Invoice ",
1243 "<Invoice xsi:type='xs:IDREF' xmlns:xs='http://www.w3.org/2001/XMLSchema' ",
1244 );
1245 assert!(matches!(
1246 check(&format!("{unsupported}</Invoice>"), 3, Some(&schema)),
1247 Err(Error::Unsupported { .. })
1248 ));
1249 assert!(matches!(
1250 check(
1251 &format!("{unsupported}<b><c/></b></Invoice>"),
1252 2,
1253 Some(&schema)
1254 ),
1255 Err(Error::Limit { .. })
1256 ));
1257 assert!(matches!(
1258 check(&format!("{unsupported}</Invoice><"), 3, Some(&schema)),
1259 Err(Error::NotXml { .. })
1260 ));
1261 assert!(matches!(
1263 check("<!DOCTYPE Invoice><Invoice/>", 3, Some(&schema)),
1264 Err(Error::Unsupported { .. })
1265 ));
1266 }
1267
1268 #[test]
1269 fn checksums() {
1270 assert_eq!(
1271 sha256_hex(b"abc"),
1272 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1273 );
1274 }
1275
1276 #[test]
1277 fn errors_are_summarised() {
1278 let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
1279 let text = first_lines(&many.join("\n"));
1280 assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
1281 }
1282}