rust_keylock 0.18.0

A password manager with goals to be Secure, Simple to use, Portable and Extensible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock.  If not, see <http://www.gnu.org/licenses/>.

use std::iter::FromIterator;
use std::time::{SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use log::*;
use rs_password_utils;
use serde::{Deserialize, Serialize};
use toml;
use toml::value::Table;
use zeroize::{Zeroize, Zeroizing};

use crate::asynch::dropbox::DropboxConfiguration;
use crate::asynch::nextcloud::NextcloudConfiguration;

use super::{datacrypt, dropbox, errors, nextcloud};

use self::safe::Safe;

pub mod safe;

/// Struct to use for retrieving and saving data from/to the file
pub(crate) struct RklContent {
    pub entries: Vec<Entry>,
    pub nextcloud_conf: nextcloud::NextcloudConfiguration,
    pub dropbox_conf: dropbox::DropboxConfiguration,
    pub system_conf: SystemConfiguration,
    pub general_conf: GeneralConfiguration,
}

impl RklContent {
    pub fn new(
        entries: Vec<Entry>,
        nextcloud_conf: nextcloud::NextcloudConfiguration,
        dropbox_conf: dropbox::DropboxConfiguration,
        system_conf: SystemConfiguration,
        general_conf: GeneralConfiguration,
    ) -> RklContent {
        RklContent {
            entries,
            nextcloud_conf,
            dropbox_conf,
            system_conf,
            general_conf,
        }
    }

    pub fn from(
        tup: (
            &Safe,
            &nextcloud::NextcloudConfiguration,
            &dropbox::DropboxConfiguration,
            &SystemConfiguration,
            &GeneralConfiguration,
        ),
    ) -> errors::Result<RklContent> {
        let entries = tup.0.get_entries_decrypted();
        let nextcloud_conf = nextcloud::NextcloudConfiguration::new(
            tup.1.server_url.clone(),
            tup.1.username.clone(),
            tup.1.decrypted_password()?.to_string(),
            tup.1.use_self_signed_certificate,
        );
        let dropbox_conf = dropbox::DropboxConfiguration::new(tup.2.decrypted_token()?);
        let system_conf =
            SystemConfiguration::new(tup.3.saved_at, tup.3.version, tup.3.last_sync_version);
        let general_configuration = GeneralConfiguration::new(tup.4.browser_extension_passphrase.clone());

        Ok(RklContent::new(
            entries,
            nextcloud_conf?,
            dropbox_conf?,
            system_conf,
            general_configuration,
        ))
    }
}

/// Keeps the Configuration
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct RklConfiguration {
    pub system: SystemConfiguration,
    pub nextcloud: nextcloud::NextcloudConfiguration,
    pub dropbox: dropbox::DropboxConfiguration,
    pub general: GeneralConfiguration,
}

impl RklConfiguration {
    pub fn update_system_for_save(&mut self, update_last_sync_version: bool) -> errors::Result<()> {
        if update_last_sync_version {
            self.update_system_last_sync();
        } else {
            self.system.version = Some((self.system.version.unwrap_or(0)) + 1);
        }
        let local_time_seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        self.system.saved_at = Some(local_time_seconds as i64);
        Ok(())
    }

    pub fn update_system_last_sync(&mut self) {
        self.system.last_sync_version = self.system.version;
    }
}

impl
    From<(
        nextcloud::NextcloudConfiguration,
        dropbox::DropboxConfiguration,
        SystemConfiguration,
        GeneralConfiguration,
    )> for RklConfiguration
{
    fn from(
        confs: (
            nextcloud::NextcloudConfiguration,
            dropbox::DropboxConfiguration,
            SystemConfiguration,
            GeneralConfiguration,
        ),
    ) -> Self {
        RklConfiguration {
            system: confs.2,
            nextcloud: confs.0,
            dropbox: confs.1,
            general: confs.3,
        }
    }
}

/// System - internal configuration
#[derive(Debug, PartialEq, Clone)]
pub struct SystemConfiguration {
    /// When the passwords were saved
    pub saved_at: Option<i64>,
    /// A number that gets incremented with each persisted change
    pub version: Option<i64>,
    /// The version that was set upon the last sync. This is the same with the version once the data is uploaded to the server
    pub last_sync_version: Option<i64>,
}

impl SystemConfiguration {
    pub fn new(
        saved_at: Option<i64>,
        version: Option<i64>,
        last_sync_version: Option<i64>,
    ) -> SystemConfiguration {
        SystemConfiguration {
            saved_at,
            version,
            last_sync_version,
        }
    }

    pub fn from_table(table: &Table) -> Result<SystemConfiguration, errors::RustKeylockError> {
        let saved_at = table
            .get("saved_at")
            .and_then(|value| value.as_integer().and_then(Some));
        let version = table
            .get("version")
            .and_then(|value| value.as_integer().and_then(Some));
        let last_sync_version = table
            .get("last_sync_version")
            .and_then(|value| value.as_integer().and_then(Some));
        Ok(SystemConfiguration::new(
            saved_at,
            version,
            last_sync_version,
        ))
    }

    pub fn to_table(&self) -> errors::Result<Table> {
        let mut table = Table::new();
        if self.saved_at.is_some() {
            table.insert(
                "saved_at".to_string(),
                toml::Value::Integer(self.saved_at.unwrap()),
            );
        }
        if self.version.is_some() {
            table.insert(
                "version".to_string(),
                toml::Value::Integer(self.version.unwrap()),
            );
        }
        if self.last_sync_version.is_some() {
            table.insert(
                "last_sync_version".to_string(),
                toml::Value::Integer(self.last_sync_version.unwrap()),
            );
        }

        Ok(table)
    }
}

impl Default for SystemConfiguration {
    fn default() -> SystemConfiguration {
        SystemConfiguration {
            saved_at: None,
            version: None,
            last_sync_version: None,
        }
    }
}

/// General configuration
#[derive(Debug, PartialEq, Clone)]
pub struct GeneralConfiguration {
    /// Passphrase to be used for securing the communication with browser extensions
    pub browser_extension_passphrase: Option<String>,
}

impl GeneralConfiguration {
    pub fn new(browser_extension_passphrase: Option<String>) -> GeneralConfiguration {
        GeneralConfiguration {
            browser_extension_passphrase,
        }
    }

    pub fn from_table(table: &Table) -> Result<GeneralConfiguration, errors::RustKeylockError> {
        let browser_extension_passphrase = table
            .get("browser_extension_passphrase")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        Ok(GeneralConfiguration::new(browser_extension_passphrase))
    }

    pub fn to_table(&self) -> errors::Result<Table> {
        let mut table = Table::new();
        if self.browser_extension_passphrase.is_some() {
            table.insert(
                "browser_extension_passphrase".to_string(),
                toml::Value::String(self.browser_extension_passphrase.clone().unwrap()),
            );
        }
        Ok(table)
    }
}

impl Default for GeneralConfiguration {
    fn default() -> GeneralConfiguration {
        GeneralConfiguration {
            browser_extension_passphrase: None,
        }
    }
}

/// Struct that defines meta-data for an entry.
#[derive(Debug, PartialEq, Eq, Clone, Zeroize, Serialize, Deserialize)]
#[zeroize(drop)]
pub struct EntryMeta {
    /// True if the password is leaked.
    pub leaked_password: bool,
}

impl EntryMeta {
    pub fn new(leaked_password: bool) -> EntryMeta {
        EntryMeta { leaked_password }
    }

    pub fn from_table(table: &Table) -> Result<EntryMeta, errors::RustKeylockError> {
        let leaked_password = table
            .get("leaked_password")
            .and_then(|value| value.as_bool());
        match leaked_password {
            Some(lp) => Ok(Self::new(lp)),
            _ => Err(errors::RustKeylockError::ParseError(
                toml::ser::to_string(&table)
                    .unwrap_or_else(|_| "Cannot dserialize toml for EntryMeta".to_string()),
            )),
        }
    }

    pub fn to_table(&self) -> Table {
        let mut table = Table::new();
        table.insert(
            "leaked_password".to_string(),
            toml::Value::Boolean(self.leaked_password),
        );

        table
    }
}

impl Default for EntryMeta {
    fn default() -> Self {
        EntryMeta {
            leaked_password: false,
        }
    }
}

/// Struct that defines a password entry.
#[derive(Debug, PartialEq, Eq, Clone, Zeroize, Serialize, Deserialize)]
#[zeroize(drop)]
pub struct Entry {
    /// The name of the Entry
    ///
    /// It is used as a label to distinguish among other Entries
    pub name: String,
    /// A URL (optional)
    pub url: String,
    /// The username
    pub user: String,
    /// The password
    pub pass: String,
    /// A description of the `Entry` (Optional)
    pub desc: String,
    /// Meta-data for the Entry
    pub meta: EntryMeta,
    /// Whether the Entry has encrypted elements (like password)
    pub encrypted: bool,
}

impl Entry {
    /// Creates a new `Entry` using the provided name, url, username, password and description
    pub fn new(
        name: String,
        url: String,
        user: String,
        pass: String,
        desc: String,
        meta: EntryMeta,
    ) -> Entry {
        Entry {
            name,
            url,
            user,
            pass,
            desc,
            meta,
            encrypted: false,
        }
    }

    /// Creates an empty `Entry`
    pub fn empty() -> Entry {
        Entry {
            name: "".to_string(),
            url: "".to_string(),
            user: "".to_string(),
            pass: "".to_string(),
            desc: "".to_string(),
            meta: EntryMeta::default(),
            encrypted: false,
        }
    }

    pub fn from_table(table: &Table) -> Result<Entry, errors::RustKeylockError> {
        let name = table
            .get("name")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        let url = table
            .get("url")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        let user = table
            .get("user")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        let pass = table
            .get("pass")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        let desc = table
            .get("desc")
            .and_then(|value| value.as_str().and_then(|str_ref| Some(str_ref.to_string())));
        let meta = table
            .get("meta")
            .and_then(|value| {
                value
                    .as_table()
                    .map(|table| EntryMeta::from_table(table).unwrap_or_default())
            })
            .unwrap_or_default();

        match (name, url, user, pass, desc) {
            (Some(n), Some(ul), Some(u), Some(p), Some(d)) => Ok(Self::new(n, ul, u, p, d, meta)),
            _ => Err(errors::RustKeylockError::ParseError(
                toml::ser::to_string(&table)
                    .unwrap_or_else(|_| "Cannot serialize toml".to_string()),
            )),
        }
    }

    pub fn to_table(&self) -> Table {
        let mut table = Table::new();
        table.insert("name".to_string(), toml::Value::String(self.name.clone()));
        table.insert("url".to_string(), toml::Value::String(self.url.clone()));
        table.insert("user".to_string(), toml::Value::String(self.user.clone()));
        table.insert("pass".to_string(), toml::Value::String(self.pass.clone()));
        table.insert("desc".to_string(), toml::Value::String(self.desc.clone()));
        table.insert("meta".to_string(), toml::Value::Table(self.meta.to_table()));

        table
    }

    pub fn encrypted(&self, cryptor: &datacrypt::EntryPasswordCryptor) -> Entry {
        let (encrypted_password, encryption_succeeded) = match cryptor.encrypt_str(&self.pass) {
            Ok(encrypted) => (encrypted, true),
            Err(_) => {
                error!(
                    "Could not encrypt password for {}. Defaulting in keeping it in plain...",
                    &self.name
                );
                (self.pass.clone(), false)
            }
        };
        Entry {
            name: self.name.clone(),
            url: self.url.clone(),
            user: self.user.clone(),
            pass: encrypted_password,
            desc: self.desc.clone(),
            meta: self.meta.clone(),
            encrypted: encryption_succeeded,
        }
    }

    pub fn decrypted(&self, cryptor: &datacrypt::EntryPasswordCryptor) -> Entry {
        let decrypted_password = if self.encrypted {
            match cryptor.decrypt_str(&self.pass) {
                Ok(decrypted) => decrypted,
                Err(_) => self.pass.clone(),
            }
        } else {
            self.pass.clone()
        };
        Entry::new(
            self.name.clone(),
            self.url.clone(),
            self.user.clone(),
            decrypted_password,
            self.desc.clone(),
            self.meta.clone(),
        )
    }
}

/// Indicates to the Editors the way how an entry should be presented to the user
#[derive(Debug)]
pub enum EntryPresentationType {
    /// Only View an Entry.
    View,
    /// Show an entry before it gets deleted.
    Delete,
    /// Edit an entry
    Edit,
}

/// A struct that allows storing general configuration values.
/// The configuration values are stored in plaintext.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Props {
    /// Inactivity timeout seconds
    idle_timeout_seconds: isize,
    /// The count of the words that comprise the generated passphraases
    generated_passphrases_words_count: isize,
    /// The current version
    version: String,
}

