cim-kit 0.6.0

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! The reader must never panic, whatever bytes it is given.
//!
//! `cargo fuzz` needs a nightly toolchain, so the targets under `fuzz/` are not part of
//! the ordinary test run. This file exercises the same contract deterministically on
//! stable: a corpus of hand-written pathological documents, plus systematic mutation of
//! valid ones. It runs on every `cargo test`, so a regression cannot reach a release
//! unnoticed even if nobody has run the fuzzer lately.

#![cfg(feature = "cgmes3")]

mod common;

use cim_kit::cgmes3::SCHEMA;
use cim_kit::error::Rule;
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>"##;

/// Read `bytes` under both strictness settings and exercise everything downstream.
///
/// Any panic here is a bug: the documented contract is an error or a model plus
/// diagnostics, never a crash.
///
/// Returns how many of the two reads succeeded, so a caller can assert that a mutation
/// campaign is still reaching the code past the parser rather than erroring out early.
#[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;

        // Everything the API promises about a successfully read dataset must hold.
        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() {
                // Every stored attribute id must be one the schema defines, and must be
                // reachable from the object's class.
                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
                );
            }
        }

        // Whatever was read must be writable, and our own output must be readable.
        let mut buf = Vec::new();
        if cim_kit::writer::write(&ds, &mut buf, &WriteOptions::default()).is_ok() {
            // Re-reading with *our* reader is the weaker half of this, and on its own it
            // is the blind spot the well-formedness gate had: a tolerant reader accepting
            // its own output says nothing about anyone else's parser. This campaign is
            // where that matters most — it is the only place that generates untidy input
            // deliberately, so it is the only place a writer defect against untidy input
            // can show up at all.
            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 {
        // A panic in `exercise` fails the test and names the case.
        println!("case: {name}");
        let _ = exercise(src.as_bytes());
    }
    // The valid document must actually be readable, or the corpus proves nothing.
    assert_eq!(
        exercise(VALID.as_bytes()),
        2,
        "the valid document did not read"
    );
}

#[test]
fn every_truncation_is_refused_and_leaves_the_dataset_as_it_was() {
    // Truncation is the failure mode of a stream that dies mid-transfer, and it reaches
    // every parser state in turn. The document ends at `>`, so no proper prefix is a
    // complete document, and none may read: a partial model must never pass as one.
    let bytes = VALID.as_bytes();
    let root = VALID.find("<rdf:RDF").unwrap();
    // The dataset already holds a model; a failed read must not touch it.
    let base = TERMINAL_ONLY.as_bytes();
    for options in [ReadOptions::lenient(), ReadOptions::strict()] {
        let mut ds = Dataset::new(SCHEMA);
        read_into(&mut ds, base, Some("base.xml"), &options).unwrap();
        let before = fingerprint(&ds);
        for cut in 0..bytes.len() {
            let err = read_into(&mut ds, &bytes[..cut], Some("cut.xml"), &options)
                .expect_err("a truncated document was read as complete");
            if cut > root {
                assert!(
                    matches!(err, cim_kit::Error::Truncated { .. }),
                    "cut at {cut}: {err}"
                );
            }
            assert_eq!(
                fingerprint(&ds),
                before,
                "cut at {cut} left something behind"
            );
        }
        // And the whole document still reads.
        read_into(&mut ds, bytes, Some("cut.xml"), &options).unwrap();
        assert_eq!(ds.headers().len(), 2);
    }
}

/// A small model to read truncations into.
const TERMINAL_ONLY: &str = 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="_44444444-4444-4444-8444-444444444444">
    <cim:IdentifiedObject.name>T1</cim:IdentifiedObject.name>
  </cim:Terminal>
</rdf:RDF>"##;

/// Everything a read can change about a dataset, compared as text.
fn fingerprint(ds: &Dataset) -> String {
    let mut out = format!(
        "{} objects, {} headers, {} differences, {} conflicts\n",
        ds.len(),
        ds.headers().len(),
        ds.differences().len(),
        ds.merge_conflicts().len()
    );
    for (_, o) in ds.iter() {
        out.push_str(&format!(
            "{} {:?}\n",
            o.mrid(),
            o.values().collect::<Vec<_>>()
        ));
    }
    out
}

