Skip to main content

isothrum_runner/
secrets.rs

1//! Sensitive values: held by the embedder, handed in per operation, never printed, never stored,
2//! and never written to a file: the tools get them in their environment
3//! ([`crate::project::inputs`]), and every event masks them.
4
5use std::collections::BTreeMap;
6use std::fmt;
7
8/// A secret's value. Its `Debug` never shows it.
9#[derive(Clone, PartialEq, Eq)]
10pub struct SecretValue(String);
11
12impl SecretValue {
13    /// Holds `value`.
14    pub fn new(value: impl Into<String>) -> SecretValue {
15        SecretValue(value.into())
16    }
17
18    /// The value itself, for the tool it is handed to.
19    #[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/// Sensitive values, by the name the tools get each under.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct Secrets(BTreeMap<String, SecretValue>);
34
35impl Secrets {
36    /// No values.
37    #[must_use]
38    pub fn new() -> Secrets {
39        Secrets::default()
40    }
41
42    /// Sets `name`'s value.
43    pub fn insert(&mut self, name: impl Into<String>, value: SecretValue) {
44        self.0.insert(name.into(), value);
45    }
46
47    /// `name`'s value, when given.
48    #[must_use]
49    pub fn get(&self, name: &str) -> Option<&SecretValue> {
50        self.0.get(name)
51    }
52
53    /// Every value given, by name.
54    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}