1use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5
6use einvoice_xpath_eval::Clock;
7use einvoice_xslt::LoadErrorKind;
8use einvoice_xslt_exec::{Executable, TransformError, TransformOptions};
9use roxmltree::ParsingOptions;
10use sha2::{Digest, Sha256};
11
12use crate::manifest::{MANIFEST_FILE, RuleSet, SchemaId, StylesheetEntry};
13use crate::report::{Report, RuleSetVersion, StylesheetFailure, StylesheetReport};
14use crate::{Error, builtin};
15
16#[derive(Debug, Clone, Copy, Default)]
18pub struct ValidateOptions<'a> {
19 document_uri: Option<&'a str>,
20 clock: Option<Clock>,
21}
22
23impl<'a> ValidateOptions<'a> {
24 #[must_use]
27 pub const fn new() -> Self {
28 Self {
29 document_uri: None,
30 clock: None,
31 }
32 }
33
34 #[must_use]
40 pub const fn clock(mut self, clock: Clock) -> Self {
41 self.clock = Some(clock);
42 self
43 }
44
45 #[must_use]
49 pub const fn document_uri(mut self, uri: &'a str) -> Self {
50 self.document_uri = Some(uri);
51 self
52 }
53}
54
55#[must_use]
58pub fn file_uri(path: &Path) -> Option<String> {
59 einvoice_xpath_eval::file_uri(path)
60}
61
62#[derive(Debug)]
67pub struct Validator {
68 rule_set: RuleSet,
69 schema: Option<einvoice_xsd::Schema>,
70 stylesheets: Vec<Executable>,
72}
73
74impl Validator {
75 pub fn builtin(name: &str) -> Result<Self, Error> {
82 let (manifest, files) = builtin::get(name)?;
83 Self::from_bundle(manifest, files)
84 }
85
86 #[cfg(feature = "cen-ubl")]
93 pub fn cen_ubl() -> Result<Self, Error> {
94 Self::builtin("cen-ubl")
95 }
96
97 pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
107 let rule_set = RuleSet::parse(manifest)?;
108 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
109 for entry in rule_set.stylesheets() {
110 let Some((_, bytes)) = files.iter().find(|(path, _)| *path == entry.path()) else {
111 return Err(Error::bundle(format!(
112 "stylesheet {}: file {} missing from the bundle",
113 entry.name(),
114 entry.path()
115 )));
116 };
117 stylesheets.push(prepare(entry, bytes, None)?);
118 }
119 Self::with(rule_set, stylesheets)
120 }
121
122 pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
130 let dir = dir.as_ref();
131 let manifest_path = dir.join(MANIFEST_FILE);
132 let manifest = read(&manifest_path)?;
133 let manifest = std::str::from_utf8(&manifest)
134 .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
135 let rule_set = RuleSet::parse(manifest)?;
136 let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
137 for entry in rule_set.stylesheets() {
138 let mut path = dir.to_path_buf();
139 path.extend(entry.path().split('/'));
140 let bytes = read(&path)?;
141 let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
142 stylesheets.push(prepare(entry, &bytes, base_uri)?);
143 }
144 Self::with(rule_set, stylesheets)
145 }
146
147 fn with(rule_set: RuleSet, stylesheets: Vec<Executable>) -> Result<Self, Error> {
148 let schema = match rule_set.schema() {
149 None => None,
150 Some(SchemaId::Ubl21) => Some(einvoice_xsd::Schema::ubl_2_1().map_err(|e| {
151 if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
152 Error::unsupported(format!("schema ubl-2.1: {e}"))
153 } else {
154 Error::internal(format!("the embedded schema ubl-2.1 does not load: {e}"))
155 }
156 })?),
157 };
158 Ok(Self {
159 rule_set,
160 schema,
161 stylesheets,
162 })
163 }
164
165 #[must_use]
167 pub const fn rule_set(&self) -> &RuleSet {
168 &self.rule_set
169 }
170
171 pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
177 self.validate_with(document, &ValidateOptions::new())
178 }
179
180 pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
187 self.validate_owned_with(document, &ValidateOptions::new())
188 }
189
190 pub fn validate_owned_with(
201 &self,
202 document: Vec<u8>,
203 options: &ValidateOptions<'_>,
204 ) -> Result<Report, Error> {
205 self.validate_text(Cow::Owned(decode_owned(document)?), options)
206 }
207
208 pub fn validate_with(
227 &self,
228 document: &[u8],
229 options: &ValidateOptions<'_>,
230 ) -> Result<Report, Error> {
231 self.validate_text(Cow::Borrowed(decode(document)?), options)
232 }
233
234 fn validate_text(
237 &self,
238 text: Cow<'_, str>,
239 options: &ValidateOptions<'_>,
240 ) -> Result<Report, Error> {
241 check_well_formed(&text)?;
242 let schema_errors = match &self.schema {
243 None => Vec::new(),
244 Some(schema) => {
245 schema
246 .validate(&text)
247 .map_err(|e| match e {
248 einvoice_xsd::DocumentError::Malformed {
249 line,
250 column,
251 message,
252 } => Error::NotXml {
253 line,
254 column,
255 message,
256 },
257 einvoice_xsd::DocumentError::Unsupported {
258 line,
259 column,
260 message,
261 } => Error::unsupported(format!(
262 "document, line {line}, column {column}: {message}"
263 )),
264 })?
265 .errors
266 }
267 };
268 let transform_options = TransformOptions {
269 implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
270 current_date_time: options.clock.map(|c| c.current_date_time()),
271 ..TransformOptions::default()
272 };
273 let mut stylesheets = Vec::with_capacity(self.stylesheets.len());
274 let count = self.stylesheets.len();
275 let mut text = Some(text);
277 for (index, (entry, executable)) in self
278 .rule_set
279 .stylesheets()
280 .iter()
281 .zip(&self.stylesheets)
282 .enumerate()
283 {
284 let source = if index + 1 == count {
285 text.take()
286 } else {
287 text.as_deref().map(Cow::Borrowed)
288 }
289 .ok_or_else(|| Error::internal("the document text was given away early"))?;
290 let result =
291 executable.transform_with(source, options.document_uri, &transform_options);
292 let report = match result {
293 Ok(result) => StylesheetReport::new(
294 entry,
295 result.output,
296 result.warnings,
297 options.document_uri,
298 )?,
299 Err(e) => match transform_error(entry, &e) {
300 Error::Transform {
303 code,
304 line,
305 message,
306 ..
307 } if !schema_errors.is_empty() => StylesheetReport::failed(
308 entry,
309 StylesheetFailure {
310 code,
311 line,
312 message,
313 },
314 options.document_uri,
315 ),
316 other => return Err(other),
317 },
318 };
319 stylesheets.push(report);
320 }
321 Ok(Report {
322 rule_set: RuleSetVersion {
323 name: self.rule_set.name().to_owned(),
324 title: self.rule_set.title().to_owned(),
325 version: self.rule_set.version().to_owned(),
326 schema: self.rule_set.schema(),
327 },
328 document_uri: options.document_uri.map(str::to_owned),
329 schema_errors,
330 stylesheets,
331 })
332 }
333}
334
335fn read(path: &Path) -> Result<Vec<u8>, Error> {
336 std::fs::read(path).map_err(|source| Error::Io {
337 path: PathBuf::from(path),
338 source,
339 })
340}
341
342pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
344 const HEX: &[u8; 16] = b"0123456789abcdef";
345 let digest = Sha256::digest(bytes);
346 let mut hex = String::with_capacity(64);
347 for byte in digest {
348 hex.push(char::from(HEX[usize::from(byte >> 4)]));
349 hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
350 }
351 hex
352}
353
354fn prepare(
356 entry: &StylesheetEntry,
357 bytes: &[u8],
358 base_uri: Option<String>,
359) -> Result<Executable, Error> {
360 let actual = sha256_hex(bytes);
361 if actual != entry.sha256() {
362 return Err(Error::Checksum {
363 path: entry.path().to_owned(),
364 expected: entry.sha256().to_owned(),
365 actual,
366 });
367 }
368 let what = format!("stylesheet {} ({})", entry.name(), entry.path());
369 let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
370 let sheet = einvoice_xslt::load(text).map_err(|errors| {
371 let unsupported = errors.0.iter().any(|e| {
372 matches!(
373 e.kind,
374 LoadErrorKind::UnsupportedElement { .. }
375 | LoadErrorKind::UnsupportedAttribute { .. }
376 | LoadErrorKind::UnsupportedValue { .. }
377 | LoadErrorKind::XPath { .. }
378 )
379 });
380 let message = format!("{what}: {}", first_lines(&errors.to_string()));
381 if unsupported {
382 Error::unsupported(message)
383 } else {
384 Error::bundle(message)
385 }
386 })?;
387 let executable = Executable::new(&sheet).map_err(|errors| {
388 Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
389 })?;
390 Ok(match base_uri {
391 Some(uri) => executable.with_base_uri(uri),
392 None => executable,
393 })
394}
395
396fn first_lines(text: &str) -> String {
398 const MAX: usize = 10;
399 let lines: Vec<&str> = text.lines().collect();
400 if lines.len() <= MAX {
401 return lines.join("; ");
402 }
403 format!(
404 "{}; and {} more",
405 lines[..MAX].join("; "),
406 lines.len() - MAX
407 )
408}
409
410fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
411 let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
412 match e.code() {
413 "UNSUPPORTED" => {
414 Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
415 }
416 "INTERNAL" | "SXXP0003" => Error::internal(format!(
419 "stylesheet {}{at}: {}: {}",
420 entry.name(),
421 e.code(),
422 e.message()
423 )),
424 code => Error::Transform {
425 stylesheet: entry.name().to_owned(),
426 code: code.to_owned(),
427 line: e.line(),
428 message: e.message().to_owned(),
429 },
430 }
431}
432
433const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
435
436fn decode(bytes: &[u8]) -> Result<&str, Error> {
439 refuse_utf16(bytes)?;
440 let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
441 check_encoding(bytes)?;
442 std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
443}
444
445fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
448 refuse_utf16(&bytes)?;
449 if bytes.starts_with(BOM) {
450 bytes.drain(..BOM.len());
451 }
452 check_encoding(&bytes)?;
453 String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
454}
455
456fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
458 bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
459}
460
461fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
463 let before = &bytes[..valid_up_to];
464 let line_start = before
465 .iter()
466 .rposition(|&b| b == b'\n')
467 .map_or(0, |i| i + 1);
468 let line = before.split(|&b| b == b'\n').count();
469 let column = String::from_utf8_lossy(&before[line_start..])
470 .chars()
471 .count()
472 + 1;
473 Error::NotXml {
474 line: u32::try_from(line).unwrap_or(u32::MAX),
475 column: u32::try_from(column).unwrap_or(u32::MAX),
476 message,
477 }
478}
479
480fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
482 if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
483 return Err(Error::unsupported(
484 "a UTF-16 document: only UTF-8 is supported",
485 ));
486 }
487 Ok(())
488}
489
490fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
494 let ascii = match declared_encoding(bytes) {
495 None => false,
496 Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
497 Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
498 Some(e) => {
499 return Err(Error::unsupported(format!(
500 "the {e} encoding: only UTF-8 is supported"
501 )));
502 }
503 };
504 if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
505 return Err(bad_at(
506 bytes,
507 i,
508 "a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
509 ));
510 }
511 Ok(())
512}
513
514fn declared_encoding(bytes: &[u8]) -> Option<&str> {
516 let declaration = bytes.strip_prefix(b"<?xml")?;
517 if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
518 return None;
519 }
520 let end = declaration.windows(2).position(|w| w == b"?>")?;
521 let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
522 let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
523 let rest = rest.trim_start().strip_prefix('=')?.trim_start();
524 let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
525 let value = &rest[1..];
526 value.find(quote).map(|end| &value[..end])
527}
528
529fn check_well_formed(text: &str) -> Result<(), Error> {
532 let options = ParsingOptions {
533 allow_dtd: false,
534 nodes_limit: u32::MAX,
535 ..ParsingOptions::default()
536 };
537 match roxmltree::Document::parse_with_options(text, options) {
538 Ok(_) => Ok(()),
539 Err(roxmltree::Error::DtdDetected) => Err(Error::unsupported(
540 "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
541 )),
542 Err(e) => Err(Error::NotXml {
543 line: e.pos().row,
544 column: e.pos().col,
545 message: e.to_string(),
546 }),
547 }
548}
549
550#[cfg(test)]
551mod tests {
552 use super::*;
553
554 #[test]
555 fn decoding_a_buffer_gives_the_same_result() {
556 for bytes in [
557 &b"<a/>"[..],
558 b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
559 b"<?xml version='1.0' encoding='UTF-8'?><a/>",
560 b"\xFF\xFE<\0a\0/\0>\0",
561 b"\xFE\xFF\0<\0a\0/\0>",
562 b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
563 b"<a>\n \xC3\xA9\xFF</a>",
564 b"\xEF\xBB\xBF<a>\n\xFF</a>",
565 b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
566 b"\xEF\xBB\xBF",
567 b"",
568 ] {
569 let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
570 let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
571 assert_eq!(owned, borrowed, "{bytes:?}");
572 }
573 }
574
575 #[test]
576 fn decoding() {
577 assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
578 assert_eq!(
579 decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
580 "<?xml version='1.0' encoding='UTF-8'?><a/>"
581 );
582 assert!(matches!(
583 decode(b"\xFF\xFE<\0a\0/\0>\0"),
584 Err(Error::Unsupported { .. })
585 ));
586 assert!(matches!(
587 decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
588 Err(Error::Unsupported { .. })
589 ));
590 match decode(b"<a>\n \xC3\xA9\xFF</a>") {
591 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
592 other => panic!("{other:?}"),
593 }
594 match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
595 Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
596 other => panic!("{other:?}"),
597 }
598 assert_eq!(
599 declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
600 None
601 );
602 }
603
604 #[test]
605 fn well_formedness() {
606 assert!(check_well_formed("<a/>").is_ok());
607 match check_well_formed("<a>\n<b></a>") {
608 Err(Error::NotXml { line, .. }) => assert_eq!(line, 2),
609 other => panic!("{other:?}"),
610 }
611 assert!(matches!(
612 check_well_formed("<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>"),
613 Err(Error::Unsupported { .. })
614 ));
615 assert!(matches!(
616 check_well_formed("<p:a/>"),
617 Err(Error::NotXml { .. })
618 ));
619 }
620
621 #[test]
622 fn checksums() {
623 assert_eq!(
624 sha256_hex(b"abc"),
625 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
626 );
627 }
628
629 #[test]
630 fn errors_are_summarised() {
631 let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
632 let text = first_lines(&many.join("\n"));
633 assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
634 }
635}