sefy-core 0.20.0

Core library for sefy: an inconspicuous encrypted secret store in a single file
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
//! The vault: an encrypted file, its in-memory database, and the operations
//! that move data between them.

use crate::copies;
use crate::crypto::{DerivedKey, SALT_LEN};
use crate::db::{self, Stamp};
use crate::error::{Error, Result};
use crate::format;
use crate::history::Version;
use crate::keys::{KeySource, Opener};
use crate::model::{Field, Item, ItemSummary, NewItem, Payload, Query};
use crate::policy::{self, Policy};
use crate::wipe::{self, Wiped};
use rusqlite::Connection;
use std::cell::Cell;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::Zeroizing;

/// An open vault.
///
/// The database lives in memory for as long as this value does; [`Vault::save`]
/// is what puts anything on disk, and it only ever writes ciphertext.
pub struct Vault {
    path: PathBuf,
    sealer: Sealer,
    connection: Connection,
    device: Option<String>,
    /// Whether this vault has a file of its own to be written to.
    ///
    /// A remote copy read from a transport's bytes, or the scratch copy a
    /// preview folds into, has none: it lives in memory, is looked at and is
    /// dropped. Neither ever leaves this crate in that state.
    backing: Backing,
    /// How many times this value has written its file.
    writes: Cell<u64>,
    /// Which version of the file this value holds, by the salt at its front:
    /// every write samples a new one. `None` until a new vault's first write.
    seen: Cell<Option<[u8; SALT_LEN]>>,
}

/// How a save gets the key it seals with.
enum Sealer {
    /// From the password, which this value holds.
    Password(Zeroizing<Vec<u8>>),
    /// From a source that holds the password elsewhere. It answers for the
    /// password this vault was opened with by giving the key for this salt
    /// again, every time it is asked for a new one.
    Source {
        source: Arc<dyn KeySource>,
        opened_salt: [u8; SALT_LEN],
        opened_key: DerivedKey,
    },
    /// From nowhere: a copy with no file of its own is never sealed.
    Nothing,
}

/// Where a vault's contents go when it is saved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Backing {
    /// To the file at the vault's path.
    File,
    /// Nowhere: a copy that exists only to be read.
    Memory,
}

/// What a password change did beyond the vault itself.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PasswordChange {
    /// The [copies](crate::copies) beside the vault, now sealed under the new
    /// password as well.
    pub resealed: usize,
    /// Copies that did not open under the old password and were left as they
    /// were: whatever they are, they are not this vault's to re-seal.
    pub left: Vec<PathBuf>,
}

impl Vault {
    /// Creates a new vault file, failing if the path is already taken.
    pub fn create(path: impl AsRef<Path>, password: &[u8]) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        if path.exists() {
            return Err(Error::AlreadyExists(path));
        }

