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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Nonce};
use anyhow::{bail, Context, Result};
use fs2::FileExt;
use hkdf::Hkdf;
use rand::Rng;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;
use zeroize::Zeroizing;

/// AES-256 key length in bytes.
const KEY_LEN: usize = 32;
/// AES-GCM nonce length in bytes.
const NONCE_LEN: usize = 12;
/// AES-GCM authentication tag length in bytes.
const TAG_LEN: usize = 16;

/// Validate that a secret key matches `[A-Za-z_][A-Za-z0-9_]*`.
/// Prevents shell injection, format corruption, and target compatibility issues.
pub fn validate_key(key: &str) -> Result<()> {
    if key.is_empty() {
        bail!("invalid secret key '': must match [A-Za-z_][A-Za-z0-9_]*");
    }
    let mut chars = key.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_alphabetic() && first != '_' {
        bail!("invalid secret key '{key}': must match [A-Za-z_][A-Za-z0-9_]*");
    }
    for c in chars {
        if !c.is_ascii_alphanumeric() && c != '_' {
            bail!("invalid secret key '{key}': must match [A-Za-z_][A-Za-z0-9_]*");
        }
    }
    Ok(())
}

/// Validate a config identifier (environment, project, app name).
///
/// Must match `[a-zA-Z][a-zA-Z0-9_-]*`, max 64 chars. Blocks path separators,
/// spaces, colons, newlines, and other characters that could cause injection
/// when interpolated into file paths, YAML, or CLI arguments.
pub(crate) fn validate_identifier(name: &str, label: &str) -> Result<()> {
    if name.is_empty() {
        bail!("invalid {label} '': must not be empty");
    }
    if name.len() > 64 {
        bail!(
            "invalid {label} '{}...': exceeds 64 character limit",
            &name[..32]
        );
    }
    let mut chars = name.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_alphabetic() {
        bail!(
            "invalid {label} '{name}': must start with a letter and match [a-zA-Z][a-zA-Z0-9_-]*"
        );
    }
    for c in chars {
        if !c.is_ascii_alphanumeric() && c != '_' && c != '-' {
            bail!("invalid {label} '{name}': must match [a-zA-Z][a-zA-Z0-9_-]*");
        }
    }
    Ok(())
}

/// Validate an environment name.
pub fn validate_environment(name: &str) -> Result<()> {
    validate_identifier(name, "environment")
}

/// Validate a project name.
pub fn validate_project(name: &str) -> Result<()> {
    validate_identifier(name, "project")
}

/// Validate an app name.
pub fn validate_app(name: &str) -> Result<()> {
    validate_identifier(name, "app")
}

#[derive(Clone, Default, Serialize, Deserialize)]
pub struct StorePayload {
    pub secrets: BTreeMap<String, String>,
    /// Monotonic high-water mark incremented on every set/delete across all environments.
    ///
    /// NOT used for reconcile decisions (env_versions handles that). Serves as:
    /// - Tombstone version base (tombstones carry this value for cross-env consistency)
    /// - Backward-compat fallback for pre-env-versioning stores (via `env_version()`)
    /// - Monotonic ceiling in reconcile output (`.max(local.version)`)
    pub version: u64,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tombstones: BTreeMap<String, u64>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env_versions: BTreeMap<String, u64>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env_last_changed_at: BTreeMap<String, String>,
}

impl StorePayload {
    /// Returns the effective version for a given environment.
    ///
    /// If the environment has a per-env version, returns that. If no per-env
    /// versions exist at all (pre-env-versioning store), falls back to the
    /// global version. Otherwise the environment is unknown and returns 0.
    pub fn env_version(&self, env: &str) -> u64 {
        match self.env_versions.get(env).copied() {
            Some(v) => v,
            None if self.env_versions.is_empty() => self.version,
            None => 0,
        }
    }

    /// Returns the RFC3339 timestamp for when the environment's version
    /// last changed, if known.
    pub fn env_last_changed_at(&self, env: &str) -> Option<&str> {
        self.env_last_changed_at.get(env).map(String::as_str)
    }

    /// Extract bare-key secrets for a specific environment.
    /// Returns the filtered secrets (with `:env` suffix stripped) and the resolved version.
    /// Returns `None` if no secrets match the given environment.
    pub fn env_secrets(&self, env: &str) -> Option<(BTreeMap<String, String>, u64)> {
        let suffix = format!(":{env}");
        let env_secrets: BTreeMap<String, String> = self
            .secrets
            .iter()
            .filter_map(|(k, v)| {
                k.strip_suffix(&suffix)
                    .map(|bare| (bare.to_string(), v.clone()))
            })
            .collect();

        if env_secrets.is_empty() {
            return None;
        }

        let version = self.env_version(env);

        Some((env_secrets, version))
    }

    /// Build a per-env StorePayload with bare keys for syncing to remotes.
    /// Strips the `:{env}` suffix from secret keys and includes env-specific
    /// version and timestamp. Returns a payload with empty tombstones and env_versions.
    #[must_use]
    pub fn for_env(&self, env: &str) -> StorePayload {
        let suffix = format!(":{env}");
        let bare: BTreeMap<String, String> = self
            .secrets
            .iter()
            .filter_map(|(k, v)| {
                k.strip_suffix(&suffix)
                    .map(|bare| (bare.to_string(), v.clone()))
            })
            .collect();
        let version = self.env_version(env);
        let mut env_last_changed_at = BTreeMap::new();
        if let Some(ts) = self.env_last_changed_at(env) {
            env_last_changed_at.insert(env.to_string(), ts.to_string());
        }
        StorePayload {
            secrets: bare,
            version,
            env_last_changed_at,
            ..Default::default()
        }
    }

    /// Convert bare keys back to composite keys (`KEY` → `KEY:env`).
    pub fn bare_to_composite(
        secrets: &BTreeMap<String, String>,
        env: &str,
    ) -> BTreeMap<String, String> {
        secrets
            .iter()
            .map(|(k, v)| (format!("{k}:{env}"), v.clone()))
            .collect()
    }
}

