stratum-node-cli 0.1.0-alpha.1

The `stratum` operator client for Stratum pod nodes: operator key files, bootstrap claim, signed config apply, audit checkpoint and backup over the loopback API
Documentation
//! Process-wide redaction of secrets from everything `stratum` writes.
//!
//! A secret the client handles in this process (the bootstrap token) is
//! registered here when it is read. [`Output`](crate::Output) passes every
//! string it writes, server-supplied error text and JSON included, through
//! [`redact`], so a node that echoes the token back cannot make the CLI
//! print it (E1.12).
//!
//! The operator's secret key is never sent to the node, so the node cannot
//! reflect it; the key is never formatted as text, and is not registered.

use std::sync::{Mutex, PoisonError};

use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
use base64::Engine as _;
use zeroize::Zeroizing;

/// What replaces a secret in output.
pub(crate) const REDACTED: &str = "<redacted>";

/// Every form of every registered secret, longest first.
static NEEDLES: Mutex<Vec<Zeroizing<String>>> = Mutex::new(Vec::new());

/// Registers a hex secret: its text in any letter case, and the standard
/// and URL-safe base64 of both its text and its decoded bytes, with and
/// without padding.
pub(crate) fn register_hex_secret(hex_text: &str) {
    let mut forms: Vec<Zeroizing<String>> = vec![Zeroizing::new(hex_text.to_ascii_lowercase())];
    let mut encode = |bytes: &[u8]| {
        for engine in [&STANDARD, &STANDARD_NO_PAD, &URL_SAFE, &URL_SAFE_NO_PAD] {
            forms.push(Zeroizing::new(engine.encode(bytes)));
        }
    };
    encode(hex_text.as_bytes());
    if let Ok(bytes) = hex::decode(hex_text) {
        encode(&Zeroizing::new(bytes));
    }
    let mut needles = NEEDLES.lock().unwrap_or_else(PoisonError::into_inner);
    for form in forms {
        if !form.is_empty() && !needles.iter().any(|known| **known == *form) {
            needles.push(form);
        }
    }
    needles.sort_by_key(|needle| std::cmp::Reverse(needle.len()));
}

/// Returns `text` with every registered secret form replaced by
/// [`REDACTED`]. Hex forms match in any letter case.
pub(crate) fn redact(text: &str) -> String {
    let needles = NEEDLES.lock().unwrap_or_else(PoisonError::into_inner);
    let mut clean = text.to_owned();
    for needle in needles.iter() {
        clean = replace_case_insensitive(&clean, needle);
    }
    clean
}

/// Replaces every ASCII-case-insensitive occurrence of `needle` in `text`.
///
/// Case-insensitive matching is what a lowercase hex token needs; for the
/// base64 forms it can only redact more, never less.
fn replace_case_insensitive(text: &str, needle: &str) -> String {
    let (hay, pat) = (text.as_bytes(), needle.as_bytes());
    if pat.is_empty() || hay.len() < pat.len() {
        return text.to_owned();
    }
    let mut out = String::with_capacity(text.len());
    let mut copied = 0;
    let mut index = 0;
    while index + pat.len() <= hay.len() {
        if hay[index..index + pat.len()].eq_ignore_ascii_case(pat) {
            // `needle` is ASCII, so both ends of a match are char boundaries.
            out.push_str(&text[copied..index]);
            out.push_str(REDACTED);
            index += pat.len();
            copied = index;
        } else {
            index += 1;
        }
    }
    out.push_str(&text[copied..]);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hex_and_base64_forms_are_redacted_in_any_case() {
        let token = "0123456789abcdef".repeat(4);
        register_hex_secret(&token);
        let upper = token.to_uppercase();
        let b64_text = STANDARD.encode(token.as_bytes());
        let b64_bytes = URL_SAFE_NO_PAD.encode(hex::decode(&token).expect("hex"));
        let text = format!("a {token} b {upper} c {b64_text} d {b64_bytes} é");
        let clean = redact(&text);
        for form in [&token, &upper, &b64_text, &b64_bytes] {
            assert!(!clean.contains(form.as_str()), "{clean}");
        }
        assert_eq!(clean.matches(REDACTED).count(), 4, "{clean}");
        assert!(clean.ends_with(" é"), "{clean}");
    }

    #[test]
    fn text_without_secrets_is_unchanged() {
        assert_eq!(redact("nothing secret here: ü"), "nothing secret here: ü");
    }
}