        let vault = Self {
            path,
            sealer: Sealer::Password(Zeroizing::new(password.to_vec())),
            connection: db::create()?,
            device: None,
            backing: Backing::File,
            writes: Cell::new(0),
            seen: Cell::new(None),
        };
        vault.save()?;
        Ok(vault)
    }

    /// Opens an existing vault file.
    pub fn open(path: impl AsRef<Path>, password: &[u8]) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let file = fs::read(&path)
            .map_err(|source| Error::io(format!("cannot read {}", path.display()), source))?;
        let database = format::decode(password, &file)?;

        Ok(Self {
            path,
            sealer: Sealer::Password(Zeroizing::new(password.to_vec())),
            connection: db::load(&database)?,
            device: None,
            backing: Backing::File,
            writes: Cell::new(0),
            seen: Cell::new(Some(format::salt_of(&file)?)),
        })
    }

    /// Opens an existing vault file with a key from `source`, which keeps the
    /// password to itself.
    ///
    /// A key that does not fit comes back as
    /// [`Error::WrongPasswordOrNotAVault`], as a wrong password does; a source
    /// with nothing to give as [`Error::KeysGone`]. Saving asks the source for
    /// a key for a fresh salt, and refuses one from a source that is no longer
    /// answering for the password that opened this.
    pub fn open_through(path: impl AsRef<Path>, source: Arc<dyn KeySource>) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let file = fs::read(&path)
            .map_err(|source| Error::io(format!("cannot read {}", path.display()), source))?;
        let salt = format::salt_of(&file)?;
        let key = source.key_for(&salt)?;
        let database = format::open_under(&key, &file)?;

        Ok(Self {
            path,
            sealer: Sealer::Source {
                source,
                opened_salt: salt,
                opened_key: key,
            },
            connection: db::load(&database)?,
            device: None,
            backing: Backing::File,
            writes: Cell::new(0),
            seen: Cell::new(Some(salt)),
        })
    }

    /// Whether this value holds the master password itself, rather than a key
    /// from a source that does.
    pub fn holds_password(&self) -> bool {
        matches!(self.sealer, Sealer::Password(_))
    }

    /// Opens a vault from the sealed bytes of its file, without a file of its
    /// own.
    ///
    /// For the copy a transport fetched: it is read, folded from and dropped,
    /// and never written anywhere. The bytes are the same ciphertext the
    /// remote holds.
    pub(crate) fn from_sealed(sealed: &[u8], opener: Opener<'_>) -> Result<Self> {
        let database = opener.open(sealed)?;
        Ok(Self {
            path: PathBuf::new(),
            sealer: Sealer::Nothing,
            connection: db::load(&database)?,
            device: None,
            backing: Backing::Memory,
            writes: Cell::new(0),
            seen: Cell::new(None),
        })
    }

    /// A copy of this vault's database to change and throw away.
    ///
    /// What a preview folds into: the merge runs for real, on contents nobody
    /// will write. The copy keeps the machine's name, so the versions a
    /// preview makes are stamped as the real merge's would be.
    pub(crate) fn scratch_copy(&self) -> Result<Self> {
        let database = Zeroizing::new(db::dump(&self.connection)?);
        Ok(Self {
            path: self.path.clone(),
            sealer: Sealer::Nothing,
            connection: db::load(&database)?,
            device: self.device.clone(),
            backing: Backing::Memory,
            writes: Cell::new(0),
            seen: Cell::new(None),
        })
    }

    /// Names the machine this vault is being changed on.
    ///
    /// Every version written from here on carries the name, so a history can
    /// say which machine a change came from — the question a merge conflict
    /// raises first. The library does not guess it: the program around it
    /// knows what the machine is called, and a test knows it is none.
    pub fn set_device(&mut self, device: Option<String>) {
        self.device = device.filter(|name| !name.trim().is_empty());
    }

    /// Path of the file backing this vault.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Encrypts the current state and replaces the vault file atomically.
    ///
    /// The ciphertext goes to a temporary file in the same directory, is
    /// flushed and synced, and only then renamed over the target. A crash
    /// leaves either the old vault or the new one — never a half-written file,
    /// and never plaintext.
    ///
    /// A file that is no longer the one this value read is left alone, with
    /// [`Error::ChangedOnDisk`]: what is in memory knows nothing of what was
    /// written there since, and sealing it over the top would erase that without
    /// a word. See [`Vault::reload`].
    pub fn save(&self) -> Result<()> {
        // Only copies made inside this crate are memory-backed, and none of
        // them is ever saved; reaching this is a bug here, not a condition a
        // caller can meet.
        assert_eq!(
            self.backing,
            Backing::File,
            "a vault with no file of its own was asked to save"
        );
        if !self.is_current() {
            return Err(Error::ChangedOnDisk(self.path.clone()));
        }
        let database = Zeroizing::new(db::dump(&self.connection)?);
        let sealed = match &self.sealer {
            Sealer::Password(password) => format::encode(password, &database)?,
            Sealer::Source {
                source,
                opened_salt,
                opened_key,
            } => {
                let fresh = source.fresh(opened_salt)?;
                // Before anything is sealed: whoever holds the password now
                // has to be holding the one that opened this.
                if !fresh.proof.same_as(opened_key) {
                    return Err(Error::KeysChanged);
                }
                format::seal_under(&fresh.salt, &fresh.key, &database)?
            }
            Sealer::Nothing => unreachable!("only a copy without a file has no sealer"),
        };
        write_atomically(&self.path, &sealed)?;
        self.seen.set(Some(format::salt_of(&sealed)?));
        self.writes.set(self.writes.get() + 1);
        Ok(())
    }

    /// Whether the file on disk is the version this value read or last wrote.
    ///
    /// Something else can write the same file at any time: another `sefy`, the
    /// same command line through the window's own agent, a sync client replacing
    /// it. A vault that has never been written has nothing to fall behind.
    pub fn is_current(&self) -> bool {
        match self.seen.get() {
            Some(seen) => version_on_disk(&self.path) == Some(seen),
            None => true,
        }
    }

    /// Reads the file again if it is no longer the version this value holds, and
    /// says whether it did.
    ///
    /// Whatever was changed here and not saved is gone, in favour of the file:
    /// call this before changing anything, not after. A file the password no
    /// longer opens leaves this value as it was.
    pub fn reload(&mut self) -> Result<bool> {
        if self.is_current() {
            return Ok(false);
        }
        let file = fs::read(&self.path)
            .map_err(|source| Error::io(format!("cannot read {}", self.path.display()), source))?;
        let salt = format::salt_of(&file)?;
        let database = match &mut self.sealer {
            Sealer::Password(password) => format::decode(password, &file)?,
            Sealer::Source {
                source,
                opened_salt,
                opened_key,
            } => {
                let key = source.key_for(&salt)?;
                let database = format::open_under(&key, &file)?;
                *opened_salt = salt;
                *opened_key = key;
                database
            }
            Sealer::Nothing => unreachable!("only a copy without a file has no sealer"),
        };
        self.connection = db::load(&database)?;
        self.seen.set(Some(salt));
        Ok(true)
    }

    /// How many times this value has written its file since it was opened.
    ///
    /// The question a program asks after a command: did that change the vault
    /// on disk? Counted at the write itself, so a command that changed nothing
    /// and saved nothing reads as exactly that.
    pub fn writes(&self) -> u64 {
        self.writes.get()
    }

    /// Adds an item and returns its identifier.
    pub fn add(&mut self, item: NewItem) -> Result<i64> {
        db::insert_item(&mut self.connection, item, now(), self.device.as_deref())
    }

    /// Adds an item that already has an identity elsewhere.
    ///
    /// For contents arriving from an export, where re-generating the identity
    /// would make the same item look like a new one. The export carries no
    /// history, so the contents start a line of their own, written at
    /// `updated_at`.
    pub fn add_existing(
        &mut self,
        item: NewItem,
        uuid: &str,
        created_at: i64,
        updated_at: i64,
    ) -> Result<i64> {
        let stamp = Stamp::new(1, updated_at, self.device.as_deref())?;
        db::insert_item_with_uuid(
            &mut self.connection,
            item,
            uuid,
            created_at,
            updated_at,
            &stamp,
        )
    }

    /// Adds an item from another vault with the version its contents are and
    /// every earlier one.
    pub(crate) fn add_travelled(
        &mut self,
        item: NewItem,
        uuid: &str,
        (created_at, updated_at): (i64, i64),
        stamp: &Stamp,
        past: &[Version],
    ) -> Result<(i64, usize)> {
        let id = db::insert_item_with_uuid(
            &mut self.connection,
            item,
            uuid,
            created_at,
            updated_at,
            stamp,
        )?;
        let mut kept = 0;
        for version in past {
            if db::keep_version(&self.connection, id, version)? {
                kept += 1;
            }
        }
        Ok((id, kept))
    }

    /// The stamp of the version an item's contents are.
    pub(crate) fn stamp(&self, id: i64) -> Result<Stamp> {
        db::stamp_of(&self.connection, id)
    }

    /// An item's earlier versions, oldest first, without the current one.
    pub(crate) fn past_versions(&self, id: i64) -> Result<Vec<Version>> {
        db::past_versions(&self.connection, id)
    }

    /// Keeps a version that came from elsewhere, unless it is already kept.
    pub(crate) fn keep_version(&mut self, id: i64, version: &Version) -> Result<bool> {
        db::keep_version(&self.connection, id, version)
    }

    /// Puts contents from elsewhere in place under the version they already
    /// are, keeping what they replace.
    pub(crate) fn take_contents(
        &mut self,
        id: i64,
        payload: &Payload,
        stamp: &Stamp,
        replaced_lost_a_conflict: bool,
    ) -> Result<()> {
        let transaction = self.connection.transaction()?;
        db::replace_contents(&transaction, id, payload, stamp, replaced_lost_a_conflict)?;
        transaction.commit()?;
        Ok(())
    }

    /// Replaces an item's title and tags, leaving its contents alone.
    pub(crate) fn set_labels(
        &mut self,
        id: i64,
        title: &str,
        tags: &[String],
        updated_at: i64,
    ) -> Result<()> {
        db::set_labels(&mut self.connection, id, title, tags, updated_at)
    }

    /// Sets when an item last changed.
    pub(crate) fn set_updated_at(&mut self, id: i64, updated_at: i64) -> Result<()> {
        db::set_updated_at(&self.connection, id, updated_at)
    }

    /// Finds the item carrying this identity, if there is one.
    pub fn find_by_uuid(&self, uuid: &str) -> Result<Option<i64>> {
        db::find_by_uuid(&self.connection, uuid)
    }

    /// Reads an item with its payload.
    pub fn get(&self, id: i64) -> Result<Item> {
        db::get_item(&self.connection, id)
    }

    /// Reads an item without its payload.
    pub fn summary(&self, id: i64) -> Result<ItemSummary> {
        db::get_summary(&self.connection, id)
    }

    /// Changes an item's title, payload or tags; `None` leaves a field alone.
    ///
    /// A payload of a different kind than the item was created with is
    /// rejected: an item's kind is fixed for its lifetime. New contents become
    /// a new version and the ones they replace stay in [`Vault::history`].
    pub fn update(
        &mut self,
        id: i64,
        title: Option<String>,
        payload: Option<Payload>,
        tags: Option<Vec<String>>,
    ) -> Result<()> {
        self.update_at(id, title, payload, tags, now())
    }

    /// [`Vault::update`] at a moment given rather than read off the clock.
    ///
    /// For tests of what a merge makes of two edits in the same second: whole
    /// seconds are what timestamps hold, and a test cannot wait its way into a
    /// tie.
    pub(crate) fn update_at(
        &mut self,
        id: i64,
        title: Option<String>,
        payload: Option<Payload>,
        tags: Option<Vec<String>>,
        at: i64,
    ) -> Result<()> {
        db::update_item(
            &mut self.connection,
            id,
            title,
            payload,
            tags,
            at,
            self.device.as_deref(),
        )
    }

    /// The database underneath, for a test that has to write what an older
    /// build would.
    #[cfg(test)]
    pub(crate) fn connection_for_tests(&self) -> &Connection {
        &self.connection
    }

    /// Every version of an item's contents, oldest first, the current one last.
    ///
    /// A title or a tag is not part of a version: renaming an item makes none,
    /// and restoring one does not bring an old name back.
    pub fn history(&self, id: i64) -> Result<Vec<Version>> {
        db::history(&self.connection, id)
    }

    /// How many earlier versions of an item's contents are kept.
    pub fn earlier_versions(&self, id: i64) -> Result<usize> {
        db::count_past_versions(&self.connection, id)
    }

    /// Brings back the contents of an earlier version, or one field of them.
    ///
    /// Restoring is an edit like any other: the contents it replaces become a
    /// version of their own, so a restore can itself be undone. With `field`,
    /// only that field comes back — in place if the record still has it, at
    /// the end if not — and every other field keeps its current value.
    ///
    /// Returns whether anything changed; contents that already match the
    /// version are left alone rather than recorded again.
    pub fn restore(&mut self, id: i64, version: &str, field: Option<&str>) -> Result<bool> {
        let versions = self.history(id)?;
        let wanted = versions
            .iter()
            .find(|candidate| candidate.uuid == version)
            .ok_or_else(|| Error::VersionNotFound {
                id,
                version: version.to_owned(),
            })?;
        let current = &versions
            .last()
            .expect("history ends with the current version")
            .payload;

        let restored = match field {
            None => wanted.payload.clone(),
            Some(name) => with_field_from(current, &wanted.payload, name)?,
        };
        if &restored == current {
            return Ok(false);
        }

        self.update(id, None, Some(restored), None)?;
        Ok(true)
    }

    /// Removes an item.
    pub fn remove(&mut self, id: i64) -> Result<()> {
        db::delete_item(&self.connection, id)
    }

    /// Finds items matching a query, newest first.
    pub fn search(&self, query: &Query) -> Result<Vec<ItemSummary>> {
        db::search(&self.connection, query)
    }

    /// Lists every item, newest first.
    pub fn list(&self) -> Result<Vec<ItemSummary>> {
        db::search(&self.connection, &Query::all())
    }

    /// Lists every tag with the number of items carrying it.
    pub fn tags(&self) -> Result<Vec<(String, i64)>> {
        db::list_tags(&self.connection)
    }

    /// Turns what a user typed into exactly one item.
    ///
    /// A reference is either an id or text. Text prefers an exact,
    /// case-insensitive title match, and falls back to a substring search
    /// across titles and item contents. Anything that resolves to more than one
    /// item comes back as [`Error::Ambiguous`] carrying the candidates, so the
    /// caller can show them rather than guess.
    pub fn resolve(&self, reference: &str) -> Result<ItemSummary> {
        let reference = reference.trim();
        if reference.is_empty() {
            return Err(Error::NotFound(String::new()));
        }

        // A bare number is an id. Titles that look like numbers stay reachable
        // through the text path below when no such id exists.
        if let Ok(id) = reference.parse::<i64>() {
            match self.summary(id) {
                Ok(summary) => return Ok(summary),
                Err(Error::ItemNotFound(_)) => {}
                Err(other) => return Err(other),
            }
        }

        let matches = self.search(&Query::all().text(reference))?;
        let exact: Vec<ItemSummary> = matches
            .iter()
            .filter(|summary| summary.title.eq_ignore_ascii_case(reference))
            .cloned()
            .collect();
        let candidates = if exact.is_empty() { matches } else { exact };

        match candidates.len() {
            0 => Err(Error::NotFound(reference.to_owned())),
            1 => Ok(candidates.into_iter().next().expect("length checked")),
            _ => Err(Error::Ambiguous {
                reference: reference.to_owned(),
                candidates,
            }),
        }
    }

    /// Replaces the master password and rewrites the file under it.
    ///
    /// The salt and nonce are fresh, so the new file shares nothing with the
    /// old one beyond its contents.
    ///
    /// The [copies](crate::copies) kept beside the vault are re-sealed under
    /// the new password too. Left as they were, they would be three more files
    /// the retired password still opens — and retiring it is usually the
    /// whole point of changing it. The vault goes first: it is the one that
    /// matters if anything stops halfway.
    ///
    /// A vault opened through a [`KeySource`] refuses with
    /// [`Error::PasswordNeeded`]: retiring a password takes knowing it, not
    /// having found the vault unlocked.
    pub fn change_password(&mut self, password: &[u8]) -> Result<PasswordChange> {
        let Sealer::Password(old) = &self.sealer else {
            return Err(Error::PasswordNeeded);
        };
        let old = old.clone();
        let before = std::mem::replace(
            &mut self.sealer,
            Sealer::Password(Zeroizing::new(password.to_vec())),
        );
        // The file still opens under the old one when this fails, and the value
        // has to go on saying so.
        if let Err(error) = self.save() {
            self.sealer = before;
            return Err(error);
        }
        copies::reseal(&self.path, &old, password)
    }

    /// What this vault holds, without revealing any of it.
    ///
    /// Every number here is about shape rather than contents: how many items,
    /// of which kinds, how many tags. It is what `sefy status` reports, and it
    /// is deliberately the whole of it — a status that printed a title would
    /// put a secret's name on a screen that was asked only whether the vault is
    /// there.
    pub fn stats(&self) -> Result<Stats> {
        Ok(Stats {
            items: db::count_items(&self.connection)?,
            by_kind: db::count_by_kind(&self.connection)?,
            tags: self.tags()?.len(),
            schema: db::schema_version(&self.connection)?,
            last_sync: self.last_sync()?,
        })
    }

    /// What and where this vault is, without revealing any of it: the file,
    /// its size, what it holds counted rather than read, the copies kept
    /// beside it and how it is sealed.
    ///
    /// The whole answer to "is this the right file, is everything in it", in
    /// one value, so that `sefy status` and the desktop app say the same thing
    /// for the same reason rather than each assembling it from parts. Like
    /// [`Vault::stats`] it names nothing inside: a title on this screen would
    /// be a secret's name shown to someone who asked only whether the vault is
    /// there.
    pub fn status(&self) -> Result<Status> {
        Ok(Status {
            path: self.path.clone(),
            // Absent rather than an error: the vault is open, so it plainly
            // exists, and a status that failed over its size would be worse
            // than one without it.
            size: fs::metadata(&self.path).ok().map(|metadata| metadata.len()),
            stats: self.stats()?,
            copies: copies::list(&self.path),
            sealing: format::SEALING,
        })
    }

    /// When this vault last reached a remote, and through which transport.
    ///
    /// `None` means it never has — or that it last did so under a build that
    /// did not record it, which reads the same way and is the honest answer.
    pub fn last_sync(&self) -> Result<Option<SyncStamp>> {
        let Some(raw) = db::meta_get(&self.connection, LAST_SYNC)? else {
            return Ok(None);
        };
        Ok(SyncStamp::parse(&raw))
    }

    /// Records that this vault has just reached a remote.
    ///
    /// The caller saves: a stamp is worth exactly as much as the file it was
    /// written into, and a push that stamped a vault it then failed to write
    /// would claim a sync that left no trace.
    pub fn record_sync(&mut self, transport: &str, operation: &str) -> Result<()> {
        let stamp = SyncStamp {
            at: now(),
            transport: transport.to_owned(),
            operation: operation.to_owned(),
        };
        db::meta_set(&self.connection, LAST_SYNC, &stamp.encode())
    }

    /// How long what this vault lets out stays out; see [`crate::policy`].
    pub fn policy(&self) -> Result<Policy> {
        Ok(Policy {
            lock_after_seconds: Policy::read(
                db::meta_get(&self.connection, policy::LOCK_AFTER_KEY)?,
                policy::LOCK_AFTER_SECONDS,
            ),
            clipboard_seconds: Policy::read(
                db::meta_get(&self.connection, policy::CLIPBOARD_KEY)?,
                policy::CLIPBOARD_SECONDS,
            ),
        })
    }

    /// Sets how long what this vault lets out stays out, to values on offer.
    ///
    /// The caller saves, as with any other change.
    pub fn set_policy(&mut self, policy: Policy) -> Result<()> {
        if !policy.is_offered() {
            return Err(Error::PolicyNotOffered);
        }
        db::meta_set(
            &self.connection,
            policy::LOCK_AFTER_KEY,
            &policy.lock_after_seconds.to_string(),
        )?;
        db::meta_set(
            &self.connection,
            policy::CLIPBOARD_KEY,
            &policy.clipboard_seconds.to_string(),
        )
    }

    /// Destroys this vault on disk: the file, the copies kept beside it and
    /// any write a crash left unfinished — every part [`wipe::parts`] lists.
    /// Each is overwritten with random bytes in place, synced and deleted.
    ///
    /// Only an open vault can be wiped. A file with no header cannot be told
    /// from any other file except by opening it, so the password is what says
    /// this is a vault, and this one; a wipe of the wrong file would be just
    /// as final. The vault is consumed: there is nothing left to save it back
    /// into.
    ///
    /// The remote copy, if the vault was ever synced, is not touched; the
    /// result says when it was last reached. See [`crate::wipe`] for what an
    /// overwrite does and does not reach.
    pub fn wipe(self) -> Wiped {
        // As with `save`: a copy without a file of its own carries the real
        // vault's path, and must never destroy what it was copied from.
        assert_eq!(
            self.backing,
            Backing::File,
            "a vault with no file of its own was asked to wipe"
        );
        // A stamp that cannot be read is a stamp that is not there: the wipe
        // goes ahead either way, and this is only what it says about the
        // remote afterwards.
        let last_sync = self.last_sync().ok().flatten();
        let parts = wipe::parts(&self.path);
        drop(self);
        wipe::carry_out(parts, last_sync)
    }
}

