esk 0.8.0

Encrypted Secrets Keeper with multi-target deploy
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
413
414
415
//! Mozilla SOPS remote — syncs secrets via the `sops` CLI.
//!
//! SOPS (Secrets OPerationS) is a file encryption tool that encrypts the
//! *values* in structured files (JSON, YAML, ENV) while leaving keys in
//! cleartext. Supports multiple key backends: AGE, PGP, AWS KMS, GCP KMS,
//! Azure Key Vault, and HashiCorp Vault Transit.
//!
//! CLI: `sops` (Mozilla SOPS).
//! Commands: `sops -e /dev/stdin` (encrypt) / `sops -d /dev/stdin` (decrypt).
//!
//! The esk store payload is serialized as JSON, encrypted via **stdin**, and
//! written to a file (one per environment). On pull, the file is decrypted via
//! stdin. Requires a `.sops.yaml` configuration file to define encryption keys
//! and rules.

use anyhow::{Context, Result};
use std::collections::BTreeMap;

use crate::config::{Config, SopsRemoteConfig};
use crate::store::StorePayload;
use crate::targets::{CommandOpts, CommandRunner};

use super::SyncRemote;

pub struct SopsRemote<'a> {
    config: &'a Config,
    remote_config: SopsRemoteConfig,
    runner: &'a dyn CommandRunner,
}

impl<'a> SopsRemote<'a> {
    pub fn new(
        config: &'a Config,
        remote_config: SopsRemoteConfig,
        runner: &'a dyn CommandRunner,
    ) -> Self {
        Self {
            config,
            remote_config,
            runner,
        }
    }

    /// Resolve the file path for an environment.
    fn resolve_path(&self, env: &str) -> String {
        self.remote_config.path.replace("{environment}", env)
    }
}