impl Default for Props {
    fn default() -> Self {
        Props {
            idle_timeout_seconds: 1800,
            generated_passphrases_words_count: 5,
            version: "".to_string(),
        }
    }
}

impl Props {
    pub(crate) fn new(
        idle_timeout_seconds: isize,
        generated_passphrases_words_count: isize,
        version: &str,
    ) -> Props {
        let version = version.to_string();
        Props {
            idle_timeout_seconds,
            generated_passphrases_words_count,
            version,
        }
    }

    pub fn from_table(table: &Table) -> Result<Props, errors::RustKeylockError> {
        let idle_timeout_seconds = table
            .get("idle_timeout_seconds")
            .and_then(|value| value.as_integer().and_then(|v| Some(v as isize)))
            .unwrap_or_else(|| Props::default().idle_timeout_seconds());
        let generated_passphrases_words_count = table
            .get("generated_passphrases_words_count")
            .and_then(|value| value.as_integer().and_then(|v| Some(v as isize)))
            .unwrap_or_else(|| Props::default().generated_passphrases_words_count());
        let version = table
            .get("version")
            .and_then(|value| value.as_str().and_then(|v| Some(v.to_string())))
            .unwrap_or_else(|| Props::default().version().to_string());

        Ok(Self::new(
            idle_timeout_seconds,
            generated_passphrases_words_count,
            &version,
        ))
    }

