kdbx-rs 0.5.2

Keepass 2 (KDBX) password database parsing and creation
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
//! Keepass data types
//!
//! A database is made up of two primary parts, a set of meta
//! information about the database itself, like the name or description
//! and a tree structure of groups and database entries. Groups can also
//! be nested within other groups.
//!
//! ## Meta information
//!
//! You can access the entire [`Meta`] struct using [`Database::meta()`].
//! For the most common information the following shortcut methods are provided:
//!
//! * [`Database::name`] / [`Database::set_name`]
//! * [`Database::description`] / [`Database::set_description`]
//!
//! ## Example operations
//!
//! ### Add a entry to the root group
//!
//! ```
//! # use kdbx_rs::database::{Database,Entry};
//! let mut database = Database::default();
//! let entry = Entry::default();
//! database.add_entry(entry);
//! ```
//!
//! ### Add a child group to the root group
//!
//! ```
//! # use kdbx_rs::database::{Database,Group};
//! let mut database = Database::default();
//! let group = Group::new("Child group");
//! database.add_group(group);
//! ```
//!
//! ### Updating a password for a given URL
//!
//! ```
//! # let mut database = kdbx_rs::database::doc_sample_db();
//! database.find_entry_mut(|f| f.url() == Some("http://example.com"))
//!     .unwrap()
//!     .set_password("password2")
//! ```
//!
//! ### Moving an entry from one folder to another
//!
//! [`Group::find_entry_mut()`] gives us a reference, while moving a folder to
//! another group requires an owned [`Entry`]. So instead we take its UUID
//! and remove it from the source group first.
//!
//! ```
//! # let mut database = kdbx_rs::database::doc_sample_db();
//! let uuid = database.find_entry_mut(|f| f.title() == Some("Foo"))
//!     .unwrap()
//!     .uuid();
//! # let mut source_group = database.root_mut();
//! let entry = source_group.remove_entry(uuid).unwrap();
//!
//! let mut target_group = database.find_group_mut(|g| g.name() == "Child Group").unwrap();
//! target_group.add_entry(entry);
//! ```

use chrono::{NaiveDateTime, Timelike};
use std::borrow::Cow;
use std::ops::{Index, IndexMut};
use uuid::Uuid;

#[doc(hidden)]
pub fn doc_sample_db() -> Database {
    let mut database = Database::default();

    let mut root_entry = Entry::default();
    root_entry.set_title("Foo");
    root_entry.set_url("http://example.com");
    root_entry.set_password("password1");

    database.add_entry(root_entry);

    let child_group = Group::new("Child Group");
    database.add_group(child_group);

    let mut child_entry = Entry::default();
    child_entry.set_title("Bar");
    child_entry.set_url("http://example.com");
    child_entry.set_password("password2");
    database
        .find_group_mut(|g: &Group| g.name == "Child Group")
        .unwrap()
        .add_entry(child_entry);

    database
}

/// A value for a `Field` stored in an `Entry`
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Value {
    /// A value using in-memory encryption
    Protected(String),
    /// A value that's unencrypted in the database
    Standard(String),
    /// A empty value
    Empty,
    /// A empty value that should be protected if filled
    ProtectEmpty,
}

