1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt::Debug};
use zeroize::Zeroize;

/// Wrapper type for secret values such as passwords or authentication keys.
///
/// Once wrapped, the inner value cannot leak accidentally, as both the [`std::fmt::Display`] and [`Debug`]
/// implementations cover up the actual value and only show the type.
///
/// If you need access to the inner value, there is an [expose](`Secret::expose`) method.
///
/// To make sure nothing leaks after the [`Secret`] has been dropped, a custom [`Drop`]
/// implementation will zero-out the underlying memory.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Secret<T: Zeroize>(T);

impl<T: Zeroize> Debug for Secret<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[REDACTED {:?}]", std::any::type_name::<T>())
    }
}

impl<T: Zeroize> Drop for Secret<T> {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

impl<T: Zeroize> From<T> for Secret<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: Zeroize> Secret<T> {
    pub fn new(secret: T) -> Self {
        Self(secret)
    }

    /// Expose the underlying value of the secret
    pub fn expose(&self) -> &T {
        &self.0
    }

    /// Display a placeholder for the secret
    pub fn redacted(&self) -> &str {
        "********"
    }
}

/// Store that holds all the secrets available to a deployment
#[derive(Deserialize, Serialize, Clone)]
#[serde(transparent)]
pub struct SecretStore {
    pub(crate) secrets: BTreeMap<String, Secret<String>>,
}

impl SecretStore {
    pub fn new(secrets: BTreeMap<String, Secret<String>>) -> Self {
        Self { secrets }
    }

    pub fn get(&self, key: &str) -> Option<String> {
        self.secrets.get(key).map(|s| s.expose().to_owned())
    }
}

impl IntoIterator for SecretStore {
    type Item = (String, String);
    type IntoIter = <BTreeMap<String, String> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.secrets
            .into_iter()
            .map(|(k, s)| (k, s.expose().to_owned()))
            .collect::<BTreeMap<_, _>>()
            .into_iter()
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod secrets_tests {
    use super::*;

    #[test]
    fn redacted() {
        let password_string = String::from("VERYSECRET");
        let secret = Secret::new(password_string);
        assert_eq!(secret.redacted(), "********");
    }

    #[test]
    fn debug() {
        let password_string = String::from("VERYSECRET");
        let secret = Secret::new(password_string);
        let printed = format!("{:?}", secret);
        assert_eq!(printed, "[REDACTED \"alloc::string::String\"]");
    }

    #[test]
    fn expose() {
        let password_string = String::from("VERYSECRET");
        let secret = Secret::new(password_string);
        let printed = secret.expose();
        assert_eq!(printed, "VERYSECRET");
    }

    #[test]
    fn secret_struct() {
        #[derive(Debug)]
        struct Wrapper {
            password: Secret<String>,
        }

        let password_string = String::from("VERYSECRET");
        let secret = Secret::new(password_string);
        let wrapper = Wrapper { password: secret };
        let printed = format!("{:?}", wrapper);
        assert_eq!(
            printed,
            "Wrapper { password: [REDACTED \"alloc::string::String\"] }"
        );
    }

    #[test]
    fn secretstore_intoiter() {
        let bt = BTreeMap::from([
            ("1".to_owned(), "2".to_owned().into()),
            ("3".to_owned(), "4".to_owned().into()),
        ]);
        let ss = SecretStore::new(bt);

        let mut iter = ss.into_iter();
        assert_eq!(iter.next(), Some(("1".to_owned(), "2".to_owned())));
        assert_eq!(iter.next(), Some(("3".to_owned(), "4".to_owned())));
        assert_eq!(iter.next(), None);
    }
}