#[test]
fn single_byte_corruption_does_not_panic() {
    // Walk one corrupting byte through the document. This reaches malformed tags,
    // broken entities, invalid UTF-8 and truncated attribute values without needing a
    // fuzzer's randomness, and it is fully deterministic.
    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() {
    // A very long attribute value, a very long element name, and many repetitions of one
    // attribute: each stresses a different growth path.
    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();
    // Splice an invalid continuation byte into element text.
    if let Some(pos) = VALID.find("Line") {
        bytes[pos] = 0x80;
    }
    let _ = exercise(&bytes);

    // A document that is entirely invalid UTF-8.
    let _ = exercise(&[0xff, 0xfe, 0xfd, 0x00, 0x80, 0x81]);
}

// ---------------------------------------------------------------------------
// Deviations a malformed document produces that a valid one never does
// ---------------------------------------------------------------------------

/// Read `doc` leniently and hand back the model and what the reader had to say.
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>"##
    )
}

/// A value is the text of its own element and of no other.
///
/// IEC 61970-552 property elements hold text, one `rdf:resource`, or an inline compound —
/// never mixed content, so nesting markup inside a value is malformed. The nested element is
/// skipped with its content rather than donating its text: `<name><x>ignored</x></name>` is
/// an empty name, not `ignored`.
#[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"
    );
    // The property still ends at its own tag, so what follows it is read normally.
    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}"
    );
}

/// Objects with no identifier at all are still distinct objects.
///
/// Giving them all the same empty identifier merged them into one, so the later one's
/// values overwrote the earlier one's — under a class they need not even share.
#[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"]);

    // Nothing is invented: the stand-in is opaque, not a plausible-looking UUID, so every
    // later check still sees that the document was wrong.
    assert!(ds.iter().all(|(_, o)| !o.mrid().is_uuid()));
    assert_eq!(report.by_rule(cim_kit::Rule::Structure).count(), 2);
}

/// A lenient read answers a broken document with a diagnostic per problem, so the report
/// grows with how broken the input is. Past the cap it stops growing and says so.
#[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"
    );

    // Zero means no limit, for a caller that wants every finding.
    let (_, all) = read_lenient(&doc, &ReadOptions::lenient().with_max_diagnostics(0));
    assert_eq!(all.len(), 5_000);
}

// ---------------------------------------------------------------------------
// Entities: never expanded, never fetched, never silent
// ---------------------------------------------------------------------------

/// A DOCTYPE's entities are not definitions this reader honours: IEC 61970-552 documents
/// declare no DTD, so an internal subset is either a mistake or an attack — the billion
/// laughs, or an external entity naming a local file. Neither may expand, and since
/// keeping the reference literally is a tolerance, each one is reported.
///
/// Pins baseline SR-003. It holds today because quick-xml does not process DTDs; this is
/// what notices if an upgrade ever starts to.
#[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:?}"
    );
}

// ---------------------------------------------------------------------------
// The input budget
// ---------------------------------------------------------------------------

/// A document of `size` bytes whose padding is a comment, so it is a valid model of one
/// object however large it is made.
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))
}

/// A scratch directory for one test, removed and recreated on entry.
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:?}"),
    }
}

/// The default is a number the documentation states, so it is a number a test asserts.
#[test]
fn the_default_budget_is_eight_gibibytes() {
    assert_eq!(ReadOptions::default().max_input_bytes, 8 << 30);
    assert_eq!(ReadOptions::strict().max_input_bytes, 8 << 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}");

    // Zero is no limit, as for `max_diagnostics`.
    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);
}

/// One budget per load, not per file: three files that each fit are one model that does
/// not. And lenient loading, which turns an unreadable file into a `CIM0022` and carries
/// on, must not do that here — what it would carry on with is part of a model.
#[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}"
    );

    // Each file alone is well inside it.
    let mut one = Dataset::new(SCHEMA);
    one.load_file(&dir.join("0_EQ.xml"), &options)
        .expect("one file fits");
}

/// A decompression bomb: a small archive whose entry inflates far past the budget. What is
/// counted is what the parser receives, so the archive's own size fields — which its
/// author writes — are never consulted. The second half makes them lie.
#[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}"
    );

    // Now under-declare the entry's size in both the local header and the central
    // directory. The budget is charged what the parser receives, so the lie changes
    // nothing.
    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();
    // zip itself refuses an entry that inflates past its declared size, before the budget
    // is reached; either way the lie buys nothing, and it is reported as what it is — a
    // broken archive, naming the entry — rather than as malformed XML.
    // Lenient, the entry is one unreadable file of the set: reported, named, and nothing
    // of it in the model.
    let mut ds = Dataset::new(SCHEMA);
    let load = ds.load_file(&lying, &options).unwrap();
    let d = load
        .report
        .by_rule(cim_kit::Rule::UnreadableFile)
        .next()
        .expect("reported");
    assert!(
        d.message.contains("EQ.xml") && d.message.contains("declared"),
        "{d}"
    );
    assert_eq!(load.failed, [lying.join("EQ.xml")]);
    assert_eq!(ds.len(), 0, "nothing of a refused entry was taken as model");
    // Strict, the load fails.
    let mut ds = Dataset::new(SCHEMA);
    let err = ds
        .load_file(&lying, &ReadOptions::strict().with_max_input_bytes(1 << 20))
        .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_eq!(ds.len(), 0);
}

