1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
use serde::{Deserialize, Serialize};

use async_trait::async_trait;
use binary_stream::futures::{BinaryReader, Decodable};

use futures::io::{AsyncReadExt, AsyncSeek};
use futures::io::{BufReader, Cursor};
use tokio_util::compat::TokioAsyncReadCompatExt;

use age::x25519::{Identity, Recipient};
use bitflags::bitflags;
use indexmap::IndexMap;
use secrecy::SecretString;
use sha2::{Digest, Sha256};
use std::{
    borrow::Cow, cmp::Ordering, collections::HashMap, fmt, path::Path,
    str::FromStr,
};
use urn::Urn;
use uuid::Uuid;

use crate::{
    commit::CommitHash,
    constants::{DEFAULT_VAULT_NAME, VAULT_IDENTITY, VAULT_NSS},
    crypto::{
        AccessKey, AeadPack, Cipher, Deriver, KeyDerivation, PrivateKey, Seed,
    },
    decode, encode,
    encoding::{encoding_options, VERSION},
    events::{ReadEvent, WriteEvent},
    formats::FileIdentity,
    vault::secret::SecretId,
    vfs::File,
    Error, Result, UtcDateTime,
};

/// Identifier for vaults.
pub type VaultId = Uuid;

bitflags! {
    /// Bit flags for a vault.
    #[derive(Default, Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Hash)]
    #[serde(transparent)]
    pub struct VaultFlags: u64 {
        /// Indicates this vault should be treated as
        /// the default folder.
        const DEFAULT           =        0b0000000000000001;
        /// Indicates this vault is an identity vault used
        /// to authenticate a user.
        const IDENTITY          =        0b0000000000000010;
        /// Indicates this vault is to be used as an archive.
        const ARCHIVE           =        0b0000000000000100;
        /// Indicates this vault is to be used for
        /// two-factor authentication.
        const AUTHENTICATOR     =        0b0000000000001000;
        /// Indicates this vault is to be used to store contacts.
        const CONTACT           =        0b0000000000010000;
        /// Indicates this vault is a system vault and should
        /// not be presented to the account holder when listing
        /// available vaults.
        const SYSTEM            =        0b0000000000100000;
        /// Indicates this vault is to be used to store device
        /// specific information such as key shares or device
        /// specific private keys.
        ///
        /// Typically these vaults should also be assigned the
        /// NO_SYNC_SELF flag.
        const DEVICE            =        0b0000000001000000;
        /// Indicates this vault should not be synced with
        /// devices owned by the account holder.
        ///
        /// You may want to combine this with NO_SYNC_OTHER
        /// to completely ignore this vault from sync operations.
        ///
        /// This is useful for storing device specific keys.
        const NO_SYNC_SELF      =        0b0000000010000000;
        /// Indicates this vault should not be synced with
        /// devices owned by other accounts.
        const NO_SYNC_OTHER     =        0b0000000100000000;
        /// Indicates this vault is shared using asymmetric
        /// encryption.
        const SHARED            =        0b0000001000000000;
    }
}

impl VaultFlags {
    /// Determine if this vault is a default vault.
    pub fn is_default(&self) -> bool {
        self.contains(VaultFlags::DEFAULT)
    }

    /// Determine if this vault is an identity vault.
    pub fn is_identity(&self) -> bool {
        self.contains(VaultFlags::IDENTITY)
    }

    /// Determine if this vault is an archive vault.
    pub fn is_archive(&self) -> bool {
        self.contains(VaultFlags::ARCHIVE)
    }

    /// Determine if this vault is an authenticator vault.
    pub fn is_authenticator(&self) -> bool {
        self.contains(VaultFlags::AUTHENTICATOR)
    }

    /// Determine if this vault is for contacts.
    pub fn is_contact(&self) -> bool {
        self.contains(VaultFlags::CONTACT)
    }