    #[allow(dead_code)]
    pub fn to_table(&self) -> Table {
        let mut table = Table::new();
        table.insert(
            "idle_timeout_seconds".to_string(),
            toml::Value::Integer(self.idle_timeout_seconds as i64),
        );
        table.insert(
            "generated_passphrases_words_count".to_string(),
            toml::Value::Integer(self.generated_passphrases_words_count as i64),
        );
        table.insert(
            "version".to_string(),
            toml::Value::String(self.version().to_string()),
        );

        table
    }

    pub fn idle_timeout_seconds(&self) -> isize {
        self.idle_timeout_seconds
    }

    pub fn generated_passphrases_words_count(&self) -> isize {
        self.generated_passphrases_words_count
    }

    pub fn version(&self) -> &str {
        &self.version
    }

    #[allow(dead_code)]
    pub fn set_idle_timeout_seconds(&mut self, new_timeout: isize) {
        self.idle_timeout_seconds = new_timeout
    }

    #[allow(dead_code)]
    pub fn set_generated_passphrases_words_count(&mut self, new_generated_passphrases_words_count: isize) {
        self.generated_passphrases_words_count = new_generated_passphrases_words_count;
    }

    pub fn set_version(&mut self, new_version: &str) {
        self.version = new_version.to_string();
    }

}

