apollo-redaction 0.2.0

Redaction utility for sensitive data in error messages, debug logs, etc.
Documentation
use crate::RedactionStrategy;
use std::fmt;

/// Redact all but the first 4 characters.
///
/// Useful for API keys or tokens where the prefix identifies the key type.
///
/// If the value has 4 or fewer characters, outputs at least 4 asterisks
/// to avoid leaking information about short values.
///
/// ```rust
/// use apollo_redaction::Redacted;
/// use apollo_redaction::strategy::First4Redactor;
///
/// fn first4(input: &str) -> String {
///     Redacted::<_, First4Redactor>::new(input).to_string()
/// }
///
/// assert_eq!(first4("sk_live_abc123"), "sk_l****");
/// assert_eq!(first4("abc"), "****");
/// assert_eq!(first4("api_key_secret"), "api_****");
/// ```
#[derive(Default, Clone)]
pub struct First4Redactor;

impl<T: AsRef<str>> RedactionStrategy<T> for First4Redactor {
    fn display(&self, value: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = value.as_ref();
        let len = s.chars().count();

        if len <= 4 {
            write!(f, "****")
        } else {
            for c in s.chars().take(4) {
                write!(f, "{c}")?;
            }
            write!(f, "****")
        }
    }
}

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

    fn first4(input: &str) -> String {
        Redacted::<_, First4Redactor>::new(input).to_string()
    }

    #[test]
    fn test_first4() {
        assert_eq!(first4("sk_live_abc123"), "sk_l****");
        assert_eq!(first4("api_key_secret"), "api_****");
    }

    #[test]
    fn test_short_input() {
        assert_eq!(first4("abc"), "****");
        assert_eq!(first4("abcd"), "****");
        assert_eq!(first4("a"), "****");
        assert_eq!(first4(""), "****");
    }

    #[test]
    fn test_exactly_5_chars() {
        assert_eq!(first4("12345"), "1234****");
    }

    #[test]
    fn test_unicode() {
        assert_eq!(first4("안녕하세요한글"), "안녕하세****");
    }
}