grippo 0.2.2

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/format/xml/tests.rs
// Purpose:   The XML parser against a table of documents and the fields each writes
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use proptest::prelude::*;

use super::*;
use crate::parse::Fields;

type Rows = Vec<(String, String)>;

fn rows(out: &Fields<'_>) -> Rows {
    out.as_slice()
        .iter()
        .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
        .collect()
}

fn parsed(xml: &Xml, doc: &str) -> Rows {
    let mut out = Fields::new();
    let result = xml.parse(doc.as_bytes(), &mut out);
    assert_eq!(
        result.as_ref().ok(),
        Some(&Parsed::Done),
        "{doc}: {result:?}"
    );
    rows(&out)
}

fn want(pairs: &[(&str, &str)]) -> Rows {
    pairs
        .iter()
        .map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
        .collect()
}

const EVENT: &str = concat!(
    r#"<Event xmlns="http://schemas.example.com/event"><System>"#,
    r#"<EventID Qualifiers="0">4624</EventID><Computer>dc01</Computer></System>"#,
    r#"<EventData><Data Name="TargetUserName">alice</Data><Data Name="LogonType" x="1">3</Data>"#,
    r#"<Data>bare</Data><Data Name=" ">blank</Data></EventData></Event>"#,
);

#[test]
fn a_document_writes_the_fields_its_table_says() {
    let cases: &[(&str, &[(&str, &str)])] = &[
        ("<a/>", &[("a", "")]),
        ("<a></a>", &[("a", "")]),
        ("<a><!--c--></a>", &[("a", "")]),
        (r#"<a x="1"></a>"#, &[("a.@x", "1"), ("a", "")]),
        ("<a>t</a>", &[("a", "t")]),
        ("<a> t </a>", &[("a", " t ")]),
        ("<a><b/></a>", &[("a.b", "")]),
        ("<a> <b/> </a>", &[("a.b", "")]),
        ("<a> x <b/> y </a>", &[("a.b", ""), ("a", " x  y ")]),
        ("<a><![CDATA[ ]]></a>", &[("a", " ")]),
        ("<a><![CDATA[ ]]><b/></a>", &[("a.b", ""), ("a", " ")]),
        ("<a>1 &lt; 2 &#65;&#x42;</a>", &[("a", "1 < 2 AB")]),
        ("<a>x<![CDATA[<y>]]>z</a>", &[("a", "x<y>z")]),
        (
            r#"<a x="1 &amp; 2" y='q"'><b>1</b><b>2</b><c><d>3</d></c></a>"#,
            &[
                ("a.@x", "1 & 2"),
                ("a.@y", "q\""),
                ("a.b", "1"),
                ("a.b", "2"),
                ("a.c.d", "3"),
            ],
        ),
        (
            r#"<n:a xmlns:n="urn:x" n:k="v" xmlns="urn:y"><n:b>1</n:b></n:a>"#,
            &[("a.@k", "v"), ("a.b", "1")],
        ),
        (
            "\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- c -->\n<a>1</a>\n<?pi x?>\n",
            &[("a", "1")],
        ),
        (
            r#"<a.b x.y="1" z="2"><c.d>3</c.d><e/></a.b>"#,
            &[
                (r#"["a.b"]["@x.y"]"#, "1"),
                (r#"["a.b"].@z"#, "2"),
                (r#"["a.b"]["c.d"]"#, "3"),
                (r#"["a.b"].e"#, ""),
            ],
        ),
        (
            "<caf\u{e9} na\u{ef}ve=\"\u{fc}\">\u{e9}</caf\u{e9}>",
            &[("caf\u{e9}.@na\u{ef}ve", "\u{fc}"), ("caf\u{e9}", "\u{e9}")],
        ),
        (
            EVENT,
            &[
                ("Event.System.EventID.@Qualifiers", "0"),
                ("Event.System.EventID", "4624"),
                ("Event.System.Computer", "dc01"),
                ("Event.EventData.Data.@Name", "TargetUserName"),
                ("Event.EventData.Data", "alice"),
                ("Event.EventData.Data.@Name", "LogonType"),
                ("Event.EventData.Data.@x", "1"),
                ("Event.EventData.Data", "3"),
                ("Event.EventData.Data", "bare"),
                ("Event.EventData.Data.@Name", " "),
                ("Event.EventData.Data", "blank"),
            ],
        ),
    ];
    let xml = Xml::new();
    for (doc, fields) in cases {
        assert_eq!(parsed(&xml, doc), want(fields), "{doc}");
    }
}

#[test]
fn a_keyed_element_is_named_by_its_attribute() {
    let config = XmlParserConfig {
        keyed: vec![Keyed {
            path: "Event.EventData.Data".to_owned(),
            attribute: "Name".to_owned(),
        }],
    };
    let xml = Xml::with_config("xml:events", &config).unwrap();
    assert_eq!(xml.name(), "xml:events");
    assert_eq!(
        parsed(&xml, EVENT)[3..],
        want(&[
            ("Event.EventData.TargetUserName", "alice"),
            ("Event.EventData.LogonType.@x", "1"),
            ("Event.EventData.LogonType", "3"),
            ("Event.EventData.Data", "bare"),
            ("Event.EventData.Data.@Name", " "),
            ("Event.EventData.Data", "blank"),
        ])
    );
    // The key names the whole subtree, and a reference in it is resolved.
    let nested = r#"<Event><EventData><Data Name="a&amp;b"><v>1</v></Data></EventData></Event>"#;
    assert_eq!(
        parsed(&xml, nested),
        want(&[("Event.EventData.a&b.v", "1")])
    );
    // A key holding a dot is one key.
    let dotted = r#"<Event><EventData><Data Name="a.b"><v>1</v></Data></EventData></Event>"#;
    assert_eq!(
        parsed(&xml, dotted),
        want(&[(r#"Event.EventData["a.b"].v"#, "1")])
    );
    // A rule names an element holding a dot by its quoted name, in either spelling.
    for path in [r#"r["a.b"]"#, r#"["r"]["a.b"]"#] {
        let config = XmlParserConfig {
            keyed: vec![Keyed {
                path: path.to_owned(),
                attribute: "k".to_owned(),
            }],
        };
        let xml = Xml::with_config("xml", &config).unwrap();
        assert_eq!(
            parsed(&xml, r#"<r><a.b k="x">1</a.b><a><b k="y"/></a></r>"#),
            want(&[("r.x", "1"), ("r.a.b.@k", "y"), ("r.a.b", "")]),
            "{path}"
        );
    }

    // Only the attribute that named the element is left out, a namespace
    // declaration never names one, and a rule's path holds after a sibling
    // and inside a keyed element.
    let config = XmlParserConfig {
        keyed: vec![
            Keyed {
                path: "r.a".to_owned(),
                attribute: "k".to_owned(),
            },
            Keyed {
                path: "r.a.a".to_owned(),
                attribute: "p".to_owned(),
            },
        ],
    };
    let xml = Xml::with_config("xml", &config).unwrap();
    let doc = concat!(
        r#"<r><a k="one" n:k="two" xmlns:n="urn:n"><a xmlns:p="urn:p" p="in"/></a>"#,
        r#"<b><a k="no"/></b><a k="three"/></r>"#,
    );
    assert_eq!(
        parsed(&xml, doc),
        want(&[
            ("r.one.@k", "two"),
            ("r.one.in", ""),
            ("r.b.a.@k", "no"),
            ("r.b.a", ""),
            ("r.three", ""),
        ])
    );

    let rule = |path: &str, attribute: &str| Keyed {
        path: path.to_owned(),
        attribute: attribute.to_owned(),
    };
    let build = |name: &str, keyed: Vec<Keyed>| Xml::with_config(name, &XmlParserConfig { keyed });
    for (name, keyed, error) in [
        ("xml", vec![rule("a..b", "k")], "is empty"),
        ("xml", vec![rule(r#"a[""]"#, "k")], "is empty"),
        (
            "xml",
            vec![rule(r#"a["b"]"#, "k"), rule("a.b", "j")],
            "two keyed rules",
        ),
        ("xml", vec![rule("", "k")], "is empty"),
        ("xml", vec![rule("a", "")], "is empty"),
        (
            "xml",
            vec![rule("a", "k"), rule("a", "j")],
            "two keyed rules",
        ),
        ("json:x", vec![], "is not `xml`"),
        ("xml:Bad", vec![], "is not `xml`"),
    ] {
        let message = build(name, keyed).unwrap_err().to_string();
        assert!(message.contains(error), "{name}: {message}");
    }
}

#[test]
fn a_value_is_borrowed_unless_it_was_put_together() {
    let doc = r#"<a x="1" y="&amp;">t<b>1 &lt; 2</b><c><![CDATA[z]]></c><d> p <e/> q </d></a>"#;
    let mut out = Fields::new();
    Xml::new().parse(doc.as_bytes(), &mut out).unwrap();
    let input = doc.as_bytes().as_ptr_range();
    let mut borrowed = Vec::new();
    for (name, value) in out.as_slice() {
        if let Cow::Borrowed(bytes) = value.bytes {
            let span = bytes.as_ptr_range();
            assert!(
                bytes.is_empty() || (input.start <= span.start && span.end <= input.end),
                "{name}"
            );
            borrowed.push(name.as_str());
        }
    }
    assert_eq!(borrowed, ["a.@x", "a.c", "a.d.e", "a"]);
}

/// What a refused input comes to, and what stays true of the sink after it.
fn refused(xml: &Xml, input: &[u8]) -> Result<Parsed, ParseError> {
    let mut out = Fields::new();
    out.field("before", FieldValue::borrowed(b"kept", Hint::Text));
    let result = xml.parse(input, &mut out);
    out.field("probe", FieldValue::borrowed(b"", Hint::Text));
    let names: Vec<&str> = out.as_slice().iter().map(|(n, _)| n.as_str()).collect();
    assert_eq!(
        names,
        ["before", "probe"],
        "{:?}",
        String::from_utf8_lossy(input)
    );
    result
}

#[test]
fn what_is_not_a_document_is_no_match_and_a_broken_one_says_why() {
    let xml = Xml::new();
    for input in [
        &b""[..],
        b"plain",
        b"<",
        b"<1",
        b"<134>Oct 30 fw01 x",
        b" <a/>",
        b"\xEF\xBB\xBF",
        b"< a/>",
        b"{\"a\":1}",
    ] {
        assert_eq!(
            refused(&xml, input).ok(),
            Some(Parsed::NoMatch),
            "{input:?}"
        );
        assert!(!xml.signature().may_match(input), "{input:?}");
    }
    let cases: &[(&[u8], &str)] = &[
        (b"<a>", "never closed"),
        (b"<a></b>", "isn't well formed"),
        (b"<a/><b/>", "a second root"),
        (b"<a/>x", "text outside"),
        (b"<a/><![CDATA[y]]>", "text outside"),
        (b"<a/>&amp;", "text outside"),
        (b"<!DOCTYPE a><a/>", "DOCTYPE"),
        (b"<a>&nbsp;</a>", "reference"),
        (b"<a>&#0;</a>", "reference"),
        (b"<a>&#+65;</a>", "reference"),
        (b"<a>&#x+41;</a>", "reference"),
        (b"<a>&#x;</a>", "reference"),
        (b"<a x=\"&#-1;\"/>", "reference"),
        (b"<a x=\"&amp\"/>", "reference"),
        (b"<a x=\"&bogus;\"/>", "reference"),
        (b"<a xmlns:x=\"&bogus;\"/>", "reference"),
        (b"<a><b y=\"1\" x=\"&bogus;\"/></a>", "reference"),
        (b"<a x=\"1\" x=\"2\"/>", "attribute"),
        (b"<a x=1/>", "attribute"),
        (b"<?xml version=\"1.1\"?><a/>", "declaration"),
        (
            b"<?xml version=\"1.0\" encoding=\"UTF-16\"?><a/>",
            "declaration",
        ),
        (b"<a/><?xml version=\"1.0\"?>", "declaration"),
        (b"<!-- a -- b --><a/>", "isn't well formed"),
        (b"<!-- only a comment -->", "no root"),
        (b"<a>\xff</a>", "isn't UTF-8"),
        (b"<a><b>1</b>", "never closed"),
    ];
    for (input, reason) in cases {
        match refused(&xml, input) {
            Err(ParseError::Malformed {
                reason: got,
                offset,
            }) => {
                assert!(got.contains(reason), "{input:?}: {got}");
                assert!(offset <= input.len(), "{input:?}: {offset}");
            }
            other => panic!("{:?}: {other:?}", String::from_utf8_lossy(input)),
        }
        assert!(xml.signature().may_match(input), "{input:?}");
    }
}

#[test]
fn an_error_says_where_in_the_input_given() {
    let xml = Xml::new();
    for (input, offset) in [
        (&b"<a>&nbsp;</a>"[..], 3),
        (b"\xEF\xBB\xBF<a>&nbsp;</a>", 6),
        (b"<a><b x=\"&bogus;\"/></a>", 3),
        (b"<a>1</a><b/>", 8),
        (b"<a>\xff</a>", 3),
    ] {
        match refused(&xml, input) {
            Err(ParseError::Malformed { offset: got, .. }) => assert_eq!(got, offset, "{input:?}"),
            other => panic!("{input:?}: {other:?}"),
        }
    }
}

#[test]
fn depth_attributes_and_names_are_bounded() {
    let xml = Xml::new();
    let nest = |depth: usize| format!("{}x{}", "<a>".repeat(depth), "</a>".repeat(depth));
    assert_eq!(parsed(&xml, &nest(MAX_DEPTH)).len(), 1);
    let attributes = |count: usize| {
        let all = (0..count).fold(String::new(), |all, i| all + &format!(" k{i}=\"\""));
        format!("<a{all}/>")
    };
    assert_eq!(
        parsed(&xml, &attributes(MAX_ATTRIBUTES)).len(),
        MAX_ATTRIBUTES + 1
    );
    // A long path written two thousand times is far more name than document.
    let name = "n".repeat(20);
    let deep = format!(
        "{}{}{}",
        format!("<{name}>").repeat(60),
        "<x/>".repeat(2000),
        format!("</{name}>").repeat(60)
    );
    for (doc, what) in [
        (nest(MAX_DEPTH + 1), "depth"),
        (attributes(MAX_ATTRIBUTES + 1), "attributes"),
        (deep, "name bytes"),
    ] {
        match refused(&xml, doc.as_bytes()) {
            Err(ParseError::Limit { what: got }) => assert!(got.contains(what), "{got}"),
            other => panic!("{what}: {other:?}"),
        }
    }
}

fn element(depth: u32) -> BoxedStrategy<String> {
    let name = prop::sample::select(vec!["a", "b", "c", "item"]);
    let text = prop::sample::select(vec!["x", "two words", "1 &lt; 2", "\u{e9}t\u{e9}", "42"]);
    let attributes =
        prop::sample::subsequence(vec![" x=\"1\"", " y=\"a b\"", " z=\"&amp;\""], 0..=3)
            .prop_map(|chosen| chosen.concat());
    let leaf =
        (name.clone(), attributes.clone(), text).prop_map(|(n, a, t)| format!("<{n}{a}>{t}</{n}>"));
    if depth == 0 {
        return leaf.boxed();
    }
    // Children in name order, so repeats of a name sit together.
    let named = |kid: &str| kid[1..].split([' ', '>']).next().map(str::to_owned);
    let children = prop::collection::vec(element(depth - 1), 1..4).prop_map(move |mut kids| {
        kids.sort_by_key(|kid| named(kid));
        kids.join("\n  ")
    });
    let container =
        (name, attributes, children).prop_map(|(n, a, kids)| format!("<{n}{a}>\n  {kids}\n</{n}>"));
    prop_oneof![leaf, container].boxed()
}

/// A JSON object from `xml::to_json` as this parser's rows, by the one
/// mapping between the two: `@k` is `<path>.@k`, `#text` is `<path>`, a
/// child's array is its name written once a value.
#[cfg(feature = "xml")]
fn from_json(path: &str, value: &serde_json::Value, out: &mut Rows) {
    let serde_json::Value::Object(object) = value else {
        out.push((path.to_owned(), value.as_str().unwrap().to_owned()));
        return;
    };
    for (key, value) in object {
        match (key.as_str(), value) {
            ("_xml", _) => {}
            ("#text", text) => out.push((path.to_owned(), text.as_str().unwrap().to_owned())),
            (attribute, text) if attribute.starts_with('@') => {
                out.push((
                    format!("{path}.{attribute}"),
                    text.as_str().unwrap().to_owned(),
                ));
            }
            (child, serde_json::Value::Array(values)) => {
                for value in values {
                    from_json(&format!("{path}.{child}"), value, out);
                }
            }
            (other, value) => panic!("{other}: {value}"),
        }
    }
}

proptest! {
    /// Where `to_json` loses nothing this parser keeps, the two agree.
    #[cfg(feature = "xml")]
    #[test]
    fn the_parser_agrees_with_to_json_where_it_loses_nothing(doc in element(3)) {
        let json = crate::xml::to_json(doc.as_bytes(), &crate::xml::XmlConfig::default()).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&json).unwrap();
        let root = json["_xml"]["element"].as_str().unwrap().to_owned();
        let mut theirs = Rows::new();
        from_json(&root, &json, &mut theirs);
        let mut ours = parsed(&Xml::new(), &doc);
        theirs.sort();
        ours.sort();
        prop_assert_eq!(ours, theirs, "{}", doc);
    }

    /// A document with one byte changed never panics, and one that is
    /// refused leaves the sink and its prefixes as they were.
    #[test]
    fn a_damaged_document_is_refused_whole(
        doc in element(3),
        at in any::<prop::sample::Index>(),
        byte in any::<u8>(),
    ) {
        let mut bytes = doc.into_bytes();
        let at = at.index(bytes.len());
        bytes[at] = byte;
        let xml = Xml::new();
        let mut out = Fields::new();
        let result = xml.parse(&bytes, &mut out);
        if !matches!(result, Ok(Parsed::Done)) {
            prop_assert!(out.is_empty());
        }
        out.field("probe", FieldValue::borrowed(b"", Hint::Text));
        prop_assert_eq!(out.as_slice().last().unwrap().0.as_str(), "probe");
        let fired = xml.signature().may_match(&bytes);
        prop_assert!(fired || matches!(result, Ok(Parsed::NoMatch)));
    }
}