impl Default for Value {
    fn default() -> Value {
        Value::Empty
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
/// A key value pair
pub struct Field {
    /// The name of this field
    pub(crate) key: String,
    /// The (optionally encrypted) value of this field
    pub(crate) value: Value,
}

impl Field {
    /// Create a new field without memory protection
    pub fn new(key: &str, value: &str) -> Field {
        Field {
            key: key.to_string(),
            value: Value::Standard(value.to_string()),
        }
    }

    /// Create a new field without memory protection
    pub fn new_protected(key: &str, value: &str) -> Field {
        Field {
            key: key.to_string(),
            value: Value::Protected(value.to_string()),
        }
    }

    /// Key for this field
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Set a new key for this field
    pub fn set_key(&mut self, new_key: &str) {
        self.key = new_key.to_string();
    }

    /// Value for this field
    pub fn value(&self) -> Option<&str> {
        match self.value {
            Value::Protected(ref s) => Some(s),
            Value::Standard(ref s) => Some(s),
            _ => None,
        }
    }

    /// Set a new value for this field
    pub fn set_value(&mut self, value: &str) {
        if self.protected() {
            self.value = Value::Protected(value.to_string());
        } else {
            self.value = Value::Standard(value.to_string());
        }
    }

    /// Empty out the field stored in this value
    pub fn clear(&mut self) {
        if self.protected() {
            self.value = Value::ProtectEmpty;
        } else {
            self.value = Value::Empty;
        }
    }

    /// Get whether memory protection and extra encryption should be applied
    ///
    /// Note: This is instructional for official clients, this library does not
    /// support memory protection
    pub fn protected(&self) -> bool {
        matches!(self.value, Value::Protected(_))
    }

    /// Set whether memory protection and extra encryption should be applied
    ///
    /// Note: This is instructional for official clients, this library does not
    /// support memory protection
    pub fn set_protected(&mut self, protected: bool) {
        let existing_value = std::mem::take(&mut self.value);
        self.value = match (protected, existing_value) {
            (true, Value::Standard(s)) => Value::Protected(s),
            (false, Value::Protected(s)) => Value::Standard(s),
            (true, Value::Empty) => Value::ProtectEmpty,
            (false, Value::ProtectEmpty) => Value::Empty,
            (_, v) => v,
        }
    }
}

/// Historical versions of a single entry
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct History {
    entries: Vec<Entry>,
}

impl History {
    /// Get a history entry by its index
    pub fn get(&self, index: usize) -> Option<&Entry> {
        self.entries.get(index)
    }

    /// Get a history entry mutably by its index
    pub fn get_mut(&mut self, index: usize) -> Option<&mut Entry> {
        self.entries.get_mut(index)
    }

    /// Add a new version of an entry to the history
    pub fn push(&mut self, entry: Entry) {
        self.entries.push(entry);
    }

    /// Count of entries in this history
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Count of entries in this history
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Remove a historical version by index
    pub fn remove(&mut self, idx: usize) -> Entry {
        self.entries.remove(idx)
    }

    /// Iterate over all historical entries
    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
        self.entries.iter()
    }

    /// Iterate mutably over all historical entries
    pub fn entries_mut(&mut self) -> impl Iterator<Item = &mut Entry> {
        self.entries.iter_mut()
    }
}

impl Index<usize> for History {
    type Output = Entry;
    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).unwrap()
    }
}

impl IndexMut<usize> for History {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).unwrap()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A single password entry
pub struct Entry {
    /// Identifier for this entry
    uuid: Uuid,
    /// Key-value pairs of current data for this entry
    fields: Vec<Field>,
    /// Previous versions of this entry
    pub(crate) history: History,
    /// Information about access times
    pub(crate) times: Times,
}

impl Entry {
    /// Add a new field to the entry
    pub fn add_field(&mut self, field: Field) {
        self.fields.push(field);
    }

    /// Remove a field by its key
    ///
    /// If there are duplicate fields, removes them all
    pub fn remove_field(&mut self, key: &str) {
        let mut matching_field_indices: Vec<_> = self
            .fields
            .iter()
            .enumerate()
            .filter_map(|(idx, field)| if field.key == key { Some(idx) } else { None })
            .collect();
        matching_field_indices.sort();
        matching_field_indices.reverse();
        for index in matching_field_indices {
            self.fields.remove(index);
        }
    }

    /// Generate a new version of this entry, pushing the current state to history
    pub fn new_version(&mut self) {
        let mut new_entry = self.clone();
        new_entry.history = History::default();
        self.history.push(new_entry);
    }

    /// Iterate through all the fields
    pub fn fields(&self) -> impl Iterator<Item = &Field> {
        self.fields.iter()
    }

    /// Iterate through all the field mutably
    pub fn fields_mut(&mut self) -> impl Iterator<Item = &mut Field> {
        self.fields.iter_mut()
    }

    /// Iterate through all the fields
    pub fn history(&self) -> &History {
        &self.history
    }

