passbox 1.1.1

A password store for agents, where a fingerprint releases one secret into one process
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
//! One age file per secret. The filename is a random id, the name lives inside the ciphertext.

use crate::crypto;
use age::x25519;
use anyhow::{Context, Result, anyhow, bail};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::Zeroize;

const KEEP_VERSIONS: usize = 5;
pub const TOMB_TTL_SECS: u64 = 90 * 24 * 60 * 60;

#[derive(Serialize, Deserialize)]
pub struct Secret {
    pub name: String,
    pub value: String,
    pub created: u64,
    pub updated: u64,
}

impl Drop for Secret {
    fn drop(&mut self) {
        self.value.zeroize();
    }
}

pub fn now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/* A name, or everything under a namespace. The trailing slash is what stops `acme` dragging
in `acmecorp`. Lives here rather than in `import` because the client build has no `import`. */
#[cfg(feature = "host")]
pub fn select(all: &[String], prefix: Option<&str>) -> Vec<String> {
    let Some(prefix) = prefix else {
        return all.to_vec();
    };
    let namespace = format!("{}/", prefix.trim_end_matches('/'));
    all.iter()
        .filter(|name| *name == prefix || name.starts_with(&namespace))
        .cloned()
        .collect()
}

pub fn new_id() -> String {
    let bytes: [u8; 16] = rand::random();
    hex::encode(bytes)
}

#[derive(Clone)]
pub struct Store {
    pub dir: PathBuf,
}

impl Store {
    pub fn open() -> Result<Self> {
        let dir = match std::env::var_os("PASSBOX_DIR") {
            Some(d) => PathBuf::from(d),
            None => home()?.join(".passbox"),
        };
        Ok(Store { dir })
    }

    pub fn secrets_dir(&self) -> PathBuf {
        self.dir.join("store")
    }
    pub fn versions_dir(&self) -> PathBuf {
        self.secrets_dir().join(".versions")
    }
    pub fn wraps_dir(&self) -> PathBuf {
        self.dir.join("wraps")
    }
    fn recipient_path(&self) -> PathBuf {
        self.wraps_dir().join("recipient")
    }
    fn recovery_path(&self) -> PathBuf {
        self.wraps_dir().join("recovery.age")
    }
    /// Opened by the token rather than by a passphrase, so the file is inert on its own
    pub fn yubikey_wrap_path(&self) -> PathBuf {
        self.wraps_dir().join("yubikey.age")
    }
    pub fn has_yubikey_wrap(&self) -> bool {
        self.yubikey_wrap_path().exists()
    }

    /// One wrap per machine, because a Secure Enclave key cannot leave the Mac that made it
    pub fn se_wrap_path(&self) -> PathBuf {
        self.wraps_dir().join(format!("se-{}.json", hostname()))
    }
    pub fn socket_path(&self) -> PathBuf {
        self.dir.join("broker.sock")
    }
    /// Installed plugins, one directory each. Local and machine specific, so sync skips it
    pub fn plugins_dir(&self) -> PathBuf {
        self.dir.join("plugins")
    }
    /// Per machine, so two Macs never append to the same file through a syncer
    pub fn audit_path(&self) -> PathBuf {
        self.dir.join(format!("audit-{}.log", hostname()))
    }
    pub fn is_initialised(&self) -> bool {
        self.recipient_path().exists()
    }
    pub fn has_se_wrap(&self) -> bool {
        self.se_wrap_path().exists()
    }

    /// Generate the store key and write no wrap. The recipient stays in the clear so writing a
    /// secret never needs an unlock. The caller decides which wraps to add.
    pub fn init(&self) -> Result<x25519::Identity> {
        if self.is_initialised() {
            bail!("{} is already initialised", self.dir.display());
        }
        private_dir(&self.dir)?;
        private_dir(&self.secrets_dir())?;
        private_dir(&self.versions_dir())?;
        private_dir(&self.wraps_dir())?;

        let key = x25519::Identity::generate();
        write_private(
            &self.recipient_path(),
            key.to_public().to_string().as_bytes(),
        )?;
        Ok(key)
    }

    pub fn has_recovery_wrap(&self) -> bool {
        self.recovery_path().exists()
    }

    /// A wrap that opens the store away from this Mac. Sync is worth nothing without one.
    pub fn has_portable_wrap(&self) -> bool {
        self.has_recovery_wrap() || self.has_yubikey_wrap()
    }

