grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/scrub/redact.rs
// Purpose:   What a found secret is replaced with
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Redaction tokens: `[<RULE>_REDACTED]`, or `[<RULE>_<hex>]` with the first
//! 8 bytes of HMAC-SHA256 over the secret, so one value hashes the same on
//! every host that shares the key.

use std::fmt;

use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use zeroize::Zeroizing;

/// The name [`Redaction::Hash`] goes by in parity manifests, the same in
/// every implementation that writes these tokens.
pub const HASH_ALGORITHM: &str = "hmac-sha256-keyed-truncated-to-16-hex";

/// The key for [`Redaction::Hash`]. Its `Debug` never prints the key, and its
/// bytes are wiped when it drops.
#[derive(Clone)]
pub struct HashKey(Zeroizing<Vec<u8>>);

impl HashKey {
    /// A key from raw bytes. `None` when empty.
    #[must_use]
    pub fn new(key: impl Into<Vec<u8>>) -> Option<Self> {
        let key: Vec<u8> = key.into();
        (!key.is_empty()).then(|| Self(Zeroizing::new(key)))
    }
}

impl fmt::Debug for HashKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "HashKey({} bytes)", self.0.len())
    }
}

/// What a found secret becomes.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub enum Redaction {
    /// `[<RULE>_REDACTED]`.
    #[default]
    Mask,
    /// `[<RULE>_<16 hex>]`: keyed HMAC-SHA256 over the secret.
    Hash(HashKey),
    /// Count it and leave the bytes as they are.
    Observe,
}

/// A [`Redaction`] ready to write tokens.
#[derive(Clone)]
pub(super) enum Redactor {
    Mask,
    Hash(Hmac<Sha256>),
    Observe,
}

impl fmt::Debug for Redactor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Mask => "Mask",
            Self::Hash(_) => "Hash",
            Self::Observe => "Observe",
        })
    }
}

impl From<&Redaction> for Redactor {
    fn from(r: &Redaction) -> Self {
        match r {
            Redaction::Mask => Self::Mask,
            // HMAC takes a key of any length, so this never falls back.
            Redaction::Hash(key) => {
                <Hmac<Sha256> as KeyInit>::new_from_slice(&key.0).map_or(Self::Mask, Self::Hash)
            }
            Redaction::Observe => Self::Observe,
        }
    }
}

const HEX: &[u8; 16] = b"0123456789abcdef";

impl Redactor {
    pub const fn observes(&self) -> bool {
        matches!(self, Self::Observe)
    }

    /// The part of a token after `<RULE>_`: `REDACTED`, or 16 hex digits.
    fn suffix(&self, secret: &[u8]) -> [u8; 16] {
        match self {
            Self::Hash(mac) => {
                let mut mac = mac.clone();
                mac.update(secret);
                let mut hex = [0; 16];
                for (i, b) in mac.finalize().into_bytes()[..8].iter().enumerate() {
                    hex[2 * i] = HEX[usize::from(b >> 4)];
                    hex[2 * i + 1] = HEX[usize::from(b & 0x0f)];
                }
                hex
            }
            Self::Mask | Self::Observe => *b"REDACTED\0\0\0\0\0\0\0\0",
        }
    }

    /// Append the token for `secret`, found by the rule whose stem is `token`.
    pub fn write(&self, out: &mut Vec<u8>, token: &str, secret: &[u8]) {
        let suffix = self.suffix(secret);
        let len = suffix.iter().position(|&b| b == 0).unwrap_or(suffix.len());
        out.push(b'[');
        out.extend_from_slice(token.as_bytes());
        out.push(b'_');
        out.extend_from_slice(&suffix[..len]);
        out.push(b']');
    }

    /// As [`Redactor::write`], into a string.
    pub fn write_str(&self, out: &mut String, token: &str, secret: &[u8]) {
        let suffix = self.suffix(secret);
        out.push('[');
        out.push_str(token);
        out.push('_');
        out.extend(
            suffix
                .iter()
                .take_while(|&&b| b != 0)
                .map(|&b| char::from(b)),
        );
        out.push(']');
    }
}