secretspec 0.17.1

Declarative secrets, every environment, any provider
Documentation
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use crate::{
    Result, SecretSpecError,
    provider::{
        ProviderUrl,
        sops::{
            SopsFormat,
            SopsMode::{self},
            fields::{PATHBUF_FIELDS, STRING_FIELDS},
            pattern::SopsPathPattern,
        },
    },
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::str::FromStr;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SopsConfig {
    // Set by Provider::with_base_dir
    pub base_dir: Option<std::path::PathBuf>,

    pub format: SopsFormat,
    pub mode: SopsMode,

    // SOPS settings
    pub sops_config: Option<PathBuf>,
    pub sops_decryption_order: Option<String>,
    pub sops_editor: Option<String>,
    pub sops_enable_local_keyservice: Option<String>,
    pub sops_keyservice: Option<String>,

    // Age configuration
    pub age_key_file: Option<PathBuf>,
    pub age_key_cmd: Option<String>,
    pub age_recipients: Option<String>,
    pub age_ssh_private_key_file: Option<PathBuf>,
    pub age_ssh_private_key_cmd: Option<String>,

    // AWS KMS configuration
    pub aws_access_key_id: Option<String>,
    pub aws_profile: Option<String>,
    pub aws_region: Option<String>,
    pub kms_arn: Option<String>,

    // Azure configuration
    pub azure_client_id: Option<String>,
    pub azure_tenant_id: Option<String>,
    pub azure_keyvault_urls: Option<String>,

    // GCP configuration
    pub gcp_kms_client_type: Option<String>,
    pub gcp_kms_endpoint: Option<String>,
    pub gcp_kms_ids: Option<String>,
    pub gcp_kms_universe_domain: Option<String>,

    // PGP configuration
    pub pgp_fp: Option<String>,

    // GPG configuration
    pub gpg_exec: Option<String>,

    // HashiCorp Vault/OpenBao configuration
    pub hc_vault_addr: Option<String>,
    pub hc_vault_allowlist: Option<String>,

    // Huawei Cloud KMS
    pub huawei_sdk_project_id: Option<String>,
    pub huawei_kms_ids: Option<String>,
}

impl Default for SopsConfig {
    fn default() -> Self {
        Self {
            age_key_cmd: None,
            age_key_file: None,
            age_recipients: None,
            age_ssh_private_key_cmd: None,
            age_ssh_private_key_file: None,
            aws_access_key_id: None,
            aws_profile: None,
            aws_region: None,
            azure_client_id: None,
            azure_keyvault_urls: None,
            azure_tenant_id: None,
            base_dir: None,
            format: SopsFormat::default(),
            gcp_kms_client_type: None,
            gcp_kms_endpoint: None,
            gcp_kms_ids: None,
            gcp_kms_universe_domain: None,
            gpg_exec: None,
            hc_vault_addr: None,
            hc_vault_allowlist: None,
            huawei_kms_ids: None,
            huawei_sdk_project_id: None,
            kms_arn: None,
            mode: SopsMode::Uninitialized,
            pgp_fp: None,
            sops_config: None,
            sops_decryption_order: None,
            sops_editor: None,
            sops_enable_local_keyservice: None,
            sops_keyservice: None,
        }
    }
}

fn split_template_path(path: &str) -> (PathBuf, String) {
    match path.find('{') {
        None => (PathBuf::from(path), String::new()),
        Some(idx) => {
            let prefix = &path[..idx];
            match prefix.rfind(['/', '\\']) {
                Some(separator) => (
                    PathBuf::from(&path[..separator]),
                    path[separator + 1..].to_string(),
                ),
                None => (PathBuf::new(), path.to_string()),
            }
        }
    }
}

fn infer_format(path: &str) -> Result<SopsFormat> {
    let extension = std::path::Path::new(path)
        .extension()
        .and_then(|extension| extension.to_str())
        .ok_or_else(|| {
            SecretSpecError::ProviderOperationFailed(format!(
                "Cannot infer the SOPS format from '{path}'. Add a supported extension \
                 (.yaml, .yml, .json, .env, .dotenv, or .ini) or set ?format=."
            ))
        })?;

    SopsFormat::from_str(extension)
}

impl TryFrom<&ProviderUrl> for SopsConfig {
    type Error = SecretSpecError;

    fn try_from(url: &ProviderUrl) -> std::result::Result<Self, Self::Error> {
        if url.scheme() != "sops" {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "Invalid scheme '{}' for SOPS provider",
                url.scheme()
            )));
        }

        let mut target_path = PathBuf::new();

        if let Some(host) = url.host()
            && host != "localhost"
            && !host.is_empty()
        {
            target_path.push(host);
        }

        let url_path = url.path();

        if !url_path.is_empty() && url_path != "/" {
            let path_part = if target_path.as_os_str().is_empty() {
                url_path.as_str()
            } else {
                url_path.trim_start_matches('/')
            };

            if !path_part.is_empty() {
                target_path.push(path_part);
            }
        }

        if target_path.as_os_str().is_empty() {
            target_path = PathBuf::from("secrets.enc.yaml");
        }

        let raw_path = target_path.to_string_lossy().to_string();

        let mut config = SopsConfig::default();

        let mut explicit_format: Option<SopsFormat> = None;

        for (key, value) in url.query_pairs() {
            match key.as_ref() {
                "format" => {
                    explicit_format = Some(SopsFormat::from_str(value.as_ref()).map_err(|e| {
                        SecretSpecError::ProviderOperationFailed(format!(
                            "Invalid format parameter: {}",
                            e
                        ))
                    })?);
                }
                other => {
                    if let Err(e) = config.apply_query_parameter(other, value.as_ref()) {
                        return Err(e);
                    }
                }
            }
        }

        let (dir_path, pattern) = split_template_path(&raw_path);

        let format = match explicit_format {
            Some(format) => format,
            None => infer_format(&raw_path)?,
        };

        // SOPS does not accept `--input-type ini`. An INI override can only be
        // honored when the file itself has an INI extension and SOPS can infer
        // the store from that extension.
        if explicit_format == Some(SopsFormat::Ini) && infer_format(&raw_path)? != SopsFormat::Ini {
            return Err(SecretSpecError::ProviderOperationFailed(
                "SOPS cannot override a non-INI filename with ?format=ini; use a .ini filename"
                    .to_string(),
            ));
        }

        let mode = if pattern.is_empty() {
            SopsMode::SingleFile(PathBuf::from(raw_path))
        } else {
            SopsMode::Directory {
                path: dir_path,
                pattern: SopsPathPattern::try_from(pattern)?,
                format,
            }
        };

        Ok(SopsConfig {
            format,
            mode,
            ..config
        })
    }
}

