aul/
sensitive.rs

1//! Module for Sensitive wrapping with the [Sens] struct
2use std::fmt::{Display, Formatter};
3
4const ENV_KEY: &str = "SAFE_LOGGING";
5const ENV_VALUE: &str = "true";
6const SAFE_PRINT: &str = "[REDACTED]";
7
8/// ### Used to censor specific information in your logs. <br>
9/// Can be activated and deactivated (at any point at runtime!) by setting the environment variable `SAFE_LOGGING` to `true`
10///
11/// When activated it will only print `[REDACTED]` <br>
12///
13/// Example:
14/// ```
15///     use aul::sensitive::Sens;
16///
17///     println!("{}",Sens(&"Hello"));  // Hello
18///     //change env variable "SAFE_LOGGING" to true
19///     println!("{}",Sens(&"Hello")) // "[REDACTED]"
20/// ```
21/// ### Warning:
22/// It will look for the env key every call which has a runtime cost
23///
24/// [`SAFE_LOGGING`]: ENV_KEY
25/// [`true`]: ENV_VALUE
26/// [`REDACTED`]: SAFE_PRINT
27pub struct Sens<'a,T>(pub &'a T);
28#[cfg(color)]
29impl<T> Display for Sens<'_, T> where T: Display {
30    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31        if self.is_safe() {
32            SAFE_PRINT.black().fmt(f)
33        } else {
34            self.0.fmt(f)
35        }
36    }
37}
38
39#[cfg(not(color))]
40impl<T> Display for Sens<'_, T> where T: Display {
41    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42        if self.is_safe() {
43            SAFE_PRINT.fmt(f)
44        } else {
45            self.0.fmt(f)
46        }
47    }
48}
49
50impl<T> Sens<'_, T> {
51    fn is_safe(&self) -> bool {
52        std::env::var(ENV_KEY).is_ok_and(|t| { t.eq(ENV_VALUE) })
53    }
54}
55
56
57#[cfg(test)]
58mod tests {
59    #[cfg(color)]
60    use colored::Colorize;
61
62    use crate::sensitive::{ENV_KEY, Sens};
63
64    #[test]
65    fn test_sens_mode() {
66        std::env::set_var(ENV_KEY, "");
67        assert_eq!(Sens(&1).to_string(), "1");
68    }
69    #[cfg(color)]
70    #[test]
71    fn test_sens_mode_redacted() {
72        std::env::set_var(ENV_KEY, ENV_VALUE);
73        assert_eq!(Sens(&1).to_string(), SAFE_PRINT.black().to_string());
74    }
75}