stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! Process-wide redaction of secrets from everything `stratum` writes.
//!
//! A secret the client handles in this process (the bootstrap token, and
//! every `Authorization` value it signs) is registered here when it is read
//! or made, and stays registered until the process exits. [`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::collections::BTreeSet;
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 sha2::{Digest as _, Sha256};
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));
    }
    add_needles(forms);
}

/// Adds secret forms to the needle list, longest first.
fn add_needles(forms: Vec<Zeroizing<String>>) {
    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()));
}

/// How many leading characters of a signed token are compared before any
/// hashing. Every `Authorization` token is the standard base64 of a JSON
/// event, and every event begins with the same six bytes, so in practice
/// there is one anchor and almost no ordinary text matches it.
const ANCHOR_LEN: usize = 8;

/// How many leading characters of a token index it. They cover the start
/// of the event's random ID, so no two tokens share them in practice.
/// Tokens shorter than this are kept as ordinary needles instead.
const KEY_LEN: usize = 64;

/// The first 16 bytes of a SHA-256 digest; used only to recognise text
/// that was registered, so a collision could only redact more.
type Digest16 = [u8; 16];

/// Every signed token registered in this process, as digests: nothing is
/// forgotten and no credential is kept in the clear.
///
/// A token costs one 40-byte entry plus the tree's overhead, about 60
/// bytes in all. A process runs one command, and the command that signs
/// the most is `export`: at most 100,000 entries, each fetched, asked for
/// its ACL and rechecked once (about 300,000 signatures, some 18 MB). Each
/// request may be retried at most three times when the gate is busy, so
/// the ceiling, with every request retried, is about 1.2 million
/// signatures and 72 MB. That bound is what makes it safe to keep them all,
/// which a provisioning `last_error` shown after many polls, or a skipped
/// child's ID shown at the end of an export, requires: either can quote a
/// header sent long before.
struct Signed {
    /// The distinct lowercased first [`ANCHOR_LEN`] bytes of the tokens.
    anchors: Vec<[u8; ANCHOR_LEN]>,
    /// For each token: the digest of its lowercased first [`KEY_LEN`]
    /// bytes, its length, and the digest of the whole lowercased token.
    tokens: BTreeSet<(Digest16, usize, Digest16)>,
}

impl Signed {
    /// The length of the longest registered token that `window` starts
    /// with, compared in lowercase.
    fn matching_len(&self, window: &[u8]) -> Option<usize> {
        let key = digest16(&window[..KEY_LEN]);
        self.tokens
            .range((key, 0, [0; 16])..=(key, usize::MAX, [u8::MAX; 16]))
            .rev()
            .find(|(_, len, digest)| window.len() >= *len && digest16(&window[..*len]) == *digest)
            .map(|(_, len, _)| *len)
    }
}

/// The signed tokens of this process.
static SIGNED: Mutex<Signed> = Mutex::new(Signed {
    anchors: Vec::new(),
    tokens: BTreeSet::new(),
});

/// Returns the first 16 bytes of the SHA-256 of `bytes`.
fn digest16(bytes: &[u8]) -> Digest16 {
    let digest = Sha256::digest(bytes);
    let mut out = [0; 16];
    out.copy_from_slice(&digest[..16]);
    out
}

/// Registers a short-lived secret that is text, such as an `Authorization`
/// value. When it is `<scheme> <token>`, the token is what is registered
/// (the scheme word is not secret and stays visible in output); otherwise
/// the whole text is. The token stays registered for the life of the
/// process, however many others follow (see [`Signed`]).
pub(crate) fn register_text_secret(text: &str) {
    let token = text.split_once(' ').map_or(text, |(_, token)| token);
    if token.len() < KEY_LEN {
        add_needles(vec![Zeroizing::new(token.to_owned())]);
        return;
    }
    let lower = Zeroizing::new(token.to_ascii_lowercase());
    let bytes = lower.as_bytes();
    let mut anchor = [0; ANCHOR_LEN];
    anchor.copy_from_slice(&bytes[..ANCHOR_LEN]);
    let mut signed = SIGNED.lock().unwrap_or_else(PoisonError::into_inner);
    if !signed.anchors.contains(&anchor) {
        signed.anchors.push(anchor);
    }
    signed
        .tokens
        .insert((digest16(&bytes[..KEY_LEN]), bytes.len(), digest16(bytes)));
}

/// Returns `text` with every registered secret form replaced by
/// [`REDACTED`]. Hex forms and signed tokens 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);
    }
    drop(needles);
    replace_signed(&clean)
}