impl SopsConfig {
    pub fn apply_env(&self, cmd: &mut std::process::Command) {
        for spec in STRING_FIELDS {
            if let Some(v) = (spec.field)(self) {
                cmd.env(spec.env_key, v);
            }
        }

        for spec in PATHBUF_FIELDS {
            if let Some(v) = (spec.field)(self) {
                cmd.env(spec.env_key, self.rebase_path(v.to_path_buf()));
            }
        }

        if self.sops_config.is_none()
            && let Some(path) = self.discover_sops_config()
        {
            cmd.env("SOPS_CONFIG", path);
        }
    }

    pub fn apply_query_parameter(&mut self, key: &str, value: &str) -> Result<()> {
        for spec in STRING_FIELDS {
            if spec.url_key == key {
                *(spec.field_mut)(self) = Some(String::from(value));

                return Ok(());
            }
        }

        for spec in PATHBUF_FIELDS {
            if spec.url_key == key {
                *(spec.field_mut)(self) = Some(PathBuf::from(value));

                return Ok(());
            }
        }

        Err(SecretSpecError::ProviderOperationFailed(format!(
            "Invalid query parameter: {}",
            key
        )))
    }

    pub fn with_base_dir(&mut self, base_dir: &std::path::Path) {
        self.base_dir = Some(base_dir.to_owned());
    }

    pub fn rebase_path(&self, path: std::path::PathBuf) -> std::path::PathBuf {
        if let Some(base) = &self.base_dir {
            if path.is_relative() {
                return base.join(path);
            }
        }

        return path;
    }