impl SyncRemote for SopsRemote<'_> {
    fn name(&self) -> &'static str {
        "sops"
    }

    fn preflight(&self) -> Result<()> {
        crate::targets::check_command(self.runner, "sops").map_err(|_| {
            anyhow::anyhow!(
                "Mozilla SOPS (sops) is not installed or not in PATH. Install it from: https://github.com/getsops/sops"
            )
        })?;

        let sops_config = self.config.root.join(".sops.yaml");
        if !sops_config.exists() {
            anyhow::bail!(
                "SOPS config (.sops.yaml) not found at {}. Create it with encryption rules or set SOPS key environment variables (SOPS_AGE_KEY_FILE, SOPS_PGP_FP, etc.).",
                sops_config.display()
            );
        }

        Ok(())
    }

    fn push(&self, payload: &StorePayload, _config: &Config, env: &str) -> Result<()> {
        let Some((env_secrets, version)) = payload.env_secrets(env) else {
            return Ok(());
        };

        // Build JSON payload with bare keys + version metadata
        let mut json_map: BTreeMap<String, String> = env_secrets;
        json_map.insert(super::ESK_VERSION_KEY.to_string(), version.to_string());
        let json =
            serde_json::to_string_pretty(&json_map).context("failed to serialize secrets")?;

        let dest_path = self.resolve_path(env);

        // Encrypt via sops using stdin, capture stdout
        let output = self
            .runner
            .run(
                "sops",
                &["-e", "/dev/stdin"],
                CommandOpts {
                    stdin: Some(json.as_bytes().to_vec()),
                    ..Default::default()
                },
            )
            .context("failed to run sops encrypt")?;

        if !output.success {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("sops encrypt failed: {stderr}");
        }

        // Write encrypted output to destination path atomically
        if let Some(parent) = std::path::Path::new(&dest_path).parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;
        }
        let dir = std::path::Path::new(&dest_path)
            .parent()
            .context("path has no parent")?;
        let tmp = tempfile::NamedTempFile::new_in(dir)?;
        std::fs::write(tmp.path(), &output.stdout)?;
        tmp.persist(&dest_path)
            .with_context(|| format!("failed to write {dest_path}"))?;

        Ok(())
    }

    fn pull(&self, _config: &Config, env: &str) -> Result<Option<(BTreeMap<String, String>, u64)>> {
        let file_path = self.resolve_path(env);

        if !std::path::Path::new(&file_path).exists() {
            return Ok(None);
        }

        // Decrypt via sops
        let output = self
            .runner
            .run("sops", &["-d", &file_path], CommandOpts::default())
            .context("failed to run sops decrypt")?;

        if !output.success {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("sops decrypt failed: {stderr}");
        }

        let json_map: BTreeMap<String, String> = serde_json::from_slice(&output.stdout)
            .context("failed to parse decrypted SOPS JSON")?;

        Ok(Some(super::parse_pulled_secrets(json_map, env)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::targets::{CommandOpts, CommandOutput};
    use crate::test_support::{ConfigFixture, ErrorCommandRunner, MockCommandRunner};
    use std::sync::Mutex;

    type StdinCall = (String, Vec<String>, Option<Vec<u8>>);

    fn sops_yaml() -> &'static str {
        r#"
project: myapp
environments: [dev, prod]
remotes:
  sops:
    path: "secrets/{environment}.enc.json"
"#
    }

    fn make_payload(secrets: &[(&str, &str)], version: u64) -> StorePayload {
        let mut map = BTreeMap::new();
        for (k, v) in secrets {
            map.insert((*k).to_string(), (*v).to_string());
        }
        StorePayload {
            secrets: map,
            version,
            ..Default::default()
        }
    }

    #[test]
    fn resolve_path_substitution() {
        let fixture = ConfigFixture::new(sops_yaml()).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        assert_eq!(remote.resolve_path("dev"), "secrets/dev.enc.json");
        assert_eq!(remote.resolve_path("prod"), "secrets/prod.enc.json");
    }

    /// Create a config in a specific directory so we can also place .sops.yaml there.
    fn make_config_in(dir: &std::path::Path, yaml: &str) -> Config {
        let path = dir.join("esk.yaml");
        std::fs::write(&path, yaml).unwrap();
        Config::load(&path).unwrap()
    }

    #[test]
    fn preflight_success() {
        let dir = tempfile::tempdir().unwrap();
        // Create .sops.yaml in the project root
        std::fs::write(
            dir.path().join(".sops.yaml"),
            "creation_rules:\n  - age: age1xxx\n",
        )
        .unwrap();
        let config = make_config_in(dir.path(), sops_yaml());
        let remote_config: SopsRemoteConfig = config.remote_config("sops").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: true,
            stdout: b"sops 3.8.0".to_vec(),
            stderr: Vec::new(),
        }]);
        let remote = SopsRemote::new(&config, remote_config, &runner);
        assert!(remote.preflight().is_ok());
        let calls = runner.calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].args, vec!["--version"]);
    }

    #[test]
    fn preflight_missing_sops_config() {
        // Config root has no .sops.yaml
        let fixture = ConfigFixture::new(sops_yaml()).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: true,
            stdout: b"sops 3.8.0".to_vec(),
            stderr: Vec::new(),
        }]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        let err = remote.preflight().unwrap_err();
        assert!(err.to_string().contains(".sops.yaml"));
        assert!(err.to_string().contains("not found"));
    }

    #[test]
    fn preflight_missing_sops() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".sops.yaml"),
            "creation_rules:\n  - age: age1xxx\n",
        )
        .unwrap();
        let config = make_config_in(dir.path(), sops_yaml());
        let remote_config: SopsRemoteConfig = config.remote_config("sops").unwrap();
        let runner = ErrorCommandRunner::missing_command();
        let remote = SopsRemote::new(&config, remote_config, &runner);
        let err = remote.preflight().unwrap_err();
        assert!(err.to_string().contains("SOPS"));
        assert!(err.to_string().contains("not installed"));
    }

    #[test]
    fn push_encrypts_and_writes() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("secrets/dev.enc.json");
        let yaml = format!(
            r#"
project: myapp
environments: [dev]
remotes:
  sops:
    path: "{}/secrets/{{environment}}.enc.json"
"#,
            dir.path().display()
        );
        let fixture = ConfigFixture::new(&yaml).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();

        let encrypted = b"ENCRYPTED_CONTENT";
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: true,
            stdout: encrypted.to_vec(),
            stderr: Vec::new(),
        }]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        let payload = make_payload(&[("API_KEY:dev", "sk_test")], 3);
        remote.push(&payload, fixture.config(), "dev").unwrap();

        let calls = runner.calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].program, "sops");
        assert_eq!(calls[0].args, vec!["-e", "/dev/stdin"]);

        // Verify file was written
        assert!(dest.exists());
        let content = std::fs::read(&dest).unwrap();
        assert_eq!(content, encrypted);
    }

    #[test]
    fn push_skips_empty_env() {
        let fixture = ConfigFixture::new(sops_yaml()).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        let payload = make_payload(&[("KEY:prod", "val")], 1);
        remote.push(&payload, fixture.config(), "dev").unwrap();

        let calls = runner.calls();
        assert!(calls.is_empty());
    }

    #[test]
    fn pull_decrypts_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("secrets/dev.enc.json");
        std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        std::fs::write(&file_path, b"encrypted").unwrap();

        let yaml = format!(
            r#"
project: myapp
environments: [dev]
remotes:
  sops:
    path: "{}/secrets/{{environment}}.enc.json"
"#,
            dir.path().display()
        );
        let fixture = ConfigFixture::new(&yaml).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();

        let decrypted = serde_json::json!({
            "API_KEY": "sk_test",
            "DB_URL": "postgres://localhost",
            crate::remotes::ESK_VERSION_KEY: "5"
        });
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: true,
            stdout: serde_json::to_vec(&decrypted).unwrap(),
            stderr: Vec::new(),
        }]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        let (secrets, version) = remote.pull(fixture.config(), "dev").unwrap().unwrap();

        assert_eq!(version, 5);
        assert_eq!(secrets.get("API_KEY:dev").unwrap(), "sk_test");
        assert_eq!(secrets.get("DB_URL:dev").unwrap(), "postgres://localhost");
        assert!(!secrets.contains_key("_esk_version:dev"));
    }

    #[test]
    fn pull_missing_file_returns_none() {
        let fixture = ConfigFixture::new(sops_yaml()).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![]);
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);
        // Path "secrets/dev.enc.json" doesn't exist
        assert!(remote.pull(fixture.config(), "dev").unwrap().is_none());

        let calls = runner.calls();
        assert!(calls.is_empty());
    }

    #[test]
    fn push_uses_env_version() {
        // Capture stdin to verify version
        struct StdinCapture {
            calls: Mutex<Vec<StdinCall>>,
        }
        impl CommandRunner for StdinCapture {
            fn run(
                &self,
                program: &str,
                args: &[&str],
                opts: CommandOpts,
            ) -> Result<CommandOutput> {
                self.calls
                    .lock()
                    .expect("stdin capture mutex poisoned")
                    .push((
                        program.to_string(),
                        args.iter().map(|s| (*s).to_string()).collect(),
                        opts.stdin,
                    ));
                Ok(CommandOutput {
                    success: true,
                    stdout: b"encrypted".to_vec(),
                    stderr: Vec::new(),
                })
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let yaml = format!(
            r#"
project: myapp
environments: [dev]
remotes:
  sops:
    path: "{}/secrets/{{environment}}.enc.json"
"#,
            dir.path().display()
        );
        let fixture = ConfigFixture::new(&yaml).expect("fixture");
        let remote_config: SopsRemoteConfig = fixture.config().remote_config("sops").unwrap();

        let runner = StdinCapture {
            calls: Mutex::new(Vec::new()),
        };
        let remote = SopsRemote::new(fixture.config(), remote_config, &runner);

        let mut env_versions = BTreeMap::new();
        env_versions.insert("dev".to_string(), 99);
        let payload = StorePayload {
            secrets: BTreeMap::from([("KEY:dev".to_string(), "val".to_string())]),
            version: 1,
            env_versions,
            ..Default::default()
        };
        remote.push(&payload, fixture.config(), "dev").unwrap();

        let calls = runner.calls.lock().expect("stdin capture mutex poisoned");
        let stdin = calls[0].2.as_ref().unwrap();
        let json: BTreeMap<String, String> = serde_json::from_slice(stdin).unwrap();
        assert_eq!(json.get(crate::remotes::ESK_VERSION_KEY).unwrap(), "99");
    }
}