sefy-core 0.20.0

Core library for sefy: an inconspicuous encrypted secret store in a single file
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! What a vault holds: notes, structured records and file attachments, each
//! tagged.
//!
//! Everything but a note and a file is a **set of named fields**. A login, a
//! payment card and an SSH key differ in which fields they carry and which of
//! those are secret — not in how they are stored. That is why adding a kind
//! costs a template rather than a table, a payload variant and a new set of
//! flags each time.

use zeroize::Zeroize;

/// Kind of payload an item carries.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ItemKind {
    /// Free-form text.
    Note,
    /// An account: who you are, the secret, and where it is used.
    Login,
    /// A payment card.
    Card,
    /// An SSH key pair and its passphrase.
    SshKey,
    /// A wireless network and how to join it.
    Wifi,
    /// A token for an API: the kind of secret a program presents, not a person.
    ApiToken,
    /// A bank account.
    Bank,
    /// Arbitrary bytes kept verbatim.
    File,
    /// A kind this build does not know, carrying the name it was stored under.
    ///
    /// Vaults travel between machines, and the two ends need not run the same
    /// version. An item written by a newer sefy therefore has to be *something*
    /// here rather than a parse failure: refusing it would take down every
    /// listing, export and merge in a vault that is otherwise perfectly
    /// readable — which is exactly what 0.5.0 and earlier did.
    ///
    /// Such an item can be listed, searched, exported and merged, but not read
    /// or edited: this build does not know the shape behind the name and will
    /// not guess at it.
    Unknown(String),
}

impl ItemKind {
    /// Stable identifier used in the database and on the command line.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Note => "note",
            Self::Login => "login",
            Self::Card => "card",
            Self::SshKey => "ssh-key",
            Self::Wifi => "wifi",
            Self::ApiToken => "api-token",
            Self::Bank => "bank",
            Self::File => "file",
            Self::Unknown(name) => name,
        }
    }

    /// Reads the identifier produced by [`ItemKind::as_str`].
    ///
    /// Never fails: an unrecognized name becomes [`ItemKind::Unknown`], because
    /// a name this build has not heard of is a fact about this build, not a
    /// broken vault.
    ///
    /// `credential` is accepted as a spelling of [`ItemKind::Login`]: that is
    /// what the kind was called up to 0.6.0, and vaults, exports and scripts
    /// written then are still in use.
    pub fn parse(value: &str) -> Self {
        match value {
            "note" => Self::Note,
            "login" | LEGACY_LOGIN_NAME => Self::Login,
            "card" => Self::Card,
            "ssh-key" => Self::SshKey,
            "wifi" => Self::Wifi,
            "api-token" => Self::ApiToken,
            "bank" => Self::Bank,
            "file" => Self::File,
            other => Self::Unknown(other.to_owned()),
        }
    }

    /// Whether this build understands the payload behind the name.
    pub fn is_known(&self) -> bool {
        !matches!(self, Self::Unknown(_))
    }

    /// The fields this kind is made of, or `None` for kinds that are not.
    ///
    /// A note and a file carry a body rather than fields; an unknown kind
    /// carries a shape this build has never seen.
    pub fn template(&self) -> Option<&'static Template> {
        TEMPLATES.iter().find(|template| &template.kind == self)
    }

    /// Whether items of this kind are records made of named fields.
    ///
    /// Asked instead of listing the kinds by name, so a new kind of record is
    /// a row in the template table and nothing else.
    pub fn is_record(&self) -> bool {
        self.template().is_some()
    }

    /// Every kind this build knows how to create.
    pub fn known() -> [Self; 8] {
        [
            Self::Note,
            Self::Login,
            Self::Card,
            Self::SshKey,
            Self::Wifi,
            Self::ApiToken,
            Self::Bank,
            Self::File,
        ]
    }
}

/// What [`ItemKind::Login`] was called up to 0.6.0.
///
/// Kept as a name to read, never one to write: a vault whose rows still say
/// `credential` opens, and so does an export from then, but everything sefy
/// writes from now on says `login`.
pub const LEGACY_LOGIN_NAME: &str = "credential";

