dotlock-bin 1.2.0

Encrypted project-local environment variables manager
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
//! Transactional writes for the vault pair (`vault.toml` + `secrets.lock`).
//!
//! Every mutation of the pair goes through [`commit_vault_pair`], which uses a
//! journal plus double temp-rename so that a crash at any point leaves the pair
//! recoverable: either both files show the new state, or both show the old one.
//! [`recover_pending`] is called at the start of every vault access and resolves
//! any interrupted transaction (roll-forward or rollback) before reads happen.

use std::{
    fs::{self, OpenOptions},
    io::Write,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};

use crate::{
    crypto::{VaultKeyMetadata, integrity::compute_file_sha256},
    domain::{error::DotLockError, model::DotLockResult},
    storage::secure_fs,
};

const JOURNAL_FILE: &str = "txn.journal";
const LOCK_FILE: &str = ".txn.lock";
const TMP_SUFFIX: &str = ".txn-tmp";
const JOURNAL_VERSION: u32 = 1;

/// Final state of a vault pair mutation, built entirely in memory by the caller.
pub struct VaultPairWrite<'a> {
    /// Complete final metadata (SDK wrappings and `secrets_hash_*` already recomputed).
    pub metadata: &'a VaultKeyMetadata,
    /// New `secrets.lock` bytes; `None` means the secrets file is unchanged
    /// (e.g. a key rotation that only rewraps metadata).
    pub secrets_lock_bytes: Option<&'a [u8]>,
}

/// What [`recover_pending`] found and did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryOutcome {
    /// No interrupted transaction was found.
    Clean,
    /// The transaction had fully completed; only the journal was cleaned up.
    Completed,
    /// The crash happened mid-commit; the remaining rename was completed.
    RolledForward,
    /// The crash happened before any rename; temp files were discarded.
    RolledBack,
}

/// Points inside the commit protocol where a crash can be injected in tests.
/// The `After` prefix is intentional: each variant names the protocol step
/// that has just completed when the simulated crash fires.
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrashPoint {
    AfterTemps,
    AfterJournal,
    AfterVaultRename,
    AfterSecretsRename,
}

#[cfg(test)]
pub(crate) mod test_hooks {
    use std::cell::Cell;

    use super::CrashPoint;

    thread_local! {
        static CRASH_AFTER: Cell<Option<CrashPoint>> = const { Cell::new(None) };
    }

    pub fn set_crash_after(point: Option<CrashPoint>) {
        CRASH_AFTER.with(|cell| cell.set(point));
    }

    pub fn take_if_matches(point: CrashPoint) -> bool {
        CRASH_AFTER.with(|cell| {
            if cell.get() == Some(point) {
                cell.set(None);
                true
            } else {
                false
            }
        })
    }
}

fn crash_if_requested(point: CrashPoint) -> DotLockResult<()> {
    #[cfg(test)]
    {
        if test_hooks::take_if_matches(point) {
            return Err(DotLockError::Io(format!(
                "simulated crash at {point:?} (test hook)"
            )));
        }
    }

    // Subprocess fault injection: only honored in debug builds so release
    // binaries cannot be aborted mid-commit via the environment.
    if cfg!(debug_assertions)
        && let Ok(value) = std::env::var("DOTLOCK_TEST_CRASH_AFTER")
    {
        let requested = match value.as_str() {
            "temps" => Some(CrashPoint::AfterTemps),
            "journal" => Some(CrashPoint::AfterJournal),
            "vault_rename" | "first_rename" => Some(CrashPoint::AfterVaultRename),
            "secrets_rename" | "second_rename" => Some(CrashPoint::AfterSecretsRename),
            _ => None,
        };
        if requested == Some(point) {
            std::process::abort();
        }
    }
    Ok(())
}

#[derive(Debug, Serialize, Deserialize)]
struct TxnJournal {
    version: u32,
    created_at: i64,
    vault_old_sha256_b64: String,
    vault_new_sha256_b64: String,
    secrets_changed: bool,
    secrets_old_sha256_b64: String,
    secrets_new_sha256_b64: String,
}