    /// Determine if this vault is for system specific information.
    pub fn is_system(&self) -> bool {
        self.contains(VaultFlags::SYSTEM)
    }

    /// Determine if this vault is for device specific information.
    pub fn is_device(&self) -> bool {
        self.contains(VaultFlags::DEVICE)
    }

    /// Determine if this vault is set to ignore sync
    /// with other devices owned by the account holder.
    pub fn is_no_sync_self(&self) -> bool {
        self.contains(VaultFlags::NO_SYNC_SELF)
    }

    /// Determine if this vault is set to ignore sync
    /// with devices owned by other accounts.
    pub fn is_no_sync_other(&self) -> bool {
        self.contains(VaultFlags::NO_SYNC_OTHER)
    }

    /// Determine if this vault is shared.
    pub fn is_shared(&self) -> bool {
        self.contains(VaultFlags::SHARED)
    }
}

/// Vault meta data.
#[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultMeta {
    /// Date created timestamp.
    pub(crate) date_created: UtcDateTime,
    /// Private human-friendly description of the vault.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub(crate) description: String,
}

impl VaultMeta {
    /// Get the vault description.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Get the vault description.
    pub fn set_description(&mut self, description: String) {
        self.description = description;
    }

    /// Date this vault was initialized.
    pub fn date_created(&self) -> &UtcDateTime {
        &self.date_created
    }
}

/// Reference to a folder using an id or a named label.
#[derive(Debug, Clone)]
pub enum FolderRef {
    /// Vault identifier.
    Id(VaultId),
    /// Vault label.
    Name(String),
}

impl fmt::Display for FolderRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Id(id) => write!(f, "{}", id),
            Self::Name(name) => write!(f, "{}", name),
        }
    }
}

impl FromStr for FolderRef {
    type Err = Error;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        if let Ok(id) = Uuid::parse_str(s) {
            Ok(Self::Id(id))
        } else {
            Ok(Self::Name(s.to_string()))
        }
    }
}

impl From<VaultId> for FolderRef {
    fn from(value: VaultId) -> Self {
        Self::Id(value)
    }
}

/// Type to represent a secret as an encrypted pair of meta data
/// and secret data.
#[derive(Default, Debug, Clone, Eq, PartialEq)]
pub struct VaultEntry(pub AeadPack, pub AeadPack);

/// Type to represent an encrypted secret with an associated commit hash.
#[derive(Default, Debug, Clone, Eq, PartialEq)]
pub struct VaultCommit(pub CommitHash, pub VaultEntry);

/// Trait that defines the operations on an encrypted vault.
///
/// The storage may be in-memory, backed by a file on disc or another
/// destination for the encrypted bytes.
///
/// Use `Cow` smart pointers because when we are reading
/// from an in-memory `Vault` we can return references whereas
/// other containers such as file access would return owned data.
///
#[async_trait]
pub trait VaultAccess {
    /// Get the vault summary.
    async fn summary(&self) -> Result<Summary>;

    /// Get the name of a vault.
    async fn vault_name(&self) -> Result<Cow<'_, str>>;

    /// Set the name of a vault.
    async fn set_vault_name(&mut self, name: String) -> Result<WriteEvent>;

    /// Set the vault meta data.
    async fn set_vault_meta(
        &mut self,
        meta_data: AeadPack,
    ) -> Result<WriteEvent>;

