use std::fmt;
use einvoice_xpath::QName;
use einvoice_xslt_exec::{CompactOutput, ResultObserver};
pub use einvoice_xsd::{ErrorKind as SchemaErrorKind, ValidationError as SchemaError};
use crate::Error;
const SVRL_NS: &str = "http://purl.oclc.org/dsdl/svrl";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Verdict {
Valid,
Invalid,
}
impl Verdict {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Valid => "valid",
Self::Invalid => "invalid",
}
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Severity {
Fatal,
Warning,
Other,
}
impl Severity {
#[must_use]
pub fn from_flag(flag: Option<&str>) -> Self {
match flag {
Some("fatal") => Self::Fatal,
Some("warning") => Self::Warning,
_ => Self::Other,
}
}
#[must_use]
pub fn from_flag_fail_closed(flag: Option<&str>) -> Self {
match Self::from_flag(flag) {
Self::Other => Self::Fatal,
severity => severity,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Fatal => "fatal",
Self::Warning => "warning",
Self::Other => "other",
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FindingKind {
FailedAssert,
SuccessfulReport,
}
impl FindingKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::FailedAssert => "failed-assert",
Self::SuccessfulReport => "successful-report",
}
}
}
impl fmt::Display for FindingKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Finding {
pub kind: FindingKind,
pub id: Option<String>,
pub flag: Option<String>,
pub severity: Severity,
pub role: Option<String>,
pub location: String,
pub context: Option<String>,
pub pattern: Option<String>,
pub test: String,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StylesheetReport {
pub name: String,
pub version: String,
pub sha256: String,
svrl: CompactOutput,
pub findings: Vec<Finding>,
pub fired_rules: usize,
pub warnings: Vec<String>,
pub failure: Option<StylesheetFailure>,
pub(crate) document_uri: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct StylesheetFailure {
pub code: String,
pub line: Option<u32>,
pub message: String,
}
impl StylesheetReport {
#[must_use]
pub const fn svrl(&self) -> &CompactOutput {
&self.svrl
}
pub fn canonical_svrl(&self) -> Result<String, Error> {
if let Some(failure) = &self.failure {
return Err(Error::Transform {
stylesheet: self.name.clone(),
code: failure.code.clone(),
line: failure.line,
message: failure.message.clone(),
});
}
let uri = self.document_uri.as_deref();
einvoice_svrl::canonicalize(&self.svrl.to_text(), &|u| Some(u) == uri)
.map_err(|e| Error::internal(format!("stylesheet {}: {e}", self.name)))
}
pub(crate) fn new(
entry: &crate::StylesheetEntry,
svrl: CompactOutput,
reader: SvrlReader,
warnings: Vec<String>,
document_uri: Option<&str>,
) -> Result<Self, Error> {
let (findings, fired_rules) = reader.finish(&svrl).map_err(|m| {
Error::bundle(format!(
"stylesheet {}: its result is not an SVRL report: {m}",
entry.name()
))
})?;
Ok(Self {
name: entry.name().to_owned(),
version: entry.version().to_owned(),
sha256: entry.sha256().to_owned(),
svrl,
findings,
fired_rules,
warnings,
failure: None,
document_uri: document_uri.map(str::to_owned),
})
}
pub(crate) fn failed(
entry: &crate::StylesheetEntry,
failure: StylesheetFailure,
document_uri: Option<&str>,
) -> Self {
Self {
name: entry.name().to_owned(),
version: entry.version().to_owned(),
sha256: entry.sha256().to_owned(),
svrl: CompactOutput::default(),
findings: Vec::new(),
fired_rules: 0,
warnings: Vec::new(),
failure: Some(failure),
document_uri: document_uri.map(str::to_owned),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RuleSetVersion {
pub name: String,
pub title: String,
pub version: String,
pub schema: Option<crate::SchemaId>,
pub unchecked_schema: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NoScenario {
NoneMatches,
SeveralMatch(Vec<String>),
}
impl fmt::Display for NoScenario {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoneMatches => f.write_str("no scenario of the rule set matches the document"),
Self::SeveralMatch(names) => write!(
f,
"{} scenarios of the rule set match the document, one is required: {}",
names.len(),
names.join(", ")
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
pub rule_set: RuleSetVersion,
pub document_uri: Option<String>,
pub scenario: Option<String>,
pub no_scenario: Option<NoScenario>,
pub schema_errors: Vec<SchemaError>,
pub stylesheets: Vec<StylesheetReport>,
}
impl Report {
#[must_use]
pub fn verdict(&self) -> Verdict {
if self.no_scenario.is_none()
&& self.schema_errors.is_empty()
&& self.count(Severity::Fatal) == 0
{
Verdict::Valid
} else {
Verdict::Invalid
}
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.stylesheets.iter().all(|s| s.failure.is_none())
}
#[must_use]
pub fn is_valid(&self) -> bool {
self.verdict() == Verdict::Valid
}
pub fn findings(&self) -> impl Iterator<Item = &Finding> {
self.stylesheets.iter().flat_map(|s| s.findings.iter())
}
#[must_use]
pub fn count(&self, severity: Severity) -> usize {
self.findings().filter(|f| f.severity == severity).count()
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Severities<'a> {
pub(crate) fail_closed: bool,
pub(crate) unflagged_assert: Severity,
pub(crate) scenario: Option<&'a crate::Scenario>,
}
impl Default for Severities<'_> {
fn default() -> Self {
Self {
fail_closed: false,
unflagged_assert: Severity::Other,
scenario: None,
}
}
}
impl Severities<'_> {
pub(crate) fn of(self, kind: FindingKind, flag: Option<&str>, id: Option<&str>) -> Severity {
let severity = id
.and_then(|id| self.scenario.and_then(|s| s.level(id)))
.unwrap_or_else(|| match (kind, flag) {
(FindingKind::FailedAssert, None) => self.unflagged_assert,
_ => Severity::from_flag(flag),
});
if self.fail_closed && severity == Severity::Other {
Severity::Fatal
} else {
severity
}
}
}
#[derive(Debug, Default)]
pub(crate) struct SvrlReader<'a> {
severities: Severities<'a>,
depth: usize,
roots: usize,
root_is_svrl: bool,
bad_comment: bool,
findings: Vec<Finding>,
fired_rules: usize,
pattern: Option<String>,
context: Option<String>,
finding: Option<Reading>,
}
#[derive(Debug)]
struct Reading {
finding: Finding,
text: String,
in_text: bool,
}
impl<'a> SvrlReader<'a> {
pub(crate) fn new(severities: Severities<'a>) -> Self {
Self {
severities,
..Self::default()
}
}
fn finish(self, svrl: &CompactOutput) -> Result<(Vec<Finding>, usize), String> {
if self.roots != 1 || self.bad_comment {
einvoice_xml::check(&svrl.to_text()).map_err(|e| e.to_string())?;
if self.roots != 1 {
return Err(format!(
"{} elements at the top of the document, instead of one",
self.roots
));
}
}
if !self.root_is_svrl {
return Err("the root is not svrl:schematron-output".to_owned());
}
Ok((self.findings, self.fired_rules))
}
}
fn is_svrl(name: &QName, local: &str) -> bool {
name.namespace.as_deref() == Some(SVRL_NS) && name.local == local
}
fn attribute(attributes: &[(QName, String)], local: &str) -> Option<String> {
attributes
.iter()
.find(|(name, _)| {
name.namespace.as_deref().is_none_or(str::is_empty) && name.local == local
})
.map(|(_, value)| value.clone())
}
impl ResultObserver for SvrlReader<'_> {
fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]) {
self.depth += 1;
match self.depth {
1 => {
self.roots += 1;
if self.roots == 1 {
self.root_is_svrl = is_svrl(name, "schematron-output");
}
}
2 if self.roots == 1 && name.namespace.as_deref() == Some(SVRL_NS) => {
let kind = match name.local.as_str() {
"active-pattern" => {
self.pattern =
attribute(attributes, "id").or_else(|| attribute(attributes, "name"));
self.context = None;
return;
}
"fired-rule" => {
self.fired_rules += 1;
self.context = attribute(attributes, "context");
return;
}
"failed-assert" => FindingKind::FailedAssert,
"successful-report" => FindingKind::SuccessfulReport,
_ => return,
};
let flag = attribute(attributes, "flag");
let id = attribute(attributes, "id");
let severity = self.severities.of(kind, flag.as_deref(), id.as_deref());
let finding = Finding {
kind,
id,
severity,
flag,
role: attribute(attributes, "role"),
location: attribute(attributes, "location").unwrap_or_default(),
context: self.context.clone(),
pattern: self.pattern.clone(),
test: attribute(attributes, "test").unwrap_or_default(),
text: String::new(),
};
self.finding = Some(Reading {
finding,
text: String::new(),
in_text: false,
});
}
3 if is_svrl(name, "text") => {
if let Some(reading) = &mut self.finding {
reading.in_text = true;
}
}
_ => {}
}
}
fn end_element(&mut self) {
match self.depth {
2 => {
if let Some(Reading {
mut finding, text, ..
}) = self.finding.take()
{
finding.text = einvoice_svrl::normalize_space(&text);
self.findings.push(finding);
}
}
3 => {
if let Some(reading) = &mut self.finding {
reading.in_text = false;
}
}
_ => {}
}
self.depth = self.depth.saturating_sub(1);
}
fn text(&mut self, text: &str) {
if let Some(reading) = &mut self.finding
&& reading.in_text
{
reading.text.push_str(text);
}
}
fn comment(&mut self, text: &str) {
if text.contains("--") || text.ends_with('-') {
self.bad_comment = true;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn findings(svrl: &str, fail_closed: bool) -> Result<(Vec<Finding>, usize), String> {
let qname = |name: einvoice_xml::Name<'_, '_>| QName {
prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
namespace: name.namespace.map(str::to_owned),
local: name.local.to_owned(),
};
let mut reader = SvrlReader::new(Severities {
fail_closed,
..Severities::default()
});
let mut parser = einvoice_xml::Reader::new(svrl);
let mut depth = 0;
while let Ok(Some(event)) = parser.next_event() {
match event {
einvoice_xml::Event::Start(start) => {
let attributes: Vec<(QName, String)> = start
.attributes()
.map(|a| (qname(a.name), a.value.to_string()))
.collect();
reader.start_element(&qname(start.name()), &attributes);
depth += 1;
}
einvoice_xml::Event::End(_) => {
reader.end_element();
depth -= 1;
}
einvoice_xml::Event::Text(text) if depth > 0 => reader.text(&text.value),
einvoice_xml::Event::Comment(comment) => reader.comment(&comment.value),
_ => {}
}
}
reader.finish(&CompactOutput::from(svrl))
}
#[test]
fn reads_findings_with_their_rule_and_pattern() {
let svrl = r#"<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl">
<svrl:active-pattern id="P1"/>
<svrl:fired-rule context="/a"/>
<svrl:failed-assert id="R-1" flag="fatal" location="/a[1]" test="b">
<svrl:text> [R-1] two
lines </svrl:text>
</svrl:failed-assert>
<svrl:active-pattern name="P2"/>
<svrl:successful-report id="R-2" flag="warning" role="r" location="/" test="c"><svrl:text/></svrl:successful-report>
<svrl:fired-rule context="/z"/>
<svrl:failed-assert location="/" test="d"/>
</svrl:schematron-output>"#;
let (f, fired_rules) = findings(svrl, false).unwrap();
assert_eq!(fired_rules, 2);
assert_eq!(f.len(), 3);
assert_eq!(f[0].kind, FindingKind::FailedAssert);
assert_eq!(f[0].id.as_deref(), Some("R-1"));
assert_eq!(f[0].severity, Severity::Fatal);
assert_eq!(f[0].context.as_deref(), Some("/a"));
assert_eq!(f[0].pattern.as_deref(), Some("P1"));
assert_eq!(f[0].text, "[R-1] two lines");
assert_eq!(f[1].kind, FindingKind::SuccessfulReport);
assert_eq!(f[1].severity, Severity::Warning);
assert_eq!(f[1].role.as_deref(), Some("r"));
assert_eq!(f[1].context, None);
assert_eq!(f[1].pattern.as_deref(), Some("P2"));
assert_eq!(f[2].severity, Severity::Other);
assert_eq!(f[2].id, None);
assert_eq!(f[2].context.as_deref(), Some("/z"));
let (closed, _) = findings(svrl, true).unwrap();
let severities: Vec<Severity> = closed.iter().map(|f| f.severity).collect();
assert_eq!(
severities,
[Severity::Fatal, Severity::Warning, Severity::Fatal]
);
}
fn parser_error(text: &str) -> String {
let options = roxmltree::ParsingOptions {
allow_dtd: false,
nodes_limit: u32::MAX,
..roxmltree::ParsingOptions::default()
};
let roxmltree = roxmltree::Document::parse_with_options(text, options)
.unwrap_err()
.to_string();
assert_eq!(
einvoice_xml::check(text).unwrap_err().to_string(),
roxmltree
);
roxmltree
}
fn svrl_name(local: &str) -> QName {
QName {
prefix: Some("svrl".to_owned()),
namespace: Some(SVRL_NS.to_owned()),
local: local.to_owned(),
}
}
#[test]
fn refuses_what_is_not_svrl() {
assert_eq!(
findings("<a/>", false).unwrap_err(),
"the root is not svrl:schematron-output"
);
for text in ["<a", ""] {
assert_eq!(
findings(text, false).unwrap_err(),
parser_error(text),
"{text}"
);
}
let root = svrl_name("schematron-output");
let mut reader = SvrlReader::default();
for _ in 0..2 {
reader.start_element(&root, &[]);
reader.end_element();
}
let text = format!("<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"/><a/>");
assert_eq!(
reader.finish(&CompactOutput::from(text.as_str())),
Err(parser_error(&text))
);
for comment in ["x -- y", "x-"] {
let mut reader = SvrlReader::default();
reader.start_element(&root, &[]);
reader.comment(comment);
reader.end_element();
let text = format!(
"<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"><!--{comment}--></svrl:schematron-output>"
);
assert_eq!(
reader.finish(&CompactOutput::from(text.as_str())),
Err(parser_error(&text)),
"{comment}"
);
}
let mut reader = SvrlReader::default();
for _ in 0..2 {
reader.start_element(&root, &[]);
reader.end_element();
}
assert_eq!(
reader.finish(&CompactOutput::from("<a/>")).unwrap_err(),
"2 elements at the top of the document, instead of one"
);
}
#[test]
fn severities() {
assert_eq!(Severity::from_flag(Some("fatal")), Severity::Fatal);
assert_eq!(Severity::from_flag(Some("warning")), Severity::Warning);
assert_eq!(Severity::from_flag(Some("information")), Severity::Other);
assert_eq!(Severity::from_flag(None), Severity::Other);
assert_eq!(
Severity::from_flag_fail_closed(Some("fatal")),
Severity::Fatal
);
assert_eq!(
Severity::from_flag_fail_closed(Some("warning")),
Severity::Warning
);
assert_eq!(
Severity::from_flag_fail_closed(Some("information")),
Severity::Fatal
);
assert_eq!(Severity::from_flag_fail_closed(None), Severity::Fatal);
}
#[test]
fn severities_of_a_stylesheet() {
use FindingKind::{FailedAssert as A, SuccessfulReport as R};
let manifest = "format = 2\nname = \"n\"\ntitle = \"t\"\nversion = \"1\"\n\n[[stylesheet]]\nname = \"s\"\npath = \"s.xsl\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n\n[[scenario]]\nname = \"x\"\nnamespace = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"\nroot = \"Invoice\"\nidentifier = \"urn:x\"\nfatal = \"UP\"\nother = \"DOWN\"\n";
let rule_set = crate::RuleSet::parse(manifest).unwrap();
let scenario = rule_set.scenarios().first();
let findings = [
(A, Some("fatal"), Some("R")),
(A, Some("warning"), Some("R")),
(A, Some("information"), Some("R")),
(A, None, Some("R")),
(A, None, None),
(R, None, Some("R")),
(R, Some("fatal"), None),
(A, Some("warning"), Some("UP")),
(R, None, Some("UP")),
(A, Some("fatal"), Some("DOWN")),
(A, None, Some("DOWN")),
];
let severities = |severities: Severities<'_>| -> Vec<&str> {
findings
.iter()
.map(|(kind, flag, id)| severities.of(*kind, *flag, *id).as_str())
.collect()
};
let base = Severities::default();
assert_eq!(
severities(base),
[
"fatal", "warning", "other", "other", "other", "other", "fatal", "warning",
"other", "fatal", "other"
]
);
let unflagged = Severities {
unflagged_assert: Severity::Fatal,
..base
};
assert_eq!(
severities(unflagged),
[
"fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "warning",
"other", "fatal", "fatal"
]
);
let with_scenario = Severities {
scenario,
..unflagged
};
assert_eq!(
severities(with_scenario),
[
"fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "fatal", "fatal",
"other", "other"
]
);
let closed = Severities {
fail_closed: true,
..with_scenario
};
assert_eq!(
severities(closed),
[
"fatal", "warning", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal",
"fatal", "fatal"
]
);
}
}