use std::fmt;
use zeroize::Zeroize;
#[derive(Clone, PartialEq, Eq, Default)]
pub struct Secret<T: Zeroize>(T);
impl<T: Zeroize> Drop for Secret<T> {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl<T: Zeroize> Secret<T> {
pub fn new(value: T) -> Self {
Secret(value)
}
pub fn expose(&self) -> &T {
&self.0
}
pub fn into_inner(mut self) -> T
where
T: Default,
{
std::mem::take(&mut self.0)
}
}
pub trait SecretLen: sealed::Sealed {
fn secret_char_count(&self) -> usize;
}
mod sealed {
pub trait Sealed {}
}
impl sealed::Sealed for String {}
impl sealed::Sealed for str {}
impl<T: sealed::Sealed + ?Sized> sealed::Sealed for &T {}
impl SecretLen for String {
fn secret_char_count(&self) -> usize {
self.chars().count()
}
}
impl SecretLen for str {
fn secret_char_count(&self) -> usize {
self.chars().count()
}
}
impl<T: SecretLen + ?Sized> SecretLen for &T {
fn secret_char_count(&self) -> usize {
(**self).secret_char_count()
}
}
impl<T: Zeroize> From<T> for Secret<T> {
fn from(value: T) -> Self {
Secret::new(value)
}
}
impl<T: SecretLen + Zeroize> fmt::Debug for Secret<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", chars(self.0.secret_char_count()))
}
}
pub struct RedactedCount {
count: usize,
unit: &'static str,
}
impl fmt::Debug for RedactedCount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<{} {}>", self.count, self.unit)
}
}
pub fn chars(count: usize) -> RedactedCount {
RedactedCount { count, unit: "chars" }
}
pub fn bytes(count: usize) -> RedactedCount {
RedactedCount { count, unit: "bytes" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_secret_never_renders_its_own_value() {
let secret = Secret::new("hunter2-correct-horse".to_string());
let rendered = format!("{secret:?}");
assert!(!rendered.contains("hunter2"), "leaked: {rendered}");
assert_eq!(rendered, "<21 chars>");
}
#[test]
fn a_secret_nested_inside_a_derived_debug_still_renders_only_a_count() {
#[derive(Debug)]
#[allow(dead_code)]
struct Request {
username: String,
password: Secret<String>,
}
let rendered = format!(
"{:?}",
Request {
username: "apost".to_string(),
password: Secret::new("swordfish1".to_string()),
}
);
assert!(!rendered.contains("swordfish"), "leaked: {rendered}");
assert!(rendered.contains("<10 chars>"), "got {rendered}");
}
#[test]
fn the_count_is_characters_not_bytes() {
let secret = Secret::new("pässwörd".to_string());
assert_eq!(format!("{secret:?}"), "<8 chars>");
}
#[test]
fn expose_is_the_only_way_back_to_the_value() {
let secret = Secret::new("hunter2".to_string());
assert_eq!(secret.expose(), "hunter2");
}
#[test]
fn a_redacted_count_renders_a_count_and_a_unit_never_a_value() {
assert_eq!(format!("{:?}", chars(28)), "<28 chars>");
assert_eq!(format!("{:?}", bytes(2048)), "<2048 bytes>");
}
}
#[cfg(test)]
mod erasing {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone, Default)]
struct Counted(Option<&'static AtomicUsize>);
impl Zeroize for Counted {
fn zeroize(&mut self) {
if let Some(counter) = self.0 {
counter.fetch_add(1, Ordering::SeqCst);
}
}
}
static DROPPED: AtomicUsize = AtomicUsize::new(0);
static TAKEN: AtomicUsize = AtomicUsize::new(0);
#[test]
fn a_secret_erases_itself_when_it_goes_out_of_scope() {
DROPPED.store(0, Ordering::SeqCst);
{
let _held = Secret::new(Counted(Some(&DROPPED)));
assert_eq!(DROPPED.load(Ordering::SeqCst), 0, "not while it is still in use");
}
assert_eq!(DROPPED.load(Ordering::SeqCst), 1);
}
#[test]
fn every_displaced_value_is_erased_not_only_the_last() {
DROPPED.store(0, Ordering::SeqCst);
let mut entered = Secret::new(Counted(Some(&DROPPED)));
for _ in 0..8 {
entered = Secret::new(Counted(Some(&DROPPED)));
}
assert_eq!(DROPPED.load(Ordering::SeqCst), 8, "one per displaced value");
drop(entered);
assert_eq!(DROPPED.load(Ordering::SeqCst), 9);
}
#[test]
fn taking_the_value_out_does_not_erase_the_value_that_was_taken() {
TAKEN.store(0, Ordering::SeqCst);
let held = Secret::new(Counted(Some(&TAKEN)));
let out = held.into_inner();
assert_eq!(TAKEN.load(Ordering::SeqCst), 0, "the value that was taken must not be erased");
assert!(out.0.is_some(), "and it is the real one");
}
#[test]
fn a_string_password_is_what_this_is_for() {
let password = Secret::new("hunter2".to_string());
assert_eq!(password.expose(), "hunter2");
assert!(!format!("{password:?}").contains("hunter2"));
}
}