Skip to main content

morphir_config/
secret.rs

1//! Portable references to secrets stored outside a Morphir configuration file.
2
3use serde_json::Value;
4use std::fmt;
5use std::path::PathBuf;
6use thiserror::Error;
7
8/// An external source for a secret value.
9#[derive(Clone, PartialEq, Eq)]
10pub enum SecretReference {
11    /// A secret read from an environment variable.
12    Environment { variable: String },
13    /// A secret read from a file.
14    File { path: PathBuf },
15    /// A secret supplied by an external command.
16    Command { program: String, args: Vec<String> },
17    /// A secret stored in an operating system keyring.
18    Keyring { service: String, account: String },
19}
20
21impl fmt::Debug for SecretReference {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::Environment { variable } => formatter
25                .debug_struct("Environment")
26                .field("variable", variable)
27                .finish(),
28            Self::File { path } => formatter.debug_struct("File").field("path", path).finish(),
29            Self::Command { program, args } => formatter
30                .debug_struct("Command")
31                .field("program", program)
32                .field("args", &RedactedCommandArguments(args.len()))
33                .finish(),
34            Self::Keyring { service, account } => formatter
35                .debug_struct("Keyring")
36                .field("service", service)
37                .field("account", account)
38                .finish(),
39        }
40    }
41}
42
43struct RedactedCommandArguments(usize);
44
45impl fmt::Debug for RedactedCommandArguments {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        let noun = if self.0 == 1 { "argument" } else { "arguments" };
48        write!(formatter, "<redacted: {} {noun}>", self.0)
49    }
50}
51
52/// The structural reason a JSON value cannot represent a [`SecretReference`].
53#[derive(Debug, Clone, PartialEq, Eq, Error)]
54pub enum SecretReferenceError {
55    /// The reference is not an object.
56    #[error("secret reference must be an object")]
57    ExpectedObject,
58    /// The reference object did not have exactly one discriminator.
59    #[error("secret reference must contain exactly one discriminator")]
60    ExpectedOneDiscriminator,
61    /// The reference discriminator is unknown.
62    #[error("secret reference discriminator is not supported")]
63    UnsupportedDiscriminator,
64    /// A required string field was missing, incorrectly typed, or empty.
65    #[error("secret reference {field} must be a non-empty string")]
66    ExpectedNonEmptyString {
67        /// The field with the invalid value.
68        field: &'static str,
69    },
70    /// The command was not a string array beginning with a non-empty executable.
71    #[error(
72        "secret reference command must be a string array beginning with a non-empty executable"
73    )]
74    ExpectedCommand,
75    /// The keyring value was not an object with exactly service and account.
76    #[error("secret reference keyring must contain exactly service and account")]
77    ExpectedKeyring,
78}
79
80impl TryFrom<&Value> for SecretReference {
81    type Error = SecretReferenceError;
82
83    fn try_from(value: &Value) -> Result<Self, Self::Error> {
84        let reference = value
85            .as_object()
86            .ok_or(SecretReferenceError::ExpectedObject)?;
87
88        if reference.len() != 1 {
89            return Err(SecretReferenceError::ExpectedOneDiscriminator);
90        }
91
92        let (kind, value) = reference
93            .iter()
94            .next()
95            .ok_or(SecretReferenceError::ExpectedOneDiscriminator)?;
96
97        match kind.as_str() {
98            "env" => Ok(Self::Environment {
99                variable: required_string(value, "env")?,
100            }),
101            "file" => Ok(Self::File {
102                path: required_string(value, "file")?.into(),
103            }),
104            "command" => parse_command(value),
105            "keyring" => parse_keyring(value),
106            _ => Err(SecretReferenceError::UnsupportedDiscriminator),
107        }
108    }
109}
110
111/// Return whether a JSON value is an exact secret-reference shape.
112pub fn is_secret_reference(value: &Value) -> bool {
113    SecretReference::try_from(value).is_ok()
114}
115
116fn required_string(value: &Value, field: &'static str) -> Result<String, SecretReferenceError> {
117    value
118        .as_str()
119        .filter(|value| !value.is_empty())
120        .map(str::to_owned)
121        .ok_or(SecretReferenceError::ExpectedNonEmptyString { field })
122}
123
124fn parse_command(value: &Value) -> Result<SecretReference, SecretReferenceError> {
125    let command = value
126        .as_array()
127        .filter(|command| !command.is_empty())
128        .ok_or(SecretReferenceError::ExpectedCommand)?;
129    let program = required_string(&command[0], "command")
130        .map_err(|_| SecretReferenceError::ExpectedCommand)?;
131    let args = command[1..]
132        .iter()
133        .map(Value::as_str)
134        .collect::<Option<Vec<_>>>()
135        .ok_or(SecretReferenceError::ExpectedCommand)?
136        .into_iter()
137        .map(str::to_owned)
138        .collect();
139
140    Ok(SecretReference::Command { program, args })
141}
142
143fn parse_keyring(value: &Value) -> Result<SecretReference, SecretReferenceError> {
144    let keyring = value
145        .as_object()
146        .filter(|keyring| keyring.len() == 2)
147        .ok_or(SecretReferenceError::ExpectedKeyring)?;
148    let service = keyring
149        .get("service")
150        .ok_or(SecretReferenceError::ExpectedKeyring)
151        .and_then(|value| required_string(value, "keyring.service"))?;
152    let account = keyring
153        .get("account")
154        .ok_or(SecretReferenceError::ExpectedKeyring)
155        .and_then(|value| required_string(value, "keyring.account"))?;
156
157    Ok(SecretReference::Keyring { service, account })
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use serde_json::json;
164
165    #[test]
166    fn parses_all_exact_reference_shapes() {
167        assert_eq!(
168            SecretReference::try_from(&json!({"env": "GITHUB_TOKEN"})).unwrap(),
169            SecretReference::Environment {
170                variable: "GITHUB_TOKEN".into()
171            }
172        );
173        assert_eq!(
174            SecretReference::try_from(&json!({"file": "secrets/token"})).unwrap(),
175            SecretReference::File {
176                path: "secrets/token".into()
177            }
178        );
179        assert_eq!(
180            SecretReference::try_from(&json!({"command": ["gh", "auth", "token"]})).unwrap(),
181            SecretReference::Command {
182                program: "gh".into(),
183                args: vec!["auth".into(), "token".into()],
184            }
185        );
186        assert_eq!(
187            SecretReference::try_from(
188                &json!({"keyring": {"service": "github.com", "account": "damre"}})
189            )
190            .unwrap(),
191            SecretReference::Keyring {
192                service: "github.com".into(),
193                account: "damre".into()
194            }
195        );
196    }
197
198    #[test]
199    fn command_debug_redacts_arguments_but_keeps_the_program_and_count() {
200        let reference = SecretReference::Command {
201            program: "secret-helper".into(),
202            args: vec!["private-command-argument".into(), "second".into()],
203        };
204
205        let debug = format!("{reference:?}");
206
207        assert!(debug.contains("secret-helper"));
208        assert!(debug.contains("2 arguments"));
209        assert!(!debug.contains("private-command-argument"));
210        assert!(!debug.contains("second"));
211    }
212
213    #[test]
214    fn command_arguments_may_be_empty_after_a_non_empty_program() {
215        assert_eq!(
216            SecretReference::try_from(&json!({"command": ["helper", "", "tail"]})).unwrap(),
217            SecretReference::Command {
218                program: "helper".into(),
219                args: vec!["".into(), "tail".into()],
220            }
221        );
222    }
223
224    #[test]
225    fn command_still_rejects_an_empty_program_and_an_empty_array() {
226        for value in [json!({"command": [""]}), json!({"command": []})] {
227            assert!(SecretReference::try_from(&value).is_err());
228        }
229    }
230
231    #[test]
232    fn rejects_mixed_extra_empty_and_wrong_typed_reference_shapes() {
233        for value in [
234            json!({"env": "A", "file": "b"}),
235            json!({"command": []}),
236            json!({"command": ["gh", 1]}),
237            json!({"keyring": {"service": "github.com"}}),
238            json!({"keyring": {"service": "", "account": "damre"}}),
239            json!({"keyring": {"service": "github.com", "account": "damre", "extra": true}}),
240        ] {
241            assert!(
242                SecretReference::try_from(&value).is_err(),
243                "invalid secret reference shape was accepted"
244            );
245            assert!(!is_secret_reference(&value));
246        }
247    }
248}