/// Sniffing reads the first MiB and no more: `detect_vintage` sniffs every file of a set
/// before loading any, so an unbounded sniff would be a second, uncounted pass.
#[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");
}

// ---------------------------------------------------------------------------
// Namespace scope
// ---------------------------------------------------------------------------

const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

/// The read's error under both strictness settings, which must agree.
fn refused(doc: &str) -> cim_kit::Error {
    let mut errors = [ReadOptions::lenient(), ReadOptions::strict()].map(|options| {
        let mut ds = Dataset::new(SCHEMA);
        let err = read_into(&mut ds, doc.as_bytes(), Some("ns.xml"), &options)
            .expect_err("a namespace error must fail the read");
        assert_eq!(ds.len(), 0);
        err
    });
    let [lenient, strict] = &mut errors;
    assert_eq!(lenient.to_string(), strict.to_string());
    errors.into_iter().next().unwrap()
}

#[test]
fn a_declaration_does_not_reach_the_elements_siblings() {
    // FMS commissioning, against 0.5.1: the second element read as an ACLineSegment.
    let doc = format!(
        r#"<rdf:RDF xmlns:rdf="{RDF}">
  <x:ACLineSegment xmlns:x="http://iec.ch/TC57/CIM100#" rdf:ID="_11111111-1111-4111-8111-111111111111"/>
  <x:ACLineSegment rdf:ID="_22222222-2222-4222-8222-222222222222"/>
</rdf:RDF>"#
    );
    let err = refused(&doc);
    assert!(matches!(err, cim_kit::Error::Xml { .. }), "{err:?}");
    let at = doc.rfind("<x:ACLineSegment").unwrap() as u64;
    assert_eq!(err.position(), Some(at), "{err}");
    let text = err.to_string();
    assert!(
        text.contains("prefix x") && text.contains("ns.xml"),
        "{text}"
    );
}