impl std::fmt::Display for ItemKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The fields a kind of record is made of.
///
/// A template says what `sefy add` offers, what `sefy show` hides and what
/// order `sefy show` prints in. It does not constrain what a record may hold:
/// a field outside the template is kept and shown like any other, because a
/// store that drops what it was handed is worse than one that is untidy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Template {
    /// Kind this template describes.
    pub kind: ItemKind,
    /// Its fields, in the order they are meant to be read.
    pub fields: &'static [FieldSpec],
}

impl Template {
    /// Looks up one of the template's fields by name.
    pub fn field(&self, name: &str) -> Option<&FieldSpec> {
        self.fields.iter().find(|field| field.name == name)
    }

    /// The field `sefy get` takes when none was named.
    ///
    /// The first secret one: for a login that is the password, for a card the
    /// number, for an SSH key the private key. A kind whose fields are all
    /// public has no default — there is no obvious "the secret" to take.
    pub fn default_field(&self) -> Option<&FieldSpec> {
        self.fields.iter().find(|field| field.secret)
    }

    /// The fields `sefy fill` hands over, in the order a form asks for them.
    pub fn fill_order(&self) -> impl Iterator<Item = &FieldSpec> {
        self.fields.iter().filter(|field| field.fill)
    }
}

/// One field of a template: its name, what it is for, and whether it is secret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldSpec {
    /// Name the field is stored and addressed under.
    pub name: &'static str,
    /// What it holds, as shown in help text.
    pub description: &'static str,
    /// Whether its value is a secret: hidden by `sefy show`, prompted for
    /// rather than passed on the command line, and what `sefy get` copies.
    pub secret: bool,
    /// Whether `sefy fill` hands it over: something typed into a form when
    /// the record is used, as a login is and a note is not.
    pub fill: bool,
    /// What `sefy audit` holds its value to.
    pub audit: AuditAs,
}

impl FieldSpec {
    const fn new(
        name: &'static str,
        description: &'static str,
        secret: bool,
        fill: bool,
        audit: AuditAs,
    ) -> Self {
        Self {
            name,
            description,
            secret,
            fill,
            audit,
        }
    }
}

/// What a secret is, as far as an audit is concerned.
///
/// Said in the template rather than worked out from a field's name, so a new
/// kind of record is audited by adding its row and nothing else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditAs {
    /// A secret a person chose: it can be guessed, reused and left unchanged
    /// for years, and the audit looks for all three.
    Password,
    /// A secret someone issued: a card number, a token, a key. Nobody chose
    /// it, so it is not weak and not reused in the usual sense - but the same
    /// one in two items is almost always one thing recorded twice.
    Unique,
    /// Nothing to check: a public value, or a secret whose shape is its
    /// nature. Every PIN is four digits, and two cards sharing a CVV is
    /// chance.
    Nothing,
}

impl AuditAs {
    /// What a field of a record of `kind` is audited as.
    ///
    /// A field its kind's template lists is what the template says. One it
    /// does not list is what a field of that name is in the templates that
    /// do - a `password` added to a bank record is still a password - provided
    /// it is secret: a public value is nothing to audit, whatever its name.
    pub fn of(kind: &ItemKind, field: &Field) -> Self {
        if let Some(spec) = kind
            .template()
            .and_then(|template| template.field(&field.name))
        {
            return spec.audit;
        }
        if !field.secret {
            return Self::Nothing;
        }
        TEMPLATES
            .iter()
            .find_map(|template| template.field(&field.name))
            .map_or(Self::Nothing, |spec| spec.audit)
    }
}

/// Checks a value on its way into a field, for the fields whose value has a
/// shape, and returns what to store.
///
/// Two do. A one-time password key that cannot make a code is found out now,
/// while the site that issued it is still open, rather than at the next
/// sign-in. A date that cannot be counted from would leave an audit unable to
/// say when the record stops working - the one thing it was written down for.
pub fn normalize_value(name: &str, value: &str) -> crate::Result<String> {
    match name {
        crate::otp::FIELD => crate::otp::normalize(value),
        crate::expiry::FIELD => crate::expiry::normalize(value),
        _ => Ok(value.to_owned()),
    }
}