    /// Add an encrypted secret to the vault.
    async fn create(
        &mut self,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<WriteEvent>;

    /// Insert an encrypted secret to the vault with the given id.
    ///
    /// Used internally to support consistent identifiers when
    /// mirroring in the `Gatekeeper` implementation.
    #[doc(hidden)]
    async fn insert(
        &mut self,
        id: SecretId,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<WriteEvent>;

    /// Get an encrypted secret from the vault.
    async fn read<'a>(
        &'a self,
        id: &SecretId,
    ) -> Result<(Option<Cow<'a, VaultCommit>>, ReadEvent)>;

    /// Update an encrypted secret in the vault.
    async fn update(
        &mut self,
        id: &SecretId,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<Option<WriteEvent>>;

    /// Remove an encrypted secret from the vault.
    async fn delete(&mut self, id: &SecretId) -> Result<Option<WriteEvent>>;
}

/// Authentication information.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Auth {
    /// Salt used to derive a secret key from the passphrase.
    pub(crate) salt: Option<String>,
    /// Additional entropy to concatenate with the vault passphrase
    /// before deriving the secret key.
    pub(crate) seed: Option<Seed>,
}

/// Summary holding basic file information such as version,
/// unique identifier and name.
#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq, Clone)]
pub struct Summary {
    /// Encoding version.
    pub(crate) version: u16,
    /// Unique identifier for the vault.
    pub(crate) id: VaultId,
    /// Vault name.
    pub(crate) name: String,
    /// Encryption cipher.
    pub(crate) cipher: Cipher,
    /// Key derivation function.
    pub(crate) kdf: KeyDerivation,
    /// Flags for the vault.
    pub(crate) flags: VaultFlags,
}

impl Ord for Summary {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name)
    }
}

impl PartialOrd for Summary {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Summary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Version {} using {} with {}\n{} {}",
            self.version, self.cipher, self.kdf, self.name, self.id
        )
    }
}

impl Default for Summary {
    fn default() -> Self {
        Self {
            version: VERSION,
            cipher: Default::default(),
            kdf: Default::default(),
            id: Uuid::new_v4(),
            name: DEFAULT_VAULT_NAME.to_string(),
            flags: Default::default(),
        }
    }
}

impl Summary {
    /// Create a new summary.
    pub fn new(
        id: VaultId,
        name: String,
        cipher: Cipher,
        kdf: KeyDerivation,
        flags: VaultFlags,
    ) -> Self {
        Self {
            version: VERSION,
            cipher,
            kdf,
            id,
            name,
            flags,
        }
    }

    /// Get the version identifier.
    pub fn version(&self) -> &u16 {
        &self.version
    }

    /// Get the cipher.
    pub fn cipher(&self) -> &Cipher {
        &self.cipher
    }

    /// Get the key derivation function.
    pub fn kdf(&self) -> &KeyDerivation {
        &self.kdf
    }

    /// Get the unique identifier.
    pub fn id(&self) -> &VaultId {
        &self.id
    }

    /// Get the public name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Set the public name.
    pub fn set_name(&mut self, name: String) {
        self.name = name;
    }

    /// Get the vault flags.
    pub fn flags(&self) -> &VaultFlags {
        &self.flags
    }

    /// Get a mutable reference to the vault flags.
    pub fn flags_mut(&mut self) -> &mut VaultFlags {
        &mut self.flags
    }
}

impl From<Summary> for VaultId {
    fn from(value: Summary) -> Self {
        value.id
    }
}

/// File header, identifier and version information
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct Header {
    /// Information about the vault.
    pub(crate) summary: Summary,
    /// Encrypted meta data.
    pub(crate) meta: Option<AeadPack>,
    /// Additional authentication information such as
    /// the salt and seed entropy.
    pub(crate) auth: Auth,
    /// Recipients for a shared vault.
    pub(crate) shared_access: SharedAccess,
}

impl Header {
    /// Create a new header.
    pub fn new(
        id: VaultId,
        name: String,
        cipher: Cipher,
        kdf: KeyDerivation,
        flags: VaultFlags,
    ) -> Self {
        Self {
            summary: Summary::new(id, name, cipher, kdf, flags),
            meta: None,
            auth: Default::default(),
            shared_access: Default::default(),
        }
    }

    /// Get the vault identifier.
    pub fn id(&self) -> &VaultId {
        self.summary.id()
    }