/// The current contents of a record with one field taken from an earlier
/// version.
fn with_field_from(current: &Payload, earlier: &Payload, name: &str) -> Result<Payload> {
    let (Payload::Fields { kind, fields }, Payload::Fields { fields: then, .. }) =
        (current, earlier)
    else {
        // A note or a file is one value, not a set of fields: its version is
        // restored whole or not at all.
        return Err(Error::FieldNotInVersion {
            name: name.to_owned(),
            available: Vec::new(),
        });
    };

    let taken: &Field = then
        .iter()
        .find(|field| field.name == name)
        .ok_or_else(|| Error::FieldNotInVersion {
            name: name.to_owned(),
            available: then.iter().map(|field| field.name.clone()).collect(),
        })?;

    let mut fields = fields.clone();
    match fields.iter_mut().find(|field| field.name == name) {
        Some(field) => *field = taken.clone(),
        None => fields.push(taken.clone()),
    }
    Ok(Payload::Fields {
        kind: kind.clone(),
        fields,
    })
}

/// Which version of a vault is on disk: the salt at the front of the file, new
/// with every write. `None` when there is no file there or it is too short to
/// have one. Reads no more than the salt, so asking often costs next to nothing.
pub fn version_on_disk(path: &Path) -> Option<[u8; SALT_LEN]> {
    use std::io::Read;
    let mut salt = [0; SALT_LEN];
    fs::File::open(path).ok()?.read_exact(&mut salt).ok()?;
    Some(salt)
}

