Skip to main content

rustauth_core/
secret.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6#[serde(transparent)]
7/// Secret string wrapper that redacts its value in `Debug` output.
8pub struct SecretString(String);
9
10impl SecretString {
11    /// Wrap a secret value.
12    pub fn new(value: impl Into<String>) -> Self {
13        Self(value.into())
14    }
15
16    /// Borrow the raw secret value.
17    ///
18    /// Prefer passing the secret directly to crypto or HTTP client code and
19    /// avoid logging this value.
20    pub fn expose_secret(&self) -> &str {
21        &self.0
22    }
23
24    /// Consume the wrapper and return the raw secret value.
25    pub fn into_inner(self) -> String {
26        self.0
27    }
28}
29
30impl fmt::Debug for SecretString {
31    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32        formatter.write_str("SecretString(REDACTED)")
33    }
34}
35
36impl From<String> for SecretString {
37    fn from(value: String) -> Self {
38        Self::new(value)
39    }
40}
41
42impl From<&str> for SecretString {
43    fn from(value: &str) -> Self {
44        Self::new(value)
45    }
46}
47
48impl AsRef<str> for SecretString {
49    fn as_ref(&self) -> &str {
50        self.expose_secret()
51    }
52}