impl StorePayload {
    /// Prune tombstones that all configured remotes have acknowledged.
    ///
    /// For each tombstone, extracts the env from the composite key (`KEY:env`),
    /// looks up the minimum successfully-pushed version across all remotes for
    /// that env, and removes the tombstone if its version <= that minimum.
    ///
    /// Returns the number of pruned entries.
    pub fn prune_tombstones(
        &mut self,
        sync_index: &crate::sync_tracker::SyncIndex,
        remote_names: &[&str],
    ) -> usize {
        if self.tombstones.is_empty() || remote_names.is_empty() {
            return 0;
        }

        // Pre-compute min push version per env to avoid borrow conflict with retain
        let envs: std::collections::BTreeSet<&str> = self
            .tombstones
            .keys()
            .filter_map(|k| k.rsplit_once(':').map(|(_, env)| env))
            .collect();

        let min_versions: BTreeMap<String, Option<u64>> = envs
            .into_iter()
            .map(|env| {
                (
                    env.to_string(),
                    sync_index.min_successful_push_version(env, remote_names),
                )
            })
            .collect();

        let before = self.tombstones.len();
        self.tombstones.retain(|key, tomb_version| {
            let env = key.rsplit_once(':').map_or("", |(_, e)| e);
            match min_versions.get(env).copied().flatten() {
                Some(min_v) => *tomb_version > min_v, // keep if not yet acknowledged
                None => true,                         // keep if we can't confirm all remotes
            }
        });
        before - self.tombstones.len()
    }
}

impl std::fmt::Debug for StorePayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StorePayload")
            .field("secrets", &format_args!("<{} entries>", self.secrets.len()))
            .field("version", &self.version)
            .field(
                "tombstones",
                &format_args!("<{} entries>", self.tombstones.len()),
            )
            .field("env_versions", &self.env_versions)
            .field("env_last_changed_at", &self.env_last_changed_at)
            .finish()
    }
}

pub(crate) enum KeyProvider {
    File {
        path: PathBuf,
    },
    #[cfg_attr(not(feature = "keychain"), allow(dead_code))]
    Keychain {
        service: String,
        account: String,
    },
}

impl KeyProvider {
    pub(crate) fn from_marker(esk_dir: &Path) -> Result<Self> {
        let marker = esk_dir.join("key-provider");
        let provider = if marker.is_file() {
            std::fs::read_to_string(&marker)
                .with_context(|| format!("failed to read {}", marker.display()))?
                .trim()
                .to_string()
        } else {
            "file".to_string()
        };
        match provider.as_str() {
            "file" => Ok(Self::File {
                path: esk_dir.join("store.key"),
            }),
            "keychain" => {
                let root = esk_dir.parent().context("esk dir has no parent")?;
                let canonical = std::fs::canonicalize(root)
                    .with_context(|| format!("failed to canonicalize {}", root.display()))?;
                Ok(Self::Keychain {
                    service: "esk".to_string(),
                    account: canonical.to_string_lossy().into_owned(),
                })
            }
            other => bail!("unknown key provider in .esk/key-provider: {other}"),
        }
    }

    fn exists(&self) -> bool {
        match self {
            Self::File { path } => path.is_file(),
            #[cfg(feature = "keychain")]
            Self::Keychain { service, account } => {
                let entry = keyring::Entry::new(service, account);
                match entry {
                    Ok(e) => e.get_secret().is_ok(),
                    Err(_) => false,
                }
            }
            #[cfg(not(feature = "keychain"))]
            Self::Keychain { .. } => false,
        }
    }

    pub(crate) fn load(&self) -> Result<Zeroizing<Vec<u8>>> {
        match self {
            Self::File { path } => Self::read_key_file(path),
            #[cfg(feature = "keychain")]
            Self::Keychain { service, account } => {
                let entry = keyring::Entry::new(service, account)
                    .map_err(|e| anyhow::anyhow!("failed to access OS keychain: {e}"))?;
                let hex_str = entry.get_password().map_err(|e| match e {
                    keyring::Error::NoEntry => anyhow::anyhow!(
                        "encryption key not found in OS keychain for {account}. Run 'esk init --keychain' to set up."
                    ),
                    keyring::Error::PlatformFailure(_) | keyring::Error::NoStorageAccess(_) => {
                        anyhow::anyhow!(
                            "OS keychain is not available (headless or unsupported platform). Use file-based key storage instead."
                        )
                    }
                    _ => anyhow::anyhow!("failed to read key from OS keychain: {e}"),
                })?;
                let key = Zeroizing::new(
                    hex::decode(hex_str.trim()).context("invalid key hex from keychain")?,
                );
                if key.len() != KEY_LEN {
                    bail!(
                        "invalid key length from keychain: expected {KEY_LEN} bytes, got {}",
                        key.len()
                    );
                }
                Ok(key)
            }
            #[cfg(not(feature = "keychain"))]
            Self::Keychain { .. } => {
                bail!("keychain support is not available in this build. Use file-based key storage instead.")
            }
        }
    }

    fn create(&self) -> Result<Zeroizing<Vec<u8>>> {
        let key = Self::generate_key();
        self.store(&key)?;
        Ok(key)
    }

    pub(crate) fn store(&self, key: &[u8]) -> Result<()> {
        match self {
            Self::File { path } => Self::write_key_file(path, key),
            #[cfg(feature = "keychain")]
            Self::Keychain { service, account } => {
                let entry = keyring::Entry::new(service, account)
                    .map_err(|e| anyhow::anyhow!("failed to access OS keychain: {e}"))?;
                entry.set_password(&hex::encode(key)).map_err(|e| match e {
                    keyring::Error::PlatformFailure(_) | keyring::Error::NoStorageAccess(_) => {
                        anyhow::anyhow!(
                            "OS keychain is not available (headless or unsupported platform). Use file-based key storage instead."
                        )
                    }
                    _ => anyhow::anyhow!("failed to store key in OS keychain: {e}"),
                })?;
                Ok(())
            }
            #[cfg(not(feature = "keychain"))]
            Self::Keychain { .. } => {
                bail!("keychain support is not available in this build. Use file-based key storage instead.")
            }
        }
    }

