use std::fmt;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha384;
use zeroize::Zeroizing;
pub const HASH_ALGORITHM: &str = "hmac-sha384-keyed-truncated-to-32-hex";
#[derive(Clone)]
pub struct HashKey(Zeroizing<Vec<u8>>);
impl HashKey {
#[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())
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub enum Redaction {
#[default]
Mask,
Hash(HashKey),
Observe,
}
#[derive(Clone)]
pub(super) enum Redactor {
Mask,
Hash(Box<Hmac<Sha384>>),
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,
Redaction::Hash(key) => <Hmac<Sha384> as KeyInit>::new_from_slice(&key.0)
.map_or(Self::Mask, |mac| Self::Hash(Box::new(mac))),
Redaction::Observe => Self::Observe,
}
}
}
const HEX: &[u8; 16] = b"0123456789abcdef";
impl Redactor {
pub const fn observes(&self) -> bool {
matches!(self, Self::Observe)
}
fn suffix(&self, secret: &[u8]) -> [u8; 32] {
match self {
Self::Hash(mac) => {
let mut mac = mac.clone();
mac.update(secret);
let mut hex = [0; 32];
for (i, b) in mac.finalize().into_bytes()[..16].iter().enumerate() {
hex[2 * i] = HEX[usize::from(b >> 4)];
hex[2 * i + 1] = HEX[usize::from(b & 0x0f)];
}
hex
}
Self::Mask | Self::Observe => {
let mut mask = [0; 32];
mask[..8].copy_from_slice(b"REDACTED");
mask
}
}
}
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']');
}
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(']');
}
}