use std::fmt;
use thiserror::Error;
use zeroize::Zeroizing;
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub struct Password(Zeroizing<Vec<u8>>);
impl Password {
pub const MAX_LEN: usize = 1024;
pub fn new(bytes: Vec<u8>) -> Result<Self, PasswordError> {
let secret = Zeroizing::new(bytes);
match secret.len() {
0 => Err(PasswordError::Empty),
len if len > Self::MAX_LEN => Err(PasswordError::TooLong { len }),
_ => Ok(Self(secret)),
}
}
pub fn shared(bytes: Vec<u8>) -> Result<std::sync::Arc<Self>, PasswordError> {
Self::new(bytes).map(std::sync::Arc::new)
}
#[must_use]
pub fn byte_len(&self) -> usize {
self.0.len()
}
pub(super) fn expose(&self) -> &[u8] {
&self.0
}
}
impl fmt::Debug for Password {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Password(..)")
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PasswordError {
#[error("a password must not be empty")]
Empty,
#[error("a password must not exceed {} bytes (got {len})", Password::MAX_LEN)]
TooLong {
len: usize,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn length_bounds_are_one_to_max() {
assert_eq!(Password::new(Vec::new()).unwrap_err(), PasswordError::Empty);
assert!(Password::new(vec![0; 1]).is_ok());
assert!(Password::new(vec![0; Password::MAX_LEN]).is_ok());
assert_eq!(
Password::new(vec![0; Password::MAX_LEN + 1]).unwrap_err(),
PasswordError::TooLong {
len: Password::MAX_LEN + 1
}
);
}
#[test]
fn debug_hides_the_secret() {
let password = Password::new(b"hunter2".to_vec()).unwrap();
assert_eq!(format!("{password:?}"), "Password(..)");
assert_eq!(password.byte_len(), 7);
}
}