thread_local! {
    /// Directories whose vault lock is already held by this thread (M1).
    /// Makes [`TxnLock::acquire`] reentrant: `flock` treats every `open` of
    /// the lock file as an independent lock owner, so without this a mutator
    /// that already holds the lock across its read-modify-write would
    /// deadlock against its own `commit_vault_pair`.
    static HELD_LOCK_DIRS: std::cell::RefCell<std::collections::HashSet<PathBuf>> =
        std::cell::RefCell::new(std::collections::HashSet::new());
}

/// Inter-process guard over the vault pair. Uses `flock` on Unix so a
/// crashed writer never leaves a stale lock behind. Reentrant within a
/// thread: nested acquisitions return a no-op guard.
pub struct TxnLock {
    /// `Some` only for the outermost guard; dropped entries release the
    /// thread-local reentrancy marker.
    held_dir: Option<PathBuf>,
    _file: Option<fs::File>,
}

impl TxnLock {
    fn acquire(dir: &Path) -> DotLockResult<Self> {
        secure_fs::ensure_dir(dir, 0o700)?;
        let key = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
        let already_held = HELD_LOCK_DIRS.with(|held| held.borrow().contains(&key));
        if already_held {
            return Ok(Self {
                held_dir: None,
                _file: None,
            });
        }

        let path = dir.join(LOCK_FILE);
        secure_fs::reject_symlink(&path)?;

        let mut options = OpenOptions::new();
        options.read(true).write(true).create(true).truncate(false);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let file = options.open(&path)?;

        #[cfg(unix)]
        {
            use std::os::fd::AsRawFd;
            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
            if rc != 0 {
                return Err(DotLockError::Io(format!(
                    "failed to lock vault transaction journal: {}",
                    std::io::Error::last_os_error()
                )));
            }
        }

        HELD_LOCK_DIRS.with(|held| held.borrow_mut().insert(key.clone()));
        Ok(Self {
            held_dir: Some(key),
            _file: Some(file),
        })
    }
}

impl Drop for TxnLock {
    fn drop(&mut self) {
        if let Some(dir) = self.held_dir.take() {
            HELD_LOCK_DIRS.with(|held| {
                held.borrow_mut().remove(&dir);
            });
        }
    }
}

/// Acquires the inter-process vault-pair lock (M1). Mutators MUST hold this
/// guard across their whole load -> modify -> commit window so two concurrent
/// writers cannot lose each other's updates; `commit_vault_pair` re-enters the
/// same lock without blocking.
pub fn lock_vault_pair(vault_path: &Path) -> DotLockResult<TxnLock> {
    TxnLock::acquire(&journal_dir(vault_path))
}

fn journal_dir(vault_path: &Path) -> PathBuf {
    match vault_path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
        _ => PathBuf::from("."),
    }
}

fn tmp_path(path: &Path) -> PathBuf {
    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("dotlock");
    journal_dir(path).join(format!("{name}{TMP_SUFFIX}"))
}

fn fsync_dir(dir: &Path) -> DotLockResult<()> {
    #[cfg(unix)]
    {
        fs::File::open(dir)?.sync_all()?;
    }
    #[cfg(not(unix))]
    {
        let _ = dir;
    }
    Ok(())
}

fn write_bytes_excl(path: &Path, bytes: &[u8], file_mode: u32) -> DotLockResult<()> {
    secure_fs::reject_symlink(path)?;

    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(file_mode);
    }
    #[cfg(not(unix))]
    {
        let _ = file_mode;
    }

    let result = (|| -> DotLockResult<()> {
        let mut file = options.open(path)?;
        file.write_all(bytes)?;
        file.sync_all()?;
        Ok(())
    })();

    if result.is_err() {
        let _ = fs::remove_file(path);
    }
    result
}

fn sha256_b64_of(path: &Path) -> DotLockResult<String> {
    use base64::{Engine, engine::general_purpose};
    Ok(general_purpose::STANDARD.encode(compute_file_sha256(path)?))
}

