grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/scrub/json.rs
// Purpose:   Scrub a JSON record in place, field by field with its key path
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scrubber::scrub_value`]: every scalar goes through
//! [`Scrubber::scrub_field`] with its key path. An array element takes the
//! array's key as its name, so `passwords: [..]` redacts each element. The
//! walk keeps its own stack, so nesting depth can't overflow the thread's.

use std::fmt::Write as _;

use serde_json::Value;

use super::{FieldLayer, Report, ScrubScratch, Scrubber};

impl Scrubber {
    /// Scrub `value` in place. `true` when anything changed.
    ///
    /// A redacted number or boolean becomes its token, a string. A number is
    /// redacted only under a credential field name, never for its digits.
    pub fn scrub_value(
        &self,
        value: &mut Value,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> bool {
        self.own(report);
        let mut path: Vec<&str> = Vec::new();
        // Each entry: a value, the path length above it, its key if any, and
        // whether it is an array item.
        let mut todo: Vec<(&mut Value, usize, Option<&str>, bool)> = vec![(value, 0, None, false)];
        let mut changed = false;
        while let Some((node, depth, key, item)) = todo.pop() {
            path.truncate(depth);
            if let Some(k) = key {
                path.push(k);
                // A container under a credential name is one value: it goes whole.
                if matches!(node, Value::Object(_) | Value::Array(_)) {
                    let text = serde_json::to_string(&*node).unwrap_or_default();
                    let excepted = self.exceptions.iter().any(|e| e.covers(&path));
                    match self.field_layer(&path, text.as_bytes(), excepted, scratch, report) {
                        FieldLayer::Replaced(out) => {
                            *node = Value::String(String::from_utf8_lossy(&out).into_owned());
                            changed = true;
                            continue;
                        }
                        FieldLayer::Kept if !excepted => continue,
                        FieldLayer::Kept | FieldLayer::NotCredential => {}
                    }
                }
            }
            let out = match node {
                Value::Object(map) => {
                    let below = path.len();
                    todo.extend(
                        map.iter_mut()
                            .rev()
                            .map(|(k, v)| (v, below, Some(k.as_str()), false)),
                    );
                    continue;
                }
                Value::Array(items) => {
                    let here = path.len();
                    // An array item `[name, value]` whose name is a credential
                    // is a pair: the value is scrubbed as a field of that name.
                    let parent = path.last().copied().unwrap_or_default();
                    let pair = item
                        && matches!(items.as_slice(), [Value::String(name), _]
                            if self.credentials.matches_in(name, parent, &mut scratch.spellings));
                    if pair {
                        if let [Value::String(name), value] = items.as_mut_slice() {
                            todo.push((value, here, Some(name.as_str()), false));
                        }
                    } else {
                        todo.extend(items.iter_mut().rev().map(|v| (v, here, None, true)));
                    }
                    continue;
                }
                Value::Null => continue,
                Value::String(s) => self.scrub_field(&path, s.as_bytes(), scratch, report),
                Value::Bool(b) => {
                    let text: &[u8] = if *b { b"true" } else { b"false" };
                    self.scrub_field(&path, text, scratch, report)
                }
                Value::Number(n) => {
                    let mut text = std::mem::take(&mut scratch.number);
                    text.clear();
                    // Writing to a String can't fail.
                    let _ = write!(text, "{n}");
                    let out = self.scrub_number(&path, text.as_bytes(), scratch, report);
                    scratch.number = text;
                    out
                }
            };
            if let Some(bytes) = out {
                *node = Value::String(String::from_utf8_lossy(&bytes).into_owned());
                changed = true;
            }
        }
        changed
    }
}