    /* The passphrase wrap is the only thing that opens the store away from this Mac, which makes
    it both what syncing needs and the one file worth attacking in a synced copy. It is written
    when the user asks for sync, never before. */
    pub fn create_recovery_wrap(
        &self,
        key: &x25519::Identity,
        passphrase: SecretString,
    ) -> Result<()> {
        self.create_recovery_wrap_with_factor(key, passphrase, None)
    }

    /* The age crate calibrates scrypt to about a second of work on this machine, which is the
    right default and the wrong thing to pay sixty times over in a test suite. `log_n` lowers it,
    and only a debug build will read the environment variable that asks for that. */
    pub fn create_recovery_wrap_with_factor(
        &self,
        key: &x25519::Identity,
        passphrase: SecretString,
        log_n: Option<u8>,
    ) -> Result<()> {
        let mut recipient = age::scrypt::Recipient::new(passphrase);
        if let Some(log_n) = log_n {
            recipient.set_work_factor(log_n);
        }
        self.write_recovery_wrap(key, recipient, &self.recovery_path())
    }

    /// The same wrap written wherever the caller wants it, for a backup that never syncs
    pub fn export_recovery_wrap(
        &self,
        key: &x25519::Identity,
        passphrase: SecretString,
        to: &Path,
        log_n: Option<u8>,
    ) -> Result<()> {
        let mut recipient = age::scrypt::Recipient::new(passphrase);
        if let Some(log_n) = log_n {
            recipient.set_work_factor(log_n);
        }
        self.write_recovery_wrap(key, recipient, to)
    }

    fn write_recovery_wrap(
        &self,
        key: &x25519::Identity,
        recipient: age::scrypt::Recipient,
        to: &Path,
    ) -> Result<()> {
        let mut text = secrecy::ExposeSecret::expose_secret(&key.to_string()).to_string();
        let wrapped = crypto::encrypt(text.as_bytes(), &[Box::new(recipient)])?;
        text.zeroize();
        write_private(to, &wrapped)
    }

    /// Recipients are public, so they sit in the clear beside the wrap they opened
    pub fn yubikey_recipients_path(&self) -> PathBuf {
        self.wraps_dir().join("yubikey.recipients")
    }