    /// Clear an existing salt.
    ///
    /// Required when changing passwords so we can initialize
    /// a vault that is already initialized.
    pub(crate) fn clear_salt(&mut self) {
        self.auth.salt = None;
    }

    /// Get the public name for this vault.
    pub fn name(&self) -> &str {
        &self.summary.name
    }

    /// Set the public name for this vault.
    pub fn set_name(&mut self, name: String) {
        self.summary.set_name(name);
    }

    /// Get the encrypted meta data for the vault.
    pub fn meta(&self) -> Option<&AeadPack> {
        self.meta.as_ref()
    }

    /// Set the encrypted meta data for the vault.
    pub fn set_meta(&mut self, meta: Option<AeadPack>) {
        self.meta = meta;
    }

    /// Read the content offset for a vault file verifying
    /// the identity bytes first.
    pub async fn read_content_offset<P: AsRef<Path>>(path: P) -> Result<u64> {
        let mut stream = File::open(path.as_ref()).await?.compat();
        Header::read_content_offset_stream(&mut stream).await
    }

    /// Read the content offset for a vault slice verifying
    /// the identity bytes first.
    pub async fn read_content_offset_slice(buffer: &[u8]) -> Result<u64> {
        let mut stream = BufReader::new(Cursor::new(buffer));
        Header::read_content_offset_stream(&mut stream).await
    }

    /// Read the content offset for a stream verifying
    /// the identity bytes first.
    pub async fn read_content_offset_stream<
        R: AsyncReadExt + AsyncSeek + Unpin + Send,
    >(
        stream: R,
    ) -> Result<u64> {
        let mut reader = BinaryReader::new(stream, encoding_options());
        let identity = reader.read_bytes(VAULT_IDENTITY.len()).await?;
        FileIdentity::read_slice(&identity, &VAULT_IDENTITY)?;
        let header_len = reader.read_u32().await? as u64;
        let content_offset = VAULT_IDENTITY.len() as u64 + 4 + header_len;
        Ok(content_offset)
    }

    /// Read the summary for a vault from a file.
    pub async fn read_summary_file<P: AsRef<Path>>(
        file: P,
    ) -> Result<Summary> {
        let mut stream = File::open(file.as_ref()).await?.compat();
        Header::read_summary_stream(&mut stream).await
    }

    /// Read the summary for a slice of bytes.
    pub async fn read_summary_slice(buffer: &[u8]) -> Result<Summary> {
        let mut stream = BufReader::new(Cursor::new(buffer));
        Header::read_summary_stream(&mut stream).await
    }

    /// Read the summary from a stream.
    async fn read_summary_stream<
        R: AsyncReadExt + AsyncSeek + Unpin + Send,
    >(
        stream: R,
    ) -> Result<Summary> {
        let mut reader = BinaryReader::new(stream, encoding_options());

        // Read magic identity bytes
        FileIdentity::read_identity(&mut reader, &VAULT_IDENTITY).await?;

        // Read in the header length
        let _ = reader.read_u32().await?;

        // Read the summary
        let mut summary: Summary = Default::default();
        summary.decode(&mut reader).await?;

        Ok(summary)
    }

    /// Read the header for a vault from a file.
    pub async fn read_header_file<P: AsRef<Path>>(file: P) -> Result<Header> {
        let mut stream = File::open(file.as_ref()).await?.compat();
        Header::read_header_stream(&mut stream).await
    }

    /// Read the header from a stream.
    pub(crate) async fn read_header_stream<
        R: AsyncReadExt + AsyncSeek + Unpin + Send,
    >(
        stream: R,
    ) -> Result<Header> {
        let mut reader = BinaryReader::new(stream, encoding_options());
        let mut header: Header = Default::default();
        header.decode(&mut reader).await?;
        Ok(header)
    }
}

impl fmt::Display for Header {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.summary)
    }
}

