grippo 0.2.0

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
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
use crate::format;
use crate::parse::Parsers;

use super::{LayerError, LayerPlan, MAX_LAYERS};

fn stock() -> Parsers {
    let mut parsers = Parsers::new();
    format::register_stock(&mut parsers).unwrap();
    parsers
}

#[test]
fn a_hop_with_no_one_place_in_the_record_is_refused() {
    let parsers = stock();
    let too_long = ["ndjson"; MAX_LAYERS + 1].join(r#" > field("a"):"#);
    let cases: &[(&str, Option<usize>)] = &[
        (r#"ndjson > field("doc"):xml"#, None),
        (r#"ndjson > field("a.b"):(xml, ndjson)"#, None),
        (r#"xml > field("Event.Payload"):ndjson"#, None),
        ("auto", Some(0)),
        ("ndjson > each:xml", Some(1)),
        ("ndjson > auto*", Some(1)),
        (r#"ndjson > field("doc"):auto"#, Some(1)),
        (r#"field("doc"):ndjson"#, Some(0)),
        ("ndjson > xml", Some(1)),
        ("syslog > cef", None),
        ("cri > syslog > cef", None),
        ("syslog > (cef, syslog) > kv", None),
        ("syslog > cef > kv", Some(2)),
        ("syslog > (cef, leef) > kv", Some(2)),
        (r#"ndjson > field("m"):kv > cef"#, Some(2)),
        (&too_long, Some(MAX_LAYERS)),
    ];
    for (chain, refused) in cases {
        match (LayerPlan::chain(chain, &parsers), refused) {
            (Ok(layers), None) => assert!(!layers.is_empty(), "{chain}"),
            (Err(LayerError::Unsupported { hop, .. }), Some(want)) => {
                assert_eq!(hop, *want, "{chain}");
            }
            (got, _) => panic!("{chain}: {got:?}"),
        }
    }
    assert!(matches!(
        LayerPlan::chain(r#"ndjson > field("a"):nope"#, &parsers),
        Err(LayerError::Resolve(_))
    ));
    assert!(matches!(
        LayerPlan::chain("ndjson >", &parsers),
        Err(LayerError::Chain(_))
    ));
    let config = |hop: serde_json::Value| {
        let hops: Vec<crate::parse::HopConfig> =
            serde_json::from_value(serde_json::json!(["ndjson", hop])).unwrap();
        LayerPlan::compile(&hops, &parsers)
    };
    for hop in [
        serde_json::json!({"format": "xml", "field": "doc", "prefix": "x."}),
        serde_json::json!({"format": "xml", "field": "doc", "fallback": "reject"}),
    ] {
        assert!(
            matches!(
                config(hop.clone()),
                Err(LayerError::Unsupported { hop: 1, .. })
            ),
            "{hop}"
        );
    }
}

#[cfg(all(
    feature = "expr",
    feature = "xml",
    feature = "scrub",
    feature = "parse-cef",
    feature = "parse-syslog"
))]
mod by_hand {
    //! Each record read through its layers, against the same record with
    //! every layer parsed out by hand into one flat JSON record.

    use std::ops::Range;

    use serde_json::{Map, Value, json};

    use super::{by_hand_xml as xml, stock};
    use crate::expr::Program;
    use crate::format::{cef::Cef, syslog::Syslog};
    use crate::parse::{Fields, Hint, Parsed, Parser};
    use crate::path::keys;
    use crate::record::{LayerCache, LayerPlan};
    use crate::scrub::{RuleConfig, Scrubber};

    /// `bytes` parsed by `parser`, and the body it handed on.
    fn parsed<'a>(parser: &dyn Parser, bytes: &'a [u8]) -> (Fields<'a>, Option<Range<usize>>) {
        let mut fields = Fields::new();
        let body = match parser.parse(bytes, &mut fields) {
            Ok(Parsed::Body { span, .. }) => Some(span),
            _ => None,
        };
        (fields, body)
    }

    /// A parser's fields as JSON, nested by name, a whole number as a
    /// number, `skip` left out.
    fn fields(fields: &Fields<'_>, skip: &[&str]) -> Map<String, Value> {
        let mut out = Map::new();
        for (name, value) in fields.as_slice() {
            if skip.contains(&name.as_str()) {
                continue;
            }
            let text = String::from_utf8(value.bytes.to_vec()).unwrap();
            let value = match value.hint {
                Hint::Int => serde_json::from_str(&text).unwrap(),
                _ => Value::String(text),
            };
            let path: Vec<String> = keys(name).map(std::borrow::Cow::into_owned).collect();
            let (last, parents) = path.split_last().unwrap();
            let mut at = &mut out;
            for key in parents {
                at = at
                    .entry(key.clone())
                    .or_insert_with(|| json!({}))
                    .as_object_mut()
                    .unwrap();
            }
            at.insert(last.clone(), value);
        }
        out
    }

    /// The string at `key` of a JSON object.
    fn string<'v>(object: &'v Value, key: &str) -> &'v str {
        object[key].as_str().unwrap()
    }

    /// XML in a JSON field: the field's string read as a document.
    fn xml_in_json(record: &[u8]) -> Value {
        let mut flat: Value = serde_json::from_slice(record).unwrap();
        flat["doc"] = xml(string(&flat, "doc"));
        flat
    }

    fn json_in_xml(record: &[u8]) -> Value {
        let mut flat = xml(std::str::from_utf8(record).unwrap());
        let payload = string(&flat["Event"], "Payload").to_owned();
        flat["Event"]["Payload"] = serde_json::from_str(&payload).unwrap_or(Value::String(payload));
        flat
    }

    fn cef_in_json(record: &[u8]) -> Value {
        let mut flat: Value = serde_json::from_slice(record).unwrap();
        let ev = string(&flat, "ev").to_owned();
        let (cef, _) = parsed(&Cef::new(), ev.as_bytes());
        if !cef.is_empty() {
            flat["ev"] = Value::Object(fields(&cef, &[]));
        }
        flat
    }

    /// The syslog fields, the body's CEF fields under `cef`, its `msg` as
    /// JSON and that JSON's `x` as XML. `message`, the copy of the body the
    /// layers read, is left out.
    fn syslog_cef_json_xml(record: &[u8]) -> Value {
        let (syslog, body) = parsed(&Syslog::new(), record);
        let mut flat = fields(&syslog, &["message"]);
        let (cef, _) = parsed(&Cef::new(), &record[body.unwrap()]);
        let mut cef = Value::Object(fields(&cef, &[]));
        let mut msg: Value = serde_json::from_str(string(&cef, "msg")).unwrap();
        msg["x"] = xml(string(&msg, "x"));
        cef["msg"] = msg;
        flat.insert("cef".to_owned(), cef);
        Value::Object(flat)
    }

    /// The JSON whose `password` holds a document.
    fn xml_under_a_credential(record: &[u8]) -> Value {
        let mut flat: Value = serde_json::from_slice(record).unwrap();
        flat["password"] = xml(string(&flat, "password"));
        flat
    }

    type Flatten = fn(&[u8]) -> Value;

    /// Each combination: its chain, a record, the hand flattening, and the
    /// filters both must agree on.
    fn cases() -> Vec<(&'static str, String, Flatten, Vec<&'static str>)> {
        let doc = r#"<Event Kind="audit"><System><EventID>4624</EventID></System><Data><User>alice@example.com</User><password>hunter2</password><Note>a &amp; b</Note></Data></Event>"#;
        vec![
            (
                r#"ndjson > field("doc"):xml"#,
                json!({"host": "h1", "doc": doc, "n": 3}).to_string(),
                xml_in_json,
                vec![
                    r#"doc.Event.System.EventID == "4624""#,
                    r#"doc.Event.Data.User.endsWith("example.com")"#,
                    r#"doc.Event.Data.Note == "a & b""#,
                    "has(doc.Event.System)",
                    "has(doc.Event.Nope)",
                    r#"doc.Event.Nope == "x""#,
                    r#"doc.Event.System.EventID.x == "1""#,
                    r#"doc == "x""#,
                    r#"host == "h1" && n == 3"#,
                ],
            ),
            (
                r#"ndjson > field("doc"):xml"#,
                json!({"doc": "plain text, not a document"}).to_string(),
                |record| serde_json::from_slice(record).unwrap(),
                vec![
                    r#"doc == "plain text, not a document""#,
                    "has(doc.Event)",
                    r#"doc.Event == "x""#,
                ],
            ),
            (
                r#"xml > field("Event.Payload"):ndjson"#,
                r#"<Event><Host>h1</Host><Payload>{"user":"bob","n":3,"mail":"alice@example.com","password":"hunter2","note":"a &amp; b &lt; c"}</Payload></Event>"#.to_owned(),
                json_in_xml,
                vec![
                    "Event.Payload.n == 3",
                    "Event.Payload.n > 2",
                    r#"Event.Payload.user == "bob""#,
                    r#"Event.Payload.note == "a & b < c""#,
                    r#"Event.Host == "h1""#,
                    "has(Event.Payload.user)",
                    "has(Event.Payload.nope)",
                    r#"Event.Payload.user.x == "1""#,
                ],
            ),
            (
                r#"ndjson > field("ev"):cef"#,
                json!({
                    "ev": r"CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 suser=alice@example.com msg=paid\=yes from bob@example.com act=allow",
                    "n": 1,
                })
                .to_string(),
                cef_in_json,
                vec![
                    r#"ev.name == "login ok""#,
                    r#"ev.src.startsWith("10.")"#,
                    r#"ev.msg == "paid=yes from bob@example.com""#,
                    r#"ev.severity == "5""#,
                    r#"ev.act in ["allow", "deny"]"#,
                    "has(ev.suser)",
                    "has(ev.nope)",
                    "n == 1",
                ],
            ),
            (
                r#"syslog > cef > field("msg"):ndjson > field("x"):xml"#,
                r#"<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login|5|src=10.0.0.1 msg={"x":"<Event><User>alice@example.com</User><Id>7</Id></Event>","n":2}"#.to_owned(),
                syslog_cef_json_xml,
                vec![
                    r#"hostname == "fw01""#,
                    "pri == 134",
                    r#"cef.name == "login""#,
                    "cef.msg.n == 2",
                    r#"cef.msg.x.Event.Id == "7""#,
                    r#"cef.msg.x.Event.User.endsWith("example.com")"#,
                    "has(cef.msg.x.Event)",
                    r#"cef.nope == "x""#,
                    r#"cef.msg.x.Event.Id.deeper == "x""#,
                ],
            ),
            (
                r#"ndjson > field("password"):xml"#,
                json!({"password": "<a><b>x</b></a>", "n": 1}).to_string(),
                xml_under_a_credential,
                vec![r#"password.a.b == "x""#, "has(password.a)"],
            ),
        ]
    }

    #[test]
    fn a_layered_record_filters_and_scrubs_as_its_layers_parsed_out_by_hand() {
        let parsers = stock();
        let s = Scrubber::new(&RuleConfig::default()).unwrap();
        let (mut scratch, mut report) = (s.scratch(), s.report());
        let mut masked = 0;
        for (chain, record, flatten, filters) in cases() {
            let layers = LayerPlan::chain(chain, &parsers).unwrap();
            let flat = flatten(record.as_bytes()).to_string();
            for text in filters {
                let program = Program::compile(text).unwrap();
                let cache = LayerCache::new();
                let layered = layers.open(record.as_bytes(), &cache).unwrap();
                assert_eq!(
                    program.eval_record(layered),
                    program.eval(flat.as_bytes()),
                    "{chain}: {text}"
                );
            }

            let scrubbed = s
                .scrub_layered_bytes(&layers, record.as_bytes(), &mut scratch, &mut report)
                .unwrap()
                .unwrap_or_else(|| record.clone().into_bytes());
            let by_hand = s
                .scrub_json_bytes(flat.as_bytes(), &mut scratch, &mut report)
                .unwrap()
                .unwrap_or_else(|| flat.clone().into_bytes());
            masked += usize::from(by_hand != flat.as_bytes());
            let by_hand: Value = serde_json::from_slice(&by_hand).unwrap();
            assert_eq!(flatten(&scrubbed), by_hand, "{chain}: {record}");
        }
        assert_eq!(masked, 5, "every case but the plain text masks something");
    }

    /// The write-back through a parser layer: a value the parser decoded,
    /// found again by its escaped form, and the record read back at every
    /// layer.
    #[test]
    fn a_scrubbed_layer_is_written_in_its_own_escaping() {
        let parsers = stock();
        let s = Scrubber::new(&RuleConfig::default()).unwrap();
        let (mut scratch, mut report) = (s.scratch(), s.report());
        let layers = LayerPlan::chain(r#"ndjson > field("ev"):cef"#, &parsers).unwrap();
        let record = json!({
            "ev": r"CEF:0|Acme|Gate|1.0|100|pipe\|name|5|msg=a\=b to alice@example.com x=1",
        })
        .to_string();
        let out = s
            .scrub_layered_bytes(&layers, record.as_bytes(), &mut scratch, &mut report)
            .unwrap()
            .unwrap();
        let out: Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(
            string(&out, "ev"),
            r"CEF:0|Acme|Gate|1.0|100|pipe\|name|5|msg=a\=b to [EMAIL_REDACTED] x=1"
        );
    }

    /// A syslog header field whose grammar can't hold a token's brackets
    /// takes the token without them, and every other value keeps its token.
    #[test]
    fn a_header_field_takes_the_token_form_it_can_hold() {
        let parsers = stock();
        let s = Scrubber::new(&RuleConfig::default()).unwrap();
        let (mut scratch, mut report) = (s.scratch(), s.report());
        let layers = LayerPlan::chain("syslog > cef", &parsers).unwrap();
        let cef = "CEF:0|v|p|1|id|n|5|suser=alice@example.com x=1";
        let masked = "CEF:0|v|p|1|id|n|5|suser=[EMAIL_REDACTED] x=1";
        // The record, and what it scrubs to.
        let cases: &[(String, String)] = &[
            (
                format!("<134>Jan 15 09:00:01 bob@example.com app: {cef}"),
                format!("<134>Jan 15 09:00:01 EMAIL_REDACTED app: {masked}"),
            ),
            (
                format!("<134>Jan 15 09:00:01 host bob@example.com: {cef}"),
                format!("<134>Jan 15 09:00:01 host EMAIL_REDACTED: {masked}"),
            ),
            (
                format!("<134>Jan 15 09:00:01 bob@example.com carol@example.com: {cef}"),
                format!("<134>Jan 15 09:00:01 EMAIL_REDACTED EMAIL_REDACTED: {masked}"),
            ),
            (
                format!("<165>1 2026-01-15T09:00:01Z bob@example.com app - - - {cef}"),
                format!("<165>1 2026-01-15T09:00:01Z [EMAIL_REDACTED] app - - - {masked}"),
            ),
            (
                format!("<134>Jan 15 09:00:01 host app: {cef}"),
                format!("<134>Jan 15 09:00:01 host app: {masked}"),
            ),
        ];
        for (record, want) in cases {
            let out = s
                .scrub_layered_bytes(&layers, record.as_bytes(), &mut scratch, &mut report)
                .unwrap_or_else(|e| panic!("{record}: {e:?}"))
                .unwrap();
            assert_eq!(String::from_utf8(out).unwrap(), *want, "{record}");
        }
    }
}

#[cfg(all(
    feature = "scrub",
    feature = "parse-ndjson",
    feature = "parse-gelf",
    feature = "parse-kv",
    feature = "parse-csv",
    feature = "parse-leef",
    feature = "parse-cef",
    feature = "parse-syslog"
))]
mod escapes {
    //! A value written into each parser's layer in that format's escaping,
    //! the record read back through its layers after.

    use std::sync::Arc;

    use serde_json::json;

    use super::stock;
    use crate::format::csv::{Csv, CsvConfig};
    use crate::record::{LayerCache, LayerPlan, Miss, Record, Typed};

    /// `value` written at `path` of `record`, read through `chain`: the
    /// record after, or why it was refused.
    fn write(chain: &str, record: &str, path: &[&str], value: &str) -> Result<Vec<u8>, Miss> {
        let mut parsers = stock();
        let csv = Csv::new(CsvConfig {
            header: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
            ..CsvConfig::default()
        })
        .unwrap();
        parsers.register(Arc::new(csv)).unwrap();
        let layers = LayerPlan::chain(chain, &parsers).unwrap();
        let cache = LayerCache::new();
        let layered = layers.open(record.as_bytes(), &cache)?;
        let at = layered.find(path)?;
        let mut out = b"kept".to_vec();
        let written = layered.splice(&[(at, value)], &mut out);
        if written.is_err() {
            assert_eq!(
                out, b"kept",
                "{chain}: a refused write leaves out as it was"
            );
        }
        written.map(|()| out.split_off(4))
    }

    /// The string at `path` of `record`, read through `chain`.
    fn read(chain: &str, record: &[u8], path: &[&str]) -> String {
        let mut parsers = stock();
        let csv = Csv::new(CsvConfig {
            header: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
            ..CsvConfig::default()
        })
        .unwrap();
        parsers.register(Arc::new(csv)).unwrap();
        let layers = LayerPlan::chain(chain, &parsers).unwrap();
        let cache = LayerCache::new();
        let layered = layers.open(record, &cache).unwrap();
        let typed = layered.find(path).and_then(|at| layered.typed(at));
        match typed {
            Ok(Typed::Str(text)) => text.into_owned(),
            other => panic!("{chain} {path:?}: {other:?}"),
        }
    }

    #[test]
    fn a_mask_holding_each_formats_specials_reads_back_through_its_layer() {
        let kv = r#"ndjson > field("ev"):kv"#;
        let csv = r#"ndjson > field("ev"):csv"#;
        let leef = r#"ndjson > field("ev"):leef"#;
        let cef = r#"ndjson > field("ev"):cef"#;
        let syslog = r#"ndjson > field("ev"):syslog"#;
        let gelf = r#"ndjson > field("ev"):gelf"#;
        let sd = ["ev", "structured_data", "x@1", "b"];
        let v1 = "LEEF:1.0|V|P|1|E|a=1\tb=old\tc=2";
        let v2 = "LEEF:2.0|V|P|1|E|^|a=1^b=old^c=2";
        let gelf_ev = r#"{"version":"1.1","short_message":"hi","_a":"1","_b":"o\"ld","_c":"2"}"#;
        let bsd = "<134>Jan 15 09:00:01 host app: msg";
        // Chain, inner record, path to write, the value, and whether the
        // format can hold it there.
        let cases: &[(&str, &str, &[&str], &str, bool)] = &[
            (
                kv,
                "a=1 b=old c=2",
                &["ev", "b"],
                r#"[a b] "q" \ x=y"#,
                true,
            ),
            (kv, r#"a=1 b="o l\"d" c=2"#, &["ev", "b"], "x y", true),
            (kv, r#"a=1 b="old" c=2"#, &["ev", "b"], "plain", true),
            (csv, "1,old,2", &["ev", "b"], "a, \"b\"\r\nc", true),
            (csv, r#"1,"o,""ld",2"#, &["ev", "b"], "x", true),
            (leef, v1, &["ev", "b"], "x=y|z ^", true),
            (leef, v1, &["ev", "vendor"], r"a\|b", true),
            (leef, v1, &["ev", "b"], "tab\there", false),
            (leef, v1, &["ev", "vendor"], "a|b", false),
            (leef, v2, &["ev", "b"], "x=y|z\tw", true),
            (leef, v2, &["ev", "b"], "x^y", false),
            (
                cef,
                "CEF:0|v|p|1|id|n|5|a=1 b=old c=2",
                &["ev", "b"],
                "x=y \\ z\nw",
                true,
            ),
            (
                cef,
                r"CEF:0|v|p|1|id|n\|1|5|a=1",
                &["ev", "name"],
                r"a|b\c",
                true,
            ),
            (
                cef,
                "CEF:0|v|p|1|id|n|5|a=1 b=old c=2",
                &["ev", "b"],
                "ends ",
                false,
            ),
            (
                syslog,
                r#"<165>1 - host app - - [x@1 a="1" b="o\"ld" c="2"] msg"#,
                &sd,
                r#"q"b\s]x"#,
                true,
            ),
            (syslog, bsd, &["ev", "hostname"], "x_y", true),
            (syslog, bsd, &["ev", "hostname"], "[x]", false),
            (syslog, bsd, &["ev", "appname"], "[x]", false),
            (gelf, gelf_ev, &["ev", "b"], "say \"hi\"\n\\", true),
        ];
        for &(chain, inner, path, value, holds) in cases {
            let record = json!({"ev": inner, "n": 1}).to_string();
            let written = write(chain, &record, path, value);
            if !holds {
                assert_eq!(written, Err(Miss::Malformed), "{chain} {inner}: {value:?}");
                continue;
            }
            let out = written.unwrap_or_else(|e| panic!("{chain} {inner}: {value:?}: {e:?}"));
            assert_eq!(read(chain, &out, path), value, "{chain} {inner}");
            let mut before = path.to_vec();
            let mut after = path.to_vec();
            *before.last_mut().unwrap() = "a";
            *after.last_mut().unwrap() = "c";
            if path.last() == Some(&"b") {
                assert_eq!(read(chain, &out, &before), "1", "{chain} {inner}");
                assert_eq!(read(chain, &out, &after), "2", "{chain} {inner}");
            }
            let outer: serde_json::Value = serde_json::from_slice(&out).unwrap();
            assert_eq!(outer["n"], 1, "{chain} {inner}");
        }
    }
}

#[cfg(all(feature = "expr", feature = "xml"))]
mod opens {
    use std::borrow::Cow;

    use serde_json::json;

    use super::stock;
    use crate::expr::{Outcome, Program};
    use crate::record::{Json, LayerCache, LayerPlan, Miss, Record, Typed};

    #[test]
    fn two_paths_into_one_layer_open_it_once() {
        let layers = LayerPlan::chain(r#"ndjson > field("doc"):xml"#, &stock()).unwrap();
        let doc = r#"<Event Kind="a"><ID>7</ID><User>bob</User></Event>"#;
        let record = json!({"doc": doc, "n": 1}).to_string();
        let record = record.as_bytes();

        let cache = LayerCache::new();
        let layered = layers.over(Json::new(record), &cache);
        let id = layered.find(&["doc", "Event", "ID"]).unwrap();
        let user = layered.find(&["doc", "Event", "User"]).unwrap();
        assert_eq!(layered.typed(id), Ok(Typed::Str("7".into())));
        assert_eq!(layered.typed(user), Ok(Typed::Str("bob".into())));
        let event = layered.find(&["doc", "Event"]).unwrap();
        assert_eq!(
            layered
                .find_below(event, &["User"])
                .map(|at| layered.typed(at)),
            Ok(Ok(Typed::Str("bob".into())))
        );
        assert_eq!(cache.opened(), 1);

        // A document JSON had to unescape is decoded once into the cache, and
        // one with no escape is borrowed from the record.
        let inside =
            |record: &[u8], text: Cow<'_, str>| record.as_ptr_range().contains(&text.as_ptr());
        let root = layered.find(&["doc"]).unwrap();
        assert_eq!(layered.typed(root), Ok(Typed::Map));
        assert!(!inside(record, layered.text(root).unwrap()));
        let plain = br#"{"doc":"<Event><ID>7</ID></Event>"}"#;
        let cache = LayerCache::new();
        let layered = layers.over(Json::new(plain), &cache);
        let root = layered.find(&["doc"]).unwrap();
        assert!(inside(plain, layered.text(root).unwrap()));

        let both = Program::compile(r#"doc.Event.ID == "7" && doc.Event.User == "bob""#).unwrap();
        let away = Program::compile("n == 1").unwrap();
        for (program, opened) in [(&both, 1), (&away, 0)] {
            let cache = LayerCache::new();
            let layered = layers.over(Json::new(record), &cache);
            assert_eq!(program.eval_record(layered), Outcome::True);
            assert_eq!(cache.opened(), opened);
        }

        // A list of formats takes the first that reads the value.
        let either = LayerPlan::chain(r#"ndjson > field("doc"):(ndjson, xml)"#, &stock()).unwrap();
        for (doc, path) in [
            (r#"{"doc":"<a><b>x</b></a>"}"#, ["doc", "a", "b"]),
            (r#"{"doc":"{\"a\":{\"b\":\"x\"}}"}"#, ["doc", "a", "b"]),
        ] {
            let cache = LayerCache::new();
            let layered = either.over(Json::new(doc.as_bytes()), &cache);
            let read = layered.find(&path).and_then(|at| layered.typed(at));
            assert_eq!(read, Ok(Typed::Str("x".into())), "{doc}");
        }

        // A broken document opens, and a read into it says so.
        let broken = br#"{"doc":"<a><b></a>"}"#;
        let cache = LayerCache::new();
        let layered = layers.over(Json::new(broken), &cache);
        let read = layered
            .find(&["doc", "a", "b"])
            .and_then(|at| layered.typed(at));
        assert_eq!(read, Err(Miss::Malformed));
        assert_eq!(cache.opened(), 1);
    }
}

#[cfg(all(feature = "xml", feature = "scrub"))]
mod props {
    use std::collections::BTreeMap;
    use std::sync::LazyLock;

    use proptest::prelude::*;
    use serde_json::value::RawValue;
    use serde_json::{Value, json};

    use super::stock;
    use crate::record::LayerPlan;
    use crate::scrub::{RuleConfig, Scrubber};

    static SCRUBBER: LazyLock<Scrubber> =
        LazyLock::new(|| Scrubber::new(&RuleConfig::default()).unwrap());

    const NAMES: &[&str] = &["User", "Mail", "password", "Note", "Id"];
    const TEXTS: &[&str] = &[
        "alice@example.com",
        "4111 1111 1111 1111",
        "login password=hunter2 ok",
        r#"a < b & "c" \ d"#,
        "tab\there",
        "plain",
        "",
    ];

    /// XML text with `&`, `<` and `>` escaped.
    fn escaped(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    }

    fn flatten(record: &[u8]) -> Value {
        let mut flat: Value = serde_json::from_slice(record).unwrap();
        let doc = flat["doc"].as_str().unwrap().to_owned();
        flat["doc"] = super::by_hand_xml(&doc);
        flat
    }

    /// The bytes before and after the record's `doc` value.
    fn around_doc(record: &[u8]) -> (Vec<u8>, Vec<u8>) {
        let members: BTreeMap<String, &RawValue> = serde_json::from_slice(record).unwrap();
        let doc = members["doc"].get().as_bytes();
        let start = doc.as_ptr().addr() - record.as_ptr().addr();
        let end = start + doc.len();
        (record[..start].to_vec(), record[end..].to_vec())
    }

    proptest! {
        /// A JSON record holding a JSON-escaped XML document, scrubbed
        /// through its layers, still reads at both layers, every byte
        /// outside the document is as it was, and the result is the record
        /// scrubbed with its document parsed out by hand.
        #[test]
        fn xml_escaped_in_json_scrubs_through_both_layers(
            elements in prop::sample::subsequence(NAMES, 0..=NAMES.len())
                .prop_flat_map(|names| {
                    let n = names.len();
                    (Just(names), prop::collection::vec(prop::sample::select(TEXTS), n))
                }),
            outer in prop::sample::select(&["plain", "tab\there", "q\"uote"][..]),
        ) {
            let (names, texts) = elements;
            let mut doc = r#"<Event Kind="audit"><Head>1</Head>"#.to_owned();
            for (name, text) in names.iter().zip(&texts) {
                doc.push_str(&["<", name, ">", &escaped(text), "</", name, ">"].concat());
            }
            doc.push_str("</Event>");
            let record = json!({"a": outer, "doc": doc, "z": 7}).to_string();

            let layers = LayerPlan::chain(r#"ndjson > field("doc"):xml"#, &stock()).unwrap();
            let s = &*SCRUBBER;
            let (mut scratch, mut report) = (s.scratch(), s.report());
            let out = s
                .scrub_layered_bytes(&layers, record.as_bytes(), &mut scratch, &mut report)
                .unwrap()
                .unwrap_or_else(|| record.clone().into_bytes());

            let read: Value = serde_json::from_slice(&out).unwrap();
            prop_assert!(roxmltree::Document::parse(read["doc"].as_str().unwrap()).is_ok());
            prop_assert_eq!(around_doc(&out), around_doc(record.as_bytes()));

            let flat = flatten(record.as_bytes()).to_string();
            let by_hand = s
                .scrub_json_bytes(flat.as_bytes(), &mut scratch, &mut report)
                .unwrap()
                .unwrap_or_else(|| flat.into_bytes());
            let by_hand: Value = serde_json::from_slice(&by_hand).unwrap();
            prop_assert_eq!(flatten(&out), by_hand);
        }
    }
}

/// An XML document as a JSON object, parsed out by hand: its root element by
/// local name, an element with no child element its text, attributes as
/// `@name`. Text that isn't a document stays a string.
#[cfg(all(feature = "xml", feature = "scrub"))]
fn by_hand_xml(text: &str) -> serde_json::Value {
    use serde_json::{Map, Value, json};

    fn element(node: roxmltree::Node<'_, '_>) -> Value {
        let children: Vec<_> = node
            .children()
            .filter(roxmltree::Node::is_element)
            .collect();
        if children.is_empty() {
            let text: String = node.children().filter_map(|c| c.text()).collect();
            return Value::String(text);
        }
        let mut map = Map::new();
        for a in node.attributes() {
            map.insert(format!("@{}", a.name()), a.value().into());
        }
        for c in children {
            map.insert(c.tag_name().name().to_owned(), element(c));
        }
        Value::Object(map)
    }
    let Ok(doc) = roxmltree::Document::parse(text) else {
        return Value::String(text.to_owned());
    };
    let root = doc.root_element();
    json!({ root.tag_name().name(): element(root) })
}