isothrum_runner/
secrets.rs1use std::collections::BTreeMap;
6use std::fmt;
7
8#[derive(Clone, PartialEq, Eq)]
10pub struct SecretValue(String);
11
12impl SecretValue {
13 pub fn new(value: impl Into<String>) -> SecretValue {
15 SecretValue(value.into())
16 }
17
18 #[must_use]
20 pub fn expose(&self) -> &str {
21 &self.0
22 }
23}
24
25impl fmt::Debug for SecretValue {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 f.write_str("SecretValue(<redacted>)")
28 }
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct Secrets(BTreeMap<String, SecretValue>);
34
35impl Secrets {
36 #[must_use]
38 pub fn new() -> Secrets {
39 Secrets::default()
40 }
41
42 pub fn insert(&mut self, name: impl Into<String>, value: SecretValue) {
44 self.0.insert(name.into(), value);
45 }
46
47 #[must_use]
49 pub fn get(&self, name: &str) -> Option<&SecretValue> {
50 self.0.get(name)
51 }
52
53 pub fn iter(&self) -> impl Iterator<Item = (&str, &SecretValue)> {
55 self.0.iter().map(|(k, v)| (k.as_str(), v))
56 }
57}
58
59impl From<String> for SecretValue {
60 fn from(value: String) -> SecretValue {
61 SecretValue(value)
62 }
63}
64
65impl From<&str> for SecretValue {
66 fn from(value: &str) -> SecretValue {
67 SecretValue(value.to_owned())
68 }
69}
70
71impl<K: Into<String>, V: Into<SecretValue>> FromIterator<(K, V)> for Secrets {
72 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Secrets {
73 Secrets(iter.into_iter().map(|(k, v)| (k.into(), v.into())).collect())
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn a_secret_never_prints() {
83 let mut s = Secrets::new();
84 s.insert("DEMO_SECRET", SecretValue::new("token-hunter2"));
85 let shown = format!("{s:?}");
86 assert!(!shown.contains("hunter2") && shown.contains("<redacted>"), "{shown}");
87 assert_eq!(s.get("DEMO_SECRET").map(SecretValue::expose), Some("token-hunter2"));
88 }
89}