fn remove_if_exists(path: &Path) -> DotLockResult<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(DotLockError::from(err)),
    }
}

fn repair_error(context: &str) -> DotLockError {
    DotLockError::Io(format!(
        "interrupted vault transaction could not be resolved automatically ({context}); \
         restore `.lock/` from a trusted backup or git history"
    ))
}

/// Commits the two writes as one transaction: either both become visible or neither.
///
/// Steps: write temps (fsync) -> write journal (fsync file + dir) ->
/// rename `vault.toml` (fsync dir) -> rename `secrets.lock` (fsync dir) ->
/// remove journal (fsync dir). Because the metadata (with new SDK wrappings and
/// hash) always lands before the new `secrets.lock`, no intermediate state ever
/// contains a ciphertext without its SDK.
pub fn commit_vault_pair(
    vault_path: &Path,
    secrets_path: &Path,
    write: VaultPairWrite<'_>,
) -> DotLockResult<()> {
    let dir = journal_dir(vault_path);
    let journal_path = dir.join(JOURNAL_FILE);
    let _lock = TxnLock::acquire(&dir)?;

    // Resolve any interrupted transaction from a previous writer first.
    if journal_path.exists() {
        recover_pending_locked(vault_path, secrets_path, &journal_path)?;
    }

    let vault_tmp = tmp_path(vault_path);
    let secrets_tmp = tmp_path(secrets_path);
    // Without a journal, leftover temps are garbage from a pre-journal crash.
    remove_if_exists(&vault_tmp)?;
    remove_if_exists(&secrets_tmp)?;

    let mut metadata = write.metadata.clone();
    metadata.version = metadata.version.max(2);
    let vault_content =
        toml::to_string_pretty(&metadata).map_err(|e| DotLockError::Crypto(e.to_string()))?;

    // Step 1: temps, fsynced.
    write_bytes_excl(&vault_tmp, vault_content.as_bytes(), 0o600)?;
    if let Some(bytes) = write.secrets_lock_bytes {
        write_bytes_excl(&secrets_tmp, bytes, 0o600)?;
    }
    crash_if_requested(CrashPoint::AfterTemps)?;

    // Step 2: journal with old and new digests, fsynced along with the directory.
    let journal = TxnJournal {
        version: JOURNAL_VERSION,
        created_at: crate::storage::secrets_lock::current_unix_timestamp(),
        vault_old_sha256_b64: sha256_b64_of(vault_path)?,
        vault_new_sha256_b64: sha256_b64_of(&vault_tmp)?,
        secrets_changed: write.secrets_lock_bytes.is_some(),
        secrets_old_sha256_b64: sha256_b64_of(secrets_path)?,
        secrets_new_sha256_b64: if write.secrets_lock_bytes.is_some() {
            sha256_b64_of(&secrets_tmp)?
        } else {
            sha256_b64_of(secrets_path)?
        },
    };
    let journal_content =
        toml::to_string_pretty(&journal).map_err(|e| DotLockError::Crypto(e.to_string()))?;
    write_bytes_excl(&journal_path, journal_content.as_bytes(), 0o600)?;
    fsync_dir(&dir)?;
    crash_if_requested(CrashPoint::AfterJournal)?;

    // Step 3: metadata becomes visible first (new SDKs + hash).
    secure_fs::reject_symlink(vault_path)?;
    fs::rename(&vault_tmp, vault_path)?;
    fsync_dir(&dir)?;
    crash_if_requested(CrashPoint::AfterVaultRename)?;

    // Step 4: secrets.lock becomes visible.
    if write.secrets_lock_bytes.is_some() {
        secure_fs::reject_symlink(secrets_path)?;
        fs::rename(&secrets_tmp, secrets_path)?;
        fsync_dir(&journal_dir(secrets_path))?;
    }
    crash_if_requested(CrashPoint::AfterSecretsRename)?;

    // Step 5: transaction complete; drop the journal.
    remove_if_exists(&journal_path)?;
    fsync_dir(&dir)?;

    // M3: the committed epoch is now the newest state this machine produced;
    // anchor it (best effort — per-user state may be unavailable, e.g. no
    // HOME, and that must never fail an already-durable commit).
    let _ =
        crate::storage::epoch_anchor::advance_epoch(&metadata.project_uuid, metadata.vault_epoch);
    Ok(())
}