// Spelled out once, so a row of the table below reads as what it says.
const PUBLIC: bool = false;
const SECRET: bool = true;
const FILL: bool = true;
const KEEP: bool = false;
const CHOSEN: AuditAs = AuditAs::Password;
const ISSUED: AuditAs = AuditAs::Unique;
const UNCHECKED: AuditAs = AuditAs::Nothing;

/// Every kind that is made of fields, and what those fields are.
///
/// The order within a kind is the order `sefy show` prints, so it reads
/// top-down the way the record is thought about: who, then the secret, then
/// where.
static TEMPLATES: &[Template] = &[
    Template {
        kind: ItemKind::Login,
        fields: &[
            FieldSpec::new(
                "login",
                "username, email, or whatever the service calls it",
                PUBLIC,
                FILL,
                UNCHECKED,
            ),
            FieldSpec::new("password", "the secret itself", SECRET, FILL, CHOSEN),
            FieldSpec::new("url", "where the account lives", PUBLIC, KEEP, UNCHECKED),
            // Filled as the code it makes at that moment, never as itself.
            FieldSpec::new(
                crate::otp::FIELD,
                "key for one-time passwords",
                SECRET,
                FILL,
                ISSUED,
            ),
            FieldSpec::new(
                "notes",
                "anything else worth remembering",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
        ],
    },
    Template {
        kind: ItemKind::Card,
        fields: &[
            FieldSpec::new("number", "the card number", SECRET, FILL, ISSUED),
            FieldSpec::new(
                "holder",
                "name embossed on the card",
                PUBLIC,
                FILL,
                UNCHECKED,
            ),
            // Filled as printed, 03/29, which is what a payment form asks for.
            FieldSpec::new(
                crate::expiry::FIELD,
                "the month it runs out, as printed: 03/29",
                PUBLIC,
                FILL,
                UNCHECKED,
            ),
            FieldSpec::new(
                "cvv",
                "verification code on the back",
                SECRET,
                FILL,
                UNCHECKED,
            ),
            // Typed at a terminal, never into a form.
            FieldSpec::new("pin", "the PIN", SECRET, KEEP, UNCHECKED),
            FieldSpec::new(
                "notes",
                "bank, account, anything else",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
        ],
    },
    Template {
        kind: ItemKind::SshKey,
        fields: &[
            FieldSpec::new(
                "private-key",
                "the private key, as it appears in the file",
                SECRET,
                KEEP,
                ISSUED,
            ),
            FieldSpec::new(
                "passphrase",
                "passphrase protecting the private key",
                SECRET,
                FILL,
                CHOSEN,
            ),
            FieldSpec::new("public-key", "the public key", PUBLIC, KEEP, UNCHECKED),
            FieldSpec::new("host", "where the key is used", PUBLIC, KEEP, UNCHECKED),
            FieldSpec::new(
                "notes",
                "anything else worth remembering",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
        ],
    },
    Template {
        kind: ItemKind::Wifi,
        fields: &[
            FieldSpec::new("ssid", "the network's name", PUBLIC, FILL, UNCHECKED),
            FieldSpec::new("password", "the network key", SECRET, FILL, CHOSEN),
            FieldSpec::new("security", "WPA2, WPA3, open", PUBLIC, KEEP, UNCHECKED),
            FieldSpec::new("notes", "where it is, whose it is", PUBLIC, KEEP, UNCHECKED),
        ],
    },
    Template {
        kind: ItemKind::ApiToken,
        fields: &[
            FieldSpec::new("token", "the token itself", SECRET, FILL, ISSUED),
            FieldSpec::new(
                "url",
                "where it is issued and revoked",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
            FieldSpec::new(
                "scopes",
                "what it is allowed to do",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
            FieldSpec::new(
                crate::expiry::FIELD,
                "the last day it works: 2027-01-31",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
            FieldSpec::new("notes", "what uses it", PUBLIC, KEEP, UNCHECKED),
        ],
    },
    Template {
        kind: ItemKind::Bank,
        fields: &[
            FieldSpec::new("account", "account number or IBAN", SECRET, FILL, ISSUED),
            FieldSpec::new(
                "holder",
                "whose name the account is in",
                PUBLIC,
                FILL,
                UNCHECKED,
            ),
            FieldSpec::new("bank", "the bank", PUBLIC, FILL, UNCHECKED),
            FieldSpec::new(
                "routing",
                "SWIFT/BIC, routing or sort code",
                PUBLIC,
                FILL,
                UNCHECKED,
            ),
            FieldSpec::new(
                "notes",
                "branch, contact, anything else",
                PUBLIC,
                KEEP,
                UNCHECKED,
            ),
        ],
    },
];

/// One field of a stored record: a name, a value, and whether it is secret.
///
/// Secrecy travels with the value rather than being looked up in a template,
/// so a field the template never heard of is still hidden when it should be,
/// and a record written by another sefy keeps the secrecy it was written with.
#[derive(Debug, Clone, PartialEq, Eq, Zeroize)]
pub struct Field {
    /// What the field is called; unique within a record.
    pub name: String,
    /// What it holds.
    pub value: String,
    /// Whether the value must stay off the screen and out of listings.
    #[zeroize(skip)]
    pub secret: bool,
}

impl Field {
    /// A field holding something anyone may see.
    pub fn public(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            secret: false,
        }
    }

    /// A field holding a secret.
    pub fn secret(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            secret: true,
        }
    }
}

/// The payload of an item, in the shape its kind implies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Payload {
    /// Free-form text.
    Note {
        /// The text itself.
        text: String,
    },
    /// A record made of named fields: a login, a card, an SSH key.
    Fields {
        /// Which kind of record this is.
        kind: ItemKind,
        /// Its fields, in the order they are meant to be read.
        fields: Vec<Field>,
    },
    /// A stored file.
    File {
        /// Name the file had when it was added, used when extracting it.
        filename: String,
        /// File contents, kept byte for byte.
        bytes: Vec<u8>,
    },
    /// An item whose kind this build does not know.
    ///
    /// The contents stay in the vault untouched; there is nothing here because
    /// this build cannot say what shape they have. Carrying the name lets the
    /// item be listed and passed along without being understood.
    Unknown {
        /// The kind name the item was stored under.
        kind: String,
    },
}

impl Payload {
    /// A record of `kind` made of `fields`.
    pub fn fields(kind: ItemKind, fields: impl IntoIterator<Item = Field>) -> Self {
        Self::Fields {
            kind,
            fields: fields.into_iter().collect(),
        }
    }

    /// Kind matching this payload.
    pub fn kind(&self) -> ItemKind {
        match self {
            Self::Note { .. } => ItemKind::Note,
            Self::Fields { kind, .. } => kind.clone(),
            Self::File { .. } => ItemKind::File,
            Self::Unknown { kind } => ItemKind::Unknown(kind.clone()),
        }
    }

    /// Looks up one field of a record by name.
    pub fn field(&self, name: &str) -> Option<&Field> {
        match self {
            Self::Fields { fields, .. } => fields.iter().find(|field| field.name == name),
            _ => None,
        }
    }
}

impl Zeroize for Payload {
    fn zeroize(&mut self) {
        match self {
            Self::Note { text } => text.zeroize(),
            Self::Fields { fields, .. } => fields.zeroize(),
            Self::File { filename, bytes } => {
                filename.zeroize();
                bytes.zeroize();
            }
            // Nothing secret is held here — only the kind's name, which is not
            // a secret and is needed to describe the item.
            Self::Unknown { .. } => {}
        }
    }
}

/// An item without its payload: enough to list and search, cheap to load.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ItemSummary {
    /// Identifier within this vault. Assigned by the database, so the same item
    /// carries different ids in two vaults — use [`ItemSummary::uuid`] to
    /// recognise it across them.
    pub id: i64,
    /// Identity that survives leaving this vault: stable across machines,
    /// exports and imports, and what merging matches on.
    pub uuid: String,
    /// What the item is called.
    pub title: String,
    /// Kind of payload behind the summary.
    pub kind: ItemKind,
    /// Tags attached to the item, sorted.
    pub tags: Vec<String>,
    /// Creation time, seconds since the Unix epoch.
    pub created_at: i64,
    /// Time of the last change, seconds since the Unix epoch.
    pub updated_at: i64,
}

/// A complete item: its summary and its payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item {
    /// Listing fields.
    pub summary: ItemSummary,
    /// The secret material.
    pub payload: Payload,
}

/// A new item on its way into the vault.
#[derive(Debug, Clone)]
pub struct NewItem {
    /// What to call it.
    pub title: String,
    /// What it holds.
    pub payload: Payload,
    /// Tags to attach; duplicates and empty strings are ignored.
    pub tags: Vec<String>,
}

impl NewItem {
    /// Builds an item with a title and a payload, no tags.
    pub fn new(title: impl Into<String>, payload: Payload) -> Self {
        Self {
            title: title.into(),
            payload,
            tags: Vec::new(),
        }
    }

    /// Attaches tags to the item under construction.
    pub fn with_tags<I, S>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.tags = tags.into_iter().map(Into::into).collect();
        self
    }
}

