Skip to main content

error_forge/
redacted.rs

1//! A wrapper that keeps a value out of error text.
2
3use std::fmt;
4
5/// A value that prints as `[redacted]` in `Display` and `Debug`.
6///
7/// Wrap secrets (passwords, tokens, keys) and personal data held in an
8/// error, so they never reach `Display`, `Debug`, `dev_message`, the log
9/// adapters, or an [`ErrorCollector`](crate::ErrorCollector) summary.
10/// The default `define_errors!` format prints every field with `Debug`,
11/// so a `Redacted` field prints as `[redacted]` there too. Read the
12/// value with [`expose`](Self::expose) where it is really needed.
13///
14/// `Redacted` only changes how the value is printed. It does not wipe
15/// memory and is not a cryptographic protection.
16///
17/// # Example
18///
19/// ```
20/// use error_forge::Redacted;
21///
22/// let token = Redacted::new(String::from("hunter2"));
23/// assert_eq!(format!("{token}"), "[redacted]");
24/// assert_eq!(format!("{token:?}"), "[redacted]");
25/// assert_eq!(token.expose(), "hunter2");
26/// ```
27#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
28pub struct Redacted<T>(T);
29
30impl<T> Redacted<T> {
31    /// Wrap `value`.
32    pub const fn new(value: T) -> Self {
33        Self(value)
34    }
35
36    /// The wrapped value.
37    pub const fn expose(&self) -> &T {
38        &self.0
39    }
40
41    /// Unwrap the value.
42    pub fn into_inner(self) -> T {
43        self.0
44    }
45}
46
47impl<T> From<T> for Redacted<T> {
48    fn from(value: T) -> Self {
49        Self(value)
50    }
51}
52
53impl<T> fmt::Debug for Redacted<T> {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str("[redacted]")
56    }
57}
58
59impl<T> fmt::Display for Redacted<T> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str("[redacted]")
62    }
63}
64
65#[cfg(feature = "serde")]
66impl<T> serde::Serialize for Redacted<T> {
67    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
68        serializer.serialize_str("[redacted]")
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::Redacted;
75
76    #[test]
77    fn never_prints_the_value() {
78        let secret = Redacted::from("swordfish");
79        assert_eq!(secret.to_string(), "[redacted]");
80        assert_eq!(format!("{secret:?}"), "[redacted]");
81        assert_eq!(format!("{secret:#?}"), "[redacted]");
82        assert_eq!(*secret.expose(), "swordfish");
83        assert_eq!(secret.into_inner(), "swordfish");
84    }
85}