    fn discover_sops_config(&self) -> Option<PathBuf> {
        self.base_dir.as_deref().and_then(|base_dir| {
            base_dir
                .ancestors()
                .map(|directory| directory.join(".sops.yaml"))
                .find(|candidate| candidate.is_file())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Provider;
    use std::fs;
    use url::Url;

    #[test]
    fn test_sops_config_try_from_succeeds_for_known_query_parameters() {
        let mut url_query_parameter_keys: Vec<&str> =
            STRING_FIELDS.iter().map(|f| f.url_key).collect();

        url_query_parameter_keys.extend(PATHBUF_FIELDS.iter().map(|f| f.url_key).into_iter());

        url_query_parameter_keys.iter().for_each(|key| {
        let url: Url = Url::parse(format!("sops://src/provider/sops/test_fixtures/single_file/some-project-name.enc.json?{}=foo", key).as_str()).unwrap();

        let provider_result: std::result::Result<Box<dyn Provider>, _> = (&url).try_into();

        match provider_result {
            Err(e) => {
                assert!(false, "{}", e.to_string());
            }
            Ok(_) => ()
        }
    });
    }

    #[test]
    fn test_sops_config_try_from_errors_on_unknown_query_parameter() {
        let url = Url::parse("sops://src/provider/sops/test_fixtures/single_file/some-project-name.enc.json?invalid_parameter=foo").unwrap();

        let provider_result: std::result::Result<Box<dyn Provider>, _> = (&url).try_into();

        match provider_result {
            Err(e) => {
                assert_eq!(
                    e.to_string(),
                    "Provider operation failed: Invalid query parameter: invalid_parameter"
                );
            }
            _ => {
                assert!(false)
            }
        }
    }

    #[test]
    fn unknown_extension_returns_an_error_instead_of_panicking() {
        for spec in [
            "sops://secrets.enc",
            "sops://secrets/{project}/{profile}.enc",
        ] {
            let url = Url::parse(spec).unwrap();
            let result: std::result::Result<Box<dyn Provider>, _> = (&url).try_into();
            let error = result.err().expect("unknown extension should fail");
            assert!(
                error.to_string().contains("Supported formats"),
                "unexpected error for {spec}: {error}"
            );
        }
    }

    #[test]
    fn explicit_dotenv_format_allows_an_enc_extension() {
        let url = Url::parse("sops://secrets/{project}/.env.{profile}.enc?format=dotenv").unwrap();
        let provider: std::result::Result<Box<dyn Provider>, _> = (&url).try_into();
        assert!(provider.is_ok());
    }

    #[test]
    fn explicit_ini_format_requires_an_ini_extension() {
        let url = Url::parse("sops://secrets.enc?format=ini").unwrap();
        let result: std::result::Result<Box<dyn Provider>, _> = (&url).try_into();
        assert!(result.is_err());
    }

    #[test]
    fn template_literal_prefix_stays_in_the_pattern() {
        let url =
            Url::parse("sops://secrets-{project}/{profile}.enc.json").expect("valid SOPS URL");
        let provider_url = ProviderUrl::new(url);
        let config = SopsConfig::try_from(&provider_url).expect("valid SOPS config");

        match config.mode {
            SopsMode::Directory { path, pattern, .. } => {
                assert!(path.as_os_str().is_empty());
                assert_eq!(
                    pattern.render("myapp", "production"),
                    PathBuf::from("secrets-myapp/production.enc.json")
                );
            }
            mode => panic!("expected directory mode, got {mode:?}"),
        }
    }

    #[test]
    fn project_sops_config_is_discovered_from_the_manifest_directory() {
        let root = tempfile::tempdir().unwrap();
        let nested = root.path().join("services/api");
        fs::create_dir_all(&nested).unwrap();
        let expected = root.path().join(".sops.yaml");
        fs::write(&expected, "creation_rules: []\n").unwrap();

        let mut config = SopsConfig::default();
        config.with_base_dir(&nested);

        assert_eq!(config.discover_sops_config(), Some(expected));
    }
}