1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
use std::{
    convert::Infallible,
    fmt::{self, Debug, Display},
    str::FromStr,
};

/// Password to login. `String` newtype.
///
/// The `Debug` and `Display` implementations for this type mask the password.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, PartialEq, Eq)]
pub struct PlainText(String);

impl PlainText {
    /// Returns a new plain text password.
    pub fn new<S>(plain_text: S) -> Self
    where
        S: Into<String>,
    {
        Self(Into::<String>::into(plain_text))
    }

    /// Returns the in-memory representation of the password.
    ///
    /// This is simply the plain text password.
    pub fn encoded(&self) -> &str {
        &self.0
    }

    /// Returns the plain text password.
    pub fn plain_text(&self) -> &str {
        &self.0
    }
}

// Never reveal the password, even in `Debug`
impl Debug for PlainText {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "PlainText(\"******\")")
    }
}

impl Display for PlainText {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "******")
    }
}

impl FromStr for PlainText {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<PlainText, Infallible> {
        Ok(PlainText::new(s))
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::PlainText;

    #[test]
    fn stores_plain_text_password() {
        assert_eq!("hi", PlainText::new("hi").encoded());
    }

    #[test]
    fn returns_plain_text() {
        assert_eq!("hi", PlainText::new("hi").plain_text());
    }

    #[test]
    fn debug_masks_password() {
        assert_eq!(
            "PlainText(\"******\")",
            format!("{:?}", PlainText::new("hi"))
        )
    }

    #[test]
    fn display_masks_password() {
        assert_eq!("******", format!("{}", PlainText::new("hi")))
    }

    #[test]
    fn from_str_returns_plain_text() {
        assert_eq!(
            "hi",
            PlainText::from_str("hi")
                .unwrap_or_else(unreachable)
                .encoded()
        );
    }

    #[cfg(not(tarpaulin_include))]
    fn unreachable(_: impl std::error::Error) -> PlainText {
        unreachable!()
    }
}