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
// 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::Fields;
#[cfg(feature = "parse")]
use crate::record::Spot;
use crate::record::{Json, Miss, Walk};
#[cfg(feature = "parse")]
use crate::record::{LayerCache, LayerPlan};
#[cfg(feature = "xml")]
use crate::record::{Xml, XmlAt};

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, found before anything
    /// is counted.
    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)))?;
        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.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the bytes aren't JSON.
    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>,
    ) -> 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));
        let walked = record.walk_in(&mut scratch.json, |n| {
            events.push(Event::new(n.depth, n.key, shape(n.kind), n.at));
        });
        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.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.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the bytes aren't XML a walk reads.
    #[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>,
    ) -> 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`.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the first hop's format doesn't read the
    /// record, or a layer can't be written back as it reads, with brackets
    /// or without.
    #[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>,
    ) -> Result<bool, Miss> {
        let cache = LayerCache::new();
        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.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when a name nests too deep to walk.
    #[cfg(feature = "parse")]
    pub fn scrub_fields(
        &self,
        fields: &mut Fields<'_>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        let spots = self.field_spots(fields, scratch, report)?;
        if spots.is_empty() {
            return Ok(false);
        }
        crate::record::write_strings(fields, spots)?;
        Ok(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>) -> Result<bool, Miss>,
) -> Result<bool, Miss> {
    let mut out = std::mem::take(&mut scratch.spliced);
    let changed = splice(bytes, scratch, &mut out);
    if matches!(changed, Ok(true)) {
        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> {
        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> {
        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;
        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> {
        let spots = scrubber.field_spots(self, scratch, report)?;
        if spots.is_empty() {
            return Ok(None);
        }
        let mut copy = self.clone();
        crate::record::write_strings(&mut copy, spots)?;
        Ok(Some(copy))
    }
}