    /// Iterate through all the field mutably
    pub fn history_mut(&mut self) -> &mut History {
        &mut self.history
    }

    /// Find a field in this entry with a given key
    pub fn find(&self, key: &str) -> Option<&Field> {
        self.fields.iter().find(|i| i.key.as_str() == key)
    }

    /// Find a field in this entry with a given key
    pub fn find_mut(&mut self, key: &str) -> Option<&mut Field> {
        self.fields.iter_mut().find(|i| i.key.as_str() == key)
    }

    /// Audit times for this entry
    pub fn times(&self) -> &Times {
        &self.times
    }

    /// Mutable audit times for this entry
    pub fn times_mut(&mut self) -> &mut Times {
        &mut self.times
    }

    fn find_string_value(&self, key: &str) -> Option<&str> {
        self.find(key).and_then(|f| f.value())
    }

    /// Set the identifier for this item
    pub fn uuid(&self) -> Uuid {
        self.uuid
    }

    /// Get the identifier for this item
    pub fn set_uuid(&mut self, uuid: Uuid) {
        self.uuid = uuid;
    }

    /// Return the title of this item
    pub fn title(&self) -> Option<&str> {
        self.find_string_value("Title")
    }

    /// Set the title of this entry
    pub fn set_title<S: ToString>(&mut self, title: S) {
        let title = title.to_string();
        match self.find_mut("Title") {
            Some(f) => f.value = Value::Standard(title),
            None => self.fields.push(Field::new("Title", &title)),
        }
    }

    /// Return the username of this item
    pub fn username(&self) -> Option<&str> {
        self.find_string_value("UserName")
    }

    /// Set the username of this entry
    pub fn set_username<S: ToString>(&mut self, username: S) {
        let username = username.to_string();
        match self.find_mut("UserName") {
            Some(f) => f.value = Value::Standard(username),
            None => self.fields.push(Field::new("UserName", &username)),
        }
    }

    /// Return the URL of this item
    pub fn url(&self) -> Option<&str> {
        self.find_string_value("URL")
    }

    /// Set the URL of this entry
    pub fn set_url<S: ToString>(&mut self, url: S) {
        let url = url.to_string();
        match self.find_mut("URL") {
            Some(f) => f.value = Value::Standard(url),
            None => self.fields.push(Field::new("URL", &url)),
        }
    }

    /// Return the TOTP of this item, as stored by KeepassXC
    pub fn otp(&self) -> Option<Otp> {
        self.find_string_value("otp").map(|url| Otp {
            url: Cow::Borrowed(url),
        })
    }

    /// Return the TOTP of this item, as stored by KeepassXC
    pub fn set_otp(&mut self, otp: Otp) {
        match self.find_mut("otp") {
            Some(f) => f.value = Value::Protected(otp.url.to_string()),
            None => self
                .fields
                .push(Field::new_protected("otp", otp.url.as_ref())),
        }
    }

    /// Return the password of this item
    pub fn password(&self) -> Option<&str> {
        self.find_string_value("Password")
    }

    /// Set the password of this entry
    pub fn set_password<S: ToString>(&mut self, password: S) {
        let password = password.to_string();
        match self.find_mut("Password") {
            Some(f) => f.value = Value::Protected(password),
            None => self
                .fields
                .push(Field::new_protected("Password", &password)),
        }
    }
}