/// Access controls for shared vaults.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SharedAccess {
    /// List of recipients for a shared vault.
    ///
    /// Every recipient is able to write to the shared vault.
    WriteAccess(Vec<String>),
    /// Private list of recipients managed by an owner.
    ///
    /// Only the owner can write to the vault, other recipients
    /// can only read.
    ReadOnly(AeadPack),
}

impl Default for SharedAccess {
    fn default() -> Self {
        Self::WriteAccess(vec![])
    }
}

impl SharedAccess {
    fn parse_recipients(access: &Vec<String>) -> Result<Vec<Recipient>> {
        let mut recipients = Vec::new();
        for recipient in access {
            let recipient = recipient.parse().map_err(|s: &str| {
                Error::InvalidX25519Identity(s.to_owned())
            })?;
            recipients.push(recipient);
        }
        Ok(recipients)
    }
}

/// The vault contents
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Contents {
    pub(crate) data: IndexMap<SecretId, VaultCommit>,
}

/// Vault file storage.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Vault {
    pub(crate) header: Header,
    pub(crate) contents: Contents,
}

impl Vault {
    /// Create a new vault.
    pub fn new(
        id: VaultId,
        name: String,
        cipher: Cipher,
        kdf: KeyDerivation,
        flags: VaultFlags,
    ) -> Self {
        Self {
            header: Header::new(id, name, cipher, kdf, flags),
            contents: Default::default(),
        }
    }

    /// Shared access.
    pub fn shared_access(&self) -> &SharedAccess {
        &self.header.shared_access
    }

    /// Get the URN for a vault identifier.
    pub fn vault_urn(id: &VaultId) -> Result<Urn> {
        let vault_urn = format!("urn:sos:{}{}", VAULT_NSS, id);
        Ok(vault_urn.parse()?)
    }

    /// Initialize this vault using a password for
    /// a symmetric cipher.
    pub(crate) async fn symmetric(
        &mut self,
        password: SecretString,
        seed: Option<Seed>,
    ) -> Result<PrivateKey> {
        if self.header.auth.salt.is_none() {
            let salt = KeyDerivation::generate_salt();
            let deriver = self.deriver();
            let derived_private_key =
                deriver.derive(&password, &salt, seed.as_ref())?;
            let private_key = PrivateKey::Symmetric(derived_private_key);

            // Store the salt and seed so we can derive the same
            // private key later
            self.header.auth.salt = Some(salt.to_string());
            self.header.auth.seed = seed;

            Ok(private_key)
        } else {
            Err(Error::VaultAlreadyInit)
        }
    }

    /// Initialize this vault using asymmetric encryption.
    pub(crate) async fn asymmetric(
        &mut self,
        owner: &Identity,
        mut recipients: Vec<Recipient>,
        read_only: bool,
    ) -> Result<PrivateKey> {
        if self.header.auth.salt.is_none() {
            // Ensure the owner public key is always in the list
            // of recipients
            let owner_public = owner.to_public();
            if !recipients
                .iter()
                .any(|r| r.to_string() == owner_public.to_string())
            {
                recipients.push(owner_public);
            }

            self.flags_mut().set(VaultFlags::SHARED, true);

            let salt = KeyDerivation::generate_salt();
            let private_key = PrivateKey::Asymmetric(owner.clone());
            self.header.summary.cipher = Cipher::X25519;

            let recipients: Vec<_> =
                recipients.into_iter().map(|r| r.to_string()).collect();

            self.header.shared_access = if read_only {
                let access = SharedAccess::WriteAccess(recipients);
                let buffer = encode(&access).await?;
                let private_key = PrivateKey::Asymmetric(owner.clone());
                let cipher = self.header.summary.cipher.clone();
                let owner_recipients = vec![owner.to_public()];
                let aead = cipher
                    .encrypt_asymmetric(
                        &private_key,
                        &buffer,
                        owner_recipients,
                    )
                    .await?;
                SharedAccess::ReadOnly(aead)
            } else {
                SharedAccess::WriteAccess(recipients)
            };

            // Store the salt so we know that the vault has
            // already been initialized, for asymmetric encryption
            // it is not used
            self.header.auth.salt = Some(salt.to_string());

            Ok(private_key)
        } else {
            Err(Error::VaultAlreadyInit)
        }
    }