/// Which items to return from a search.
#[derive(Debug, Clone, Default)]
pub struct Query {
    /// Case-insensitive substring matched against titles, note text and the
    /// non-secret fields of records. Secret values and file contents are never
    /// scanned.
    pub text: Option<String>,
    /// Keep only items of this kind.
    pub kind: Option<ItemKind>,
    /// Keep only items carrying every one of these tags.
    pub tags: Vec<String>,
}

impl Query {
    /// A query matching every item in the vault.
    pub fn all() -> Self {
        Self::default()
    }

    /// Restricts the query to items matching `text`.
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Restricts the query to one kind of item.
    pub fn kind(mut self, kind: ItemKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// Restricts the query to items carrying all of `tags`.
    pub fn tags<I, S>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.tags = tags.into_iter().map(Into::into).collect();
        self
    }
}

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

    #[test]
    fn kind_names_round_trip() {
        for kind in ItemKind::known() {
            assert_eq!(ItemKind::parse(kind.as_str()), kind);
        }
    }

    #[test]
    fn an_unheard_of_kind_keeps_its_name_instead_of_failing() {
        let kind = ItemKind::parse("passport");
        assert_eq!(kind, ItemKind::Unknown("passport".to_owned()));
        assert_eq!(kind.as_str(), "passport");
        assert!(!kind.is_known());
        // It survives a round trip like any other name.
        assert_eq!(ItemKind::parse(kind.as_str()), kind);
    }

    #[test]
    fn the_old_name_for_a_login_still_reads() {
        assert_eq!(ItemKind::parse(LEGACY_LOGIN_NAME), ItemKind::Login);
        // But it is never what sefy writes.
        assert_eq!(ItemKind::Login.as_str(), "login");
    }

    #[test]
    fn only_field_backed_kinds_have_a_template() {
        assert!(ItemKind::Login.template().is_some());
        assert!(ItemKind::Card.template().is_some());
        assert!(ItemKind::SshKey.template().is_some());
        assert!(ItemKind::Wifi.template().is_some());
        assert!(ItemKind::ApiToken.template().is_some());
        assert!(ItemKind::Bank.template().is_some());
        assert!(ItemKind::Note.template().is_none());
        assert!(ItemKind::File.template().is_none());
        assert!(
            ItemKind::Unknown("passport".to_owned())
                .template()
                .is_none()
        );
    }

    #[test]
    fn every_template_names_its_fields_uniquely() {
        for template in TEMPLATES {
            let mut seen: Vec<&str> = Vec::new();
            for field in template.fields {
                assert!(
                    !seen.contains(&field.name),
                    "{} names {} twice",
                    template.kind,
                    field.name
                );
                seen.push(field.name);
            }
        }
    }

    #[test]
    fn the_default_field_is_the_first_secret_one() {
        assert_eq!(
            ItemKind::Login
                .template()
                .unwrap()
                .default_field()
                .unwrap()
                .name,
            "password"
        );
        assert_eq!(
            ItemKind::Card
                .template()
                .unwrap()
                .default_field()
                .unwrap()
                .name,
            "number"
        );
        assert_eq!(
            ItemKind::SshKey
                .template()
                .unwrap()
                .default_field()
                .unwrap()
                .name,
            "private-key"
        );
    }

    #[test]
    fn every_kind_but_a_note_and_a_file_is_a_record_with_a_template_row() {
        for kind in ItemKind::known() {
            let expected = !matches!(kind, ItemKind::Note | ItemKind::File);
            assert_eq!(kind.is_record(), expected, "{kind}");
        }
        // And every row describes a kind this build knows.
        for template in TEMPLATES {
            assert!(
                ItemKind::known().contains(&template.kind),
                "{}",
                template.kind
            );
        }
    }

    #[test]
    fn a_one_time_password_key_is_secret_wherever_a_template_has_one() {
        for template in TEMPLATES {
            if let Some(field) = template.field(crate::otp::FIELD) {
                assert!(field.secret, "{} keeps its key in the open", template.kind);
            }
        }
    }

    #[test]
    fn a_field_name_is_audited_the_same_way_in_every_template() {
        // What lets a field outside its kind's template borrow the audit of a
        // field of the same name elsewhere: the answer has to be one answer.
        for template in TEMPLATES {
            for field in template.fields {
                for other in TEMPLATES {
                    if let Some(same) = other.field(field.name) {
                        assert_eq!(
                            same.audit, field.audit,
                            "{} in {} and {}",
                            field.name, template.kind, other.kind
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn only_a_secret_is_ever_audited() {
        for template in TEMPLATES {
            for field in template.fields {
                if !field.secret {
                    assert_eq!(field.audit, AuditAs::Nothing, "{}", field.name);
                }
            }
        }
    }

    #[test]
    fn a_field_outside_the_template_is_audited_as_its_name_is_elsewhere() {
        let bank = ItemKind::Bank;
        assert_eq!(
            AuditAs::of(&bank, &Field::secret("password", "p")),
            AuditAs::Password
        );
        assert_eq!(
            AuditAs::of(&bank, &Field::secret("token", "t")),
            AuditAs::Unique
        );
        // Public, it is not a secret to audit, whatever it is called.
        assert_eq!(
            AuditAs::of(&bank, &Field::public("password", "p")),
            AuditAs::Nothing
        );
        // A name no template has.
        assert_eq!(
            AuditAs::of(&bank, &Field::secret("recovery", "r")),
            AuditAs::Nothing
        );
        // Its own template answers first.
        assert_eq!(
            AuditAs::of(&ItemKind::Card, &Field::secret("pin", "1234")),
            AuditAs::Nothing
        );
    }

    #[test]
    fn a_value_with_a_shape_is_checked_and_stored_in_it() {
        assert_eq!(normalize_value("expires", "03/29").unwrap(), "2029-03");
        assert!(normalize_value("expires", "soon").is_err());
        assert_eq!(normalize_value("notes", " as is ").unwrap(), " as is ");
        assert!(normalize_value(crate::otp::FIELD, "not a key!").is_err());
    }

    #[test]
    fn a_login_fills_in_the_order_a_sign_in_form_asks() {
        let order: Vec<&str> = ItemKind::Login
            .template()
            .unwrap()
            .fill_order()
            .map(|field| field.name)
            .collect();
        assert_eq!(order, ["login", "password", crate::otp::FIELD]);
    }

    #[test]
    fn a_field_is_looked_up_by_name() {
        let payload = Payload::fields(
            ItemKind::Login,
            [
                Field::public("login", "ada"),
                Field::secret("password", "s"),
            ],
        );
        assert_eq!(payload.field("login").unwrap().value, "ada");
        assert!(payload.field("password").unwrap().secret);
        assert!(payload.field("url").is_none());
    }
}