impl Default for Entry {
    fn default() -> Entry {
        Entry {
            uuid: Uuid::new_v4(),
            fields: Vec::new(),
            history: History::default(),
            times: Times::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A group or folder of password entries and child groups
pub struct Group {
    /// Identifier for this group
    uuid: Uuid,
    /// Name of this group
    name: String,
    /// Password items within this group
    entries: Vec<Entry>,
    /// Subfolders of this group
    groups: Vec<Group>,
    /// Access times for this group
    pub(crate) times: Times,
}

impl Group {
    /// Create a new group with the given name
    pub fn new<S: ToString>(name: S) -> Group {
        Group {
            uuid: Uuid::new_v4(),
            name: name.to_string(),
            entries: Vec::new(),
            groups: Vec::new(),
            times: Times::default(),
        }
    }

    /// Identifier for this group
    pub fn uuid(&self) -> Uuid {
        self.uuid
    }

    /// Set identifier for this group
    pub fn set_uuid(&mut self, uuid: Uuid) {
        self.uuid = uuid
    }

    /// Display name for this group
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Set display name for this group
    pub fn set_name<S: ToString>(&mut self, name: S) {
        self.name = name.to_string();
    }

    /// Add a new entry to this group
    pub fn add_entry(&mut self, entry: Entry) {
        self.entries.push(entry);
    }

    /// Remove an entry by its UUID
    ///
    /// This is a no-op if the no direct child of this group has the
    /// given UUID
    pub fn remove_entry(&mut self, uuid: Uuid) -> Option<Entry> {
        let index = self
            .entries
            .iter()
            .enumerate()
            .find(|(_, entry)| entry.uuid() == uuid)
            .map(|(index, _)| index);

        if let Some(index) = index {
            Some(self.entries.remove(index))
        } else {
            None
        }
    }

    /// Add a new child group to this group
    pub fn add_group(&mut self, group: Group) {
        self.groups.push(group);
    }

    /// Remove an child group by its UUID
    ///
    /// This is a no-op if the no direct child of this group has the
    /// given UUID
    pub fn remove_group(&mut self, uuid: Uuid) -> Option<Group> {
        let index = self
            .groups
            .iter()
            .enumerate()
            .find(|(_, group)| group.uuid() == uuid)
            .map(|(index, _)| index);

        if let Some(index) = index {
            Some(self.groups.remove(index))
        } else {
            None
        }
    }

    /// Iterate through all the direct child groups of this group
    pub fn groups(&self) -> impl Iterator<Item = &Group> {
        self.groups.iter()
    }

    /// Iterate mutably through all the direct child groups of this group
    pub fn groups_mut(&mut self) -> impl Iterator<Item = &mut Group> {
        self.groups.iter_mut()
    }

    /// Count of direct child groups of this group
    pub fn group_count(&self) -> usize {
        self.groups.len()
    }

    /// Count of direct entries of this group
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Iterate through all the direct entries of this group
    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
        self.entries.iter()
    }

    /// Iterate mutably through all the direct entries of this group
    pub fn entries_mut(&mut self) -> impl Iterator<Item = &mut Entry> {
        self.entries.iter_mut()
    }

    /// Iterator through all entries in this group or children
    pub fn recursive_entries<'a>(&'a self) -> Box<dyn Iterator<Item = &Entry> + 'a> {
        Box::new(
            self.groups
                .iter()
                .flat_map(|c| c.recursive_entries())
                .chain(self.entries.iter()),
        )
    }