    /// Key derivation function deriver.
    pub fn deriver(&self) -> Box<dyn Deriver<Sha256> + Send + 'static> {
        self.header.summary.kdf.deriver()
    }

    /// Set whether this vault is a default vault.
    pub fn set_default_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::DEFAULT, value);
    }

    /// Set whether this vault is an archive vault.
    pub fn set_archive_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::ARCHIVE, value);
    }

    /// Set whether this vault is an authenticator vault.
    pub fn set_authenticator_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::AUTHENTICATOR, value);
    }

    /// Set whether this vault is for contacts.
    pub fn set_contact_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::CONTACT, value);
    }

    /// Set whether this vault is for system specific information.
    pub fn set_system_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::SYSTEM, value);
    }

    /// Set whether this vault is for device specific information.
    pub fn set_device_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::DEVICE, value);
    }

    /// Set whether this vault should not sync with own devices.
    pub fn set_no_sync_self_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::NO_SYNC_SELF, value);
    }

    /// Set whether this vault should not sync with devices
    /// owned by other accounts.
    pub fn set_no_sync_other_flag(&mut self, value: bool) {
        self.flags_mut().set(VaultFlags::NO_SYNC_OTHER, value);
    }

    /// Insert a secret into this vault.
    pub(crate) fn insert_entry(&mut self, id: SecretId, entry: VaultCommit) {
        self.contents.data.insert(id, entry);
    }

    /// Get a secret in this vault.
    pub fn get(&self, id: &SecretId) -> Option<&VaultCommit> {
        self.contents.data.get(id)
    }

    /// Encrypt plaintext using the cipher assigned to this vault.
    pub async fn encrypt(
        &self,
        key: &PrivateKey,
        plaintext: &[u8],
    ) -> Result<AeadPack> {
        match self.cipher() {
            Cipher::XChaCha20Poly1305 | Cipher::AesGcm256 => {
                self.cipher().encrypt_symmetric(key, plaintext, None).await
            }
            Cipher::X25519 => {
                let recipients = match &self.header.shared_access {
                    SharedAccess::WriteAccess(access) => {
                        SharedAccess::parse_recipients(access)?
                    }
                    SharedAccess::ReadOnly(aead) => {
                        let buffer = self
                            .decrypt(key, aead)
                            .await
                            .map_err(|_| Error::PermissionDenied)?;
                        let shared_access: SharedAccess =
                            decode(&buffer).await?;
                        if let SharedAccess::WriteAccess(access) =
                            &shared_access
                        {
                            SharedAccess::parse_recipients(access)?
                        } else {
                            return Err(Error::PermissionDenied);
                        }
                    }
                };

                self.cipher()
                    .encrypt_asymmetric(key, plaintext, recipients)
                    .await
            }
        }
    }

    /// Decrypt ciphertext using the cipher assigned to this vault.
    pub async fn decrypt(
        &self,
        key: &PrivateKey,
        aead: &AeadPack,
    ) -> Result<Vec<u8>> {
        match self.cipher() {
            Cipher::XChaCha20Poly1305 | Cipher::AesGcm256 => {
                self.cipher().decrypt_symmetric(key, aead).await
            }
            Cipher::X25519 => {
                self.cipher().decrypt_asymmetric(key, aead).await
            }
        }
    }

    /// Choose a new identifier for this vault.
    ///
    /// This is useful when importing a vault and the identifier
    /// collides with an existing vault; rather than overwriting the
    /// existing vault we can import it alongside by choosing a new
    /// identifier.
    pub fn rotate_identifier(&mut self) {
        self.header.summary.id = Uuid::new_v4();
    }

    /// Verify an access key.
    pub async fn verify(&self, key: &AccessKey) -> Result<()> {
        let salt = self.salt().ok_or(Error::VaultNotInit)?;
        let meta_aead = self.header().meta().ok_or(Error::VaultNotInit)?;
        let private_key = match key {
            AccessKey::Password(password) => {
                let salt = KeyDerivation::parse_salt(salt)?;
                let deriver = self.deriver();
                PrivateKey::Symmetric(deriver.derive(
                    password,
                    &salt,
                    self.seed(),
                )?)
            }
            AccessKey::Identity(id) => PrivateKey::Asymmetric(id.clone()),
        };

        let _ = self
            .decrypt(&private_key, meta_aead)
            .await
            .map_err(|_| Error::PassphraseVerification)?;

        Ok(())
    }

    /// Iterator for the secret keys and values.
    pub fn iter(&self) -> impl Iterator<Item = (&Uuid, &VaultCommit)> {
        self.contents.data.iter()
    }

    /// Iterator for the secret keys.
    pub fn keys(&self) -> impl Iterator<Item = &Uuid> {
        self.contents.data.keys()
    }

    /// Iterator for the secret values.
    pub fn values(&self) -> impl Iterator<Item = &VaultCommit> {
        self.contents.data.values()
    }

    /// Number of secrets in this vault.
    pub fn len(&self) -> usize {
        self.contents.data.len()
    }

    /// Determine if this vault is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Convert this vault into a create vault event.
    ///
    /// Ensures the vault is head-only before encoding into the event.
    pub async fn into_event(&self) -> Result<WriteEvent> {
        let buffer = if self.is_empty() {
            encode(self).await?
        } else {
            let header = self.header.clone();
            let vault: Vault = header.into();
            encode(&vault).await?
        };
        Ok(WriteEvent::CreateVault(buffer))
    }

    /// Iterator for the secret keys and commit hashes.
    pub fn commits(&self) -> impl Iterator<Item = (&Uuid, &CommitHash)> {
        self.contents
            .data
            .keys()
            .zip(self.contents.data.values().map(|v| &v.0))
    }

    /// Get the salt used for passphrase authentication.
    pub fn salt(&self) -> Option<&String> {
        self.header.auth.salt.as_ref()
    }

    /// Get the seed used for passphrase authentication.
    pub fn seed(&self) -> Option<&Seed> {
        self.header.auth.seed.as_ref()
    }

    /// Get the summary for this vault.
    pub fn summary(&self) -> &Summary {
        &self.header.summary
    }

    /// Get a reference to the vault flags.
    pub fn flags(&self) -> &VaultFlags {
        self.header.summary.flags()
    }

    /// Get a mutable reference to the vault flags.
    pub fn flags_mut(&mut self) -> &mut VaultFlags {
        self.header.summary.flags_mut()
    }

    /// Get the unique identifier for this vault.
    pub fn id(&self) -> &VaultId {
        &self.header.summary.id
    }

    /// Get the public name for this vault.
    pub fn name(&self) -> &str {
        self.header.name()
    }

    /// Set the public name for this vault.
    pub fn set_name(&mut self, name: String) {
        self.header.set_name(name);
    }

    /// Get the encryption cipher for this vault.
    pub fn cipher(&self) -> &Cipher {
        &self.header.summary.cipher
    }

    /// Get the key derivation function.
    pub fn kdf(&self) -> &KeyDerivation {
        &self.header.summary.kdf
    }

    /// Get the vault header.
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Get the mutable vault header.
    pub fn header_mut(&mut self) -> &mut Header {
        &mut self.header
    }

    /// Get the meta data for all the secrets.
    pub fn meta_data(&self) -> HashMap<&Uuid, &AeadPack> {
        self.contents
            .data
            .iter()
            .map(|(k, v)| (k, &v.1 .0))
            .collect::<HashMap<_, _>>()
    }

    /// Write this vault to a file.
    pub async fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        use tokio::io::AsyncWriteExt;
        let mut stream = File::create(path).await?;
        let buffer = encode(self).await?;
        stream.write_all(&buffer).await?;
        stream.flush().await?;
        Ok(())
    }

    /// Compute the hash of the encoded encrypted buffer
    /// for the meta and secret data.
    pub async fn commit_hash(
        meta_aead: &AeadPack,
        secret_aead: &AeadPack,
    ) -> Result<(CommitHash, Vec<u8>)> {
        // Compute the hash of the encrypted and encoded bytes
        let encoded_meta = encode(meta_aead).await?;
        let encoded_data = encode(secret_aead).await?;
        let mut hash_bytes =
            Vec::with_capacity(encoded_meta.len() + encoded_data.len());
        hash_bytes.extend_from_slice(&encoded_meta);
        hash_bytes.extend_from_slice(&encoded_data);
        let commit = CommitHash(
            Sha256::digest(hash_bytes.as_slice())
                .as_slice()
                .try_into()?,
        );
        Ok((commit, hash_bytes))
    }
}