    fn generate_key() -> Zeroizing<Vec<u8>> {
        let mut key = Zeroizing::new(vec![0u8; KEY_LEN]);
        rand::rng().fill_bytes(&mut key);
        key
    }

    fn read_key_file(path: &Path) -> Result<Zeroizing<Vec<u8>>> {
        let hex_str = Zeroizing::new(
            std::fs::read_to_string(path)
                .with_context(|| format!("failed to read key from {}", path.display()))?,
        );
        let key = Zeroizing::new(hex::decode(hex_str.trim()).context("invalid key hex")?);
        if key.len() != KEY_LEN {
            bail!(
                "invalid key length: expected {KEY_LEN} bytes, got {}",
                key.len()
            );
        }
        Ok(key)
    }

    fn write_key_file(path: &Path, key: &[u8]) -> Result<()> {
        let dir = path.parent().context("key path has no parent")?;
        let tmp = NamedTempFile::new_in(dir)?;
        let hex_key = Zeroizing::new(hex::encode(key));
        std::fs::write(tmp.path(), hex_key.as_bytes())?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o600))?;
        }
        tmp.persist(path)
            .with_context(|| format!("failed to persist key to {}", path.display()))?;
        Ok(())
    }

    pub(crate) fn write_marker(esk_dir: &Path, value: &str) -> Result<()> {
        let marker = esk_dir.join("key-provider");
        std::fs::write(&marker, value)
            .with_context(|| format!("failed to write {}", marker.display()))?;
        Ok(())
    }
}

pub struct SecretStore {
    key: Zeroizing<Vec<u8>>,
    store_path: PathBuf,
}

impl std::fmt::Debug for SecretStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SecretStore")
            .field("store_path", &self.store_path)
            .finish_non_exhaustive()
    }
}

impl SecretStore {
    /// Load existing store or create a new empty one.
    pub fn load_or_create(root: &Path) -> Result<Self> {
        Self::load_or_create_with_provider(root, None)
    }

    /// Load existing store or create a new one, optionally forcing a specific key provider.
    /// When `provider_override` is `Some`, writes the marker file and uses that provider.
    pub(crate) fn load_or_create_with_provider(
        root: &Path,
        provider_override: Option<&str>,
    ) -> Result<Self> {
        let esk_dir = root.join(".esk");
        if !esk_dir.is_dir() {
            std::fs::create_dir_all(&esk_dir)
                .with_context(|| format!("failed to create {}", esk_dir.display()))?;
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&esk_dir, std::fs::Permissions::from_mode(0o700))?;
        }

        if let Some(prov) = provider_override {
            KeyProvider::write_marker(&esk_dir, prov)?;
        }

        let provider = KeyProvider::from_marker(&esk_dir)?;
        let store_path = esk_dir.join("store.enc");

        let key = if provider.exists() {
            provider.load()?
        } else {
            provider.create()?
        };

        let store = Self { key, store_path };

        // Create empty store file if it doesn't exist
        if !store.store_path.is_file() {
            store.write_payload(&StorePayload::default())?;
        }

        Ok(store)
    }

    /// Open an existing store (errors if key or store file is missing).
    pub fn open(root: &Path) -> Result<Self> {
        let esk_dir = root.join(".esk");
        let store_path = esk_dir.join("store.enc");

        let provider = KeyProvider::from_marker(&esk_dir)?;

        if !provider.exists() {
            bail!("encryption key not found. Run `esk init` first.");
        }
        if !store_path.is_file() {
            bail!(
                "encrypted store not found at {}. Run `esk init` first.",
                store_path.display()
            );
        }

        let key = provider.load()?;
        Ok(Self { key, store_path })
    }

    fn lock_path(&self) -> PathBuf {
        self.store_path
            .parent()
            .expect("store_path has no parent")
            .join("lock")
    }

    /// Acquire an exclusive file lock on `.esk/lock`, run the closure, then release.
    fn with_lock<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce() -> Result<R>,
    {
        let lock_path = self.lock_path();
        if !lock_path.exists() {
            std::fs::File::create(&lock_path)
                .with_context(|| format!("failed to create lock file {}", lock_path.display()))?;
        }
        let file = std::fs::File::open(&lock_path)
            .with_context(|| format!("failed to open {} for locking", lock_path.display()))?;
        file.lock_exclusive()
            .with_context(|| format!("failed to acquire lock on {}", lock_path.display()))?;
        let result = f();
        // Lock released when `file` is dropped
        drop(file);
        result
    }

    /// Decrypt and return the full payload.
    pub fn payload(&self) -> Result<StorePayload> {
        let ciphertext = std::fs::read_to_string(&self.store_path)
            .with_context(|| format!("failed to read {}", self.store_path.display()))?;
        let ciphertext = ciphertext.trim();
        if ciphertext.is_empty() {
            return Ok(StorePayload::default());
        }
        self.decrypt(ciphertext)
    }

    /// Get a single secret by composite key (e.g., "MY_SECRET:dev").
    pub fn get(&self, key: &str, env: &str) -> Result<Option<String>> {
        let payload = self.payload()?;
        let composite = format!("{key}:{env}");
        Ok(payload.secrets.get(&composite).cloned())
    }

    /// Set a secret, incrementing both global and env-specific versions. Acquires exclusive lock.
    pub fn set(&self, key: &str, env: &str, value: &str) -> Result<StorePayload> {
        validate_key(key)?;
        if value.contains('\0') {
            bail!("secret value for '{key}' contains null bytes");
        }
        self.with_lock(|| {
            let mut payload = self.payload()?;
            let composite = format!("{key}:{env}");
            payload.secrets.insert(composite.clone(), value.to_string());
            payload.tombstones.remove(&composite);
            payload.version += 1;
            let env_v = payload.env_versions.entry(env.to_string()).or_insert(0);
            *env_v += 1;
            payload
                .env_last_changed_at
                .insert(env.to_string(), chrono::Utc::now().to_rfc3339());
            self.write_payload(&payload)?;
            Ok(payload)
        })
    }

    /// Delete a secret, adding a tombstone. Acquires exclusive lock.
    pub fn delete(&self, key: &str, env: &str) -> Result<StorePayload> {
        validate_key(key)?;
        self.with_lock(|| {
            let mut payload = self.payload()?;
            let composite = format!("{key}:{env}");
            if payload.secrets.remove(&composite).is_none() {
                bail!("secret '{key}' has no value for environment '{env}'");
            }
            payload.version += 1;
            let env_v = payload.env_versions.entry(env.to_string()).or_insert(0);
            *env_v += 1;
            payload
                .env_last_changed_at
                .insert(env.to_string(), chrono::Utc::now().to_rfc3339());
            payload.tombstones.insert(composite, payload.version);
            self.write_payload(&payload)?;
            Ok(payload)
        })
    }

    /// Write a full payload under exclusive lock. Used by pull reconciliation.
    pub fn set_payload(&self, payload: &StorePayload) -> Result<()> {
        self.with_lock(|| self.write_payload(payload))
    }

    /// List all secrets (returns the full BTreeMap).
    pub fn list(&self) -> Result<BTreeMap<String, String>> {
        Ok(self.payload()?.secrets)
    }

    /// Write a payload to the store, encrypting it.
    pub(crate) fn write_payload(&self, payload: &StorePayload) -> Result<()> {
        let json = Zeroizing::new(serde_json::to_string(payload)?);
        let encrypted = self.encrypt(&json)?;

        let dir = self
            .store_path
            .parent()
            .context("store path has no parent")?;
        let tmp = NamedTempFile::new_in(dir)?;
        std::fs::write(tmp.path(), &encrypted)?;
        // Restrict permissions before persisting so the file is never world-readable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o600))?;
        }
        tmp.persist(&self.store_path)
            .with_context(|| format!("failed to persist store to {}", self.store_path.display()))?;
        Ok(())
    }

    /// Expose the master key for domain-specific derivation.
    pub(crate) fn master_key(&self) -> &[u8] {
        &self.key
    }

    /// Encrypt arbitrary plaintext into nonce:ciphertext:tag hex format.
    pub(crate) fn encrypt(&self, plaintext: &str) -> Result<String> {
        encrypt_with_key(&self.key, plaintext)
    }

    /// Decrypt ciphertext (nonce:ciphertext:tag hex format) into a StorePayload.
    pub(crate) fn decrypt(&self, encoded: &str) -> Result<StorePayload> {
        let json = Zeroizing::new(decrypt_with_key(&self.key, encoded)?);
        serde_json::from_str(&json).context("decrypted payload is not valid JSON")
    }
}