/// Enumeration of the several different Menus that an `Editor` implementation should handle.
#[derive(Debug, PartialEq, Clone)]
pub enum Menu {
    /// The User should provide a password and a number.
    /// If bool is true, the last_sync_version will be updated to be the same with the local_version.
    /// If false, nothing will be updated.
    TryPass(bool),
    /// The User should provide a new password and a new number.
    ChangePass,
    /// The User should be presented with the main menu.
    Main,
    /// The User should be presented with a list of all the saved password `Entries`, optiolally filtered by the string provided as argument.
    EntriesList(Option<String>),
    /// The User should create a new `Entry`. The optional Entry argument is an initial entry from which the User could start.
    /// It may contain a system-generated passphrase etc.
    NewEntry(Option<Entry>),
    /// The User should be presented with a selected `Entry`.
    ///
    /// The index of the `Entry` inside the `Entries` list is provided.
    ShowEntry(usize),
    /// The User should edit a selected `Entry`.
    ///
    /// The index of the `Entry` inside the `Entries` list is provided.
    EditEntry(usize),
    /// The User deletes a selected `Entry`.
    ///
    /// The index of the `Entry` inside the `Entries` list is provided.
    DeleteEntry(usize),
    /// The User encrypts and saves all the existing `Entries` list.
    /// If bool is true, the last_sync_version will be updated to be the same with the local_version.
    /// If false, only the local_version will be updated.
    Save(bool),
    /// The User selects to Exit _rust-keylock_
    Exit,
    /// The User selects to Exit _rust-keylock_, even if there is unsaved data.
    ForceExit,
    /// Parsing the `Entries` _after_ decrypting them may lead to wrong data. This Menu informs the User about the situation and offers an attempt to recover anything that is recoverable.
    TryFileRecovery,
    /// The user should be able to import password `Entries`.
    ImportEntries,
    /// The user should be able to export password `Entries`.
    ExportEntries,
    /// The user should be presented with the configuration menu
    ShowConfiguration,
    /// Temporarily creates a web server and waits for the callback HTTP request that obtains the Dropbox token
    WaitForDbxTokenCallback(String),
    /// Sets the dropbox token
    SetDbxToken(Zeroizing<String>),
    /// Stay in the current menu
    Current,
}

/// Represents a User selection that is returned after showing a `Menu`.
#[derive(Debug, PartialEq, Clone)]
pub enum UserSelection {
    /// The User selected an `Entry`.
    NewEntry(Entry),
    /// The User updated an `Entry`.
    ReplaceEntry(usize, Entry),
    /// The User deleted an `Entry`.
    DeleteEntry(usize),
    /// The User selected to go to a `Menu`.
    GoTo(Menu),
    /// The User provided a password and a number.
    ProvidedPassword(Zeroizing<String>, Zeroizing<usize>),
    /// The User acknowledges something.
    Ack,
    /// The User selected to export the password `Entries` to a path.
    ExportTo(String),
    /// The User selected to import the password `Entries` from a path.
    ImportFrom(String, Zeroizing<String>, Zeroizing<usize>),
    /// The User selected to import the password `Entries` from a file in the default location.
    ImportFromDefaultLocation(String, Zeroizing<String>, Zeroizing<usize>),
    /// The User may be offered to select one of the Options.
    UserOption(UserOption),
    /// The User updates the configuration.
    UpdateConfiguration(AllConfigurations),
    /// The user copies content to the clipboard.
    AddToClipboard(String),
    /// The user wants to generate a passphrase for en `Entry`.
    /// Option<usize> is None if the entry for which the passphrase will be generated is new.
    GeneratePassphrase(Option<usize>, Entry),
    /// The user wants to check the passwords status quality.
    CheckPasswords,
    /// The user wants to generate a new Browser Extension passphrase
    GenerateBrowserExtensionPassphrase,
}