/// Resolves an interrupted transaction, if any. Called at the start of every
/// vault access (unlock/read) so a crashed writer never leaves the pair in a
/// mixed state observable by readers.
pub fn recover_pending(vault_path: &Path, secrets_path: &Path) -> DotLockResult<RecoveryOutcome> {
    let dir = journal_dir(vault_path);
    let journal_path = dir.join(JOURNAL_FILE);
    if !journal_path.exists() {
        return Ok(RecoveryOutcome::Clean);
    }

    let _lock = TxnLock::acquire(&dir)?;
    if !journal_path.exists() {
        // Another process finished recovery while we waited for the lock.
        return Ok(RecoveryOutcome::Clean);
    }
    recover_pending_locked(vault_path, secrets_path, &journal_path)
}

fn recover_pending_locked(
    vault_path: &Path,
    secrets_path: &Path,
    journal_path: &Path,
) -> DotLockResult<RecoveryOutcome> {
    let dir = journal_dir(vault_path);
    let vault_tmp = tmp_path(vault_path);
    let secrets_tmp = tmp_path(secrets_path);

    let journal = secure_fs::read_to_string(journal_path)
        .ok()
        .and_then(|content| toml::from_str::<TxnJournal>(&content).ok());

    let Some(journal) = journal else {
        // Unreadable/truncated journal: the journal is written before any
        // rename, so if the vault temp is still present nothing was renamed
        // yet and a clean rollback is safe.
        if vault_tmp.exists() {
            remove_if_exists(&vault_tmp)?;
            remove_if_exists(&secrets_tmp)?;
            remove_if_exists(journal_path)?;
            fsync_dir(&dir)?;
            return Ok(RecoveryOutcome::RolledBack);
        }
        return Err(repair_error("journal unreadable and temp files missing"));
    };

    let vault_now = sha256_b64_of(vault_path)?;
    let secrets_now = sha256_b64_of(secrets_path)?;
    let vault_is_new = vault_now == journal.vault_new_sha256_b64;
    let vault_is_old = vault_now == journal.vault_old_sha256_b64;
    let secrets_is_new = !journal.secrets_changed || secrets_now == journal.secrets_new_sha256_b64;
    let secrets_is_old = !journal.secrets_changed || secrets_now == journal.secrets_old_sha256_b64;

    if vault_is_new && secrets_is_new {
        // Transaction completed; only the journal removal was interrupted.
        remove_if_exists(&vault_tmp)?;
        remove_if_exists(&secrets_tmp)?;
        remove_if_exists(journal_path)?;
        fsync_dir(&dir)?;
        return Ok(RecoveryOutcome::Completed);
    }

    if vault_is_old && secrets_is_old {
        // Crash before the first rename: discard temps, keep the old pair.
        remove_if_exists(&vault_tmp)?;
        remove_if_exists(&secrets_tmp)?;
        remove_if_exists(journal_path)?;
        fsync_dir(&dir)?;
        return Ok(RecoveryOutcome::RolledBack);
    }

    if vault_is_new && journal.secrets_changed && secrets_now == journal.secrets_old_sha256_b64 {
        // Mixed state: vault renamed, secrets not yet. Roll forward using the
        // surviving secrets temp.
        if secrets_tmp.exists() && sha256_b64_of(&secrets_tmp)? == journal.secrets_new_sha256_b64 {
            secure_fs::reject_symlink(secrets_path)?;
            fs::rename(&secrets_tmp, secrets_path)?;
            fsync_dir(&journal_dir(secrets_path))?;
            remove_if_exists(&vault_tmp)?;
            remove_if_exists(journal_path)?;
            fsync_dir(&dir)?;
            return Ok(RecoveryOutcome::RolledForward);
        }
        return Err(repair_error(
            "secrets temp file for an interrupted transaction is missing or altered",
        ));
    }

    Err(repair_error(
        "vault pair does not match either side of the interrupted transaction",
    ))
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::PathBuf,
        time::{SystemTime, UNIX_EPOCH},
    };

    use super::*;
    use crate::{
        crypto::{AccessMode, VaultConfig, VaultKeyMetadata},
        storage::vault_file::{load_vault_metadata, save_vault_metadata},
    };

    fn temp_dir(name: &str) -> PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("dotlock-txn-{name}-{unique}"));
        fs::create_dir_all(&dir).expect("create dir");
        dir
    }

    fn metadata(marker: &str) -> VaultKeyMetadata {
        VaultKeyMetadata {
            version: 5,
            project_uuid: "project".to_string(),
            project: marker.to_string(),
            environment: "dev".to_string(),
            kdf: "argon2id".to_string(),
            salt_b64: "salt".to_string(),
            memory_kib: 1,
            iterations: 1,
            parallelism: 1,
            kek_version: 1,
            kek_writes_since_rotate: 0,
            wrapped_dek_nonce_b64: "nonce".to_string(),
            wrapped_dek_b64: "wrapped".to_string(),
            wrapped_sdks_under_dek: std::collections::HashMap::new(),
            access_mode: AccessMode::MasterPassword,
            recipients: Vec::new(),
            authorized_signers: Vec::new(),
            config: VaultConfig::default(),
            secrets_hash_nonce_b64: "hash_nonce".to_string(),
            secrets_hash_b64: "hash".to_string(),
            secrets_hash_sha256_b64: "hash_plain".to_string(),
            last_rotated_at: 0,
            vault_epoch: 0,
            metadata_mac_b64: String::new(),
        }
    }

    struct Paths {
        vault: PathBuf,
        secrets: PathBuf,
        dir: PathBuf,
    }

    fn setup(name: &str) -> Paths {
        let dir = temp_dir(name);
        let vault = dir.join("vault.toml");
        let secrets = dir.join("secrets.lock");
        save_vault_metadata(&vault, &metadata("old")).expect("save vault");
        fs::write(&secrets, b"old-secrets").expect("write secrets");
        Paths {
            vault,
            secrets,
            dir,
        }
    }

    fn commit_new(paths: &Paths, crash: Option<CrashPoint>) -> DotLockResult<()> {
        test_hooks::set_crash_after(crash);
        let result = commit_vault_pair(
            &paths.vault,
            &paths.secrets,
            VaultPairWrite {
                metadata: &metadata("new"),
                secrets_lock_bytes: Some(b"new-secrets"),
            },
        );
        test_hooks::set_crash_after(None);
        result
    }

    fn assert_consistent_pair(paths: &Paths, expect_new: bool) {
        let meta = load_vault_metadata(&paths.vault).expect("load vault");
        let secrets = fs::read(&paths.secrets).expect("read secrets");
        if expect_new {
            assert_eq!(meta.project, "new");
            assert_eq!(secrets, b"new-secrets");
        } else {
            assert_eq!(meta.project, "old");
            assert_eq!(secrets, b"old-secrets");
        }
        assert!(!paths.dir.join(JOURNAL_FILE).exists());
        assert!(!tmp_path(&paths.vault).exists());
        assert!(!tmp_path(&paths.secrets).exists());
    }

    #[test]
    fn commit_vault_pair_writes_both_files_and_removes_journal() {
        let paths = setup("commit");
        commit_new(&paths, None).expect("commit");
        assert_consistent_pair(&paths, true);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn commit_vault_pair_supports_metadata_only_writes() {
        let paths = setup("meta-only");
        commit_vault_pair(
            &paths.vault,
            &paths.secrets,
            VaultPairWrite {
                metadata: &metadata("new"),
                secrets_lock_bytes: None,
            },
        )
        .expect("commit");
        let meta = load_vault_metadata(&paths.vault).expect("load vault");
        assert_eq!(meta.project, "new");
        assert_eq!(fs::read(&paths.secrets).expect("secrets"), b"old-secrets");
        assert!(!paths.dir.join(JOURNAL_FILE).exists());
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn crash_after_temps_rolls_back_cleanly() {
        let paths = setup("crash-temps");
        assert!(commit_new(&paths, Some(CrashPoint::AfterTemps)).is_err());
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        // No journal was written yet, so nothing pending; stale temps are
        // cleaned by the next commit.
        assert_eq!(outcome, RecoveryOutcome::Clean);
        commit_new(&paths, None).expect("retry commit");
        assert_consistent_pair(&paths, true);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn crash_after_journal_rolls_back_to_old_pair() {
        let paths = setup("crash-journal");
        assert!(commit_new(&paths, Some(CrashPoint::AfterJournal)).is_err());
        assert!(paths.dir.join(JOURNAL_FILE).exists());
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        assert_eq!(outcome, RecoveryOutcome::RolledBack);
        assert_consistent_pair(&paths, false);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn crash_between_renames_rolls_forward_to_new_pair() {
        let paths = setup("crash-mid");
        assert!(commit_new(&paths, Some(CrashPoint::AfterVaultRename)).is_err());
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        assert_eq!(outcome, RecoveryOutcome::RolledForward);
        assert_consistent_pair(&paths, true);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn crash_after_both_renames_completes_on_recovery() {
        let paths = setup("crash-late");
        assert!(commit_new(&paths, Some(CrashPoint::AfterSecretsRename)).is_err());
        assert!(paths.dir.join(JOURNAL_FILE).exists());
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        assert_eq!(outcome, RecoveryOutcome::Completed);
        assert_consistent_pair(&paths, true);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn recovery_is_noop_without_journal() {
        let paths = setup("noop");
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        assert_eq!(outcome, RecoveryOutcome::Clean);
        assert_consistent_pair(&paths, false);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn unreadable_journal_with_temps_rolls_back() {
        let paths = setup("bad-journal");
        assert!(commit_new(&paths, Some(CrashPoint::AfterJournal)).is_err());
        fs::write(paths.dir.join(JOURNAL_FILE), b"garbage").expect("corrupt journal");
        let outcome = recover_pending(&paths.vault, &paths.secrets).expect("recover");
        assert_eq!(outcome, RecoveryOutcome::RolledBack);
        assert_consistent_pair(&paths, false);
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn tampered_pair_after_crash_reports_repair_error() {
        let paths = setup("tampered");
        assert!(commit_new(&paths, Some(CrashPoint::AfterVaultRename)).is_err());
        // Tamper with the surviving secrets temp so roll-forward must refuse.
        fs::write(tmp_path(&paths.secrets), b"evil").expect("tamper");
        let err = recover_pending(&paths.vault, &paths.secrets).expect_err("must refuse");
        assert!(err.to_string().contains("interrupted vault transaction"));
        let _ = fs::remove_dir_all(&paths.dir);
    }

    #[test]
    fn crash_never_yields_mixed_state_for_any_crash_point() {
        for point in [
            CrashPoint::AfterTemps,
            CrashPoint::AfterJournal,
            CrashPoint::AfterVaultRename,
            CrashPoint::AfterSecretsRename,
        ] {
            let paths = setup("matrix");
            assert!(commit_new(&paths, Some(point)).is_err());
            recover_pending(&paths.vault, &paths.secrets).expect("recover");
            let meta = load_vault_metadata(&paths.vault).expect("load vault");
            let secrets = fs::read(&paths.secrets).expect("read secrets");
            let pair = (meta.project.as_str(), secrets.as_slice());
            assert!(
                pair == ("old", b"old-secrets".as_slice())
                    || pair == ("new", b"new-secrets".as_slice()),
                "mixed state after crash at {point:?}: {:?}",
                pair.0
            );
            let _ = fs::remove_dir_all(&paths.dir);
        }
    }
}