/// Encrypt plaintext with the given key. Returns nonce:ciphertext:tag hex.
pub(crate) fn encrypt_with_key(key: &[u8], plaintext: &str) -> Result<String> {
    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|e| anyhow::anyhow!("failed to create cipher: {e}"))?;

    let mut nonce_bytes = [0u8; NONCE_LEN];
    rand::rng().fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);

    let ciphertext = cipher
        .encrypt(nonce, plaintext.as_bytes())
        .map_err(|e| anyhow::anyhow!("encryption failed: {e}"))?;

    // AES-GCM appends tag to ciphertext. Split for our format.
    // aes-gcm crate: ciphertext includes the TAG_LEN-byte tag at the end
    let tag_start = ciphertext.len() - TAG_LEN;
    let ct = &ciphertext[..tag_start];
    let tag = &ciphertext[tag_start..];

    Ok(format!(
        "{}:{}:{}",
        hex::encode(nonce_bytes),
        hex::encode(ct),
        hex::encode(tag)
    ))
}

/// Decrypt nonce:ciphertext:tag hex with the given key. Returns plaintext string.
pub(crate) fn decrypt_with_key(key: &[u8], encoded: &str) -> Result<String> {
    let parts: Vec<&str> = encoded.split(':').collect();
    if parts.len() != 3 {
        bail!("invalid store format: expected nonce:ciphertext:tag");
    }

    let nonce_bytes = hex::decode(parts[0]).context("invalid nonce hex")?;
    let ct_bytes = hex::decode(parts[1]).context("invalid ciphertext hex")?;
    let tag_bytes = hex::decode(parts[2]).context("invalid tag hex")?;

    if nonce_bytes.len() != NONCE_LEN {
        bail!(
            "invalid nonce length: expected {NONCE_LEN}, got {}",
            nonce_bytes.len()
        );
    }

    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|e| anyhow::anyhow!("failed to create cipher: {e}"))?;
    let nonce = Nonce::from_slice(&nonce_bytes);

    // Recombine ciphertext + tag for aes-gcm
    let mut combined = ct_bytes;
    combined.extend_from_slice(&tag_bytes);

    let plaintext = cipher
        .decrypt(nonce, combined.as_ref())
        .map_err(|_| anyhow::anyhow!("decryption failed — wrong key or corrupted store"))?;

    String::from_utf8(plaintext).context("decrypted payload is not valid UTF-8")
}

