Skip to main content

asterust_junos/
secret.rs

1//! Passwords, keys and shared secrets, which are read only when the `secrets` feature is enabled.
2
3use std::fmt;
4
5/// A password, key or shared secret as written in the configuration, usually the encrypted `$9$...` form.
6///
7/// `Debug` never prints the value. Read it with [`expose`](Self::expose).
8#[derive(Clone, PartialEq, Eq)]
9pub struct Secret(String);
10
11impl Secret {
12    /// The value as written, without its quotes.
13    pub fn expose(&self) -> &str {
14        &self.0
15    }
16}
17
18impl fmt::Debug for Secret {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        f.write_str("Secret(<redacted>)")
21    }
22}
23
24/// `value` as a [`Secret`], or `None` unless the `secrets` feature is enabled.
25pub(crate) fn secret_value(value: Option<&str>) -> Option<Secret> {
26    if cfg!(feature = "secrets") {
27        value.map(|v| Secret(crate::unquote(v).to_string()))
28    } else {
29        None
30    }
31}
32
33#[cfg(test)]
34/// What a fixture's secret reads as in this build.
35pub(crate) fn expected(value: &str) -> Option<&str> {
36    cfg!(feature = "secrets").then_some(value)
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn debug_hides_the_value() {
45        let secret = Secret("$9$abc".to_string());
46        assert_eq!(format!("{secret:?}"), "Secret(<redacted>)");
47        assert_eq!(secret.expose(), "$9$abc");
48    }
49
50    #[cfg(feature = "secrets")]
51    #[test]
52    fn reads_and_unquotes_with_the_feature() {
53        assert_eq!(secret_value(Some("\"$9$abc\"")).unwrap().expose(), "$9$abc");
54        assert_eq!(secret_value(None), None);
55    }
56
57    #[cfg(not(feature = "secrets"))]
58    #[test]
59    fn reads_nothing_without_the_feature() {
60        assert_eq!(secret_value(Some("$9$abc")), None);
61    }
62}