/// `meta` key under which the last sync is recorded.
const LAST_SYNC: &str = "last_sync";

/// What a vault holds, counted rather than read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stats {
    /// How many items in total.
    pub items: usize,
    /// How many of each kind, in the order the kinds are declared, skipping
    /// kinds this vault has none of.
    pub by_kind: Vec<(String, usize)>,
    /// How many distinct tags are in use.
    pub tags: usize,
    /// Schema version of the database inside the blob.
    pub schema: i64,
    /// When this vault last reached a remote, if it ever has.
    pub last_sync: Option<SyncStamp>,
}

impl Stats {
    /// Whether the database was last written by a newer sefy than this one.
    ///
    /// Nothing is wrong when it was — an older build reads what it knows and
    /// carries the rest — but it is the first thing worth knowing when this
    /// build does not show something another machine does.
    pub fn written_by_newer(&self) -> bool {
        self.schema > db::SCHEMA_VERSION
    }
}

/// What and where a vault is; see [`Vault::status`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
    /// The vault file.
    pub path: PathBuf,
    /// Its size in bytes, when the file system says.
    pub size: Option<u64>,
    /// What it holds, counted.
    pub stats: Stats,
    /// The copies kept beside it, most recent first.
    pub copies: Vec<copies::Copy>,
    /// How it is sealed.
    pub sealing: format::Sealing,
}

