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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! GCP Secret Manager remote — syncs secrets via the `gcloud` CLI.
//!
//! Google Cloud Secret Manager is a managed service for storing API keys,
//! passwords, certificates, and other sensitive data. Secrets are versioned
//! (each update creates a new immutable version) and integrate with IAM for
//! access control.
//!
//! CLI: `gcloud` (Google Cloud CLI).
//! Commands: `gcloud secrets versions add --data-file=-` / `gcloud secrets versions access latest`.
//!
//! The entire esk store payload is serialized as JSON and pushed as a new
//! secret version via **stdin** (`--data-file=-`). On first push, creates the
//! secret if it doesn't exist. Supports `--project` for GCP project targeting.

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

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

use super::SyncRemote;

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

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

    /// Resolve the GCP secret name for an environment.
    fn secret_name(&self, env: &str) -> String {
        self.remote_config
            .secret_name
            .replace("{project}", &self.config.project)
            .replace("{environment}", env)
    }
}

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

    fn preflight(&self) -> Result<()> {
        crate::targets::check_command(self.runner, "gcloud").map_err(|_| {
            anyhow::anyhow!(
                "Google Cloud CLI (gcloud) is not installed or not in PATH. Install it from: https://cloud.google.com/sdk/docs/install"
            )
        })?;

        let project = &self.remote_config.project;
        let output = self
            .runner
            .run(
                "gcloud",
                &["auth", "print-access-token", "--project", project],
                CommandOpts::default(),
            )
            .context("failed to run gcloud auth check")?;
        if !output.success {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("GCP project '{project}' not accessible: {stderr}");
        }
        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(&json_map).context("failed to serialize secrets")?;

        let secret_name = self.secret_name(env);
        let project = &self.remote_config.project;

        // Try to add a new version
        let output = self
            .runner
            .run(
                "gcloud",
                &[
                    "secrets",
                    "versions",
                    "add",
                    &secret_name,
                    "--data-file=-",
                    "--project",
                    project,
                ],
                CommandOpts {
                    stdin: Some(json.as_bytes().to_vec()),
                    ..Default::default()
                },
            )
            .context("failed to run gcloud secrets versions add")?;

        if !output.success {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("NOT_FOUND") {
                // Secret doesn't exist — create it first
                let create_output = self
                    .runner
                    .run(
                        "gcloud",
                        &["secrets", "create", &secret_name, "--project", project],
                        CommandOpts::default(),
                    )
                    .context("failed to run gcloud secrets create")?;
                if !create_output.success {
                    let err = String::from_utf8_lossy(&create_output.stderr);
                    anyhow::bail!("gcloud secrets create failed: {err}");
                }

                // Retry versions add
                let retry_output = self
                    .runner
                    .run(
                        "gcloud",
                        &[
                            "secrets",
                            "versions",
                            "add",
                            &secret_name,
                            "--data-file=-",
                            "--project",
                            project,
                        ],
                        CommandOpts {
                            stdin: Some(json.as_bytes().to_vec()),
                            ..Default::default()
                        },
                    )
                    .context("failed to run gcloud secrets versions add (retry)")?;
                if !retry_output.success {
                    let err = String::from_utf8_lossy(&retry_output.stderr);
                    anyhow::bail!("gcloud secrets versions add failed: {err}");
                }
            } else {
                anyhow::bail!("gcloud secrets versions add failed: {stderr}");
            }
        }

        Ok(())
    }

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

        let output = self
            .runner
            .run(
                "gcloud",
                &[
                    "secrets",
                    "versions",
                    "access",
                    "latest",
                    &format!("--secret={secret_name}"),
                    "--project",
                    project,
                ],
                CommandOpts::default(),
            )
            .context("failed to run gcloud secrets versions access")?;

        if !output.success {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("NOT_FOUND") {
                return Ok(None);
            }
            anyhow::bail!("gcloud secrets versions access failed: {stderr}");
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let json_map: BTreeMap<String, String> =
            serde_json::from_str(&stdout).context("failed to parse GCP secret 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 gcp_yaml() -> &'static str {
        r#"
project: myapp
environments: [dev, prod]
remotes:
  gcp:
    project: my-gcp-project
    secret_name: "{project}-{environment}"
"#
    }

    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 secret_name_substitution() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        assert_eq!(remote.secret_name("dev"), "myapp-dev");
        assert_eq!(remote.secret_name("prod"), "myapp-prod");
    }

    #[test]
    fn preflight_success() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![
            CommandOutput {
                success: true,
                stdout: b"gcloud 400.0.0".to_vec(),
                stderr: Vec::new(),
            },
            CommandOutput {
                success: true,
                stdout: b"ya29.token".to_vec(),
                stderr: Vec::new(),
            },
        ]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        assert!(remote.preflight().is_ok());
        let calls = runner.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].args, vec!["--version"]);
        assert!(calls[1].args.contains(&"auth".to_string()));
    }

    #[test]
    fn preflight_missing_gcloud() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = ErrorCommandRunner::missing_command();
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        let err = remote.preflight().unwrap_err();
        assert!(err.to_string().contains("gcloud"));
        assert!(err.to_string().contains("not installed"));
    }

    #[test]
    fn preflight_auth_failure() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![
            CommandOutput {
                success: true,
                stdout: b"gcloud 400.0.0".to_vec(),
                stderr: Vec::new(),
            },
            CommandOutput {
                success: false,
                stdout: Vec::new(),
                stderr: b"ERROR: (gcloud.auth.print-access-token) not authenticated".to_vec(),
            },
        ]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        let err = remote.preflight().unwrap_err();
        assert!(err.to_string().contains("not accessible"));
    }

    #[test]
    fn push_success() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: true,
            stdout: Vec::new(),
            stderr: Vec::new(),
        }]);
        let remote = GcpSecretManagerRemote::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, "gcloud");
        assert!(calls[0].args.contains(&"versions".to_string()));
        assert!(calls[0].args.contains(&"add".to_string()));
        assert!(calls[0].args.contains(&"myapp-dev".to_string()));
    }

    #[test]
    fn push_creates_secret_on_not_found() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![
            // First versions add fails with NOT_FOUND
            CommandOutput {
                success: false,
                stdout: Vec::new(),
                stderr: b"NOT_FOUND: Secret not found".to_vec(),
            },
            // secrets create succeeds
            CommandOutput {
                success: true,
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
            // Retry versions add succeeds
            CommandOutput {
                success: true,
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
        ]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        let payload = make_payload(&[("KEY:dev", "val")], 1);
        remote.push(&payload, fixture.config(), "dev").unwrap();

        let calls = runner.calls();
        assert_eq!(calls.len(), 3);
        assert!(calls[1].args.contains(&"create".to_string()));
    }

    #[test]
    fn push_skips_empty_env() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        // Only prod secrets, pushing dev — should skip
        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_success() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let json = 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(&json).unwrap(),
            stderr: Vec::new(),
        }]);
        let remote = GcpSecretManagerRemote::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_not_found_returns_none() {
        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = MockCommandRunner::from_outputs(vec![CommandOutput {
            success: false,
            stdout: Vec::new(),
            stderr: b"NOT_FOUND: Secret not found".to_vec(),
        }]);
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);
        assert!(remote.pull(fixture.config(), "dev").unwrap().is_none());
    }

    #[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: Vec::new(),
                    stderr: Vec::new(),
                })
            }
        }

        let fixture = ConfigFixture::new(gcp_yaml()).expect("fixture");
        let remote_config: GcpSecretManagerRemoteConfig =
            fixture.config().remote_config("gcp").unwrap();
        let runner = StdinCapture {
            calls: Mutex::new(Vec::new()),
        };
        let remote = GcpSecretManagerRemote::new(fixture.config(), remote_config, &runner);

        let mut env_versions = BTreeMap::new();
        env_versions.insert("dev".to_string(), 42);
        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(), "42");
    }
}