    pub fn yubikey_recipients(&self) -> Vec<String> {
        fs::read_to_string(self.yubikey_recipients_path())
            .map(|raw| {
                raw.lines()
                    .map(str::trim)
                    .filter(|l| !l.is_empty())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default()
    }

    /* age takes any number of recipients, so a second token is added to the same wrap rather
    than replacing it. Adding one re-encrypts to every recipient, which is why it needs the key. */
    #[cfg(feature = "host")]
    pub fn add_yubikey_recipient(&self, key: &x25519::Identity, recipient: &str) -> Result<usize> {
        let mut all = self.yubikey_recipients();
        let recipient = recipient.trim().to_string();
        if !all.contains(&recipient) {
            all.push(recipient);
        }

        let mut to = Vec::new();
        for text in &all {
            to.push(crate::yubikey::recipient(text)?);
        }

        let mut plain = secrecy::ExposeSecret::expose_secret(&key.to_string()).to_string();
        let wrapped = crypto::encrypt(plain.as_bytes(), &to)?;
        plain.zeroize();

        write_private(&self.yubikey_wrap_path(), &wrapped)?;
        write_private(&self.yubikey_recipients_path(), all.join("\n").as_bytes())?;
        Ok(all.len())
    }

    /// The token prompts for a touch itself, so passbox raises nothing here
    #[cfg(feature = "host")]
    pub fn unlock_with_yubikey(&self) -> Result<x25519::Identity> {
        let wrapped = fs::read(self.yubikey_wrap_path()).context("no YubiKey wrap")?;
        let raw = crypto::decrypt(&wrapped, &[crate::yubikey::identity()?])
            .context("the YubiKey refused, or it is not the one this was wrapped to")?;
        key_from_bytes(&raw)
    }

    pub fn recipient(&self) -> Result<x25519::Recipient> {
        let raw = fs::read_to_string(self.recipient_path())
            .with_context(|| format!("no store at {}, run `passbox init`", self.dir.display()))?;
        x25519::Recipient::from_str(raw.trim()).map_err(|e| anyhow!("bad recipient file: {e}"))
    }

    pub fn unlock_with_passphrase(&self, passphrase: SecretString) -> Result<x25519::Identity> {
        let wrapped = fs::read(self.recovery_path()).context("no recovery wrap")?;
        let raw = crypto::decrypt(
            &wrapped,
            &[Box::new(age::scrypt::Identity::new(passphrase))],
        )
        .context("wrong passphrase")?;
        key_from_bytes(&raw)
    }

    /// Bind the store key to this Mac's Secure Enclave. Neither step raises a prompt.
    #[cfg(feature = "host")]
    pub fn create_se_wrap(&self, key: &x25519::Identity) -> Result<()> {
        let mut text = secrecy::ExposeSecret::expose_secret(&key.to_string()).to_string();
        let wrap = crate::se::wrap(text.as_bytes())?;
        text.zeroize();
        write_private(&self.se_wrap_path(), &serde_json::to_vec(&wrap)?)
    }

    /// Raise a Touch ID prompt worded by `reason`, then open the store key.
    #[cfg(feature = "host")]
    pub fn unlock_with_se(&self, reason: &str) -> Result<x25519::Identity> {
        let raw =
            fs::read(self.se_wrap_path()).context("no Secure Enclave wrap on this machine")?;
        let wrap: crate::se::SeWrap = serde_json::from_slice(&raw)?;
        let plain = crate::se::unwrap(&wrap, reason)?;
        key_from_bytes(&plain)
    }

    /// Ids with a secret file and no tombstone.
    pub fn ids(&self) -> Result<Vec<String>> {
        let mut out = self.ids_with_files()?;
        out.retain(|id| !self.tomb_path(id).exists());
        Ok(out)
    }

    /// Every id that still has a file, tombstoned or not. A delete that arrived through a
    /// sync leaves the file in place, so undeleting it is a matter of dropping the tombstone.
    pub fn ids_with_files(&self) -> Result<Vec<String>> {
        let mut out = Vec::new();
        let dir = self.secrets_dir();
        if !dir.exists() {
            return Ok(out);
        }
        for entry in fs::read_dir(&dir)? {
            let path = entry?.path();
            if path.extension().and_then(|e| e.to_str()) != Some("age") {
                continue;
            }
            if let Some(id) = path.file_stem().and_then(|s| s.to_str()) {
                out.push(id.to_string());
            }
        }
        out.sort();
        Ok(out)
    }

    pub fn untomb(&self, id: &str) -> Result<()> {
        let tomb = self.tomb_path(id);
        if tomb.exists() {
            fs::remove_file(tomb)?;
        }
        Ok(())
    }

    pub fn secret_path(&self, id: &str) -> PathBuf {
        self.secrets_dir().join(format!("{id}.age"))
    }
    pub fn tomb_path(&self, id: &str) -> PathBuf {
        self.secrets_dir().join(format!("{id}.tomb"))
    }

    pub fn load(&self, id: &str, key: &x25519::Identity) -> Result<Secret> {
        self.load_path(&self.secret_path(id), key)
    }

    pub fn load_path(&self, path: &Path, key: &x25519::Identity) -> Result<Secret> {
        let raw = fs::read(path)?;
        let mut plain = crypto::decrypt(&raw, &[Box::new(key.clone())])?;
        let secret = serde_json::from_slice(&plain).context("secret file is not valid json");
        plain.zeroize();
        secret
    }

    pub fn find(&self, name: &str, key: &x25519::Identity) -> Result<Option<(String, Secret)>> {
        for id in self.ids()? {
            let secret = self.load(&id, key)?;
            if secret.name == name {
                return Ok(Some((id, secret)));
            }
        }
        Ok(None)
    }

    /* A host to ask instead of a local broker. One line, `machine:port`, which a client writes
    once. A machine with no Enclave has nothing to unlock and no sensor to ask, so asking a
    machine that has both is the only thing it can usefully do. */
    pub fn host_path(&self) -> PathBuf {
        self.dir.join("host")
    }

    pub fn host(&self) -> Option<String> {
        if let Ok(from_env) = std::env::var("PASSBOX_HOST")
            && !from_env.is_empty()
        {
            return Some(from_env);
        }
        let text = fs::read_to_string(self.host_path()).ok()?;
        let line = text.lines().next()?.trim().to_string();
        (!line.is_empty()).then_some(line)
    }

    /// Versions before 0.13.43 kept every name in the clear here, so remove what they left
    pub fn remove_name_index(&self) -> Result<()> {
        match fs::remove_file(self.dir.join("names")) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
            _ => Ok(()),
        }
    }

    /* serde skips a field the struct does not name without building it, so the value is never
    copied out of the decrypted buffer, which wipes itself when dropped. */
    pub fn names(&self, key: &x25519::Identity) -> Result<Vec<String>> {
        #[derive(Deserialize)]
        struct NameOnly {
            name: String,
        }
        let mut out = Vec::new();
        for id in self.ids()? {
            let raw = fs::read(self.secret_path(&id))?;
            let plain = crypto::decrypt(&raw, &[Box::new(key.clone())])?;
            let entry: NameOnly =
                serde_json::from_slice(&plain).context("secret file is not valid json")?;
            out.push(entry.name);
        }
        out.sort();
        Ok(out)
    }

    /// Encrypt and write, keeping the previous file as a version.
    pub fn put(&self, id: &str, secret: &Secret, recipient: &x25519::Recipient) -> Result<()> {
        private_dir(&self.secrets_dir())?;
        let json = serde_json::to_vec(secret)?;
        let ct = crypto::encrypt(&json, &[Box::new(recipient.clone())])?;
        self.keep_version(id)?;
        write_private(&self.secret_path(id), &ct)?;
        let tomb = self.tomb_path(id);
        if tomb.exists() {
            fs::remove_file(tomb)?;
        }
        Ok(())
    }

    /// Move the current file into `.versions`, trimming to the newest KEEP_VERSIONS.
    pub fn keep_version(&self, id: &str) -> Result<()> {
        let current = self.secret_path(id);
        if !current.exists() {
            return Ok(());
        }
        let dir = self.versions_dir().join(id);
        private_dir(&dir)?;
        let mut stamp = now();
        while dir.join(format!("{stamp}.age")).exists() {
            stamp += 1;
        }
        fs::rename(&current, dir.join(format!("{stamp}.age")))?;

        let mut kept = self.versions(id)?;
        while kept.len() > KEEP_VERSIONS {
            let (_, oldest) = kept.remove(0);
            fs::remove_file(oldest)?;
        }
        Ok(())
    }

    /// Versions for an id, oldest first.
    pub fn versions(&self, id: &str) -> Result<Vec<(u64, PathBuf)>> {
        let dir = self.versions_dir().join(id);
        let mut out = Vec::new();
        if !dir.exists() {
            return Ok(out);
        }
        for entry in fs::read_dir(&dir)? {
            let path = entry?.path();
            let stamp = path
                .file_stem()
                .and_then(|s| s.to_str())
                .and_then(|s| s.parse::<u64>().ok());
            if let Some(stamp) = stamp {
                out.push((stamp, path));
            }
        }
        out.sort_by_key(|(stamp, _)| *stamp);
        Ok(out)
    }

    /// Version the current file, then leave a tombstone so the delete survives a sync.
    pub fn delete(&self, id: &str) -> Result<()> {
        self.keep_version(id)?;
        write_private(&self.tomb_path(id), now().to_string().as_bytes())
    }

    /// Drop tombstones older than the TTL, along with the versions they guard.
    pub fn prune_tombs(&self) -> Result<usize> {
        let dir = self.secrets_dir();
        if !dir.exists() {
            return Ok(0);
        }
        let mut pruned = 0;
        for entry in fs::read_dir(&dir)? {
            let path = entry?.path();
            if path.extension().and_then(|e| e.to_str()) != Some("tomb") {
                continue;
            }
            let stamp = fs::read_to_string(&path)
                .ok()
                .and_then(|s| s.trim().parse::<u64>().ok())
                .unwrap_or(0);
            if now().saturating_sub(stamp) < TOMB_TTL_SECS {
                continue;
            }
            if let Some(id) = path.file_stem().and_then(|s| s.to_str()) {
                let versions = self.versions_dir().join(id);
                if versions.exists() {
                    fs::remove_dir_all(versions)?;
                }
            }
            fs::remove_file(&path)?;
            pruned += 1;
        }
        Ok(pruned)
    }
}

fn home() -> Result<PathBuf> {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .ok_or_else(|| anyhow!("HOME is not set"))
}

pub fn hostname() -> String {
    std::process::Command::new("hostname")
        .arg("-s")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "unknown".to_string())
}

