#![cfg(feature = "cgmes3")]
mod common;
use cim_kit::cgmes3::SCHEMA;
use cim_kit::prelude::*;
use cim_kit::reader::read_into;
const VALID: &str = r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:eu="http://iec.ch/TC57/CIM100-European#"
xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<md:FullModel rdf:about="urn:uuid:11111111-1111-4111-8111-111111111111">
<md:Model.scenarioTime>2021-03-25T15:30:00Z</md:Model.scenarioTime>
<md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
<md:Model.DependentOn rdf:resource="urn:uuid:22222222-2222-4222-8222-222222222222"/>
</md:FullModel>
<cim:ACLineSegment rdf:ID="_33333333-3333-4333-8333-333333333333">
<cim:IdentifiedObject.name>Line</cim:IdentifiedObject.name>
<cim:ACLineSegment.r>1.5</cim:ACLineSegment.r>
<eu:IdentifiedObject.shortName>L</eu:IdentifiedObject.shortName>
</cim:ACLineSegment>
<cim:Terminal rdf:ID="_44444444-4444-4444-8444-444444444444">
<cim:Terminal.ConductingEquipment rdf:resource="#_33333333-3333-4333-8333-333333333333"/>
<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode.ABC"/>
</cim:Terminal>
<cim:Location rdf:ID="_55555555-5555-4555-8555-555555555555">
<cim:Location.mainAddress rdf:parseType="Resource">
<cim:StreetAddress.postalCode>1000</cim:StreetAddress.postalCode>
<cim:StreetAddress.townDetail rdf:parseType="Resource">
<cim:TownDetail.name>Brussels</cim:TownDetail.name>
</cim:StreetAddress.townDetail>
</cim:Location.mainAddress>
</cim:Location>
</rdf:RDF>"##;
#[must_use]
fn exercise(bytes: &[u8]) -> usize {
let mut succeeded = 0;
for options in [ReadOptions::lenient(), ReadOptions::strict()] {
let mut ds = Dataset::new(SCHEMA);
let Ok(outcome) = read_into(&mut ds, bytes, Some("fuzz.xml"), &options) else {
continue;
};
succeeded += 1;
let _ = cim_kit::validate::validate(&ds);
let _ = ds.dangling_references();
let _ = cim_kit::InverseIndex::build(&ds);
let _ = cim_kit::validate::profile_coverage(&ds);
for (id, o) in ds.iter() {
assert!(ds.get(id).is_some());
assert!(
ds.by_mrid(o.mrid()).is_some(),
"index disagrees with storage"
);
for slot in o.slots() {
let def = SCHEMA.attr(slot.attr);
assert!(
SCHEMA.class(o.class()).all_attrs.contains(&slot.attr),
"{} stored on {} which does not have it",
def.name,
SCHEMA.class(o.class()).name
);
}
}
let mut buf = Vec::new();
if cim_kit::writer::write(&ds, &mut buf, &WriteOptions::default()).is_ok() {
let text = String::from_utf8(buf.clone())
.expect("the writer must produce UTF-8, whatever it was given");
if let Err(e) = common::check_well_formed(&text) {
panic!("a mutated document produced output that is not well-formed XML: {e}");
}
let mut back = Dataset::new(SCHEMA);
let again = read_into(&mut back, buf.as_slice(), None, &ReadOptions::lenient())
.expect("the writer must produce readable output");
assert!(
!again.report.has_errors(),
"re-reading our own output produced errors:\n{}",
again.report
);
assert_eq!(back.len(), ds.len(), "round-trip changed the object count");
}
if let Some(diff) = outcome.difference {
let mut copy = Dataset::new(SCHEMA);
let _ = read_into(&mut copy, bytes, None, &ReadOptions::lenient());
let _ = copy.apply_difference(&diff);
}
}
succeeded
}
#[test]
fn pathological_documents_do_not_panic() {
let cases: &[(&str, &str)] = &[
("empty", ""),
("whitespace", " \n\t "),
("not xml", "hello world"),
("declaration only", r#"<?xml version="1.0"?>"#),
("unclosed root", "<rdf:RDF>"),
("unclosed element", "<rdf:RDF><cim:Terminal"),
(
"no namespaces",
"<rdf:RDF><cim:Terminal rdf:ID=\"_x\"/></rdf:RDF>",
),
("wrong root", "<html><body>not cim</body></html>"),
(
"root without namespace declarations",
r#"<rdf:RDF><md:FullModel rdf:about="urn:uuid:1"/></rdf:RDF>"#,
),
(
"object without identifier",
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:Terminal><cim:IdentifiedObject.name>x</cim:IdentifiedObject.name></cim:Terminal></rdf:RDF>"##,
),
(
"deeply nested",
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:Terminal rdf:ID="_a"><cim:IdentifiedObject.name><b><c><d>x</d></c></b></cim:IdentifiedObject.name></cim:Terminal></rdf:RDF>"##,
),
(
"attribute without an object",
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:ACLineSegment.r>1.0</cim:ACLineSegment.r></rdf:RDF>"##,
),
(
"difference with no statements",
r##"<rdf:RDF xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<dm:DifferenceModel rdf:about="urn:uuid:1"><dm:forwardDifferences rdf:parseType="Statements"/></dm:DifferenceModel></rdf:RDF>"##,
),
(
"self-referencing object",
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:Terminal rdf:ID="_55555555-5555-4555-8555-555555555555">
<cim:Terminal.ConductingEquipment rdf:resource="#_55555555-5555-4555-8555-555555555555"/>
</cim:Terminal></rdf:RDF>"##,
),
(
"duplicate attribute on a single-valued field",
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:ACLineSegment rdf:ID="_a"><cim:ACLineSegment.r>1</cim:ACLineSegment.r>
<cim:ACLineSegment.r>2</cim:ACLineSegment.r></cim:ACLineSegment></rdf:RDF>"##,
),
("valid", VALID),
];
for (name, src) in cases {
println!("case: {name}");
let _ = exercise(src.as_bytes());
}
assert_eq!(
exercise(VALID.as_bytes()),
2,
"the valid document did not read"
);
}
#[test]
fn truncation_at_every_byte_boundary_does_not_panic() {
let bytes = VALID.as_bytes();
let mut readable = 0;
for cut in 0..bytes.len() {
readable += exercise(&bytes[..cut]);
}
assert!(
readable > 50,
"only {readable} truncations parsed; the campaign is not reaching the model"
);
}
#[test]
fn single_byte_corruption_does_not_panic() {
let original = VALID.as_bytes();
let mut readable = 0;
let mut cases = 0;
for replacement in [b'<', b'>', b'"', b'&', b'/', 0x00, 0xff] {
for i in (0..original.len()).step_by(7) {
let mut bytes = original.to_vec();
bytes[i] = replacement;
readable += exercise(&bytes);
cases += 1;
}
}
println!("{cases} corruptions, {readable} still readable");
assert!(readable > cases / 4, "too few corruptions produced a model");
}
#[test]
fn deletion_of_each_region_does_not_panic() {
let original = VALID.as_bytes();
let chunk = 16;
for start in (0..original.len()).step_by(chunk) {
let end = (start + chunk).min(original.len());
let mut bytes = Vec::with_capacity(original.len());
bytes.extend_from_slice(&original[..start]);
bytes.extend_from_slice(&original[end..]);
let _ = exercise(&bytes);
}
}
#[test]
fn pathological_sizes_are_handled() {
let long_value = "x".repeat(1 << 16);
let doc = format!(
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:ACLineSegment rdf:ID="_66666666-6666-4666-8666-666666666666">
<cim:IdentifiedObject.name>{long_value}</cim:IdentifiedObject.name>
</cim:ACLineSegment>
</rdf:RDF>"##
);
assert_eq!(exercise(doc.as_bytes()), 2, "a long value must still read");
let long_name = "A".repeat(4096);
let doc = format!(
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:{long_name} rdf:ID="_a"/>
</rdf:RDF>"##
);
let _ = exercise(doc.as_bytes());
let mut repeated = String::from(
r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:Diagram rdf:ID="_77777777-7777-4777-8777-777777777777">"##,
);
for i in 0..5000 {
repeated.push_str(&format!(
"<cim:IdentifiedObject.name>n{i}</cim:IdentifiedObject.name>"
));
}
repeated.push_str("</cim:Diagram></rdf:RDF>");
assert_eq!(
exercise(repeated.as_bytes()),
2,
"many repetitions must still read"
);
}
#[test]
fn invalid_utf8_is_an_error_not_a_panic() {
let mut bytes = VALID.as_bytes().to_vec();
if let Some(pos) = VALID.find("Line") {
bytes[pos] = 0x80;
}
let _ = exercise(&bytes);
let _ = exercise(&[0xff, 0xfe, 0xfd, 0x00, 0x80, 0x81]);
}
fn read_lenient(doc: &str, options: &ReadOptions) -> (Dataset, cim_kit::Report) {
let mut ds = Dataset::new(SCHEMA);
let outcome = read_into(&mut ds, doc.as_bytes(), Some("probe.xml"), options).expect("read");
(ds, outcome.report)
}
fn wrap(body: &str) -> String {
format!(
r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
{body}
</rdf:RDF>"##
)
}
#[test]
fn markup_nested_inside_a_value_does_not_become_the_value() {
let doc = wrap(
r##" <cim:ACLineSegment rdf:ID="_33333333-3333-4333-8333-333333333333">
<cim:IdentifiedObject.name><vendor:tag xmlns:vendor="http://v/">ignored</vendor:tag></cim:IdentifiedObject.name>
<cim:IdentifiedObject.description>kept</cim:IdentifiedObject.description>
</cim:ACLineSegment>"##,
);
let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
let o = ds
.by_mrid(&Mrid::parse("33333333-3333-4333-8333-333333333333"))
.expect("the line");
assert_eq!(
o.get(cim_kit::cgmes3::attributes::identified_object::name)
.and_then(|v| v.as_str()),
Some(""),
"the nested element's text is not the value"
);
assert_eq!(
o.get(cim_kit::cgmes3::attributes::identified_object::description)
.and_then(|v| v.as_str()),
Some("kept")
);
assert!(
report
.by_rule(cim_kit::Rule::Structure)
.any(|d| d.message.contains("inside a value")),
"the deviation is reported: {report}"
);
}
#[test]
fn objects_without_an_identifier_do_not_collapse_into_one() {
let doc = wrap(
r##" <cim:ACLineSegment>
<cim:IdentifiedObject.name>first</cim:IdentifiedObject.name>
</cim:ACLineSegment>
<cim:Terminal>
<cim:IdentifiedObject.name>second</cim:IdentifiedObject.name>
</cim:Terminal>"##,
);
let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
assert_eq!(ds.len(), 2, "two elements, two objects");
let mut names: Vec<&str> = ds
.iter()
.filter_map(|(_, o)| {
o.get(cim_kit::cgmes3::attributes::identified_object::name)?
.as_str()
})
.collect();
names.sort_unstable();
assert_eq!(names, ["first", "second"]);
assert!(ds.iter().all(|(_, o)| !o.mrid().is_uuid()));
assert_eq!(report.by_rule(cim_kit::Rule::Structure).count(), 2);
}
#[test]
fn the_report_a_broken_document_produces_is_bounded() {
let mut body = String::new();
for i in 0..5_000 {
body.push_str(&format!(" <cim:NoSuchClass{i}/>\n"));
}
let doc = wrap(&body);
let (_, capped) = read_lenient(&doc, &ReadOptions::lenient().with_max_diagnostics(100));
assert_eq!(capped.len(), 101, "100 findings plus the note that says so");
assert!(
capped
.iter()
.last()
.is_some_and(|d| d.message.contains("stopped recording")),
"the truncation is stated rather than silent"
);
let (_, all) = read_lenient(&doc, &ReadOptions::lenient().with_max_diagnostics(0));
assert_eq!(all.len(), 5_000);
}
#[test]
fn declared_and_external_entities_are_never_expanded() {
let doc = r##"<?xml version="1.0"?>
<!DOCTYPE rdf:RDF [
<!ENTITY a "aaaaaaaaaa">
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
<!ENTITY secret SYSTEM "file:///etc/passwd">
]>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:ACLineSegment rdf:ID="_66666666-6666-4666-8666-666666666666">
<cim:IdentifiedObject.name>&d;|&secret;</cim:IdentifiedObject.name>
<cim:ConductingEquipment.BaseVoltage rdf:resource="#_&secret;"/>
</cim:ACLineSegment>
</rdf:RDF>"##;
let (ds, report) = read_lenient(doc, &ReadOptions::lenient());
let line = ds
.find(&Mrid::parse("_66666666-6666-4666-8666-666666666666"))
.and_then(|id| ds.get(id))
.expect("the line is read");
let name = line.get(cim_kit::cgmes3::names::attributes::identified_object::name);
assert_eq!(
name.and_then(Value::as_str),
Some("&d;|&secret;"),
"the references stay text"
);
let unexpanded: Vec<_> = report
.iter()
.filter(|d| d.message.contains("entity"))
.collect();
assert_eq!(
unexpanded.len(),
3,
"each undefined reference — two in text, one in an attribute — is reported: {report:?}"
);
}
fn padded(id: &str, size: usize) -> String {
let head = wrap(&format!(
r#"<cim:ACLineSegment rdf:ID="_{id}"><cim:IdentifiedObject.name>x</cim:IdentifiedObject.name></cim:ACLineSegment>
<!--"#
));
let (open, close) = head.split_at(head.rfind("</rdf:RDF>").unwrap());
let fill = size.saturating_sub(head.len() + 3);
format!("{open}{}-->\n{close}", " ".repeat(fill))
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cim-robust-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn too_large(e: &cim_kit::Error) -> (u64, u64) {
match e {
cim_kit::Error::InputTooLarge { limit, read, .. } => (*limit, *read),
other => panic!("expected InputTooLarge, got {other:?}"),
}
}
#[test]
fn the_default_budget_is_two_gibibytes() {
assert_eq!(ReadOptions::default().max_input_bytes, 2 << 30);
assert_eq!(ReadOptions::strict().max_input_bytes, 2 << 30);
}
#[test]
fn a_document_over_the_budget_is_refused() {
const MIB: u64 = 1 << 20;
let doc = padded("77777777-7777-4777-8777-777777777777", 2 << 20);
let mut ds = Dataset::new(SCHEMA);
let options = ReadOptions::lenient().with_max_input_bytes(MIB);
let err = read_into(&mut ds, doc.as_bytes(), Some("big.xml"), &options).unwrap_err();
let (limit, read) = too_large(&err);
assert_eq!(limit, MIB);
assert!(
read > MIB && read <= MIB + (64 << 10),
"overshoot is one buffer, not the file: {read}"
);
assert!(err.to_string().contains("big.xml"), "{err}");
assert!(err.to_string().contains("with_max_input_bytes"), "{err}");
let mut ds = Dataset::new(SCHEMA);
read_into(
&mut ds,
doc.as_bytes(),
None,
&options.clone().with_max_input_bytes(0),
)
.expect("an unlimited read takes it all");
assert_eq!(ds.len(), 1);
}
#[test]
fn a_directory_shares_one_budget_and_leniency_does_not_hide_it() {
let dir = scratch("budget-dir");
for (i, id) in ["11", "22", "33"].iter().enumerate() {
let id = format!("{id}{id}{id}{id}{id}{id}{id}{id}-1111-4111-8111-111111111111");
std::fs::write(dir.join(format!("{i}_EQ.xml")), padded(&id, 400 << 10)).unwrap();
}
let options = ReadOptions::lenient().with_max_input_bytes(1 << 20);
let mut ds = Dataset::new(SCHEMA);
let err = ds
.load_files(cim_kit::instance_files(&dir), &options)
.expect_err("the third file exceeds the shared budget");
too_large(&err);
assert!(
err.to_string().contains("2_EQ.xml"),
"names the file it stopped in: {err}"
);
let mut one = Dataset::new(SCHEMA);
one.load_file(&dir.join("0_EQ.xml"), &options)
.expect("one file fits");
}
#[test]
#[cfg(feature = "zip")]
fn an_archive_is_charged_its_decompressed_bytes_whatever_it_declares() {
use std::io::Write as _;
let dir = scratch("budget-zip");
let path = dir.join("bomb.zip");
let inflated = padded("88888888-8888-4888-8888-888888888888", 64 << 20);
{
let mut zw = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
zw.start_file(
"EQ.xml",
zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated),
)
.unwrap();
zw.write_all(inflated.as_bytes()).unwrap();
zw.finish().unwrap();
}
let compressed = std::fs::metadata(&path).unwrap().len();
assert!(
compressed < 1 << 20,
"a real bomb: {compressed} bytes on disk"
);
let options = ReadOptions::lenient().with_max_input_bytes(1 << 20);
let mut ds = Dataset::new(SCHEMA);
let err = ds.load_file(&path, &options).unwrap_err();
let (_, read) = too_large(&err);
assert!(
read <= (1 << 20) + (64 << 10),
"stopped at the budget: {read}"
);
let mut bytes = std::fs::read(&path).unwrap();
for (signature, offset) in [(0x0403_4b50_u32, 22), (0x0201_4b50_u32, 24)] {
let at = bytes
.windows(4)
.position(|w| w == signature.to_le_bytes())
.expect("header present");
bytes[at + offset..at + offset + 4].copy_from_slice(&1024_u32.to_le_bytes());
}
let lying = dir.join("lying.zip");
std::fs::write(&lying, bytes).unwrap();
let mut ds = Dataset::new(SCHEMA);
let err = ds
.load_file(&lying, &options)
.expect_err("a declared kilobyte that inflates to 64 MiB is refused");
match &err {
cim_kit::Error::InputTooLarge { read, .. } => assert_eq!(*read, (1 << 20) + 1),
cim_kit::Error::Zip(m) => assert!(m.contains("EQ.xml") && m.contains("declared"), "{m}"),
other => panic!("expected the budget or the archive to refuse it, got {other:?}"),
}
assert!(
ds.len() <= 1,
"nothing past the declared kilobyte was taken as model"
);
}
#[test]
fn sniffing_reads_a_bounded_prefix() {
let declared = |pad: usize| {
format!(
"<?xml version=\"1.0\"?>\n<!--{}-->\n<rdf:RDF xmlns:cim=\"http://iec.ch/TC57/CIM100#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"/>",
" ".repeat(pad)
)
};
let near = cim_kit::reader::sniff(declared(1000).as_bytes()).unwrap();
assert!(near.is_some(), "a root in the first MiB is found");
let far = cim_kit::reader::sniff(declared(2 << 20).as_bytes()).unwrap();
assert!(far.is_none(), "a root past the first MiB is not looked for");
}