use std::fmt;
const MASK: &str = "<redacted>";
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);
impl Secret {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn expose(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_exposed(self) -> String {
self.0
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
}
impl fmt::Debug for Secret {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(MASK)
}
}
impl fmt::Display for Secret {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(MASK)
}
}
impl From<String> for Secret {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for Secret {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
const MARKER: &str = "SharedAccessKey=NEEDLE-9f2c";
#[test]
fn debug_does_not_print_the_value() {
let printed = format!("{:?}", Secret::new(MARKER));
assert_eq!(printed, MASK);
assert!(!printed.contains("NEEDLE"));
}
#[test]
fn display_does_not_print_the_value() {
assert!(!Secret::new(MARKER).to_string().contains("NEEDLE"));
assert!(!format!("{}", Secret::new(MARKER)).contains("NEEDLE"));
}
#[test]
fn a_secret_inside_a_derived_debug_stays_hidden() {
#[derive(Debug)]
#[allow(dead_code)]
struct Config {
queue: &'static str,
key: Secret,
}
let printed = format!(
"{:?}",
Config {
queue: "orders",
key: Secret::new(MARKER),
}
);
assert!(printed.contains("orders"));
assert!(!printed.contains("NEEDLE"));
}
#[test]
fn the_value_is_reachable_when_asked_for() {
assert_eq!(Secret::new(MARKER).expose(), MARKER);
assert_eq!(Secret::new(MARKER).into_exposed(), MARKER);
}
#[test]
fn a_length_is_reportable_but_the_content_is_not() {
let secret = Secret::new(MARKER);
assert_eq!(secret.len(), MARKER.len());
assert!(!secret.is_empty());
assert!(Secret::new("").is_empty());
}
#[test]
fn conversion_from_the_usual_string_types() {
assert_eq!(Secret::from("x").expose(), "x");
assert_eq!(Secret::from(String::from("y")).expose(), "y");
}
}