    /// Mutable Iterator through all entries in this group or children
    pub fn recursive_entries_mut<'a>(&'a mut self) -> Box<dyn Iterator<Item = &mut Entry> + 'a> {
        Box::new(
            self.groups
                .iter_mut()
                .flat_map(|c| c.recursive_entries_mut())
                .chain(self.entries.iter_mut()),
        )
    }

    /// Iterator through all child groups of this group
    pub fn recursive_groups<'a>(&'a self) -> Box<dyn Iterator<Item = &Group> + 'a> {
        Box::new(
            self.groups
                .iter()
                .flat_map(|g| g.recursive_groups())
                .chain(self.groups.iter()),
        )
    }

    /// Find a group in this group's children or it's children's children
    pub fn find_group<F: FnMut(&Group) -> bool>(&self, mut f: F) -> Option<&Group> {
        self.find_group_internal(&mut f)
    }

    fn find_group_internal<F: FnMut(&Group) -> bool>(&self, f: &mut F) -> Option<&Group> {
        for group in self.groups() {
            if f(group) {
                return Some(group);
            } else if let Some(g) = group.find_group_internal(f) {
                return Some(g);
            }
        }
        None
    }

    /// Find a mutable group in this group's children or it's children's children
    pub fn find_group_mut<F: FnMut(&Group) -> bool>(&mut self, mut f: F) -> Option<&mut Group> {
        self.find_group_mut_internal(&mut f)
    }

    fn find_group_mut_internal<F: FnMut(&Group) -> bool>(
        &mut self,
        f: &mut F,
    ) -> Option<&mut Group> {
        for group in self.groups_mut() {
            if f(group) {
                return Some(group);
            } else if let Some(g) = group.find_group_mut_internal(f) {
                return Some(g);
            }
        }
        None
    }

    /// Find a entry in this group's children or it's children's children
    pub fn find_entry<F: FnMut(&Entry) -> bool>(&self, mut f: F) -> Option<&Entry> {
        self.find_entry_internal(&mut f)
    }

    fn find_entry_internal<F: FnMut(&Entry) -> bool>(&self, f: &mut F) -> Option<&Entry> {
        for entry in self.entries() {
            if f(entry) {
                return Some(entry);
            }
        }
        for group in self.groups() {
            if let Some(e) = group.find_entry_internal(f) {
                return Some(e);
            }
        }
        None
    }

    /// Find a mutable entry in this group's children or it's children's children
    pub fn find_entry_mut<F: FnMut(&Entry) -> bool>(&mut self, mut f: F) -> Option<&mut Entry> {
        self.find_entry_mut_internal(&mut f)
    }

    fn find_entry_mut_internal<F: FnMut(&Entry) -> bool>(
        &mut self,
        f: &mut F,
    ) -> Option<&mut Entry> {
        let found_in_entries = self
            .entries()
            .enumerate()
            .find(|(_, e)| f(e))
            .map(|(idx, _)| idx);

        if let Some(idx) = found_in_entries {
            return Some(&mut self.entries[idx]);
        } else {
            for group in self.groups_mut() {
                if let Some(e) = group.find_entry_mut_internal(f) {
                    return Some(e);
                }
            }
        }
        None
    }

    /// Audit times for this group
    pub fn times(&self) -> &Times {
        &self.times
    }

    /// Mutable audit times for this group
    pub fn times_mut(&mut self) -> &mut Times {
        &mut self.times
    }
}