impl UserSelection {
    pub fn is_same_variant_with(&self, other: &UserSelection) -> bool {
        self.ordinal() == other.ordinal()
    }

    pub fn new_provided_password<T: Into<Zeroizing<String>>, U: Into<Zeroizing<usize>>>(
        password: T,
        number: U,
    ) -> UserSelection {
        UserSelection::ProvidedPassword(password.into(), number.into())
    }

    pub fn new_import_from<T: Into<Zeroizing<String>>, U: Into<Zeroizing<usize>>>(
        location: String,
        password: T,
        number: U,
    ) -> UserSelection {
        UserSelection::ImportFrom(location, password.into(), number.into())
    }

    pub fn new_import_from_default_location<
        T: Into<Zeroizing<String>>,
        U: Into<Zeroizing<usize>>,
    >(
        location: String,
        password: T,
        number: U,
    ) -> UserSelection {
        UserSelection::ImportFromDefaultLocation(location, password.into(), number.into())
    }

    fn ordinal(&self) -> i8 {
        match self {
            UserSelection::NewEntry(_) => 1,
            UserSelection::ReplaceEntry(_, _) => 2,
            UserSelection::DeleteEntry(_) => 3,
            UserSelection::GoTo(_) => 4,
            UserSelection::ProvidedPassword(_, _) => 5,
            UserSelection::Ack => 6,
            UserSelection::ExportTo(_) => 7,
            UserSelection::ImportFrom(_, _, _) => 8,
            UserSelection::ImportFromDefaultLocation(_, _, _) => 9,
            UserSelection::UserOption(_) => 10,
            UserSelection::UpdateConfiguration(_) => 11,
            UserSelection::AddToClipboard(_) => 12,
            UserSelection::GeneratePassphrase(_, _) => 13,
            UserSelection::CheckPasswords => 14,
            UserSelection::GenerateBrowserExtensionPassphrase => 15,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct AllConfigurations {
    pub nextcloud: nextcloud::NextcloudConfiguration,
    pub dropbox: dropbox::DropboxConfiguration,
    pub general: GeneralConfiguration,
}

impl AllConfigurations {
    pub fn new(
        nextcloud: nextcloud::NextcloudConfiguration,
        dropbox: dropbox::DropboxConfiguration,
        general: GeneralConfiguration,
    ) -> AllConfigurations {
        AllConfigurations {
            nextcloud,
            dropbox,
            general,
        }
    }
}

impl Default for AllConfigurations {
    fn default() -> Self {
        AllConfigurations::new(
            NextcloudConfiguration::default(),
            DropboxConfiguration::default(),
            GeneralConfiguration::default(),
        )
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct UserOption {
    pub label: String,
    pub value: UserOptionType,
    pub short_label: String,
}

impl<'a> From<&'a UserOption> for UserOption {
    fn from(uo: &UserOption) -> Self {
        UserOption {
            label: uo.label.clone(),
            value: uo.value.clone(),
            short_label: uo.short_label.clone(),
        }
    }
}

impl From<(String, String, String)> for UserOption {
    fn from(f: (String, String, String)) -> Self {
        UserOption {
            label: f.0,
            value: UserOptionType::from(f.1.as_ref()),
            short_label: f.2,
        }
    }
}

impl UserOption {
    pub fn new(label: &str, option_type: UserOptionType, short_label: &str) -> UserOption {
        UserOption {
            label: label.to_string(),
            value: option_type,
            short_label: short_label.to_string(),
        }
    }

    pub fn empty() -> UserOption {
        UserOption {
            label: "".to_string(),
            value: UserOptionType::None,
            short_label: "".to_string(),
        }
    }

    pub fn ok() -> UserOption {
        UserOption {
            label: "Ok".to_string(),
            value: UserOptionType::String("Ok".to_string()),
            short_label: "o".to_string(),
        }
    }

    pub fn cancel() -> UserOption {
        UserOption {
            label: "Cancel".to_string(),
            value: UserOptionType::String("Cancel".to_string()),
            short_label: "c".to_string(),
        }
    }

    pub fn yes() -> UserOption {
        UserOption {
            label: "Yes".to_string(),
            value: UserOptionType::String("Yes".to_string()),
            short_label: "y".to_string(),
        }
    }

    pub fn no() -> UserOption {
        UserOption {
            label: "No".to_string(),
            value: UserOptionType::String("No".to_string()),
            short_label: "n".to_string(),
        }
    }
}

/// Represents a type for a `UserOption`
#[derive(Debug, PartialEq, Clone)]
pub enum UserOptionType {
    Number(isize),
    String(String),
    None,
}

impl UserOptionType {
    fn extract_value_from_string(s: &str) -> errors::Result<String> {
        let start = s.find('(');
        if s.ends_with(')') {
            match start {
                Some(st) => {
                    let i = s.chars().skip(st + 1).take(s.len() - st - 2);
                    let s = String::from_iter(i);
                    Ok(s)
                }
                _ => {
                    Err(errors::RustKeylockError::ParseError(format!("Could not extract UserOptionType value from {}. The \
                                                                      UserOptionType can be extracted from strings like String(value)",
                                                                     s)))
                }
            }
        } else {
            Err(errors::RustKeylockError::ParseError(format!("Could not extract UserOptionType value from {}. The UserOptionType can be \
                                                              extracted from strings like String(value)",
                                                             s)))
        }
    }
}

impl ToString for UserOptionType {
    fn to_string(&self) -> String {
        match *self {
            UserOptionType::String(ref s) => format!("String({})", s),
            _ => format!("{:?}", &self),
        }
    }
}

impl<'a> From<&'a str> for UserOptionType {
    fn from(string: &str) -> Self {
        match string {
            ref s if s.starts_with("String") => match Self::extract_value_from_string(s) {
                Ok(value) => UserOptionType::String(value),
                Err(error) => {
                    error!("Could not create UserOptionType from {}: {:?}. Please consider opening a bug to the developers.", s, error);
                    UserOptionType::None
                }
            },
            ref s if s.starts_with("Number") => {
                let m = Self::extract_value_from_string(s).and_then(|value| {
                    value.parse::<i64>().map_err(|_| {
                        errors::RustKeylockError::ParseError(format!(
                            "Could not parse {} to i64",
                            value
                        ))
                    })
                });
                match m {
                    Ok(num) => UserOptionType::Number(num as isize),
                    Err(error) => {
                        error!("Could not create UserOptionType from {}: {:?}. Please consider opening a bug to the developers.", s, error);
                        UserOptionType::None
                    }
                }
            }
            other => {
                error!("Could not create UserOptionType from {}. Please consider opening a bug to the developers.", other);
                UserOptionType::None
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub(crate) struct EditorShowMessageWrapper {
    pub message: String,
    pub user_options: Vec<UserOption>,
    pub severity: MessageSeverity,
}

impl EditorShowMessageWrapper {
    pub(crate) fn new(
        message: &str,
        user_options: Vec<UserOption>,
        severity: MessageSeverity,
    ) -> EditorShowMessageWrapper {
        EditorShowMessageWrapper {
            message: message.to_string(),
            user_options,
            severity,
        }
    }
}

/// Severity for the messages presented to the Users
#[derive(Debug, PartialEq, Clone)]
pub enum MessageSeverity {
    Info,
    Warn,
    Error,
}

impl Default for MessageSeverity {
    fn default() -> Self {
        MessageSeverity::Info
    }
}

impl ToString for MessageSeverity {
    fn to_string(&self) -> String {
        format!("{:?}", &self)
    }
}

#[async_trait]
pub(crate) trait PasswordChecker {
    async fn is_unsafe(&self, password: &str) -> errors::Result<bool>;
}

pub(crate) struct RklPasswordChecker {}

impl Default for RklPasswordChecker {
    fn default() -> Self {
        RklPasswordChecker {}
    }
}

#[async_trait]
impl PasswordChecker for RklPasswordChecker {
    async fn is_unsafe(&self, password: &str) -> errors::Result<bool> {
        Ok(rs_password_utils::pwned::is_pwned(password).await?)
    }
}

#[cfg(test)]
mod api_unit_tests {
    use toml;

    use crate::api::{AllConfigurations, EntryMeta};
    use crate::datacrypt::EntryPasswordCryptor;

    use super::{Entry, Menu, UserOption, UserSelection};

    #[test]
    fn entry_from_table_success() {
        let toml = r#"
			name = "name1"
			url = "url1"
			user = "user1"
			pass = "123"
			desc = "some description"
			meta = { leaked_password = true }
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let entry_opt = Entry::from_table(&table);
        assert!(entry_opt.is_ok());
        let entry = entry_opt.unwrap();
        assert!(entry.name == "name1");
        assert!(entry.url == "url1");
        assert!(entry.user == "user1");
        assert!(entry.pass == "123");
        assert!(entry.desc == "some description");
        assert!(entry.meta.leaked_password)
    }

    #[test]
    fn entry_from_table_success_no_meta() {
        let toml = r#"
			name = "name1"
			url = "url1"
			user = "user1"
			pass = "123"
			desc = "some description"
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let entry_opt = Entry::from_table(&table);
        assert!(entry_opt.is_ok());
        let entry = entry_opt.unwrap();
        assert!(entry.name == "name1");
        assert!(entry.url == "url1");
        assert!(entry.user == "user1");
        assert!(entry.pass == "123");
        assert!(entry.desc == "some description");
        assert!(!entry.meta.leaked_password)
    }

    #[test]
    fn entry_from_table_failure_wrong_key() {
        let toml = r#"
			wrong_key = "name1"
			url = "url"
			user = "user1"
			pass = "123"
			desc = "some description"
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let entry_opt = super::Entry::from_table(&table);
        assert!(entry_opt.is_err());
    }

    #[test]
    fn entry_from_table_failure_wrong_value() {
        let toml = r#"
			name = 1
			url = "url"
			user = "user1"
			pass = "123"
			desc = "some description"
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let entry_opt = super::Entry::from_table(&table);
        assert!(entry_opt.is_err());
    }

    #[test]
    fn entry_to_table() {
        let toml = r#"
			name = "name1"
			url = "url1"
			user = "user1"
			pass = "123"
			desc = "some description"
			meta = {leaked_password = false}
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let entry_opt = super::Entry::from_table(&table);
        assert!(entry_opt.is_ok());
        let entry = entry_opt.unwrap();
        let new_table = entry.to_table();
        dbg!(&new_table);
        assert!(table == new_table);
    }

    #[test]
    fn entry_to_encrypted() {
        let cryptor = EntryPasswordCryptor::new();
        let entry = super::Entry::new(
            "name".to_string(),
            "url".to_string(),
            "user".to_string(),
            "pass".to_string(),
            "desc".to_string(),
            EntryMeta::default(),
        );
        let enc_entry = entry.encrypted(&cryptor);
        assert!(enc_entry.name == entry.name);
        assert!(enc_entry.url == entry.url);
        assert!(enc_entry.user == entry.user);
        assert!(enc_entry.pass != entry.pass);
        assert!(enc_entry.desc == entry.desc);
        let dec_entry = enc_entry.decrypted(&cryptor);
        assert!(dec_entry.pass == entry.pass);
    }

    #[test]
    fn entry_to_encrypted_encryption_may_fail() {
        let cryptor = EntryPasswordCryptor::new();
        let entry = super::Entry::new(
            "name".to_string(),
            "url".to_string(),
            "user".to_string(),
            "pass".to_string(),
            "desc".to_string(),
            EntryMeta::default(),
        );
        let dec_entry = entry.decrypted(&cryptor);
        assert!(dec_entry.pass == entry.pass);
    }

    #[test]
    fn props_from_table_success() {
        let toml = r#"
        idle_timeout_seconds = 33
        generated_passphrases_words_count = 5
        version = "0.0.0"
        "#;

        let table = toml.parse::<toml::Table>().unwrap();
        let props_opt = super::Props::from_table(&table);
        assert!(props_opt.is_ok());
        let props = props_opt.unwrap();
        assert!(props.idle_timeout_seconds() == 33);
        assert!(props.generated_passphrases_words_count() == 5);
        assert!(props.version() == "0.0.0");
    }

    #[test]
    fn props_from_table_not_all_elements() {
        let toml1 = r#"
        idle_timeout_seconds = 33
        "#;
        let table1 = toml1.parse::<toml::Table>().unwrap();
        let props_opt1 = super::Props::from_table(&table1);
        assert!(props_opt1.is_ok());
        let props1 = props_opt1.unwrap();
        assert!(props1.idle_timeout_seconds() == 33);
        assert!(props1.generated_passphrases_words_count() == 5);

        let toml2 = r#"
        generated_passphrases_words_count = 5
        "#;
        let table2 = toml2.parse::<toml::Table>().unwrap();
        let props_opt2 = super::Props::from_table(&table2);
        assert!(props_opt2.is_ok());
        let props2 = props_opt2.unwrap();
        assert!(props2.idle_timeout_seconds() == 1800);
        assert!(props2.generated_passphrases_words_count() == 5);

        let toml3 = r#"
        version = "0.0.0"
        "#;
        let table3 = toml3.parse::<toml::Table>().unwrap();
        let props_opt3 = super::Props::from_table(&table3);
        assert!(props_opt3.is_ok());
        let props3 = props_opt3.unwrap();
        assert!(props3.idle_timeout_seconds() == 1800);
        assert!(props3.generated_passphrases_words_count() == 5);
        assert!(props3.version() == "0.0.0");
    }

    #[test]
    fn props_from_table_failure_wrong_key() {
        let toml = r#"wrong_key = "alas""#;

        let table = toml.parse::<toml::Table>().unwrap();
        let props_opt = super::Props::from_table(&table);
        assert!(props_opt.is_ok());
    }

    #[test]
    fn props_from_table_failure_wrong_value() {
        let toml = r#"salt = 1"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let props_opt = super::Props::from_table(&table);
        assert!(props_opt.is_ok());
    }

    #[test]
    fn props_to_table() {
        let toml = r#"
        idle_timeout_seconds = 33
        generated_passphrases_words_count = 5
        version = "0.0.0"
        "#;

        let table = toml.parse::<toml::Table>().unwrap();
        let props_opt = super::Props::from_table(&table);
        assert!(props_opt.is_ok());
        let props = props_opt.unwrap();
        let new_table = props.to_table();
        assert!(table == new_table);
    }

    #[test]
    fn props_mutate() {
        let toml = r#"
        idle_timeout_seconds = 3
        generated_passphrases_words_count = 3
        version = "0.0.0"
        "#;

        let table = toml.parse::<toml::Table>().unwrap();
        let props_opt = super::Props::from_table(&table);
        assert!(props_opt.is_ok());
        let mut props = props_opt.unwrap();

        props.set_idle_timeout_seconds(33);
        props.set_generated_passphrases_words_count(33);
        props.set_version("0.0.1");

        assert!(props.idle_timeout_seconds() == 33);
        assert!(props.generated_passphrases_words_count() == 33);
        assert!(props.version() == "0.0.1");
    }

    #[test]
    fn user_option_constructors() {
        let opt1 = super::UserOption::cancel();
        assert!(&opt1.label == "Cancel");
        assert!(opt1.value == super::UserOptionType::String("Cancel".to_string()));
        assert!(&opt1.short_label == "c");

        let opt2 = super::UserOption::empty();
        assert!(&opt2.label == "");
        assert!(opt2.value == super::UserOptionType::None);
        assert!(&opt2.short_label == "");

        let opt3 = super::UserOption::ok();
        assert!(&opt3.label == "Ok");
        assert!(opt3.value == super::UserOptionType::String("Ok".to_string()));
        assert!(&opt3.short_label == "o");
    }

    #[test]
    fn user_option_type_extract_value_from_string() {
        let s1 = "String(my string)";
        let sr1 = super::UserOptionType::extract_value_from_string(&s1).unwrap();
        assert!(sr1 == "my string");

        let s2 = "String(wrong";
        assert!(super::UserOptionType::extract_value_from_string(&s2).is_err());

        let s3 = "String wrong)";
        assert!(super::UserOptionType::extract_value_from_string(&s3).is_err());

        let s4 = "String((my string))";
        let sr4 = super::UserOptionType::extract_value_from_string(&s4).unwrap();
        assert!(sr4 == "(my string)");
    }

    #[test]
    fn user_option_type_from_string() {
        assert!(
            super::UserOptionType::from("String(my string)")
                == super::UserOptionType::String("my string".to_string())
        );
        assert!(super::UserOptionType::from("Number(33)") == super::UserOptionType::Number(33));
        assert!(super::UserOptionType::from("Other(33)") == super::UserOptionType::None);
    }

    #[test]
    fn user_option_type_to_string_from_string() {
        let user_option_type = super::UserOptionType::String("my string".to_string());
        let string = user_option_type.to_string();
        assert!(string == "String(my string)");
        let s: &str = &string;
        assert!(
            super::UserOptionType::from(s)
                == super::UserOptionType::String("my string".to_string())
        );
    }

    #[test]
    fn system_configuration_to_table() {
        let toml = r#"
			saved_at = 123
			version = 1
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let res = super::SystemConfiguration::from_table(&table);
        assert!(res.is_ok());
        let conf = res.unwrap();
        let new_table = conf.to_table().unwrap();
        assert!(table == new_table);
    }

    #[test]
    fn system_configuration_from_table_success() {
        let toml = r#"
			saved_at = 123
			version = 1
		"#;

        let table = toml.parse::<toml::Table>().unwrap();
        let res = super::SystemConfiguration::from_table(&table);
        assert!(res.is_ok());
        let conf = res.unwrap();
        assert!(conf.saved_at == Some(123));
        assert!(conf.version == Some(1));
    }

    #[test]
    fn user_selection_ordinal() {
        assert!(UserSelection::NewEntry(Entry::empty()).ordinal() == 1);
        assert!(UserSelection::ReplaceEntry(1, Entry::empty()).ordinal() == 2);
        assert!(UserSelection::DeleteEntry(1).ordinal() == 3);
        assert!(UserSelection::GoTo(Menu::TryPass(false)).ordinal() == 4);
        assert!(UserSelection::new_provided_password("".to_owned(), 33).ordinal() == 5);
        assert!(UserSelection::Ack.ordinal() == 6);
        assert!(UserSelection::ExportTo("".to_owned()).ordinal() == 7);
        assert!(UserSelection::new_import_from("".to_owned(), "".to_owned(), 1).ordinal() == 8);
        assert!(
            UserSelection::new_import_from_default_location("".to_owned(), "".to_owned(), 1)
                .ordinal()
                == 9
        );
        assert!(UserSelection::UserOption(UserOption::empty()).ordinal() == 10);
        assert!(UserSelection::UpdateConfiguration(AllConfigurations::default()).ordinal() == 11);
        assert!(UserSelection::AddToClipboard("".to_owned()).ordinal() == 12);
    }

    #[test]
    fn is_same_variant_with() {
        assert!(
            UserSelection::new_provided_password("".to_owned(), 33).is_same_variant_with(
                &UserSelection::new_provided_password("other".to_owned(), 11)
            )
        );
    }
}