impl From<Header> for Vault {
    fn from(header: Header) -> Self {
        Vault {
            header,
            contents: Default::default(),
        }
    }
}

impl From<Vault> for Header {
    fn from(value: Vault) -> Self {
        value.header
    }
}

impl IntoIterator for Vault {
    type Item = (SecretId, VaultCommit);
    type IntoIter = indexmap::map::IntoIter<SecretId, VaultCommit>;

    fn into_iter(self) -> Self::IntoIter {
        self.contents.data.into_iter()
    }
}

#[async_trait]
impl VaultAccess for Vault {
    async fn summary(&self) -> Result<Summary> {
        Ok(self.header.summary.clone())
    }

    async fn vault_name(&self) -> Result<Cow<'_, str>> {
        Ok(Cow::Borrowed(self.name()))
    }

    async fn set_vault_name(&mut self, name: String) -> Result<WriteEvent> {
        self.set_name(name.clone());
        Ok(WriteEvent::SetVaultName(name))
    }

    async fn set_vault_meta(
        &mut self,
        meta_data: AeadPack,
    ) -> Result<WriteEvent> {
        self.header.set_meta(Some(meta_data.clone()));
        Ok(WriteEvent::SetVaultMeta(meta_data))
    }

    async fn create(
        &mut self,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<WriteEvent> {
        let id = Uuid::new_v4();
        self.insert(id, commit, secret).await
    }

    async fn insert(
        &mut self,
        id: SecretId,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<WriteEvent> {
        let value = self
            .contents
            .data
            .entry(id)
            .or_insert(VaultCommit(commit, secret));
        Ok(WriteEvent::CreateSecret(id, value.clone()))
    }

    async fn read<'a>(
        &'a self,
        id: &SecretId,
    ) -> Result<(Option<Cow<'a, VaultCommit>>, ReadEvent)> {
        let result = self.contents.data.get(id).map(Cow::Borrowed);
        Ok((result, ReadEvent::ReadSecret(*id)))
    }

    async fn update(
        &mut self,
        id: &SecretId,
        commit: CommitHash,
        secret: VaultEntry,
    ) -> Result<Option<WriteEvent>> {
        let _vault_id = *self.id();
        if let Some(value) = self.contents.data.get_mut(id) {
            *value = VaultCommit(commit, secret);
            Ok(Some(WriteEvent::UpdateSecret(*id, value.clone())))
        } else {
            Ok(None)
        }
    }

    async fn delete(&mut self, id: &SecretId) -> Result<Option<WriteEvent>> {
        let entry = self.contents.data.shift_remove(id);
        if entry.is_some() {
            Ok(Some(WriteEvent::DeleteSecret(*id)))
        } else {
            Ok(None)
        }
    }
}