Skip to main content

kellnr_common/
plain_token.rs

1use std::fmt;
2
3/// The secret of an auth token or a session as the client sends it. Only its
4/// hash is stored. It has no `Display` and its `Debug` hides the secret, so it
5/// cannot end up in logs by accident.
6#[derive(Clone, PartialEq, Eq)]
7pub struct PlainToken(String);
8
9impl PlainToken {
10    pub fn new(token: impl Into<String>) -> Self {
11        Self(token.into())
12    }
13
14    pub fn expose_secret(&self) -> &str {
15        &self.0
16    }
17
18    pub fn into_secret(self) -> String {
19        self.0
20    }
21}
22
23impl From<String> for PlainToken {
24    fn from(token: String) -> Self {
25        Self(token)
26    }
27}
28
29impl From<&str> for PlainToken {
30    fn from(token: &str) -> Self {
31        Self(token.to_owned())
32    }
33}
34
35impl fmt::Debug for PlainToken {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str("PlainToken(<redacted>)")
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn debug_hides_the_secret() {
47        let token = PlainToken::from("s3cr3t");
48        let debug = format!("{token:?}");
49        assert_eq!("PlainToken(<redacted>)", debug);
50        assert!(!debug.contains("s3cr3t"));
51        assert_eq!("s3cr3t", token.expose_secret());
52    }
53}