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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeployIndex {
    pub records: BTreeMap<String, DeployRecord>,
    #[serde(skip)]
    path: PathBuf,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeployRecord {
    pub target: String,
    pub value_hash: String,
    #[serde(alias = "last_synced_at")]
    pub last_deployed_at: String,
    #[serde(alias = "last_sync_status")]
    pub last_deploy_status: DeployStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeployStatus {
    Success,
    Failed,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TrackerKeyParts {
    pub key: String,
    pub service: String,
    pub app: Option<String>,
    pub env: String,
}

impl DeployIndex {
    /// Sentinel hash for tombstone (deleted key) tracking.
    /// Never collides with real SHA-256 hashes (which are 64-char hex).
    pub const TOMBSTONE_HASH: &str = "__tombstone__";

    pub fn new(path: &Path) -> Self {
        Self {
            records: BTreeMap::new(),
            path: path.to_path_buf(),
        }
    }

    pub fn load(path: &Path) -> Self {
        if !path.is_file() {
            return Self::new(path);
        }
        let contents = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("Warning: could not read deploy index ({e}), starting fresh");
                return Self::new(path);
            }
        };
        match serde_json::from_str::<DeployIndex>(&contents) {
            Ok(mut index) => {
                index.path = path.to_path_buf();
                index
            }
            Err(e) => {
                eprintln!("Warning: deploy index corrupted ({e}), starting fresh");
                Self::new(path)
            }
        }
    }

    pub fn save(&self) -> Result<()> {
        let json = serde_json::to_string_pretty(&self)?;
        let dir = self
            .path
            .parent()
            .context("deploy index path has no parent")?;
        let tmp = NamedTempFile::new_in(dir)?;
        std::fs::write(tmp.path(), json)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o600))?;
        }
        tmp.persist(&self.path).with_context(|| {
            format!("failed to persist deploy index to {}", self.path.display())
        })?;
        Ok(())
    }

    /// Build a tracker key: "KEY:target:app:env" or "KEY:target:env"
    pub fn tracker_key(secret_key: &str, target: &str, app: Option<&str>, env: &str) -> String {
        match app {
            Some(a) => format!("{secret_key}:{target}:{a}:{env}"),
            None => format!("{secret_key}:{target}:{env}"),
        }
    }

    /// Parse a tracker key back into its component parts.
    /// Returns `None` for malformed keys.
    pub fn parse_tracker_key(tracker_key: &str) -> Option<TrackerKeyParts> {
        let parts: Vec<&str> = tracker_key.split(':').collect();
        match parts.len() {
            3 => Some(TrackerKeyParts {
                key: parts[0].to_string(),
                service: parts[1].to_string(),
                app: None,
                env: parts[2].to_string(),
            }),
            4 => Some(TrackerKeyParts {
                key: parts[0].to_string(),
                service: parts[1].to_string(),
                app: Some(parts[2].to_string()),
                env: parts[3].to_string(),
            }),
            _ => None,
        }
    }

    /// Determine if a deploy is needed.
    pub fn should_deploy(&self, tracker_key: &str, value_hash: &str, force: bool) -> bool {
        if force {
            return true;
        }
        match self.records.get(tracker_key) {
            None => true,
            Some(record) => {
                record.last_deploy_status == DeployStatus::Failed || record.value_hash != value_hash
            }
        }
    }

    pub fn record_success(&mut self, tracker_key: String, target: String, value_hash: String) {
        self.records.insert(
            tracker_key,
            DeployRecord {
                target,
                value_hash,
                last_deployed_at: chrono::Utc::now().to_rfc3339(),
                last_deploy_status: DeployStatus::Success,
                last_error: None,
            },
        );
    }

    pub fn record_failure(
        &mut self,
        tracker_key: String,
        target: String,
        value_hash: String,
        error: String,
    ) {
        self.records.insert(
            tracker_key,
            DeployRecord {
                target,
                value_hash,
                last_deployed_at: chrono::Utc::now().to_rfc3339(),
                last_deploy_status: DeployStatus::Failed,
                last_error: Some(error),
            },
        );
    }

    /// Remove a record from the index by tracker key.
    pub fn remove_record(&mut self, tracker_key: &str) {
        self.records.remove(tracker_key);
    }

    /// Compute SHA-256 hash of a value.
    pub fn hash_value(value: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(value.as_bytes());
        hex::encode(hasher.finalize())
    }
}

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

    #[test]
    fn new_empty() {
        let index = DeployIndex::new(Path::new("/tmp/test.json"));
        assert!(index.records.is_empty());
    }

    #[test]
    fn load_nonexistent_returns_empty() {
        let index = DeployIndex::load(Path::new("/nonexistent/path/test.json"));
        assert!(index.records.is_empty());
    }

    #[test]
    fn load_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.json");
        let mut index = DeployIndex::new(&path);
        index.record_success(
            "KEY:.env:web:dev".to_string(),
            ".env:web:dev".to_string(),
            "abc".to_string(),
        );
        index.save().unwrap();

        let loaded = DeployIndex::load(&path);
        assert_eq!(loaded.records.len(), 1);
        assert!(loaded.records.contains_key("KEY:.env:web:dev"));
    }

    #[test]
    fn load_corrupted_returns_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.json");
        std::fs::write(&path, "not valid json").unwrap();
        let index = DeployIndex::load(&path);
        assert!(index.records.is_empty());
    }

    #[test]
    fn save_and_reload() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.json");
        let mut index = DeployIndex::new(&path);
        index.record_success(
            "A:.env:web:dev".to_string(),
            ".env:web:dev".to_string(),
            "hash1".to_string(),
        );
        index.record_failure(
            "B:cf:prod".to_string(),
            "cf:prod".to_string(),
            "hash2".to_string(),
            "err".to_string(),
        );
        index.save().unwrap();

        let loaded = DeployIndex::load(&path);
        assert_eq!(loaded.records.len(), 2);
        assert_eq!(
            loaded.records["A:.env:web:dev"].last_deploy_status,
            DeployStatus::Success
        );
        assert_eq!(
            loaded.records["B:cf:prod"].last_deploy_status,
            DeployStatus::Failed
        );
    }

    #[test]
    fn save_atomic() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.json");
        let index = DeployIndex::new(&path);
        index.save().unwrap();
        assert!(path.is_file());
    }

    #[test]
    fn tracker_key_with_app() {
        let key = DeployIndex::tracker_key("SECRET", ".env", Some("web"), "dev");
        assert_eq!(key, "SECRET:.env:web:dev");
    }

    #[test]
    fn tracker_key_without_app() {
        let key = DeployIndex::tracker_key("SECRET", "cloudflare", None, "prod");
        assert_eq!(key, "SECRET:cloudflare:prod");
    }

    #[test]
    fn should_deploy_force_true() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_success("K".to_string(), "t".to_string(), "hash".to_string());
        assert!(index.should_deploy("K", "hash", true));
    }

    #[test]
    fn should_deploy_no_record() {
        let index = DeployIndex::new(Path::new("/tmp/test.json"));
        assert!(index.should_deploy("K", "hash", false));
    }

    #[test]
    fn should_deploy_hash_match_success() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_success("K".to_string(), "t".to_string(), "hash".to_string());
        assert!(!index.should_deploy("K", "hash", false));
    }

    #[test]
    fn should_deploy_hash_mismatch() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_success("K".to_string(), "t".to_string(), "old_hash".to_string());
        assert!(index.should_deploy("K", "new_hash", false));
    }

    #[test]
    fn should_deploy_previous_failure() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_failure(
            "K".to_string(),
            "t".to_string(),
            "hash".to_string(),
            "err".to_string(),
        );
        assert!(index.should_deploy("K", "hash", false));
    }

    #[test]
    fn record_success_sets_fields() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_success(
            "K".to_string(),
            ".env:web:dev".to_string(),
            "abc".to_string(),
        );
        let record = &index.records["K"];
        assert_eq!(record.target, ".env:web:dev");
        assert_eq!(record.value_hash, "abc");
        assert_eq!(record.last_deploy_status, DeployStatus::Success);
        assert!(record.last_error.is_none());
    }

    #[test]
    fn record_failure_sets_fields() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_failure(
            "K".to_string(),
            "cf:prod".to_string(),
            "abc".to_string(),
            "timeout".to_string(),
        );
        let record = &index.records["K"];
        assert_eq!(record.target, "cf:prod");
        assert_eq!(record.value_hash, "abc");
        assert_eq!(record.last_deploy_status, DeployStatus::Failed);
        assert_eq!(record.last_error.as_deref(), Some("timeout"));
    }

    #[test]
    fn record_overwrites_previous() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_failure(
            "K".to_string(),
            "t".to_string(),
            "h1".to_string(),
            "err".to_string(),
        );
        index.record_success("K".to_string(), "t".to_string(), "h2".to_string());
        let record = &index.records["K"];
        assert_eq!(record.last_deploy_status, DeployStatus::Success);
        assert_eq!(record.value_hash, "h2");
    }

    #[test]
    fn hash_value_deterministic() {
        let h1 = DeployIndex::hash_value("hello");
        let h2 = DeployIndex::hash_value("hello");
        assert_eq!(h1, h2);
    }

    #[test]
    fn hash_value_different_inputs() {
        let h1 = DeployIndex::hash_value("hello");
        let h2 = DeployIndex::hash_value("world");
        assert_ne!(h1, h2);
    }

    #[test]
    fn hash_value_empty_string() {
        let hash = DeployIndex::hash_value("");
        // SHA-256 of empty string is well-known
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn tombstone_hash_is_not_valid_sha256() {
        // TOMBSTONE_HASH must never collide with a real SHA-256 output
        let any_hash = DeployIndex::hash_value("anything");
        assert_ne!(DeployIndex::TOMBSTONE_HASH, any_hash);
        assert_ne!(DeployIndex::TOMBSTONE_HASH.len(), 64); // SHA-256 hex is 64 chars
    }

    #[test]
    fn should_deploy_tombstone_success_skips() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_success(
            "K".to_string(),
            "t".to_string(),
            DeployIndex::TOMBSTONE_HASH.to_string(),
        );
        assert!(!index.should_deploy("K", DeployIndex::TOMBSTONE_HASH, false));
    }

    #[test]
    fn parse_tracker_key_without_app() {
        let parsed = DeployIndex::parse_tracker_key("SECRET:cloudflare:prod").unwrap();
        assert_eq!(
            parsed,
            TrackerKeyParts {
                key: "SECRET".to_string(),
                service: "cloudflare".to_string(),
                app: None,
                env: "prod".to_string(),
            }
        );
    }

    #[test]
    fn parse_tracker_key_with_app() {
        let parsed = DeployIndex::parse_tracker_key("SECRET:.env:web:dev").unwrap();
        assert_eq!(
            parsed,
            TrackerKeyParts {
                key: "SECRET".to_string(),
                service: ".env".to_string(),
                app: Some("web".to_string()),
                env: "dev".to_string(),
            }
        );
    }

    #[test]
    fn parse_tracker_key_roundtrip_without_app() {
        let key = DeployIndex::tracker_key("API_KEY", "fly", None, "prod");
        let parsed = DeployIndex::parse_tracker_key(&key).unwrap();
        assert_eq!(parsed.key, "API_KEY");
        assert_eq!(parsed.service, "fly");
        assert_eq!(parsed.app, None);
        assert_eq!(parsed.env, "prod");
    }

    #[test]
    fn parse_tracker_key_roundtrip_with_app() {
        let key = DeployIndex::tracker_key("DB_URL", ".env", Some("web"), "staging");
        let parsed = DeployIndex::parse_tracker_key(&key).unwrap();
        assert_eq!(parsed.key, "DB_URL");
        assert_eq!(parsed.service, ".env");
        assert_eq!(parsed.app, Some("web".to_string()));
        assert_eq!(parsed.env, "staging");
    }

    #[test]
    fn parse_tracker_key_too_few_parts() {
        assert!(DeployIndex::parse_tracker_key("SECRET:only").is_none());
    }

    #[test]
    fn parse_tracker_key_too_many_parts() {
        assert!(DeployIndex::parse_tracker_key("A:B:C:D:E").is_none());
    }

    #[test]
    fn parse_tracker_key_empty() {
        assert!(DeployIndex::parse_tracker_key("").is_none());
    }

    #[test]
    fn parse_tracker_key_single() {
        assert!(DeployIndex::parse_tracker_key("SECRET").is_none());
    }

    #[test]
    fn should_deploy_tombstone_failure_retries() {
        let mut index = DeployIndex::new(Path::new("/tmp/test.json"));
        index.record_failure(
            "K".to_string(),
            "t".to_string(),
            DeployIndex::TOMBSTONE_HASH.to_string(),
            "err".to_string(),
        );
        assert!(index.should_deploy("K", DeployIndex::TOMBSTONE_HASH, false));
    }
}