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
//! Cloud file remote — syncs secrets via a local filesystem path.
//!
//! Designed for cloud-synced folders (Dropbox, Google Drive, OneDrive, iCloud)
//! where writing a file to a local directory automatically syncs it to other
//! machines. Can also be used with any mounted filesystem.
//!
//! No external CLI required — reads and writes files directly.
//!
//! The store payload is serialized as JSON (one file per environment). The file
//! can be stored either in cleartext or encrypted using AES-256-GCM with a
//! domain-derived key (HKDF-SHA256 from the master key). Paths support
//! `{project}`, `{environment}`, and `~` expansion. Writes are atomic via
//! temp-file-then-rename.

use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;

use crate::config::{CloudFileFormat, CloudFileRemoteConfig, Config};
use crate::store::{decrypt_with_key, derive_key, encrypt_with_key, SecretStore, StorePayload};

use super::SyncRemote;

const CLOUD_SYNC_DOMAIN: &[u8] = b"esk-cloud-sync-v1";

pub struct CloudFileRemote {
    name: String,
    project: String,
    remote_config: CloudFileRemoteConfig,
}

impl CloudFileRemote {
    pub fn new(name: String, project: String, remote_config: CloudFileRemoteConfig) -> Self {
        Self {
            name,
            project,
            remote_config,
        }
    }

    /// Expand `{project}` and tilde in path.
    fn expand_path(&self) -> Result<PathBuf> {
        let path = self.remote_config.path.replace("{project}", &self.project);
        if let Some(rest) = path.strip_prefix("~/") {
            let home = std::env::var("HOME").context("HOME environment variable not set")?;
            Ok(PathBuf::from(home).join(rest))
        } else {
            Ok(PathBuf::from(path))
        }
    }

    /// Atomic write: write to temp file then rename.
    fn atomic_write(path: &Path, content: &[u8]) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;
        }
        let dir = path.parent().context("path has no parent")?;
        let tmp = NamedTempFile::new_in(dir)?;
        std::fs::write(tmp.path(), content)?;
        tmp.persist(path)
            .with_context(|| format!("failed to write {}", path.display()))?;
        Ok(())
    }
}

impl SyncRemote for CloudFileRemote {
    fn name(&self) -> &str {
        &self.name
    }

    fn uses_cleartext_format(&self) -> bool {
        matches!(
            self.remote_config.format,
            crate::config::CloudFileFormat::Cleartext
        )
    }

    fn preflight(&self) -> Result<()> {
        let path = self.expand_path()?;
        if !path.is_dir() {
            std::fs::create_dir_all(&path).with_context(|| {
                format!(
                    "failed to create {} sync folder at {}",
                    self.name,
                    path.display()
                )
            })?;
        }
        // Verify write access
        let probe = path.join(".esk-probe");
        std::fs::write(&probe, b"").map_err(|e| {
            anyhow::anyhow!(
                "{} sync folder at {} is not writable: {e}",
                self.name,
                path.display()
            )
        })?;
        let _ = std::fs::remove_file(&probe);
        Ok(())
    }

    fn push(&self, payload: &StorePayload, config: &Config, env: &str) -> Result<()> {
        let base_path = self.expand_path()?;
        let env_payload = payload.for_env(env);

        match self.remote_config.format {
            CloudFileFormat::Encrypted => {
                // Build per-env payload, encrypt with a domain-derived key
                let store = SecretStore::open(&config.root)?;
                let dk = derive_key(store.master_key(), CLOUD_SYNC_DOMAIN);
                let json = serde_json::to_string(&env_payload)
                    .context("failed to serialize env payload")?;
                let encrypted = encrypt_with_key(&dk, &json)?;
                let dest = base_path.join(format!("secrets-{env}.enc"));
                Self::atomic_write(&dest, encrypted.as_bytes())?;
            }
            CloudFileFormat::Cleartext => {
                let dest = base_path.join(format!("secrets-{env}.json"));
                let json = serde_json::to_string_pretty(&env_payload)
                    .context("failed to serialize env payload")?;
                Self::atomic_write(&dest, json.as_bytes())?;
            }
        }

        Ok(())
    }