/// A note that this vault reached a remote, and when.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncStamp {
    /// Unix seconds.
    pub at: i64,
    /// Short name of the transport it went through.
    pub transport: String,
    /// Which operation wrote it: `push`, `pull` or `sync`.
    pub operation: String,
}

impl SyncStamp {
    /// Renders the stamp for storage: seconds, transport, operation.
    ///
    /// A flat string rather than JSON, because it is three fields that will
    /// stay three fields, and a parser that cannot fail is worth more here
    /// than one that can express more.
    fn encode(&self) -> String {
        format!("{} {} {}", self.at, self.transport, self.operation)
    }

    /// Reads a stamp back, or nothing if the value is not one.
    ///
    /// Unreadable is treated as absent rather than as an error: this is a
    /// convenience recorded by some build, possibly a future one, and a vault
    /// that will not open because it carries a note about itself would be a
    /// poor trade.
    fn parse(raw: &str) -> Option<Self> {
        let mut parts = raw.split(' ');
        let at = parts.next()?.parse().ok()?;
        let transport = parts.next()?.to_owned();
        let operation = parts.next().unwrap_or("sync").to_owned();
        Some(Self {
            at,
            transport,
            operation,
        })
    }
}

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

/// Seconds since the Unix epoch, or zero on a clock set before it.
pub(crate) fn now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs() as i64)
        .unwrap_or(0)
}

