use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use einvoice_xpath_eval::{
Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DynamicContext, ErrorCode, Item,
LimitExceeded, NoHost, SimpleStaticContext,
};
use einvoice_xslt::LoadErrorKind;
use einvoice_xslt_exec::{
DEFAULT_MAX_STACK, Executable, TransformError, TransformOptions, max_nesting_for_depth,
};
use sha2::{Digest, Sha256};
use crate::manifest::{
CII, MANIFEST_FILE, RuleSet, Scenario, SchemaId, StylesheetEntry, UBL_CREDIT_NOTE, UBL_INVOICE,
namespace_map,
};
use crate::report::{
NoScenario, Report, RuleSetVersion, SchemaError, Severities, StylesheetFailure,
StylesheetReport, SvrlReader,
};
use crate::resources::{BUNDLE_URI, Resources};
use crate::{Error, builtin};
#[derive(Debug, Clone, Copy)]
pub struct ValidateOptions<'a> {
document_uri: Option<&'a str>,
clock: Option<Clock>,
max_depth: u32,
max_stack: u32,
fail_closed: bool,
}
impl Default for ValidateOptions<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> ValidateOptions<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
document_uri: None,
clock: None,
max_depth: DEFAULT_MAX_DEPTH,
max_stack: DEFAULT_MAX_STACK,
fail_closed: false,
}
}
#[must_use]
pub const fn fail_closed(mut self, fail_closed: bool) -> Self {
self.fail_closed = fail_closed;
self
}
#[must_use]
pub const fn max_depth(mut self, max_depth: u32) -> Self {
self.max_depth = max_depth;
self
}
#[must_use]
pub const fn max_stack(mut self, bytes: u32) -> Self {
self.max_stack = bytes;
self
}
#[must_use]
pub const fn clock(mut self, clock: Clock) -> Self {
self.clock = Some(clock);
self
}
#[must_use]
pub const fn document_uri(mut self, uri: &'a str) -> Self {
self.document_uri = Some(uri);
self
}
}
#[must_use]
pub fn file_uri(path: &Path) -> Option<String> {
einvoice_xpath_eval::file_uri(path)
}
#[derive(Debug, Clone)]
pub struct Validator {
rule_set: RuleSet,
schema: Option<Arc<einvoice_xsd::Schema>>,
stylesheets: Arc<[Executable]>,
resources: Arc<Resources>,
selections: Arc<[Selection]>,
all: Arc<[usize]>,
}
#[derive(Debug)]
struct Selection {
matches: CompiledExpr,
stylesheets: Vec<usize>,
}
impl Validator {
pub fn builtin(name: &str) -> Result<Self, Error> {
let (manifest, files) = builtin::get(name)?;
Self::from_bundle(manifest, files)
}
#[cfg(feature = "cen-ubl")]
pub fn cen_ubl() -> Result<Self, Error> {
Self::builtin("cen-ubl")
}
#[cfg(feature = "cen-cii")]
pub fn cen_cii() -> Result<Self, Error> {
Self::builtin("cen-cii")
}
pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
let rule_set = RuleSet::parse(manifest)?;
let file = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, b)| *b);
let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
for entry in rule_set.stylesheets() {
let Some(bytes) = file(entry.path()) else {
return Err(Error::bundle(format!(
"stylesheet {}: file {} missing from the bundle",
entry.name(),
entry.path()
)));
};
let base_uri = format!("{BUNDLE_URI}{}", entry.path());
stylesheets.push(prepare(entry, bytes, Some(base_uri))?);
}
let mut resources = Resources::default();
for entry in rule_set.resources() {
let Some(bytes) = file(entry.path()) else {
return Err(Error::bundle(format!(
"resource {}: file missing from the bundle",
entry.path()
)));
};
resources.add(entry, bytes, format!("{BUNDLE_URI}{}", entry.path()))?;
}
Self::with(rule_set, stylesheets, resources)
}
pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
let dir = dir.as_ref();
let manifest_path = dir.join(MANIFEST_FILE);
let manifest = read(&manifest_path)?;
let manifest = std::str::from_utf8(&manifest)
.map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
let rule_set = RuleSet::parse(manifest)?;
let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
for entry in rule_set.stylesheets() {
let mut path = dir.to_path_buf();
path.extend(entry.path().split('/'));
let bytes = read(&path)?;
let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
stylesheets.push(prepare(entry, &bytes, base_uri)?);
}
let mut resources = Resources::default();
for entry in rule_set.resources() {
let mut path = dir.to_path_buf();
path.extend(entry.path().split('/'));
let bytes = read(&path)?;
let uri = std::path::absolute(&path)
.ok()
.and_then(|p| file_uri(&p))
.ok_or_else(|| {
Error::bundle(format!(
"resource {}: no file URI for {}",
entry.path(),
path.display()
))
})?;
resources.add(entry, &bytes, uri)?;
}
Self::with(rule_set, stylesheets, resources)
}
fn with(
rule_set: RuleSet,
stylesheets: Vec<Executable>,
resources: Resources,
) -> Result<Self, Error> {
let schema = match rule_set.schema() {
None => None,
Some(id) => {
let loaded = match id {
SchemaId::Ubl21 => einvoice_xsd::Schema::ubl_2_1(),
SchemaId::CiiD16b => einvoice_xsd::Schema::cii_d16b(),
};
Some(loaded.map_err(|e| {
if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
Error::unsupported(format!("schema {id}: {e}"))
} else {
Error::internal(format!("the embedded schema {id} does not load: {e}"))
}
})?)
}
};
let selections = if rule_set.selects_by_scenario() {
rule_set
.scenarios()
.iter()
.map(|scenario| selection(&rule_set, scenario))
.collect::<Result<Vec<_>, Error>>()?
} else {
Vec::new()
};
Ok(Self {
rule_set,
schema: schema.map(Arc::new),
all: (0..stylesheets.len()).collect(),
stylesheets: stylesheets.into(),
resources: Arc::new(resources),
selections: selections.into(),
})
}
#[must_use]
pub const fn rule_set(&self) -> &RuleSet {
&self.rule_set
}
pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
self.validate_with(document, &ValidateOptions::new())
}
pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
self.validate_owned_with(document, &ValidateOptions::new())
}
pub fn validate_owned_with(
&self,
document: Vec<u8>,
options: &ValidateOptions<'_>,
) -> Result<Report, Error> {
self.validate_text(Cow::Owned(decode_owned(document)?), options)
}
pub fn validate_with(
&self,
document: &[u8],
options: &ValidateOptions<'_>,
) -> Result<Report, Error> {
self.validate_text(Cow::Borrowed(decode(document)?), options)
}
fn validate_text(
&self,
text: Cow<'_, str>,
options: &ValidateOptions<'_>,
) -> Result<Report, Error> {
let selects = self.rule_set.selects_by_scenario();
let identify = !selects && !self.rule_set.scenarios().is_empty();
let checked = check(&text, options.max_depth, self.schema.as_deref(), identify)?;
let schema_errors = checked.schema_errors;
let (scenario, run) = if selects {
match self.select(&text, options)? {
Ok(index) => (
self.rule_set.scenarios().get(index),
self.selections
.get(index)
.map(|s| s.stylesheets.as_slice())
.unwrap_or_default(),
),
Err(no_scenario) => return Ok(self.without_scenario(no_scenario, options)),
}
} else {
(
checked.identification.scenario(self.rule_set.scenarios()),
self.all.as_ref(),
)
};
let transform_options = TransformOptions {
implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
current_date_time: options.clock.map(|c| c.current_date_time()),
max_depth: options.max_depth,
max_nesting: max_nesting_for_depth(options.max_depth),
max_stack: options.max_stack,
resolver: Some(&*self.resources),
..TransformOptions::default()
};
let mut stylesheets = Vec::with_capacity(run.len());
let count = run.len();
let mut text = Some(text);
for (index, &stylesheet) in run.iter().enumerate() {
let (Some(entry), Some(executable)) = (
self.rule_set.stylesheets().get(stylesheet),
self.stylesheets.get(stylesheet),
) else {
return Err(Error::internal(
"a scenario names no stylesheet of the rule set",
));
};
let source = if index + 1 == count {
text.take()
} else {
text.as_deref().map(Cow::Borrowed)
}
.ok_or_else(|| Error::internal("the document text was given away early"))?;
let mut reader = SvrlReader::new(Severities {
fail_closed: options.fail_closed,
unflagged_assert: entry.unflagged_assert(),
scenario,
});
let result = executable.transform_compact(
source,
options.document_uri,
&transform_options,
&mut reader,
);
let report = match result {
Ok(result) => StylesheetReport::new(
entry,
result.output,
reader,
result.warnings,
options.document_uri,
)?,
Err(e) => match transform_error(entry, &e) {
Error::Transform {
code,
line,
message,
..
} if !schema_errors.is_empty() => StylesheetReport::failed(
entry,
StylesheetFailure {
code,
line,
message,
},
options.document_uri,
),
other => return Err(other),
},
};
stylesheets.push(report);
}
Ok(Report {
rule_set: self.version(),
document_uri: options.document_uri.map(str::to_owned),
scenario: scenario.map(|s| s.name().to_owned()),
no_scenario: None,
schema_errors,
stylesheets,
})
}
fn without_scenario(&self, no_scenario: NoScenario, options: &ValidateOptions<'_>) -> Report {
Report {
rule_set: self.version(),
document_uri: options.document_uri.map(str::to_owned),
scenario: None,
no_scenario: Some(no_scenario),
schema_errors: Vec::new(),
stylesheets: Vec::new(),
}
}
fn version(&self) -> RuleSetVersion {
RuleSetVersion {
name: self.rule_set.name().to_owned(),
title: self.rule_set.title().to_owned(),
version: self.rule_set.version().to_owned(),
schema: self.rule_set.schema(),
unchecked_schema: self.rule_set.unchecked_schema().map(str::to_owned),
}
}
fn select(
&self,
text: &str,
options: &ValidateOptions<'_>,
) -> Result<Result<usize, NoScenario>, Error> {
let document =
Document::parse_with_max_depth(text, None, options.max_depth).map_err(|e| {
Error::internal(format!("the document for the scenarios: {}", e.message()))
})?;
let clock = match options.clock {
Some(clock) => clock,
None => system_clock()?,
};
let dc = DynamicContext::new(&NoHost, clock);
let context = Context::for_item(Item::Node(document.root()));
let mut matched = Vec::new();
for (index, (scenario, selection)) in self
.rule_set
.scenarios()
.iter()
.zip(self.selections.iter())
.enumerate()
{
match selection.matches.effective_boolean_value(&dc, &context) {
Ok(true) => matched.push(index),
Ok(false) => {}
Err(e) => {
let what = format!("scenario {:?}: match: {}", scenario.name(), e.message());
if let Some(limit) = e.limit() {
return Err(Error::Limit {
limit,
message: what,
});
}
match e.code() {
ErrorCode::Unsupported => return Err(Error::unsupported(what)),
ErrorCode::Internal => return Err(Error::internal(what)),
_ => {}
}
}
}
}
Ok(match matched[..] {
[index] => Ok(index),
[] => Err(NoScenario::NoneMatches),
_ => Err(NoScenario::SeveralMatch(
matched
.iter()
.filter_map(|&i| self.rule_set.scenarios().get(i))
.map(|s| s.name().to_owned())
.collect(),
)),
})
}
}
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
fn system_clock() -> Result<Clock, Error> {
Clock::system(0).map_err(|e| Error::internal(format!("the system clock: {}", e.message())))
}
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
fn system_clock() -> Result<Clock, Error> {
Err(Error::unsupported(
"no system clock on this target: give ValidateOptions::clock",
))
}
fn selection(rule_set: &RuleSet, scenario: &Scenario) -> Result<Selection, Error> {
let what = format!("scenario {:?}: match", scenario.name());
let Some(text) = scenario.match_expression() else {
return Err(Error::internal(format!("{what}: none")));
};
let expr = einvoice_xpath::parse_expr(text, &namespace_map(scenario.namespaces()))
.map_err(|e| Error::bundle(format!("{what}: {e}")))?;
let matches = einvoice_xpath_eval::compile(&expr, &SimpleStaticContext::new())
.map_err(|e| Error::unsupported(format!("{what}: {}", e.message())))?;
let stylesheets = match scenario.stylesheets() {
None => (0..rule_set.stylesheets().len()).collect(),
Some(names) => names
.iter()
.map(|name| {
rule_set
.stylesheets()
.iter()
.position(|s| s.name() == name)
.ok_or_else(|| Error::internal(format!("{what}: no stylesheet {name}")))
})
.collect::<Result<_, Error>>()?,
};
Ok(Selection {
matches,
stylesheets,
})
}
fn read(path: &Path) -> Result<Vec<u8>, Error> {
std::fs::read(path).map_err(|source| Error::Io {
path: PathBuf::from(path),
source,
})
}
pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(64);
for byte in digest {
hex.push(char::from(HEX[usize::from(byte >> 4)]));
hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
hex
}
fn prepare(
entry: &StylesheetEntry,
bytes: &[u8],
base_uri: Option<String>,
) -> Result<Executable, Error> {
let actual = sha256_hex(bytes);
if actual != entry.sha256() {
return Err(Error::Checksum {
path: entry.path().to_owned(),
expected: entry.sha256().to_owned(),
actual,
});
}
let what = format!("stylesheet {} ({})", entry.name(), entry.path());
let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
let sheet = einvoice_xslt::load(text).map_err(|errors| {
let unsupported = errors.0.iter().any(|e| {
matches!(
e.kind,
LoadErrorKind::UnsupportedElement { .. }
| LoadErrorKind::UnsupportedAttribute { .. }
| LoadErrorKind::UnsupportedValue { .. }
| LoadErrorKind::XPath { .. }
| LoadErrorKind::TooDeep { .. }
)
});
let message = format!("{what}: {}", first_lines(&errors.to_string()));
if unsupported {
Error::unsupported(message)
} else {
Error::bundle(message)
}
})?;
let executable = Executable::new(&sheet).map_err(|errors| {
Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
})?;
Ok(match base_uri {
Some(uri) => executable.with_base_uri(uri),
None => executable,
})
}
fn first_lines(text: &str) -> String {
const MAX: usize = 10;
let lines: Vec<&str> = text.lines().collect();
if lines.len() <= MAX {
return lines.join("; ");
}
format!(
"{}; and {} more",
lines[..MAX].join("; "),
lines.len() - MAX
)
}
fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
if let Some(limit) = e.limit() {
return Error::Limit {
limit,
message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
};
}
match e.code() {
"UNSUPPORTED" => {
Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
}
"INTERNAL" | "SXXP0003" => Error::internal(format!(
"stylesheet {}{at}: {}: {}",
entry.name(),
e.code(),
e.message()
)),
code => Error::Transform {
stylesheet: entry.name().to_owned(),
code: code.to_owned(),
line: e.line(),
message: e.message().to_owned(),
},
}
}
const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
pub(crate) fn decode(bytes: &[u8]) -> Result<&str, Error> {
refuse_utf16(bytes)?;
let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
check_encoding(bytes)?;
std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
}
fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
refuse_utf16(&bytes)?;
if bytes.starts_with(BOM) {
bytes.drain(..BOM.len());
}
check_encoding(&bytes)?;
String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
}
fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
}
fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
let before = &bytes[..valid_up_to];
let line_start = before
.iter()
.rposition(|&b| b == b'\n')
.map_or(0, |i| i + 1);
let line = before.split(|&b| b == b'\n').count();
let column = String::from_utf8_lossy(&before[line_start..])
.chars()
.count()
+ 1;
Error::NotXml {
line: u32::try_from(line).unwrap_or(u32::MAX),
column: u32::try_from(column).unwrap_or(u32::MAX),
message,
}
}
fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
return Err(Error::unsupported(
"a UTF-16 document: only UTF-8 is supported",
));
}
Ok(())
}
fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
let ascii = match declared_encoding(bytes) {
None => false,
Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
Some(e) => {
return Err(Error::unsupported(format!(
"the {e} encoding: only UTF-8 is supported"
)));
}
};
if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
return Err(bad_at(
bytes,
i,
"a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
));
}
Ok(())
}
fn declared_encoding(bytes: &[u8]) -> Option<&str> {
let declaration = bytes.strip_prefix(b"<?xml")?;
if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
return None;
}
let end = declaration.windows(2).position(|w| w == b"?>")?;
let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
let rest = rest.trim_start().strip_prefix('=')?.trim_start();
let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
let value = &rest[1..];
value.find(quote).map(|end| &value[..end])
}
const UBL_CBC: &str = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
const CII_RAM: &str =
"urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
fn identifier_path(namespace: &str, local: &str) -> &'static [(&'static str, &'static str)] {
match (namespace, local) {
(UBL_INVOICE, "Invoice") | (UBL_CREDIT_NOTE, "CreditNote") => {
&[(UBL_CBC, "CustomizationID")]
}
(CII, "CrossIndustryInvoice") => &[
(CII, "ExchangedDocumentContext"),
(CII_RAM, "GuidelineSpecifiedDocumentContextParameter"),
(CII_RAM, "ID"),
],
_ => &[],
}
}
#[derive(Debug, Default)]
struct Identification {
root: Option<(String, String)>,
path: &'static [(&'static str, &'static str)],
matched: usize,
text: Option<String>,
identifiers: Vec<String>,
}
impl Identification {
fn start(&mut self, name: &einvoice_xml::Name<'_, '_>, depth: u32) {
let Ok(depth) = usize::try_from(depth) else {
return;
};
let namespace = name.namespace.unwrap_or("");
if depth == 1 {
self.path = identifier_path(namespace, name.local);
self.root = Some((namespace.to_owned(), name.local.to_owned()));
return;
}
if self.matched + 2 == depth
&& self
.path
.get(self.matched)
.is_some_and(|&(ns, local)| ns == namespace && local == name.local)
{
self.matched += 1;
if self.matched == self.path.len() {
self.text = Some(String::new());
}
}
}
fn end(&mut self, depth: u32) {
let Ok(depth) = usize::try_from(depth) else {
return;
};
if depth >= 2 && self.matched + 1 == depth {
if self.matched == self.path.len()
&& let Some(text) = self.text.take()
{
self.identifiers.push(text);
}
self.matched -= 1;
}
}
fn text(&mut self, text: &str) {
if let Some(value) = &mut self.text {
value.push_str(text);
}
}
fn scenario<'s>(&self, scenarios: &'s [Scenario]) -> Option<&'s Scenario> {
let (namespace, local) = self.root.as_ref()?;
scenarios.iter().find(|s| {
s.namespace() == Some(namespace.as_str())
&& s.root() == Some(local.as_str())
&& self
.identifiers
.iter()
.any(|i| Some(i.as_str()) == s.identifier())
})
}
}
#[derive(Debug)]
struct Checked {
schema_errors: Vec<SchemaError>,
identification: Identification,
}
fn check(
text: &str,
max_depth: u32,
schema: Option<&einvoice_xsd::Schema>,
identify: bool,
) -> Result<Checked, Error> {
let mut reader = einvoice_xml::Reader::new(text);
let mut validation = schema.map(|schema| schema.validation(text));
let mut identification = Identification::default();
let mut depth = 0u32;
let mut too_deep = None;
loop {
let event = match reader.next_event() {
Ok(Some(event)) => event,
Ok(None) => break,
Err(einvoice_xml::Error::DtdDetected) => {
return Err(Error::unsupported(
"a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
));
}
Err(e) => {
return Err(Error::NotXml {
line: e.pos().row,
column: e.pos().col,
message: e.to_string(),
});
}
};
match &event {
einvoice_xml::Event::Start(start) => {
depth = depth.saturating_add(1);
if identify {
identification.start(&start.name(), depth);
}
if depth > max_depth && too_deep.is_none() {
let at = einvoice_xml::TextPos::at(text, start.range().start);
too_deep = Some(LimitExceeded::Depth {
max: max_depth,
line: at.row,
column: at.col,
});
validation = None;
}
}
einvoice_xml::Event::End(_) => {
if identify {
identification.end(depth);
}
depth = depth.saturating_sub(1);
}
einvoice_xml::Event::Text(t) if identify => identification.text(&t.value),
_ => {}
}
if let Some(validation) = &mut validation {
validation.event(event);
}
}
if let Some(limit) = too_deep {
return Err(Error::Limit {
limit,
message: format!("document, {limit}"),
});
}
let schema_errors = match validation {
None => Vec::new(),
Some(validation) => schema_errors(validation)?,
};
Ok(Checked {
schema_errors,
identification,
})
}
fn schema_errors(validation: einvoice_xsd::Validation<'_, '_>) -> Result<Vec<SchemaError>, Error> {
match validation.finish() {
Ok(report) => Ok(report.errors),
Err(einvoice_xsd::DocumentError::Malformed {
line,
column,
message,
}) => Err(Error::NotXml {
line,
column,
message,
}),
Err(einvoice_xsd::DocumentError::Unsupported {
line,
column,
message,
}) => Err(Error::unsupported(format!(
"document, line {line}, column {column}: {message}"
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(
text: &str,
max_depth: u32,
schema: Option<&einvoice_xsd::Schema>,
) -> Result<Vec<SchemaError>, Error> {
super::check(text, max_depth, schema, false).map(|c| c.schema_errors)
}
fn identify(text: &str) -> (Option<(String, String)>, Vec<String>) {
let checked = super::check(text, DEFAULT_MAX_DEPTH, None, true).unwrap();
(
checked.identification.root,
checked.identification.identifiers,
)
}
#[test]
fn specification_identifiers() {
let root = |ns: &str, local: &str| Some((ns.to_owned(), local.to_owned()));
let ubl = format!(
"<Invoice xmlns='{UBL_INVOICE}' xmlns:cbc='{UBL_CBC}'><cbc:CustomizationID> urn:a</cbc:CustomizationID>\
<x><cbc:CustomizationID>no</cbc:CustomizationID></x>\
<cbc:CustomizationID>u<!-- c -->rn:<![CDATA[b]]><i>c</i></cbc:CustomizationID><CustomizationID>no</CustomizationID></Invoice>"
);
assert_eq!(
identify(&ubl),
(
root(UBL_INVOICE, "Invoice"),
vec![" urn:a".to_owned(), "urn:bc".to_owned()]
)
);
let credit_note = format!(
"<c:CreditNote xmlns:c='{UBL_CREDIT_NOTE}'><b:CustomizationID xmlns:b='{UBL_CBC}'>urn:x</b:CustomizationID></c:CreditNote>"
);
assert_eq!(
identify(&credit_note),
(
root(UBL_CREDIT_NOTE, "CreditNote"),
vec!["urn:x".to_owned()]
)
);
let cii = format!(
"<rsm:CrossIndustryInvoice xmlns:rsm='{CII}' xmlns:ram='{CII_RAM}'>\
<rsm:ExchangedDocumentContext><ram:ID>no</ram:ID>\
<ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:y</ram:ID><ram:Other>no</ram:Other></ram:GuidelineSpecifiedDocumentContextParameter>\
<ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:z</ram:ID></ram:GuidelineSpecifiedDocumentContextParameter>\
</rsm:ExchangedDocumentContext><ram:ID>no</ram:ID></rsm:CrossIndustryInvoice>"
);
assert_eq!(
identify(&cii),
(
root(CII, "CrossIndustryInvoice"),
vec!["urn:y".to_owned(), "urn:z".to_owned()]
)
);
assert_eq!(
identify(&format!(
"<Order xmlns='{UBL_INVOICE}'><CustomizationID xmlns='{UBL_CBC}'>x</CustomizationID></Order>"
)),
(root(UBL_INVOICE, "Order"), vec![])
);
assert_eq!(identify("<a/>"), (root("", "a"), vec![]));
}
#[test]
fn decoding_a_buffer_gives_the_same_result() {
for bytes in [
&b"<a/>"[..],
b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
b"<?xml version='1.0' encoding='UTF-8'?><a/>",
b"\xFF\xFE<\0a\0/\0>\0",
b"\xFE\xFF\0<\0a\0/\0>",
b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
b"<a>\n \xC3\xA9\xFF</a>",
b"\xEF\xBB\xBF<a>\n\xFF</a>",
b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
b"\xEF\xBB\xBF",
b"",
] {
let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
assert_eq!(owned, borrowed, "{bytes:?}");
}
}
#[test]
fn decoding() {
assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
assert_eq!(
decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
"<?xml version='1.0' encoding='UTF-8'?><a/>"
);
assert!(matches!(
decode(b"\xFF\xFE<\0a\0/\0>\0"),
Err(Error::Unsupported { .. })
));
assert!(matches!(
decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
Err(Error::Unsupported { .. })
));
match decode(b"<a>\n \xC3\xA9\xFF</a>") {
Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
other => panic!("{other:?}"),
}
match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
other => panic!("{other:?}"),
}
assert_eq!(
declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
None
);
}
#[test]
fn well_formedness() {
assert!(check("<a/>", 1, None).is_ok());
match check("<a>\n<b></a>", DEFAULT_MAX_DEPTH, None) {
Err(Error::NotXml {
line,
column,
message,
}) => assert_eq!(
(line, column, message.as_str()),
(2, 4, "expected 'b' tag, not 'a' at 2:4")
),
other => panic!("{other:?}"),
}
assert!(matches!(
check(
"<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
DEFAULT_MAX_DEPTH,
None
),
Err(Error::Unsupported { .. })
));
assert!(matches!(
check("<p:a/>", DEFAULT_MAX_DEPTH, None),
Err(Error::NotXml { .. })
));
}
#[test]
fn one_pass_order_of_errors() {
let schema = einvoice_xsd::Schema::ubl_2_1().unwrap();
let invoice = "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' \
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
let depth = |text: &str, max| match check(text, max, Some(&schema)) {
Err(Error::Limit {
limit: LimitExceeded::Depth { line, column, .. },
..
}) => Some((line, column)),
_ => None,
};
let errors = check(&format!("{invoice}</Invoice>"), 3, Some(&schema)).unwrap();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].kind.as_str(), "missing-element");
let deep = format!("{invoice}\n<a><b><c/></b></a><d><e><f/></e></d></Invoice>");
assert_eq!(depth(&deep, 2), Some((2, 4)));
assert_eq!(depth(&deep, 3), Some((2, 7)));
assert_eq!(depth(&deep, 4), None);
let malformed = format!("{deep}<");
assert!(matches!(
check(&malformed, 2, Some(&schema)),
Err(Error::NotXml { .. })
));
assert!(matches!(
check(&malformed, 2, None),
Err(Error::NotXml { .. })
));
let unsupported = invoice.replace(
"<Invoice ",
"<Invoice xsi:type='xs:IDREF' xmlns:xs='http://www.w3.org/2001/XMLSchema' ",
);
assert!(matches!(
check(&format!("{unsupported}</Invoice>"), 3, Some(&schema)),
Err(Error::Unsupported { .. })
));
assert!(matches!(
check(
&format!("{unsupported}<b><c/></b></Invoice>"),
2,
Some(&schema)
),
Err(Error::Limit { .. })
));
assert!(matches!(
check(&format!("{unsupported}</Invoice><"), 3, Some(&schema)),
Err(Error::NotXml { .. })
));
assert!(matches!(
check("<!DOCTYPE Invoice><Invoice/>", 3, Some(&schema)),
Err(Error::Unsupported { .. })
));
}
#[test]
fn checksums() {
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn errors_are_summarised() {
let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
let text = first_lines(&many.join("\n"));
assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
}
}