    fn pull(&self, config: &Config, env: &str) -> Result<Option<(BTreeMap<String, String>, u64)>> {
        let base_path = self.expand_path()?;

        match self.remote_config.format {
            CloudFileFormat::Encrypted => {
                let per_env = base_path.join(format!("secrets-{env}.enc"));
                if !per_env.is_file() {
                    return Ok(None);
                }
                let content = std::fs::read_to_string(&per_env)
                    .with_context(|| format!("failed to read {}", per_env.display()))?;
                let content = content.trim();
                if content.is_empty() {
                    return Ok(None);
                }
                let store = SecretStore::open(&config.root)?;
                let dk = derive_key(store.master_key(), CLOUD_SYNC_DOMAIN);
                let json = decrypt_with_key(&dk, content)?;
                let payload: StorePayload =
                    serde_json::from_str(&json).context("decrypted payload is not valid JSON")?;
                Ok(Some((
                    StorePayload::bare_to_composite(&payload.secrets, env),
                    payload.version,
                )))
            }
            CloudFileFormat::Cleartext => {
                let per_env = base_path.join(format!("secrets-{env}.json"));
                if !per_env.is_file() {
                    return Ok(None);
                }
                let content = std::fs::read_to_string(&per_env)
                    .with_context(|| format!("failed to read {}", per_env.display()))?;
                let payload: StorePayload =
                    serde_json::from_str(&content).context("failed to parse secrets JSON")?;
                Ok(Some((
                    StorePayload::bare_to_composite(&payload.secrets, env),
                    payload.version,
                )))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::SecretStore;

    fn make_config_with_store(dir: &Path) -> Config {
        let yaml = "project: testapp\nenvironments: [dev, prod]";
        let path = dir.join("esk.yaml");
        std::fs::write(&path, yaml).unwrap();
        SecretStore::load_or_create(dir).unwrap();
        Config::load(&path).unwrap()
    }

    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 cloud_file_preflight_success() {
        let cloud_dir = tempfile::tempdir().unwrap();
        let remote = CloudFileRemote::new(
            "dropbox".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );
        assert!(remote.preflight().is_ok());
    }

    #[test]
    fn cloud_file_preflight_not_writable() {
        use std::os::unix::fs::PermissionsExt;
        let cloud_dir = tempfile::tempdir().unwrap();
        let readonly = cloud_dir.path().join("readonly");
        std::fs::create_dir(&readonly).unwrap();
        std::fs::set_permissions(&readonly, std::fs::Permissions::from_mode(0o444)).unwrap();
        let remote = CloudFileRemote::new(
            "dropbox".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: readonly.to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );
        let err = remote.preflight().unwrap_err();
        assert!(err.to_string().contains("not writable"));
        // Restore permissions so tempdir cleanup works
        std::fs::set_permissions(&readonly, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn cloud_file_preflight_creates_missing_dir() {
        let base = tempfile::tempdir().unwrap();
        let nested = base.path().join("deep/nested/sync");
        let remote = CloudFileRemote::new(
            "dropbox".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: nested.to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );
        assert!(remote.preflight().is_ok());
        assert!(nested.is_dir());
    }

    #[test]
    fn cleartext_push_pull_roundtrip() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let config = make_config_with_store(project_dir.path());

        let remote = CloudFileRemote::new(
            "test_cloud".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        let payload = make_payload(&[("KEY:dev", "val1"), ("KEY:prod", "val2")], 5);
        remote.push(&payload, &config, "dev").unwrap();

        // Per-env file created, not global
        assert!(cloud_dir.path().join("secrets-dev.json").is_file());
        assert!(!cloud_dir.path().join("secrets.json").is_file());

        let (secrets, version) = remote.pull(&config, "dev").unwrap().unwrap();
        assert_eq!(version, 5);
        assert_eq!(secrets.get("KEY:dev").unwrap(), "val1");
        // prod key should NOT be in the dev-specific file
        assert!(!secrets.contains_key("KEY:prod"));
    }

    #[test]
    fn encrypted_push_pull_roundtrip() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let config = make_config_with_store(project_dir.path());

        // Write some secrets to the store
        let store = SecretStore::open(&config.root).unwrap();
        store.set("KEY", "dev", "encrypted_val").unwrap();

        let remote = CloudFileRemote::new(
            "test_enc".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Encrypted,
            },
        );

        let payload = store.payload().unwrap();
        remote.push(&payload, &config, "dev").unwrap();

        // Per-env file created, not global
        assert!(cloud_dir.path().join("secrets-dev.enc").is_file());
        assert!(!cloud_dir.path().join("secrets.enc").is_file());

        let (secrets, version) = remote.pull(&config, "dev").unwrap().unwrap();
        assert_eq!(version, 1);
        assert_eq!(secrets.get("KEY:dev").unwrap(), "encrypted_val");
    }

    #[test]
    fn per_env_isolation() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let config = make_config_with_store(project_dir.path());

        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        // Push dev secrets
        let payload = make_payload(&[("KEY:dev", "dev_val"), ("KEY:prod", "prod_val")], 5);
        remote.push(&payload, &config, "dev").unwrap();
        // Push prod secrets
        remote.push(&payload, &config, "prod").unwrap();

        // Dev file should only have dev secrets
        let (dev_secrets, _) = remote.pull(&config, "dev").unwrap().unwrap();
        assert_eq!(dev_secrets.get("KEY:dev").unwrap(), "dev_val");
        assert!(!dev_secrets.contains_key("KEY:prod"));

        // Prod file should only have prod secrets
        let (prod_secrets, _) = remote.pull(&config, "prod").unwrap().unwrap();
        assert_eq!(prod_secrets.get("KEY:prod").unwrap(), "prod_val");
        assert!(!prod_secrets.contains_key("KEY:dev"));
    }

    #[test]
    fn pull_nonexistent_returns_none() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let config = make_config_with_store(project_dir.path());

        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        assert!(remote.pull(&config, "dev").unwrap().is_none());
    }

    #[test]
    fn pull_encrypted_nonexistent_returns_none() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let config = make_config_with_store(project_dir.path());

        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: cloud_dir.path().to_string_lossy().to_string(),
                format: CloudFileFormat::Encrypted,
            },
        );

        assert!(remote.pull(&config, "dev").unwrap().is_none());
    }

    #[test]
    fn push_creates_parent_dirs() {
        let project_dir = tempfile::tempdir().unwrap();
        let cloud_dir = tempfile::tempdir().unwrap();
        let nested = cloud_dir.path().join("deep/nested/path");
        let config = make_config_with_store(project_dir.path());

        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: nested.to_string_lossy().to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        let payload = make_payload(&[("A:dev", "1")], 1);
        remote.push(&payload, &config, "dev").unwrap();
        assert!(nested.join("secrets-dev.json").is_file());
    }

    #[test]
    fn tilde_expansion() {
        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: "~/test/path".to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        let expanded = remote.expand_path().unwrap();
        assert!(!expanded.to_string_lossy().contains('~'));
        assert!(expanded.to_string_lossy().ends_with("/test/path"));
    }

    #[test]
    fn no_tilde_expansion_for_absolute() {
        let remote = CloudFileRemote::new(
            "test".to_string(),
            "testapp".to_string(),
            CloudFileRemoteConfig {
                path: "/absolute/path".to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        let expanded = remote.expand_path().unwrap();
        assert_eq!(expanded, PathBuf::from("/absolute/path"));
    }

    #[test]
    fn project_interpolation() {
        let remote = CloudFileRemote::new(
            "test".to_string(),
            "myapp".to_string(),
            CloudFileRemoteConfig {
                path: "/cloud/esk/{project}".to_string(),
                format: CloudFileFormat::Cleartext,
            },
        );

        let expanded = remote.expand_path().unwrap();
        assert_eq!(expanded, PathBuf::from("/cloud/esk/myapp"));
    }

    #[test]
    fn project_interpolation_with_tilde() {
        let remote = CloudFileRemote::new(
            "test".to_string(),
            "myapp".to_string(),
            CloudFileRemoteConfig {
                path: "~/Dropbox/esk/{project}".to_string(),
                format: CloudFileFormat::Encrypted,
            },
        );

        let expanded = remote.expand_path().unwrap();
        assert!(!expanded.to_string_lossy().contains('~'));
        assert!(!expanded.to_string_lossy().contains("{project}"));
        assert!(expanded.to_string_lossy().ends_with("/Dropbox/esk/myapp"));
    }
}