grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/scrub/record.rs
// Purpose:   Scrub any record that walks: raw JSON bytes, parser fields, or a source of your own
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scrubber::scrub_record`] runs the structure rules [`Scrubber::scrub_value`]
//! runs over any [`Walk`] record and hands back what it replaced.
//! [`Scrubber::scrub_json_bytes`] and [`Scrubber::scrub_fields`] write those
//! back to raw JSON and to [`Fields`], `scrub_xml_bytes` to raw XML, and
//! [`Scrubber::scrub_layered_bytes`] to a record read through a [`LayerPlan`].
//! [`JsonBytes`], `XmlBytes` and [`LayeredBytes`] name raw bytes' format for
//! [`Scrubber::scrub_in_place`] and [`Scrubber::scrub`].

#[cfg(feature = "parse")]
use crate::parse::{FieldValue, Fields, Hint};
#[cfg(feature = "parse")]
use crate::record::Spot;
#[cfg(feature = "parse")]
use crate::record::{FirstRead, LayerCache, LayerPlan};
use crate::record::{Json, Kind, Miss, Walk, Walked};
#[cfg(feature = "xml")]
use crate::record::{Xml, XmlAt};

use super::closed::{self, Unread};
use super::field;
use super::walk::{Event, Malformed, RecordValues, recycle, shape};
use super::{Report, Scrub, ScrubScratch, Scrubber};

/// A raw JSON record, for [`Scrubber::scrub_in_place`] and [`Scrubber::scrub`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct JsonBytes(pub Vec<u8>);

/// A raw XML document, for [`Scrubber::scrub_in_place`] and [`Scrubber::scrub`].
#[cfg(feature = "xml")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct XmlBytes(pub Vec<u8>);

/// A raw record read through the layers of `plan`, for
/// [`Scrubber::scrub_in_place`] and [`Scrubber::scrub`].
#[cfg(feature = "parse")]
#[derive(Debug, Clone)]
pub struct LayeredBytes<'p> {
    /// The layers the record is read through.
    pub plan: &'p LayerPlan,
    /// The record.
    pub bytes: Vec<u8>,
}

impl Scrubber {
    /// Scrub a record, calling `masked` with each value it replaces and the
    /// bytes that value becomes, a string, in document order.
    ///
    /// The rules are [`Scrubber::scrub_value`]'s: a string goes through
    /// [`Scrubber::scrub_field`] with its key path, a number or bool is
    /// redacted only under a credential field name, a list or object under
    /// one goes whole, and a list element `[name, value]` naming a
    /// credential is a pair.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the record is broken or doesn't
    /// [`Walk::read_whole`], found before `masked` is first called, or when a
    /// value can't be read, `masked` and `report` holding what was found
    /// before it. The record isn't scrubbed, so don't pass it on: mask it, as
    /// `scrub_json_bytes` does.
    pub fn scrub_record<'a, R: Walk<'a>>(
        &self,
        record: R,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        masked: impl FnMut(R::At, Vec<u8>),
    ) -> Result<(), Miss> {
        let mut events = Vec::new();
        record.walk(|n| events.push(Event::new(n.depth, n.key, shape(n.kind), n.at)))?;
        if !record.read_whole() {
            return Err(Miss::Malformed);
        }
        self.scrub_events(&mut events, &RecordValues(record), scratch, report, masked)
            .map_err(|Malformed| Miss::Malformed)
    }

    /// Scrub a raw JSON record. `None` when nothing changed, else the record
    /// with each replaced value written as a JSON string at its place and
    /// every other byte as it was.
    ///
    /// A record that doesn't parse fails closed. Every string, number and bare
    /// word the bytes let the scan delimit is masked, keys included, and only
    /// the delimiters and white space stay. A string that never closes, or a
    /// record with no token, makes the whole record the mask. Each mask is
    /// counted as [`super::Kind::Malformed`] on the credential-field row, at
    /// least one for every rejected record, and the original bytes are never
    /// returned. Under
    /// [`Redaction::Observe`](super::Redaction::Observe) the count is made and
    /// the bytes are left alone.
    ///
    /// # Errors
    ///
    /// None for a record that doesn't parse. The `Result` stays for the
    /// record's shared signature.
    pub fn scrub_json_bytes(
        &self,
        json: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Vec<u8>>, Miss> {
        let mut out = Vec::new();
        let changed = self.splice_json(json, scratch, report, &mut out);
        Ok(changed.then_some(out))
    }

    /// As [`Scrubber::scrub_json_bytes`], the record written to `out` and
    /// `true` when anything changed. `out` is left alone when nothing did.
    fn splice_json(
        &self,
        json: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> bool {
        let done = self.splice_parsed_json(json, scratch, report, out);
        done.unwrap_or_else(|_| self.fail_closed(Unread::Json, json, report, out))
    }

    /// A record that didn't read, or couldn't be written back, masked by the
    /// scan `unread` names: see [`Scrubber::scrub_json_bytes`]. `true` when
    /// `out` holds the masked record, `false` under observe. The scan writes
    /// at least one mask, so every rejected record is counted.
    #[cold]
    #[inline(never)]
    fn fail_closed(
        &self,
        unread: Unread,
        bytes: &[u8],
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> bool {
        self.own(report);
        let mut masked = Vec::new();
        let n = closed::mask(unread, bytes, self.pair_token.as_bytes(), &mut masked);
        report.add_n(self.compiled().rules.len(), super::Kind::Malformed, n);
        if self.redactor.observes() {
            return false;
        }
        report.set_changed();
        *out = masked;
        true
    }

    /// As [`Scrubber::splice_json`], for a record that parses.
    fn splice_parsed_json(
        &self,
        json: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> Result<bool, Miss> {
        let record = Json::new(json);
        let mut edits: Vec<(&str, Vec<u8>)> = Vec::new();
        // The walk's buffers live in the scratch, so its walk allocates nothing.
        let mut events: Vec<Event<'_, &str>> = recycle(std::mem::take(&mut scratch.events));
        // The events of the lists and objects still open.
        let mut opened = std::mem::take(&mut scratch.stack);
        opened.clear();
        let walked = record.walk_once_in(&mut scratch.json, |step| match step {
            Walked::Value(n) => {
                if let Kind::List | Kind::Map = n.kind {
                    opened.push(events.len());
                }
                events.push(Event::new(n.depth, n.key, shape(n.kind), n.at));
            }
            // The root object's close finds none open: it has no event.
            Walked::Closed(at) => {
                if let Some(i) = opened.pop() {
                    events[i].set_pos(at);
                }
            }
        });
        scratch.stack = opened;
        // Every name and value is a piece of the record, so one scan of it tells
        // whether any of them can need an escape, a colour sequence or another script.
        scratch
            .spellings
            .set_plain(self.tokens_plain && field::is_plain(json));
        let scrubbed = walked.and_then(|()| {
            self.scrub_events(
                &mut events,
                &RecordValues(record),
                scratch,
                report,
                |at, out| {
                    edits.push((at, out));
                },
            )
            .map_err(|Malformed| Miss::Malformed)
        });
        scratch.spellings.set_plain(false);
        scratch.events = recycle(events);
        scrubbed?;
        if edits.is_empty() {
            return Ok(false);
        }
        out.clear();
        out.reserve(json.len() + 32 * edits.len());
        record.splice_strings(&edits, out)?;
        Ok(true)
    }

    /// Scrub a raw XML document. `None` when nothing changed, else the
    /// document with each replaced value written as escaped text at its
    /// place and every other byte as it was. [`Xml::splice_text`] says how an
    /// element with child elements is replaced.
    ///
    /// A document a walk doesn't read, UTF-8 well-formed XML, fails closed as
    /// a JSON record does in [`Scrubber::scrub_json_bytes`]. Every name,
    /// attribute value and run of text is masked, and only markup's `<`, `>`,
    /// `/` and `=`, a value's quotes and the white space between them stay. A
    /// value that never closes, or a document with no token, is the mask whole.
    ///
    /// # Errors
    ///
    /// None for a document that doesn't read. The `Result` stays for the
    /// record's shared signature.
    #[cfg(feature = "xml")]
    pub fn scrub_xml_bytes(
        &self,
        xml: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Vec<u8>>, Miss> {
        let mut out = Vec::new();
        let changed = self.splice_xml(xml, scratch, report, &mut out);
        Ok(changed.then_some(out))
    }

    /// As [`Scrubber::scrub_xml_bytes`], the document written to `out` and
    /// `true` when anything changed. `out` is left alone when nothing did.
    #[cfg(feature = "xml")]
    fn splice_xml(
        &self,
        xml: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> bool {
        let done = self.splice_read_xml(xml, scratch, report, out);
        done.unwrap_or_else(|_| self.fail_closed(Unread::Xml, xml, report, out))
    }

    /// As [`Scrubber::splice_xml`], for a document that reads.
    #[cfg(feature = "xml")]
    fn splice_read_xml(
        &self,
        xml: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> Result<bool, Miss> {
        let record = Xml::new(xml);
        let mut edits: Vec<(XmlAt, Vec<u8>)> = Vec::new();
        self.scrub_record(record, scratch, report, |at, out| edits.push((at, out)))?;
        if edits.is_empty() {
            return Ok(false);
        }
        out.clear();
        out.reserve(xml.len() + 32 * edits.len());
        record.splice_text(&edits, out)?;
        Ok(true)
    }

    /// Scrub a record read through the layers of `plan`. `None` when nothing changed,
    /// else the record with each replaced value written back into the layer
    /// that holds it, innermost first, as
    /// [`crate::record::Layered::splice`] writes it. A value inside a layer
    /// is scrubbed under its full path from the record's root. A value its
    /// layer can't hold with a token's `[` and `]`, a syslog hostname or
    /// tag, is written with every `[` and `]` dropped: `EMAIL_REDACTED`.
    ///
    /// A record fails closed when the first hop's format doesn't read it, a
    /// layer opens and its values don't walk, or a layer can't be written
    /// back as it reads, with brackets or without. A record the first layer
    /// read as JSON or XML is masked as [`Scrubber::scrub_json_bytes`] or
    /// `scrub_xml_bytes` masks one that doesn't read, and any other is the
    /// mask whole.
    ///
    /// # Errors
    ///
    /// None for a record that fails closed. The `Result` stays for the
    /// record's shared signature.
    #[cfg(feature = "parse")]
    pub fn scrub_layered_bytes(
        &self,
        plan: &LayerPlan,
        record: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Vec<u8>>, Miss> {
        let mut out = Vec::new();
        let changed = self.splice_layered(plan, record, scratch, report, &mut out);
        Ok(changed.then_some(out))
    }

    /// As [`Scrubber::scrub_layered_bytes`], the record written to `out` and
    /// `true` when anything changed. `out` is left alone when nothing did.
    #[cfg(feature = "parse")]
    fn splice_layered(
        &self,
        plan: &LayerPlan,
        record: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> bool {
        let cache = LayerCache::new();
        let done = self.splice_read_layered(plan, record, &cache, scratch, report, out);
        done.unwrap_or_else(|_| {
            let unread = match cache.first_read() {
                Some(FirstRead::Json) => Unread::Json,
                #[cfg(feature = "xml")]
                Some(FirstRead::Xml) => Unread::Xml,
                Some(FirstRead::Fields) | None => Unread::Whole,
            };
            self.fail_closed(unread, record, report, out)
        })
    }

    /// As [`Scrubber::splice_layered`], for a record whose layers read and
    /// write back.
    #[cfg(feature = "parse")]
    fn splice_read_layered<'c>(
        &self,
        plan: &'c LayerPlan,
        record: &'c [u8],
        cache: &'c LayerCache<'c>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        out: &mut Vec<u8>,
    ) -> Result<bool, Miss> {
        let layered = plan.open(record, cache)?;
        let mut edits: Vec<(_, Vec<u8>)> = Vec::new();
        self.scrub_record(layered, scratch, report, |at, out| edits.push((at, out)))?;
        if edits.is_empty() {
            return Ok(false);
        }
        out.clear();
        out.reserve(record.len() + 32 * edits.len());
        if layered.splice(&edits, out).is_ok() {
            return Ok(true);
        }
        // A field whose grammar has no room for a bracket, such as a syslog
        // hostname, takes its tokens without them.
        let mut alone = Vec::new();
        for i in 0..edits.len() {
            alone.clear();
            if layered.splice(&edits[i..=i], &mut alone).is_err() {
                edits[i].1.retain(|b| !matches!(b, b'[' | b']'));
            }
        }
        out.clear();
        layered.splice(&edits, out)?;
        Ok(true)
    }

    /// Scrub the fields a parser chain wrote, in place, read as
    /// [`Walk`] reads them. `true` when anything changed.
    ///
    /// A replaced value becomes a `Hint::Text` field. A list or object under
    /// a credential name becomes one field under that name. A value inside a
    /// `Hint::Json` field is replaced in its JSON.
    ///
    /// Fields that don't walk, such as a name that nests too deep, or whose
    /// edits can't be written, fail closed: every value becomes the mask, a
    /// `Hint::Text` field, each counted as [`super::Kind::Malformed`] on the
    /// credential-field row. Names aren't masked. Under
    /// [`Redaction::Observe`](super::Redaction::Observe) the count is made and
    /// the fields are left alone.
    ///
    /// # Errors
    ///
    /// None for fields that fail closed. The `Result` stays for the record's
    /// shared signature.
    #[cfg(feature = "parse")]
    pub fn scrub_fields(
        &self,
        fields: &mut Fields<'_>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        let written = self.field_spots(fields, scratch, report).and_then(|spots| {
            if spots.is_empty() {
                return Ok(false);
            }
            crate::record::write_strings(fields, spots)?;
            Ok(true)
        });
        Ok(written.unwrap_or_else(|_| self.fields_closed(fields, report)))
    }

    /// Fields that didn't walk or write, every value masked: see
    /// [`Scrubber::scrub_fields`]. `true` when they changed, `false` under
    /// observe.
    #[cfg(feature = "parse")]
    fn fields_closed(&self, fields: &mut Fields<'_>, report: &mut Report) -> bool {
        self.own(report);
        let n = fields.len().max(1);
        report.add_n(self.compiled().rules.len(), super::Kind::Malformed, n);
        if self.redactor.observes() {
            return false;
        }
        for (_, value) in fields.as_mut_slice() {
            *value = FieldValue::owned(self.pair_token.as_bytes().to_vec(), Hint::Text);
        }
        report.set_changed();
        true
    }

    /// Each place in `fields` the rules replace, with its new bytes.
    #[cfg(feature = "parse")]
    fn field_spots(
        &self,
        fields: &Fields<'_>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Vec<(Spot, Vec<u8>)>, Miss> {
        let mut edits = Vec::new();
        self.scrub_record(fields, scratch, report, |at, out| edits.push((at, out)))?;
        edits
            .into_iter()
            .map(|(at, out)| crate::record::spot(fields, at).map(|s| (s, out)))
            .collect()
    }
}

/// Splices with `splice` into the scratch's buffer, then copies the result
/// over `bytes`, whose allocation is kept where it's big enough.
fn rewrite(
    bytes: &mut Vec<u8>,
    scratch: &mut ScrubScratch,
    splice: impl FnOnce(&[u8], &mut ScrubScratch, &mut Vec<u8>) -> bool,
) -> bool {
    let mut out = std::mem::take(&mut scratch.spliced);
    let changed = splice(bytes, scratch, &mut out);
    if changed {
        bytes.clear();
        bytes.extend_from_slice(&out);
    }
    scratch.spliced = out;
    changed
}

impl Scrub for JsonBytes {
    type Error = Miss;

    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        Ok(rewrite(&mut self.0, scratch, |json, scratch, out| {
            scrubber.splice_json(json, scratch, report, out)
        }))
    }

    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Miss> {
        Ok(scrubber
            .scrub_json_bytes(&self.0, scratch, report)?
            .map(Self))
    }
}

#[cfg(feature = "xml")]
impl Scrub for XmlBytes {
    type Error = Miss;

    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        Ok(rewrite(&mut self.0, scratch, |xml, scratch, out| {
            scrubber.splice_xml(xml, scratch, report, out)
        }))
    }

    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Miss> {
        Ok(scrubber
            .scrub_xml_bytes(&self.0, scratch, report)?
            .map(Self))
    }
}

#[cfg(feature = "parse")]
impl Scrub for LayeredBytes<'_> {
    type Error = Miss;

    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        let plan = self.plan;
        Ok(rewrite(&mut self.bytes, scratch, |record, scratch, out| {
            scrubber.splice_layered(plan, record, scratch, report, out)
        }))
    }

    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Miss> {
        let out = scrubber.scrub_layered_bytes(self.plan, &self.bytes, scratch, report)?;
        Ok(out.map(|bytes| Self {
            plan: self.plan,
            bytes,
        }))
    }
}

#[cfg(feature = "parse")]
impl Scrub for Fields<'_> {
    type Error = Miss;

    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        scrubber.scrub_fields(self, scratch, report)
    }

    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Miss> {
        if let Ok(spots) = scrubber.field_spots(self, scratch, report) {
            if spots.is_empty() {
                return Ok(None);
            }
            let mut copy = self.clone();
            if crate::record::write_strings(&mut copy, spots).is_ok() {
                return Ok(Some(copy));
            }
        }
        let mut copy = self.clone();
        Ok(scrubber.fields_closed(&mut copy, report).then_some(copy))
    }
}