/// Replaces every registered signed token in `text`, wherever it starts
/// (characters glued to either end do not hide it).
///
/// Each position is compared with the few anchors; only where one matches
/// is the next [`KEY_LEN`] bytes' digest looked up, and only a token found
/// that way is hashed in full. The cost is linear in the text, whatever
/// the number of tokens.
fn replace_signed(text: &str) -> String {
    let signed = SIGNED.lock().unwrap_or_else(PoisonError::into_inner);
    if signed.tokens.is_empty() {
        return text.to_owned();
    }
    // ASCII lowercasing keeps every byte at its offset.
    let lower = text.to_ascii_lowercase();
    let hay = lower.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut copied = 0;
    let mut index = 0;
    while index + KEY_LEN <= hay.len() {
        let window = &hay[index..];
        if signed
            .anchors
            .iter()
            .any(|anchor| window.starts_with(anchor))
        {
            if let Some(len) = signed.matching_len(window) {
                // A token is ASCII, so both ends of a match are char
                // boundaries.
                out.push_str(&text[copied..index]);
                out.push_str(REDACTED);
                index += len;
                copied = index;
                continue;
            }
        }
        index += 1;
    }
    out.push_str(&text[copied..]);
    out
}

/// 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: ü");
    }

    /// An `Authorization` value shaped like the ones `client::sign` makes:
    /// the scheme and the standard base64 of a JSON event, distinct per `n`.
    fn authorization(n: usize) -> String {
        let event = format!(
            r#"{{"id":"{n:064x}","pubkey":"{}","kind":27235,"tags":[["u","https://x/{n}"]]}}"#,
            "ab".repeat(32)
        );
        format!("Nostr {}", STANDARD.encode(event))
    }

    #[test]
    fn every_signature_of_a_command_stays_registered() {
        // The first of many signatures, echoed back late (a provisioning
        // `last_error` shown after many polls), is still redacted.
        let first = authorization(1_000_000);
        register_text_secret(&first);
        for n in 0..1_000 {
            register_text_secret(&authorization(n));
        }
        let token = first.split_once(' ').expect("scheme").1;
        for echo in [
            format!("last_error: bad header {first}"),
            format!("{{\"error\":\"{token}\"}}"),
            token.to_ascii_lowercase(),
        ] {
            let clean = redact(&echo);
            assert!(
                !clean
                    .to_ascii_lowercase()
                    .contains(&token.to_ascii_lowercase()),
                "{clean}"
            );
            assert!(clean.contains(REDACTED), "{clean}");
        }
    }

    #[test]
    fn a_token_glued_to_other_characters_is_still_redacted() {
        let value = authorization(2_000_000);
        register_text_secret(&value);
        let token = value.split_once(' ').expect("scheme").1;
        let clean = redact(&format!("A{token}zz+/ and again:{token}"));
        assert!(!clean.contains(token), "{clean}");
        assert_eq!(
            clean,
            format!("A{REDACTED}zz+/ and again:{REDACTED}"),
            "{clean}"
        );
    }

    #[test]
    fn a_whole_export_of_signatures_stays_cheap() {
        // An export's worth of signatures; no timing is asserted, but a
        // redaction that grew with the number of registrations would make
        // this test crawl.
        for n in 3_000_000..3_100_000 {
            register_text_secret(&authorization(n));
        }
        let line =
            "skipped: \"https://elsewhere/x\" (listed in /pods/abc/): another origin ".repeat(50);
        for _ in 0..100 {
            assert_eq!(redact(&line), line, "plain text is unchanged");
        }
        let late = authorization(3_000_000);
        assert!(
            !redact(&late).contains(late.split_once(' ').expect("scheme").1),
            "first kept"
        );
    }

    #[test]
    fn real_signatures_share_the_anchor_and_differ_within_the_key() {
        // The index relies on the token layout `client::sign` produces: the
        // standard base64 of an event whose JSON starts with `{"id":"`, so
        // the anchor is shared and the key covers random ID digits.
        let key = stratum_node_core::NostrSecretKey::from_hex(&"07".repeat(32)).expect("key");
        let sign = || crate::client::sign(&key, "GET", "https://x/pods/", None).expect("sign");
        let (first, second) = (sign(), sign());
        let token = |value: &str| value.split_once(' ').expect("scheme").1.to_owned();
        let (a, b) = (token(&first), token(&second));
        assert!(a.len() > KEY_LEN, "a token is longer than its key");
        assert_eq!(a[..ANCHOR_LEN], b[..ANCHOR_LEN], "one shared anchor");
        assert_ne!(a[..KEY_LEN], b[..KEY_LEN], "the key differs per token");
        register_text_secret(&first);
        let clean = redact(&format!("echo: {first}"));
        assert_eq!(clean, format!("echo: Nostr {REDACTED}"), "{clean}");
    }
}