#[test]
fn a_rebinding_ends_with_its_element() {
    // One object moves `cim` to another namespace for itself; the next is unaffected.
    let doc = format!(
        r#"<rdf:RDF xmlns:rdf="{RDF}" xmlns:cim="http://iec.ch/TC57/CIM100#">
  <cim:Vendor xmlns:cim="http://example.com/vendor#" rdf:ID="_11111111-1111-4111-8111-111111111111">
    <cim:Vendor.note>x</cim:Vendor.note>
  </cim:Vendor>
  <cim:ACLineSegment rdf:ID="_22222222-2222-4222-8222-222222222222"/>
  <cim:Terminal xmlns:cim="http://example.com/vendor#" rdf:ID="_33333333-3333-4333-8333-333333333333"/>
  <cim:Terminal rdf:ID="_44444444-4444-4444-8444-444444444444"/>
</rdf:RDF>"#
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
    // The vendor element and the self-closed vendor Terminal are unknown; the rest resolve.
    assert_eq!(ds.len(), 2, "{report}");
    assert_eq!(report.by_rule(Rule::UnknownClass).count(), 2, "{report}");
}

#[test]
fn an_undeclared_attribute_prefix_is_malformed() {
    let err = refused(&format!(
        r#"<rdf:RDF xmlns:rdf="{RDF}" xmlns:cim="http://iec.ch/TC57/CIM100#">
  <cim:Terminal y:foo="1" rdf:ID="_11111111-1111-4111-8111-111111111111"/>
</rdf:RDF>"#
    ));
    assert!(matches!(err, cim_kit::Error::Xml { .. }), "{err:?}");
    assert!(err.to_string().contains("y:foo"), "{err}");
}

#[test]
fn an_undeclared_prefix_is_malformed_even_where_the_reader_skips() {
    // Lenient skips an unknown class's subtree unread, but the document is still not
    // namespace-well-formed. (Strict refuses the class itself first.)
    let doc = format!(
        r#"<rdf:RDF xmlns:rdf="{RDF}" xmlns:cim="http://iec.ch/TC57/CIM100#">
  <cim:Unknown rdf:ID="_11111111-1111-4111-8111-111111111111"><z:a/></cim:Unknown>
</rdf:RDF>"#
    );
    let mut ds = Dataset::new(SCHEMA);
    let err = read_into(&mut ds, doc.as_bytes(), None, &ReadOptions::lenient()).unwrap_err();
    assert!(matches!(err, cim_kit::Error::Xml { .. }), "{err:?}");
}

#[test]
fn forbidden_declarations_are_malformed() {
    for decl in [
        r#"xmlns:p="""#,
        r#"xmlns:xml="http://example.com/""#,
        r#"xmlns:p="http://www.w3.org/XML/1998/namespace""#,
        r#"xmlns:xmlns="http://example.com/""#,
        r#"xmlns="http://www.w3.org/2000/xmlns/""#,
    ] {
        let err = refused(&format!(
            r#"<rdf:RDF xmlns:rdf="{RDF}"><rdf:Description {decl}/></rdf:RDF>"#
        ));
        assert!(matches!(err, cim_kit::Error::Xml { .. }), "{decl}: {err:?}");
    }
}

#[test]
fn the_reserved_and_default_namespaces_behave_as_xml_defines_them() {
    // `xml:` needs no declaration; `xmlns=""` undeclares the default namespace, so an
    // unprefixed element below it is in no namespace and merely unknown.
    let doc = format!(
        r#"<rdf:RDF xmlns:rdf="{RDF}" xmlns="http://iec.ch/TC57/CIM100#" xml:lang="en">
  <Terminal rdf:ID="_11111111-1111-4111-8111-111111111111"/>
  <Terminal xmlns="" rdf:ID="_22222222-2222-4222-8222-222222222222"/>
  <Terminal rdf:ID="_33333333-3333-4333-8333-333333333333"/>
</rdf:RDF>"#
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
    assert_eq!(ds.len(), 2, "{report}");
    assert_eq!(report.by_rule(Rule::UnknownClass).count(), 1, "{report}");
}

#[test]
fn an_undeclared_prefix_is_shown_escaped() {
    let err = refused(&format!(
        "<rdf:RDF xmlns:rdf=\"{RDF}\"><a\u{1b}[2J:b/></rdf:RDF>"
    ));
    let text = err.to_string();
    assert!(!text.contains('\u{1b}'), "{text:?}");
}

#[test]
fn declarations_on_a_wrapper_hold_for_the_document_inside_it() {
    let doc = format!(
        r#"<wrap xmlns:rdf="{RDF}" xmlns:cim="http://iec.ch/TC57/CIM100#">
<rdf:RDF>
  <cim:Terminal rdf:ID="_11111111-1111-4111-8111-111111111111"/>
</rdf:RDF>
</wrap>"#
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::strict());
    assert_eq!(ds.len(), 1, "{report}");
}

#[test]
fn a_character_xml_cannot_hold_is_removed_from_an_identifier_and_reported() {
    // Found by the `roundtrip` fuzz target: the identifier with U+0000 was kept, stripped
    // on write, and then collided with the real `_7fae…` in the output.
    let doc = format!(
        "<rdf:RDF xmlns:rdf=\"{RDF}\" xmlns:cim=\"http://iec.ch/TC57/CIM100#\">
  <cim:Terminal rdf:ID=\"_7fae7c9d-952f-4321-830d-aa667d21969d\"/>
  <cim:Terminal rdf:about=\"#_7fae7c9\u{0}d-952f-4321-830d-aa667d21969d\"/>
  <cim:Terminal rdf:ID=\"_baa7aef1-a\u{1e}cd-4981-97c0-ccec7b5ad4e0\"/>
</rdf:RDF>"
    );
    let (ds, report) = read_lenient(&doc, &ReadOptions::lenient());
    assert_eq!(
        report.by_rule(Rule::IllegalXmlCharacter).count(),
        2,
        "{report}"
    );
    assert!(
        ds.iter()
            .all(|(_, o)| !cim_kit::xml::has_illegal(&o.mrid().as_written()))
    );

    let mut out = Vec::new();
    cim_kit::writer::write(&ds, &mut out, &WriteOptions::default()).unwrap();
    let (back, report) = read_lenient(std::str::from_utf8(&out).unwrap(), &ReadOptions::lenient());
    assert!(!report.has_errors(), "{report}");
    assert_eq!(back.len(), ds.len());
}