/// Derive a 32-byte domain-specific key from the master key via HKDF-SHA256.
///
/// Uses `None` for salt per RFC 5869 §3.1: when IKM is already uniformly random
/// (32 bytes from CSPRNG), a salt is not required. Domain separation is handled
/// by the `info` parameter. A fixed app salt would be a breaking change for
/// existing encrypted remotes with no meaningful security gain.
pub(crate) fn derive_key(master: &[u8], domain: &[u8]) -> Zeroizing<Vec<u8>> {
    let hk = Hkdf::<Sha256>::new(None, master);
    let mut out = Zeroizing::new(vec![0u8; KEY_LEN]);
    hk.expand(domain, &mut out)
        .expect("32 bytes is valid HKDF-SHA256 output");
    out
}

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

    fn tmp_root() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    #[test]
    fn load_or_create_fresh() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        assert!(dir.path().join(".esk/store.key").is_file());
        assert!(dir.path().join(".esk/store.enc").is_file());
        let payload = store.payload().unwrap();
        assert!(payload.secrets.is_empty());
        assert_eq!(payload.version, 0);
    }

    #[test]
    fn load_or_create_existing() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        let key_before = std::fs::read_to_string(dir.path().join(".esk/store.key")).unwrap();

        let store2 = SecretStore::load_or_create(dir.path()).unwrap();
        let key_after = std::fs::read_to_string(dir.path().join(".esk/store.key")).unwrap();
        assert_eq!(key_before, key_after);
        assert_eq!(store2.get("KEY", "dev").unwrap(), Some("val".to_string()));
    }

    #[test]
    fn load_or_create_key_exists_no_store() {
        let dir = tmp_root();
        // Create key only
        SecretStore::load_or_create(dir.path()).unwrap();
        std::fs::remove_file(dir.path().join(".esk/store.enc")).unwrap();

        let store = SecretStore::load_or_create(dir.path()).unwrap();
        assert!(dir.path().join(".esk/store.enc").is_file());
        let payload = store.payload().unwrap();
        assert_eq!(payload.version, 0);
    }

    #[test]
    fn open_missing_key() {
        let dir = tmp_root();
        // Create .esk dir so from_marker can run, but no key file
        std::fs::create_dir_all(dir.path().join(".esk")).unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("encryption key not found"));
    }

    #[test]
    fn open_missing_store() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        std::fs::remove_file(dir.path().join(".esk/store.enc")).unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("encrypted store not found"));
    }

    #[test]
    fn open_both_exist() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        SecretStore::open(dir.path()).unwrap();
    }

    #[test]
    fn set_and_get_roundtrip() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("API_KEY", "dev", "sk_test_123").unwrap();
        assert_eq!(
            store.get("API_KEY", "dev").unwrap(),
            Some("sk_test_123".to_string())
        );
    }

    #[test]
    fn get_nonexistent_key() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        assert_eq!(store.get("NOPE", "dev").unwrap(), None);
    }

    #[test]
    fn get_wrong_env() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        assert_eq!(store.get("KEY", "prod").unwrap(), None);
    }

    #[test]
    fn set_increments_version() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let p1 = store.set("A", "dev", "1").unwrap();
        let p2 = store.set("B", "dev", "2").unwrap();
        let p3 = store.set("C", "dev", "3").unwrap();
        assert_eq!(p1.version, 1);
        assert_eq!(p2.version, 2);
        assert_eq!(p3.version, 3);
    }

    #[test]
    fn set_overwrites_existing() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "old").unwrap();
        store.set("KEY", "dev", "new").unwrap();
        assert_eq!(store.get("KEY", "dev").unwrap(), Some("new".to_string()));
    }

    #[test]
    fn list_empty_store() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        assert!(store.list().unwrap().is_empty());
    }

    #[test]
    fn list_multiple_secrets() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("A", "dev", "1").unwrap();
        store.set("B", "prod", "2").unwrap();
        let list = store.list().unwrap();
        assert_eq!(list.len(), 2);
        assert!(list.contains_key("A:dev"));
        assert!(list.contains_key("B:prod"));
    }

    #[test]
    fn payload_empty_file() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        // Overwrite the enc file with empty content
        std::fs::write(dir.path().join(".esk/store.enc"), "").unwrap();
        let payload = store.payload().unwrap();
        assert_eq!(payload.version, 0);
        assert!(payload.secrets.is_empty());
    }

    #[test]
    fn encrypt_decrypt_roundtrip() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let plaintext = r#"{"secrets":{"KEY:dev":"val"},"version":1}"#;
        let encrypted = store.encrypt(plaintext).unwrap();
        let decrypted = store.decrypt(&encrypted).unwrap();
        assert_eq!(decrypted.secrets.get("KEY:dev").unwrap(), "val");
        assert_eq!(decrypted.version, 1);
    }

    #[test]
    fn decrypt_wrong_key() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let encrypted = store.encrypt(r#"{"secrets":{},"version":0}"#).unwrap();

        // Create a different key
        let dir2 = tmp_root();
        let store2 = SecretStore::load_or_create(dir2.path()).unwrap();
        let err = store2.decrypt(&encrypted).unwrap_err();
        assert!(err.to_string().contains("wrong key or corrupted"));
    }

    #[test]
    fn decrypt_invalid_format_no_colons() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("nocolonshere").unwrap_err();
        assert!(err.to_string().contains("invalid store format"));
    }

    #[test]
    fn decrypt_invalid_format_two_parts() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("aa:bb").unwrap_err();
        assert!(err.to_string().contains("invalid store format"));
    }

    #[test]
    fn decrypt_invalid_format_four_parts() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("aa:bb:cc:dd").unwrap_err();
        assert!(err.to_string().contains("invalid store format"));
    }

    #[test]
    fn decrypt_invalid_nonce_hex() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("zzzz:aabb:ccdd").unwrap_err();
        assert!(err.to_string().contains("invalid nonce hex"));
    }

    #[test]
    fn decrypt_invalid_ciphertext_hex() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("aabb:zzzz:ccdd").unwrap_err();
        assert!(err.to_string().contains("invalid ciphertext hex"));
    }

    #[test]
    fn decrypt_invalid_tag_hex() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.decrypt("aabb:ccdd:zzzz").unwrap_err();
        assert!(err.to_string().contains("invalid tag hex"));
    }

    #[test]
    fn decrypt_wrong_nonce_length() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        // 8 bytes instead of 12
        let nonce = hex::encode([0u8; 8]);
        let ct = hex::encode([0u8; 16]);
        let tag = hex::encode([0u8; 16]);
        let err = store.decrypt(&format!("{nonce}:{ct}:{tag}")).unwrap_err();
        assert!(err.to_string().contains("invalid nonce length"));
    }

    #[test]
    fn decrypt_tampered_ciphertext() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let encrypted = store.encrypt(r#"{"secrets":{},"version":0}"#).unwrap();
        let parts: Vec<&str> = encrypted.split(':').collect();
        let mut ct_bytes = hex::decode(parts[1]).unwrap();
        if !ct_bytes.is_empty() {
            ct_bytes[0] ^= 0xFF;
        }
        let tampered = format!("{}:{}:{}", parts[0], hex::encode(&ct_bytes), parts[2]);
        assert!(store.decrypt(&tampered).is_err());
    }

    #[test]
    fn decrypt_tampered_tag() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let encrypted = store.encrypt(r#"{"secrets":{},"version":0}"#).unwrap();
        let parts: Vec<&str> = encrypted.split(':').collect();
        let mut tag_bytes = hex::decode(parts[2]).unwrap();
        tag_bytes[0] ^= 0xFF;
        let tampered = format!("{}:{}:{}", parts[0], parts[1], hex::encode(&tag_bytes));
        assert!(store.decrypt(&tampered).is_err());
    }

    #[test]
    fn decrypt_tampered_nonce() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let encrypted = store.encrypt(r#"{"secrets":{},"version":0}"#).unwrap();
        let parts: Vec<&str> = encrypted.split(':').collect();
        let mut nonce_bytes = hex::decode(parts[0]).unwrap();
        nonce_bytes[0] ^= 0xFF;
        let tampered = format!("{}:{}:{}", hex::encode(&nonce_bytes), parts[1], parts[2]);
        assert!(store.decrypt(&tampered).is_err());
    }

    #[test]
    fn decrypt_truncated_ciphertext() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let encrypted = store.encrypt(r#"{"secrets":{},"version":0}"#).unwrap();
        let parts: Vec<&str> = encrypted.split(':').collect();
        let ct_bytes = hex::decode(parts[1]).unwrap();
        let truncated = &ct_bytes[..ct_bytes.len().saturating_sub(4).max(1)];
        let tampered = format!("{}:{}:{}", parts[0], hex::encode(truncated), parts[2]);
        assert!(store.decrypt(&tampered).is_err());
    }

    #[test]
    #[cfg(unix)]
    fn key_file_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        let metadata = std::fs::metadata(dir.path().join(".esk/store.key")).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[test]
    fn key_is_32_bytes() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        let hex_str = std::fs::read_to_string(dir.path().join(".esk/store.key")).unwrap();
        let key_bytes = hex::decode(hex_str.trim()).unwrap();
        assert_eq!(key_bytes.len(), 32);
    }

    #[test]
    fn key_hex_roundtrip() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        let hex_str = std::fs::read_to_string(dir.path().join(".esk/store.key")).unwrap();
        let key_bytes = hex::decode(hex_str.trim()).unwrap();
        assert_eq!(hex::encode(&key_bytes), hex_str.trim());
    }

    #[test]
    fn write_payload_atomic() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        assert!(dir.path().join(".esk/store.enc").is_file());
        // No temp files left behind
        let entries: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(std::result::Result::ok)
            .filter(|e| e.file_name().to_string_lossy().starts_with(".tmp"))
            .collect();
        assert!(entries.is_empty());
    }

    #[test]
    fn multiple_encryptions_differ() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let plaintext = r#"{"secrets":{},"version":0}"#;
        let enc1 = store.encrypt(plaintext).unwrap();
        let enc2 = store.encrypt(plaintext).unwrap();
        assert_ne!(enc1, enc2); // Random nonce each time
    }

    #[test]
    fn invalid_key_hex_in_file() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        std::fs::write(dir.path().join(".esk/store.key"), "not_valid_hex_zzz").unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("invalid key hex"));
    }

    #[test]
    fn empty_key_file() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        std::fs::write(dir.path().join(".esk/store.key"), "").unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("invalid key length"));
    }

    #[test]
    fn delete_removes_secret() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        let payload = store.delete("KEY", "dev").unwrap();
        assert_eq!(payload.version, 2);
        assert!(!payload.secrets.contains_key("KEY:dev"));
        assert!(store.get("KEY", "dev").unwrap().is_none());
    }

    #[test]
    fn delete_adds_tombstone() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        let payload = store.delete("KEY", "dev").unwrap();
        assert_eq!(payload.tombstones.get("KEY:dev"), Some(&2));
    }

    #[test]
    fn delete_nonexistent_errors() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.delete("NOPE", "dev").unwrap_err();
        assert!(err.to_string().contains("no value for environment"));
    }

    #[test]
    fn delete_preserves_other_envs() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "dev_val").unwrap();
        store.set("KEY", "prod", "prod_val").unwrap();
        store.delete("KEY", "dev").unwrap();
        assert!(store.get("KEY", "dev").unwrap().is_none());
        assert_eq!(
            store.get("KEY", "prod").unwrap(),
            Some("prod_val".to_string())
        );
    }

    #[test]
    fn set_clears_tombstone() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        store.delete("KEY", "dev").unwrap();
        let payload = store.set("KEY", "dev", "new_val").unwrap();
        assert!(!payload.tombstones.contains_key("KEY:dev"));
    }

    #[test]
    fn tombstone_serialization_roundtrip() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("A", "dev", "val").unwrap();
        store.delete("A", "dev").unwrap();

        // Reload and verify tombstones survived
        let store2 = SecretStore::open(dir.path()).unwrap();
        let payload = store2.payload().unwrap();
        assert_eq!(payload.tombstones.get("A:dev"), Some(&2));
        assert!(!payload.secrets.contains_key("A:dev"));
    }

    #[test]
    fn set_increments_env_version() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let p1 = store.set("A", "dev", "1").unwrap();
        assert_eq!(p1.env_versions.get("dev"), Some(&1));
        let p2 = store.set("B", "dev", "2").unwrap();
        assert_eq!(p2.env_versions.get("dev"), Some(&2));
        // Setting a prod key shouldn't increment dev version
        let p3 = store.set("C", "prod", "3").unwrap();
        assert_eq!(p3.env_versions.get("dev"), Some(&2));
        assert_eq!(p3.env_versions.get("prod"), Some(&1));
    }

    #[test]
    fn delete_increments_env_version() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("A", "dev", "1").unwrap();
        store.set("B", "prod", "2").unwrap();
        let p = store.delete("A", "dev").unwrap();
        assert_eq!(p.env_versions.get("dev"), Some(&2));
        assert_eq!(p.env_versions.get("prod"), Some(&1));
    }

    #[test]
    fn set_and_delete_update_env_last_changed_at() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();

        let p1 = store.set("A", "dev", "1").unwrap();
        assert!(p1.env_last_changed_at("dev").is_some());

        let p2 = store.set("B", "prod", "2").unwrap();
        assert!(p2.env_last_changed_at("dev").is_some());
        assert!(p2.env_last_changed_at("prod").is_some());

        let p3 = store.delete("A", "dev").unwrap();
        assert!(p3.env_last_changed_at("dev").is_some());
        assert!(p3.env_last_changed_at("prod").is_some());
    }

    #[test]
    fn env_versions_absent_from_old_payloads() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let json = r#"{"secrets":{"KEY:dev":"val"},"version":1}"#;
        let encrypted = store.encrypt(json).unwrap();
        std::fs::write(dir.path().join(".esk/store.enc"), &encrypted).unwrap();
        let payload = store.payload().unwrap();
        assert!(payload.env_versions.is_empty());
    }

    #[test]
    fn env_last_changed_at_absent_from_old_payloads() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let json = r#"{"secrets":{"KEY:dev":"val"},"version":1}"#;
        let encrypted = store.encrypt(json).unwrap();
        std::fs::write(dir.path().join(".esk/store.enc"), &encrypted).unwrap();
        let payload = store.payload().unwrap();
        assert!(payload.env_last_changed_at.is_empty());
    }

    #[test]
    fn tombstone_absent_from_old_payloads() {
        // Simulate an old-format payload without tombstones field
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let json = r#"{"secrets":{"KEY:dev":"val"},"version":1}"#;
        let encrypted = store.encrypt(json).unwrap();
        std::fs::write(dir.path().join(".esk/store.enc"), &encrypted).unwrap();

        let payload = store.payload().unwrap();
        assert!(payload.tombstones.is_empty());
        assert_eq!(payload.secrets.get("KEY:dev").unwrap(), "val");
    }

    #[test]
    fn validate_key_valid() {
        assert!(validate_key("API_KEY").is_ok());
        assert!(validate_key("_PRIVATE").is_ok());
        assert!(validate_key("a").is_ok());
        assert!(validate_key("A123").is_ok());
        assert!(validate_key("my_secret_key_42").is_ok());
    }

    #[test]
    fn validate_key_invalid() {
        assert!(validate_key("").is_err());
        assert!(validate_key("123ABC").is_err());
        assert!(validate_key("KEY-NAME").is_err());
        assert!(validate_key("KEY.NAME").is_err());
        assert!(validate_key("KEY NAME").is_err());
        assert!(validate_key("KEY=VAL").is_err());
        assert!(validate_key("$KEY").is_err());
    }

    #[test]
    fn set_rejects_invalid_key() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.set("invalid-key", "dev", "val").unwrap_err();
        assert!(err.to_string().contains("invalid secret key"));
    }

    #[test]
    fn delete_rejects_invalid_key() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("VALID_KEY", "dev", "val").unwrap();
        let err = store.delete("invalid-key", "dev").unwrap_err();
        assert!(err.to_string().contains("invalid secret key"));
    }

    // --- Phase 2a: identifier validation tests ---

    #[test]
    fn validate_identifier_valid() {
        assert!(validate_identifier("dev", "env").is_ok());
        assert!(validate_identifier("prod", "env").is_ok());
        assert!(validate_identifier("staging_v2", "env").is_ok());
        assert!(validate_identifier("my-app", "app").is_ok());
        assert!(validate_identifier("MyProject", "project").is_ok());
    }

    #[test]
    fn validate_identifier_empty() {
        let err = validate_identifier("", "env").unwrap_err();
        assert!(err.to_string().contains("must not be empty"));
    }

    #[test]
    fn validate_identifier_path_separator() {
        let err = validate_identifier("../escape", "env").unwrap_err();
        assert!(err.to_string().contains("must start with a letter"));
    }

    #[test]
    fn validate_identifier_colon() {
        let err = validate_identifier("key:val", "env").unwrap_err();
        assert!(err.to_string().contains("must match"));
    }

    #[test]
    fn validate_identifier_newline() {
        let err = validate_identifier("dev\ninjection", "env").unwrap_err();
        assert!(err.to_string().contains("must match"));
    }

    #[test]
    fn validate_identifier_space() {
        let err = validate_identifier("my app", "env").unwrap_err();
        assert!(err.to_string().contains("must match"));
    }

    #[test]
    fn validate_identifier_starts_with_number() {
        let err = validate_identifier("123abc", "env").unwrap_err();
        assert!(err.to_string().contains("must start with a letter"));
    }

    #[test]
    fn validate_identifier_too_long() {
        let long = "a".repeat(65);
        let err = validate_identifier(&long, "env").unwrap_err();
        assert!(err.to_string().contains("exceeds 64"));
    }

    // --- Phase 4a: debug redaction tests ---

    #[test]
    fn store_payload_debug_redacts_secrets() {
        let mut secrets = BTreeMap::new();
        secrets.insert("KEY:dev".to_string(), "super_secret_value".to_string());
        let payload = StorePayload {
            secrets,
            version: 1,
            ..Default::default()
        };
        let debug = format!("{payload:?}");
        assert!(!debug.contains("super_secret_value"));
        assert!(debug.contains("1 entries"));
    }

    #[test]
    fn secret_store_debug_redacts_key() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let debug = format!("{store:?}");
        assert!(!debug.contains(&hex::encode(&store.key)));
        assert!(debug.contains("store_path"));
    }

    // --- Phase 5a: directory permissions ---

    #[test]
    #[cfg(unix)]
    fn esk_dir_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        let metadata = std::fs::metadata(dir.path().join(".esk")).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o700);
    }

    // --- Phase 5b: store.enc permissions ---

    #[test]
    #[cfg(unix)]
    fn store_enc_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "val").unwrap();
        let metadata = std::fs::metadata(dir.path().join(".esk/store.enc")).unwrap();
        let mode = metadata.permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    // --- Phase 5c: key length validation ---

    #[test]
    fn key_load_rejects_short_key() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        // Write a 16-byte key (32 hex chars for 16 bytes)
        let short_key = hex::encode([0u8; 16]);
        std::fs::write(dir.path().join(".esk/store.key"), &short_key).unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("invalid key length"));
        assert!(err.to_string().contains("expected 32 bytes, got 16"));
    }

    #[test]
    fn key_load_rejects_empty() {
        let dir = tmp_root();
        SecretStore::load_or_create(dir.path()).unwrap();
        std::fs::write(dir.path().join(".esk/store.key"), "").unwrap();
        let err = SecretStore::open(dir.path()).unwrap_err();
        assert!(err.to_string().contains("invalid key length"));
    }

    // --- Phase 6a: null byte rejection ---

    #[test]
    fn set_rejects_null_bytes() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        let err = store.set("KEY", "dev", "val\0ue").unwrap_err();
        assert!(err.to_string().contains("contains null bytes"));
    }

    #[test]
    fn set_accepts_newlines() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("KEY", "dev", "line1\nline2").unwrap();
        assert_eq!(
            store.get("KEY", "dev").unwrap(),
            Some("line1\nline2".to_string())
        );
    }

    #[test]
    fn store_unicode_values() {
        let dir = tmp_root();
        let store = SecretStore::load_or_create(dir.path()).unwrap();
        store.set("EMOJI", "dev", "🔐🔑✨").unwrap();
        store.set("CJK", "dev", "秘密鍵").unwrap();
        assert_eq!(
            store.get("EMOJI", "dev").unwrap(),
            Some("🔐🔑✨".to_string())
        );
        assert_eq!(store.get("CJK", "dev").unwrap(), Some("秘密鍵".to_string()));
    }

    #[test]
    fn env_version_returns_per_env_version() {
        let mut payload = StorePayload {
            version: 10,
            ..Default::default()
        };
        payload.env_versions.insert("dev".to_string(), 3);
        assert_eq!(payload.env_version("dev"), 3);
    }

    #[test]
    fn env_version_falls_back_to_global_when_no_env_versions() {
        let payload = StorePayload {
            version: 7,
            ..Default::default()
        };
        assert_eq!(payload.env_version("dev"), 7);
    }

    #[test]
    fn env_version_returns_zero_for_unknown_env() {
        let mut payload = StorePayload {
            version: 10,
            ..Default::default()
        };
        payload.env_versions.insert("dev".to_string(), 3);
        assert_eq!(payload.env_version("prod"), 0);
    }

    #[test]
    fn prune_tombstones_all_acknowledged() {
        use crate::sync_tracker::SyncIndex;

        let mut payload = StorePayload {
            version: 5,
            tombstones: BTreeMap::from([
                ("KEY_A:dev".to_string(), 2),
                ("KEY_B:dev".to_string(), 3),
            ]),
            ..Default::default()
        };
        let mut index = SyncIndex::new(Path::new("/tmp/test.json"));
        index.record_success("remote_a", "dev", 5);
        index.record_success("remote_b", "dev", 4);

        let pruned = payload.prune_tombstones(&index, &["remote_a", "remote_b"]);
        assert_eq!(pruned, 2);
        assert!(payload.tombstones.is_empty());
    }

    #[test]
    fn prune_tombstones_partially_acknowledged() {
        use crate::sync_tracker::SyncIndex;

        let mut payload = StorePayload {
            version: 5,
            tombstones: BTreeMap::from([
                ("KEY_A:dev".to_string(), 2),
                ("KEY_B:dev".to_string(), 4),
            ]),
            ..Default::default()
        };
        let mut index = SyncIndex::new(Path::new("/tmp/test.json"));
        index.record_success("remote_a", "dev", 3);

        let pruned = payload.prune_tombstones(&index, &["remote_a"]);
        assert_eq!(pruned, 1);
        assert_eq!(payload.tombstones.len(), 1);
        assert!(payload.tombstones.contains_key("KEY_B:dev"));
    }

    #[test]
    fn prune_tombstones_no_remotes() {
        let mut payload = StorePayload {
            version: 5,
            tombstones: BTreeMap::from([("KEY_A:dev".to_string(), 2)]),
            ..Default::default()
        };
        let index = crate::sync_tracker::SyncIndex::new(Path::new("/tmp/test.json"));

        let pruned = payload.prune_tombstones(&index, &[]);
        assert_eq!(pruned, 0);
        assert_eq!(payload.tombstones.len(), 1);
    }

    #[test]
    fn prune_tombstones_mixed_envs() {
        use crate::sync_tracker::SyncIndex;

        let mut payload = StorePayload {
            version: 5,
            tombstones: BTreeMap::from([
                ("KEY_A:dev".to_string(), 2),
                ("KEY_B:prod".to_string(), 3),
            ]),
            ..Default::default()
        };
        let mut index = SyncIndex::new(Path::new("/tmp/test.json"));
        index.record_success("remote_a", "dev", 5);
        // No record for prod

        let pruned = payload.prune_tombstones(&index, &["remote_a"]);
        assert_eq!(pruned, 1);
        assert!(!payload.tombstones.contains_key("KEY_A:dev"));
        assert!(payload.tombstones.contains_key("KEY_B:prod"));
    }

    #[test]
    fn prune_tombstones_empty_tombstones() {
        let mut payload = StorePayload {
            version: 5,
            ..Default::default()
        };
        let mut index = crate::sync_tracker::SyncIndex::new(Path::new("/tmp/test.json"));
        index.record_success("remote_a", "dev", 5);

        let pruned = payload.prune_tombstones(&index, &["remote_a"]);
        assert_eq!(pruned, 0);
    }
}