fn key_from_bytes(raw: &[u8]) -> Result<x25519::Identity> {
    let text = std::str::from_utf8(raw).context("the wrap is not a key")?;
    x25519::Identity::from_str(text.trim()).map_err(|e| anyhow!("bad store key: {e}"))
}

pub fn private_dir(path: &Path) -> Result<()> {
    fs::create_dir_all(path)?;
    fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
    Ok(())
}

/// Write through a temporary file so a crash cannot leave a half written secret.
pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
    let tmp = path.with_extension("tmp");
    fs::write(&tmp, bytes)?;
    fs::set_permissions(&tmp, fs::Permissions::from_mode(0o600))?;
    fs::rename(&tmp, path)?;
    Ok(())
}

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

    #[test]
    fn removing_an_old_name_index_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store {
            dir: dir.path().to_path_buf(),
        };
        std::fs::write(dir.path().join("names"), "a/one\n").unwrap();
        store.remove_name_index().unwrap();
        assert!(!dir.path().join("names").exists());
        store.remove_name_index().unwrap();
    }

    fn store() -> (tempfile::TempDir, Store, x25519::Identity) {
        let tmp = tempfile::tempdir().unwrap();
        let store = Store {
            dir: tmp.path().to_path_buf(),
        };
        let pass = SecretString::from("hunter2".to_string());
        let key = store.init().unwrap();
        store
            .create_recovery_wrap_with_factor(&key, pass, Some(10))
            .unwrap();
        (tmp, store, key)
    }

    fn secret(name: &str, value: &str) -> Secret {
        Secret {
            name: name.to_string(),
            value: value.to_string(),
            created: now(),
            updated: now(),
        }
    }

    #[test]
    fn round_trip_by_name() {
        let (_tmp, store, key) = store();
        let r = store.recipient().unwrap();
        store
            .put(&new_id(), &secret("github/token", "ghp_abc"), &r)
            .unwrap();

        let (_id, found) = store.find("github/token", &key).unwrap().unwrap();
        assert_eq!(found.value, "ghp_abc");
        assert!(store.find("missing", &key).unwrap().is_none());
    }

    #[test]
    fn filename_never_holds_the_name() {
        let (_tmp, store, _key) = store();
        let r = store.recipient().unwrap();
        store
            .put(&new_id(), &secret("github/token", "ghp_abc"), &r)
            .unwrap();

        for id in store.ids().unwrap() {
            assert!(!id.contains("github"));
            assert!(!id.contains("token"));
            let raw = fs::read(store.secret_path(&id)).unwrap();
            assert!(!String::from_utf8_lossy(&raw).contains("github"));
        }
    }

    #[test]
    fn wrong_passphrase_is_refused() {
        let (_tmp, store, _key) = store();
        let wrong = SecretString::from("hunter3".to_string());
        assert!(store.unlock_with_passphrase(wrong).is_err());
    }

    #[test]
    fn overwrite_keeps_a_version() {
        let (_tmp, store, key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "old"), &r).unwrap();
        store.put(&id, &secret("db", "new"), &r).unwrap();

        assert_eq!(store.load(&id, &key).unwrap().value, "new");
        assert_eq!(store.versions(&id).unwrap().len(), 1);
    }

    #[test]
    fn versions_are_trimmed() {
        let (_tmp, store, _key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        for i in 0..KEEP_VERSIONS + 4 {
            store.put(&id, &secret("db", &format!("v{i}")), &r).unwrap();
        }
        assert_eq!(store.versions(&id).unwrap().len(), KEEP_VERSIONS);
    }

    #[test]
    fn delete_leaves_a_tombstone_and_hides_the_id() {
        let (_tmp, store, _key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "v"), &r).unwrap();
        store.delete(&id).unwrap();

        assert!(store.ids().unwrap().is_empty());
        assert!(store.tomb_path(&id).exists());
        assert_eq!(store.versions(&id).unwrap().len(), 1);
    }

    #[test]
    fn writing_again_clears_the_tombstone() {
        let (_tmp, store, key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "v"), &r).unwrap();
        store.delete(&id).unwrap();
        store.put(&id, &secret("db", "back"), &r).unwrap();

        assert_eq!(store.ids().unwrap().len(), 1);
        assert_eq!(store.load(&id, &key).unwrap().value, "back");
    }

    #[test]
    fn fresh_tombstones_survive_pruning() {
        let (_tmp, store, _key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "v"), &r).unwrap();
        store.delete(&id).unwrap();

        assert_eq!(store.prune_tombs().unwrap(), 0);
        write_private(&store.tomb_path(&id), b"1").unwrap();
        assert_eq!(store.prune_tombs().unwrap(), 1);
        assert!(!store.versions_dir().join(&id).exists());
    }

    /* The reference `age` CLI is a separate implementation in another language. If it can open
    what we wrote, the files are standard age files rather than something only this crate reads,
    and the store stays recoverable with off the shelf tools if passbox ever goes away. */
    #[test]
    fn a_secret_file_opens_with_the_reference_age_cli() {
        let Ok(age_cli) = which("age") else {
            eprintln!("skipped, the age CLI is not installed");
            return;
        };
        let (tmp, store, key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "swordfish"), &r).unwrap();

        let identity = tmp.path().join("identity.txt");
        fs::write(
            &identity,
            secrecy::ExposeSecret::expose_secret(&key.to_string()),
        )
        .unwrap();

        let out = std::process::Command::new(age_cli)
            .arg("--decrypt")
            .arg("-i")
            .arg(&identity)
            .arg(store.secret_path(&id))
            .output()
            .unwrap();

        assert!(
            out.status.success(),
            "age refused our file: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let plain = String::from_utf8_lossy(&out.stdout);
        assert!(plain.contains("swordfish"), "{plain}");
        assert!(plain.contains("\"name\":\"db\""), "{plain}");
    }

    fn which(tool: &str) -> Result<PathBuf> {
        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(format!("command -v {tool}"))
            .output()?;
        let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if path.is_empty() {
            bail!("{tool} not found");
        }
        Ok(PathBuf::from(path))
    }

    #[cfg(feature = "host")]
    #[test]
    fn a_tampered_audit_line_is_refused() {
        let (_tmp, store, key) = store();
        let line = crypto::encrypt_line(b"{\"at\":1}", &store.recipient().unwrap()).unwrap();

        assert!(crypto::decrypt_line(&line, &key).is_ok());

        let mut bytes = line.into_bytes();
        let last = bytes.len() - 1;
        bytes[last] = if bytes[last] == b'a' { b'b' } else { b'a' };
        let tampered = String::from_utf8(bytes).unwrap();
        assert!(crypto::decrypt_line(&tampered, &key).is_err());
    }

    /// A flipped byte must fail rather than hand back something that looks like a secret
    #[test]
    fn a_tampered_secret_file_is_refused() {
        let (_tmp, store, key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "swordfish"), &r).unwrap();

        let path = store.secret_path(&id);
        let mut raw = fs::read(&path).unwrap();
        let last = raw.len() - 1;
        raw[last] ^= 0x01;
        fs::write(&path, &raw).unwrap();

        let opened = store.load(&id, &key);
        assert!(opened.is_err(), "a tampered file decrypted");
    }

    #[test]
    fn a_truncated_secret_file_is_refused() {
        let (_tmp, store, key) = store();
        let r = store.recipient().unwrap();
        let id = new_id();
        store.put(&id, &secret("db", "swordfish"), &r).unwrap();

        let path = store.secret_path(&id);
        let raw = fs::read(&path).unwrap();
        fs::write(&path, &raw[..raw.len() / 2]).unwrap();

        assert!(store.load(&id, &key).is_err());
    }

    #[test]
    fn a_tampered_recovery_wrap_is_refused() {
        let (_tmp, store, _key) = store();
        let path = store.wraps_dir().join("recovery.age");
        let mut raw = fs::read(&path).unwrap();
        let last = raw.len() - 1;
        raw[last] ^= 0x01;
        fs::write(&path, &raw).unwrap();

        let pass = SecretString::from("hunter2".to_string());
        assert!(store.unlock_with_passphrase(pass).is_err());
    }

    #[test]
    fn yubikey_recipients_accumulate_on_disk() {
        let (_tmp, store, _key) = store();
        assert!(store.yubikey_recipients().is_empty());

        write_private(
            &store.yubikey_recipients_path(),
            b"age1yubikey1aaa\nage1yubikey1bbb\n",
        )
        .unwrap();
        assert_eq!(
            store.yubikey_recipients(),
            vec!["age1yubikey1aaa", "age1yubikey1bbb"]
        );
    }

    #[test]
    fn a_yubikey_wrap_counts_as_a_way_off_this_mac() {
        let (_tmp, store, _key) = store();
        assert!(
            store.has_portable_wrap(),
            "the test store has a passphrase wrap"
        );

        fs::remove_file(store.wraps_dir().join("recovery.age")).unwrap();
        assert!(!store.has_portable_wrap());

        write_private(&store.yubikey_wrap_path(), b"x").unwrap();
        assert!(store.has_portable_wrap());
    }

    #[test]
    fn init_refuses_twice() {
        let (_tmp, store, _key) = store();
        assert!(store.init().is_err());
    }
}