/// Writes `bytes` to `path` so that the file is either fully replaced or
/// untouched.
pub(crate) fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> {
    let directory = path.parent().filter(|p| !p.as_os_str().is_empty());
    if let Some(directory) = directory {
        fs::create_dir_all(directory).map_err(|source| {
            Error::io(format!("cannot create {}", directory.display()), source)
        })?;
    }

    let temporary = temporary_path(path);

    let write = || -> std::io::Result<()> {
        let mut file = fs::File::create(&temporary)?;
        file.write_all(bytes)?;
        file.sync_all()
    };
    if let Err(source) = write() {
        let _ = fs::remove_file(&temporary);
        return Err(Error::io(
            format!("cannot write {}", temporary.display()),
            source,
        ));
    }

    // `fs::rename` replaces an existing destination on both Unix and Windows,
    // so the swap is a single step: readers see either vault, never a partial
    // one.
    if let Err(source) = fs::rename(&temporary, path) {
        let _ = fs::remove_file(&temporary);
        return Err(Error::io(
            format!("cannot replace {}", path.display()),
            source,
        ));
    }
    Ok(())
}

/// Sibling path holding the ciphertext until the rename makes it the vault.
///
/// The name is derived from the target rather than randomized: a leftover
/// temporary from a crashed write is then reused instead of accumulating, and
/// anything already sitting at that path — including a directory — surfaces as
/// a write error rather than being quietly worked around. A wipe looks for it
/// by the same name.
pub(crate) fn temporary_path(path: &Path) -> PathBuf {
    let mut name = path
        .file_name()
        .unwrap_or_else(|| std::ffi::OsStr::new("vault"))
        .to_os_string();
    name.push(".sefy-tmp");
    path.with_file_name(name)
}