impl Default for Group {
    fn default() -> Group {
        Group {
            uuid: Uuid::new_v4(),
            name: String::new(),
            entries: Vec::new(),
            groups: Vec::new(),
            times: Times::default(),
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
/// Identifies which fields are encrypted in memory for official clients
pub struct MemoryProtection {
    /// Whether title fields should be encrypted
    pub protect_title: bool,
    /// Whether username fields should be encrypted
    pub protect_user_name: bool,
    /// Whether password fields should be encrypted
    pub protect_password: bool,
    /// Whether URL fields should be encrypted
    pub protect_url: bool,
    /// Whether Notes fields should be encrypted
    pub protect_notes: bool,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
/// Meta information about this database
pub struct Meta {
    /// Application used to generate this database
    pub generator: String,
    /// Short name for the database
    pub database_name: String,
    /// Longer description of the database
    pub database_description: String,
    /// Non standard information from plugins and other clients
    pub custom_data: Vec<Field>,
    /// Memory protection configuration for this client
    pub memory_protection: MemoryProtection,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Audit times for this item
pub struct Times {
    /// Time last edited
    pub last_modification_time: NaiveDateTime,
    /// Time created
    pub creation_time: NaiveDateTime,
    /// Time last accessed
    pub last_access_time: NaiveDateTime,
    /// Time at which this password needs rotation
    pub expiry_time: NaiveDateTime,
    /// Time at which this password was last moved within the database
    pub location_changed: NaiveDateTime,
    /// Whether this password expires
    pub expires: bool,
    /// Count of usages with autofill functions
    pub usage_count: u32,
}

impl Default for Times {
    fn default() -> Times {
        let now = chrono::Local::now()
            .naive_local()
            .with_nanosecond(0)
            .unwrap();
        Times {
            expires: false,
            usage_count: 0,
            last_modification_time: now,
            creation_time: now,
            last_access_time: now,
            expiry_time: now,
            location_changed: now,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Decrypted password database
///
/// See the [module-level documentation][crate::database] for more information.
pub struct Database {
    /// Meta information about this database
    pub(crate) meta: Meta,
    /// Trees of items in this database
    pub(crate) groups: Vec<Group>,
}

impl Default for Database {
    fn default() -> Self {
        let root = Group::new("Root");
        Database {
            meta: Meta::default(),
            groups: vec![root],
        }
    }
}

impl Database {
    /// Return meta information about the database like name and access times
    pub fn meta(&self) -> &Meta {
        &self.meta
    }

    /// Mutable meta information about the database like name and access times
    pub fn meta_mut(&mut self) -> &mut Meta {
        &mut self.meta
    }

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

    /// Set the database name
    pub fn set_name<S: ToString>(&mut self, name: S) {
        self.meta.database_name = name.to_string();
    }

    /// Get the database description
    pub fn description(&self) -> &str {
        &self.meta.database_description
    }

    /// Set the database name
    pub fn set_description<S: ToString>(&mut self, desc: S) {
        self.meta.database_description = desc.to_string();
    }

    /// Add a entry to the root group
    pub fn add_entry(&mut self, entry: Entry) {
        self.groups[0].entries.push(entry);
    }

    /// Add a child group to the root group
    pub fn add_group(&mut self, entry: Group) {
        self.groups[0].groups.push(entry);
    }

    /// Replace the root group (and therefore all entries!) with a custom tree
    pub fn replace_root(&mut self, group: Group) {
        self.groups = vec![group];
    }

    /// Recursively searches for the first group matching a filter
    pub fn find_group<F: FnMut(&Group) -> bool>(&self, f: F) -> Option<&Group> {
        self.root().find_group(f)
    }

    /// Recursively searches for the first group matching a filter, returns it mutably
    pub fn find_group_mut<F: FnMut(&Group) -> bool>(&mut self, f: F) -> Option<&mut Group> {
        self.root_mut().find_group_mut(f)
    }

    /// Recursively searches for the first entry matching a filter
    pub fn find_entry<F: FnMut(&Entry) -> bool>(&self, f: F) -> Option<&Entry> {
        self.root().find_entry(f)
    }

    /// Recursively searches for the first entry matching a filter, returns it mutably
    pub fn find_entry_mut<F: FnMut(&Entry) -> bool>(&mut self, f: F) -> Option<&mut Entry> {
        self.root_mut().find_entry_mut(f)
    }

    /// Top level group for database entries
    pub fn root(&self) -> &Group {
        &self.groups[0]
    }

    /// Mutable top level group for database entries
    pub fn root_mut(&mut self) -> &mut Group {
        &mut self.groups[0]
    }
}

/// TOTP one time password secret in KeepassXC format
pub struct Otp<'a> {
    url: Cow<'a, str>,
}

impl<'a> Otp<'a> {
    /// Create a new OTP password from the given details
    pub fn new<S: ToString>(secret: S, period: u32, digits: u32) -> Otp<'static> {
        let url = format!(
            "otpauth://totp/kdbxrs:kdbxrs?secret={}&period={}&digits={}",
            secret.to_string(),
            period,
            digits
        );
        Otp {
            url: Cow::Owned(url),
        }
    }

    fn find_url_param(&self, key: &str) -> Option<&str> {
        let mut parts = self.url.split('?');
        let _path = parts.next()?;
        let params = parts.next()?;
        let params = params.split('&');

        for param in params {
            let mut param_parts = param.split('=');
            let pkey = param_parts.next()?;
            if pkey == key {
                return param_parts.next();
            }
        }
        None
    }

    /// Retrieve the secret used to generate one time passwords
    pub fn secret(&self) -> Option<&str> {
        self.find_url_param("secret")
    }

    /// Return the period for which passwords are valid
    pub fn period(&self) -> Option<u32> {
        self.find_url_param("secret").and_then(|p| p.parse().ok())
    }

    /// Return the number of digits in the resulting code
    pub fn digits(&self) -> Option<u32> {
        self.find_url_param("digits").and_then(|p| p.parse().ok())
    }
}