Skip to main content

sefy_core/
model.rs

1//! What a vault holds: notes, structured records and file attachments, each
2//! tagged.
3//!
4//! Everything but a note and a file is a **set of named fields**. A login, a
5//! payment card and an SSH key differ in which fields they carry and which of
6//! those are secret — not in how they are stored. That is why adding a kind
7//! costs a template rather than a table, a payload variant and a new set of
8//! flags each time.
9
10use zeroize::Zeroize;
11
12/// Kind of payload an item carries.
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub enum ItemKind {
15    /// Free-form text.
16    Note,
17    /// An account: who you are, the secret, and where it is used.
18    Login,
19    /// A payment card.
20    Card,
21    /// An SSH key pair and its passphrase.
22    SshKey,
23    /// A wireless network and how to join it.
24    Wifi,
25    /// A token for an API: the kind of secret a program presents, not a person.
26    ApiToken,
27    /// A bank account.
28    Bank,
29    /// Arbitrary bytes kept verbatim.
30    File,
31    /// A kind this build does not know, carrying the name it was stored under.
32    ///
33    /// Vaults travel between machines, and the two ends need not run the same
34    /// version. An item written by a newer sefy therefore has to be *something*
35    /// here rather than a parse failure: refusing it would take down every
36    /// listing, export and merge in a vault that is otherwise perfectly
37    /// readable — which is exactly what 0.5.0 and earlier did.
38    ///
39    /// Such an item can be listed, searched, exported and merged, but not read
40    /// or edited: this build does not know the shape behind the name and will
41    /// not guess at it.
42    Unknown(String),
43}
44
45impl ItemKind {
46    /// Stable identifier used in the database and on the command line.
47    pub fn as_str(&self) -> &str {
48        match self {
49            Self::Note => "note",
50            Self::Login => "login",
51            Self::Card => "card",
52            Self::SshKey => "ssh-key",
53            Self::Wifi => "wifi",
54            Self::ApiToken => "api-token",
55            Self::Bank => "bank",
56            Self::File => "file",
57            Self::Unknown(name) => name,
58        }
59    }
60
61    /// Reads the identifier produced by [`ItemKind::as_str`].
62    ///
63    /// Never fails: an unrecognized name becomes [`ItemKind::Unknown`], because
64    /// a name this build has not heard of is a fact about this build, not a
65    /// broken vault.
66    ///
67    /// `credential` is accepted as a spelling of [`ItemKind::Login`]: that is
68    /// what the kind was called up to 0.6.0, and vaults, exports and scripts
69    /// written then are still in use.
70    pub fn parse(value: &str) -> Self {
71        match value {
72            "note" => Self::Note,
73            "login" | LEGACY_LOGIN_NAME => Self::Login,
74            "card" => Self::Card,
75            "ssh-key" => Self::SshKey,
76            "wifi" => Self::Wifi,
77            "api-token" => Self::ApiToken,
78            "bank" => Self::Bank,
79            "file" => Self::File,
80            other => Self::Unknown(other.to_owned()),
81        }
82    }
83
84    /// Whether this build understands the payload behind the name.
85    pub fn is_known(&self) -> bool {
86        !matches!(self, Self::Unknown(_))
87    }
88
89    /// The fields this kind is made of, or `None` for kinds that are not.
90    ///
91    /// A note and a file carry a body rather than fields; an unknown kind
92    /// carries a shape this build has never seen.
93    pub fn template(&self) -> Option<&'static Template> {
94        TEMPLATES.iter().find(|template| &template.kind == self)
95    }
96
97    /// Whether items of this kind are records made of named fields.
98    ///
99    /// Asked instead of listing the kinds by name, so a new kind of record is
100    /// a row in the template table and nothing else.
101    pub fn is_record(&self) -> bool {
102        self.template().is_some()
103    }
104
105    /// Every kind this build knows how to create.
106    pub fn known() -> [Self; 8] {
107        [
108            Self::Note,
109            Self::Login,
110            Self::Card,
111            Self::SshKey,
112            Self::Wifi,
113            Self::ApiToken,
114            Self::Bank,
115            Self::File,
116        ]
117    }
118}
119
120/// What [`ItemKind::Login`] was called up to 0.6.0.
121///
122/// Kept as a name to read, never one to write: a vault whose rows still say
123/// `credential` opens, and so does an export from then, but everything sefy
124/// writes from now on says `login`.
125pub const LEGACY_LOGIN_NAME: &str = "credential";
126
127impl std::fmt::Display for ItemKind {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        f.write_str(self.as_str())
130    }
131}
132
133/// The fields a kind of record is made of.
134///
135/// A template says what `sefy add` offers, what `sefy show` hides and what
136/// order `sefy show` prints in. It does not constrain what a record may hold:
137/// a field outside the template is kept and shown like any other, because a
138/// store that drops what it was handed is worse than one that is untidy.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Template {
141    /// Kind this template describes.
142    pub kind: ItemKind,
143    /// Its fields, in the order they are meant to be read.
144    pub fields: &'static [FieldSpec],
145}
146
147impl Template {
148    /// Looks up one of the template's fields by name.
149    pub fn field(&self, name: &str) -> Option<&FieldSpec> {
150        self.fields.iter().find(|field| field.name == name)
151    }
152
153    /// The field `sefy get` takes when none was named.
154    ///
155    /// The first secret one: for a login that is the password, for a card the
156    /// number, for an SSH key the private key. A kind whose fields are all
157    /// public has no default — there is no obvious "the secret" to take.
158    pub fn default_field(&self) -> Option<&FieldSpec> {
159        self.fields.iter().find(|field| field.secret)
160    }
161
162    /// The fields `sefy fill` hands over, in the order a form asks for them.
163    pub fn fill_order(&self) -> impl Iterator<Item = &FieldSpec> {
164        self.fields.iter().filter(|field| field.fill)
165    }
166}
167
168/// One field of a template: its name, what it is for, and whether it is secret.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct FieldSpec {
171    /// Name the field is stored and addressed under.
172    pub name: &'static str,
173    /// What it holds, as shown in help text.
174    pub description: &'static str,
175    /// Whether its value is a secret: hidden by `sefy show`, prompted for
176    /// rather than passed on the command line, and what `sefy get` copies.
177    pub secret: bool,
178    /// Whether `sefy fill` hands it over: something typed into a form when
179    /// the record is used, as a login is and a note is not.
180    pub fill: bool,
181    /// What `sefy audit` holds its value to.
182    pub audit: AuditAs,
183}
184
185impl FieldSpec {
186    const fn new(
187        name: &'static str,
188        description: &'static str,
189        secret: bool,
190        fill: bool,
191        audit: AuditAs,
192    ) -> Self {
193        Self {
194            name,
195            description,
196            secret,
197            fill,
198            audit,
199        }
200    }
201}
202
203/// What a secret is, as far as an audit is concerned.
204///
205/// Said in the template rather than worked out from a field's name, so a new
206/// kind of record is audited by adding its row and nothing else.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum AuditAs {
209    /// A secret a person chose: it can be guessed, reused and left unchanged
210    /// for years, and the audit looks for all three.
211    Password,
212    /// A secret someone issued: a card number, a token, a key. Nobody chose
213    /// it, so it is not weak and not reused in the usual sense - but the same
214    /// one in two items is almost always one thing recorded twice.
215    Unique,
216    /// Nothing to check: a public value, or a secret whose shape is its
217    /// nature. Every PIN is four digits, and two cards sharing a CVV is
218    /// chance.
219    Nothing,
220}
221
222impl AuditAs {
223    /// What a field of a record of `kind` is audited as.
224    ///
225    /// A field its kind's template lists is what the template says. One it
226    /// does not list is what a field of that name is in the templates that
227    /// do - a `password` added to a bank record is still a password - provided
228    /// it is secret: a public value is nothing to audit, whatever its name.
229    pub fn of(kind: &ItemKind, field: &Field) -> Self {
230        if let Some(spec) = kind
231            .template()
232            .and_then(|template| template.field(&field.name))
233        {
234            return spec.audit;
235        }
236        if !field.secret {
237            return Self::Nothing;
238        }
239        TEMPLATES
240            .iter()
241            .find_map(|template| template.field(&field.name))
242            .map_or(Self::Nothing, |spec| spec.audit)
243    }
244}
245
246/// Checks a value on its way into a field, for the fields whose value has a
247/// shape, and returns what to store.
248///
249/// Two do. A one-time password key that cannot make a code is found out now,
250/// while the site that issued it is still open, rather than at the next
251/// sign-in. A date that cannot be counted from would leave an audit unable to
252/// say when the record stops working - the one thing it was written down for.
253pub fn normalize_value(name: &str, value: &str) -> crate::Result<String> {
254    match name {
255        crate::otp::FIELD => crate::otp::normalize(value),
256        crate::expiry::FIELD => crate::expiry::normalize(value),
257        _ => Ok(value.to_owned()),
258    }
259}
260
261// Spelled out once, so a row of the table below reads as what it says.
262const PUBLIC: bool = false;
263const SECRET: bool = true;
264const FILL: bool = true;
265const KEEP: bool = false;
266const CHOSEN: AuditAs = AuditAs::Password;
267const ISSUED: AuditAs = AuditAs::Unique;
268const UNCHECKED: AuditAs = AuditAs::Nothing;
269
270/// Every kind that is made of fields, and what those fields are.
271///
272/// The order within a kind is the order `sefy show` prints, so it reads
273/// top-down the way the record is thought about: who, then the secret, then
274/// where.
275static TEMPLATES: &[Template] = &[
276    Template {
277        kind: ItemKind::Login,
278        fields: &[
279            FieldSpec::new(
280                "login",
281                "username, email, or whatever the service calls it",
282                PUBLIC,
283                FILL,
284                UNCHECKED,
285            ),
286            FieldSpec::new("password", "the secret itself", SECRET, FILL, CHOSEN),
287            FieldSpec::new("url", "where the account lives", PUBLIC, KEEP, UNCHECKED),
288            // Filled as the code it makes at that moment, never as itself.
289            FieldSpec::new(
290                crate::otp::FIELD,
291                "key for one-time passwords",
292                SECRET,
293                FILL,
294                ISSUED,
295            ),
296            FieldSpec::new(
297                "notes",
298                "anything else worth remembering",
299                PUBLIC,
300                KEEP,
301                UNCHECKED,
302            ),
303        ],
304    },
305    Template {
306        kind: ItemKind::Card,
307        fields: &[
308            FieldSpec::new("number", "the card number", SECRET, FILL, ISSUED),
309            FieldSpec::new(
310                "holder",
311                "name embossed on the card",
312                PUBLIC,
313                FILL,
314                UNCHECKED,
315            ),
316            // Filled as printed, 03/29, which is what a payment form asks for.
317            FieldSpec::new(
318                crate::expiry::FIELD,
319                "the month it runs out, as printed: 03/29",
320                PUBLIC,
321                FILL,
322                UNCHECKED,
323            ),
324            FieldSpec::new(
325                "cvv",
326                "verification code on the back",
327                SECRET,
328                FILL,
329                UNCHECKED,
330            ),
331            // Typed at a terminal, never into a form.
332            FieldSpec::new("pin", "the PIN", SECRET, KEEP, UNCHECKED),
333            FieldSpec::new(
334                "notes",
335                "bank, account, anything else",
336                PUBLIC,
337                KEEP,
338                UNCHECKED,
339            ),
340        ],
341    },
342    Template {
343        kind: ItemKind::SshKey,
344        fields: &[
345            FieldSpec::new(
346                "private-key",
347                "the private key, as it appears in the file",
348                SECRET,
349                KEEP,
350                ISSUED,
351            ),
352            FieldSpec::new(
353                "passphrase",
354                "passphrase protecting the private key",
355                SECRET,
356                FILL,
357                CHOSEN,
358            ),
359            FieldSpec::new("public-key", "the public key", PUBLIC, KEEP, UNCHECKED),
360            FieldSpec::new("host", "where the key is used", PUBLIC, KEEP, UNCHECKED),
361            FieldSpec::new(
362                "notes",
363                "anything else worth remembering",
364                PUBLIC,
365                KEEP,
366                UNCHECKED,
367            ),
368        ],
369    },
370    Template {
371        kind: ItemKind::Wifi,
372        fields: &[
373            FieldSpec::new("ssid", "the network's name", PUBLIC, FILL, UNCHECKED),
374            FieldSpec::new("password", "the network key", SECRET, FILL, CHOSEN),
375            FieldSpec::new("security", "WPA2, WPA3, open", PUBLIC, KEEP, UNCHECKED),
376            FieldSpec::new("notes", "where it is, whose it is", PUBLIC, KEEP, UNCHECKED),
377        ],
378    },
379    Template {
380        kind: ItemKind::ApiToken,
381        fields: &[
382            FieldSpec::new("token", "the token itself", SECRET, FILL, ISSUED),
383            FieldSpec::new(
384                "url",
385                "where it is issued and revoked",
386                PUBLIC,
387                KEEP,
388                UNCHECKED,
389            ),
390            FieldSpec::new(
391                "scopes",
392                "what it is allowed to do",
393                PUBLIC,
394                KEEP,
395                UNCHECKED,
396            ),
397            FieldSpec::new(
398                crate::expiry::FIELD,
399                "the last day it works: 2027-01-31",
400                PUBLIC,
401                KEEP,
402                UNCHECKED,
403            ),
404            FieldSpec::new("notes", "what uses it", PUBLIC, KEEP, UNCHECKED),
405        ],
406    },
407    Template {
408        kind: ItemKind::Bank,
409        fields: &[
410            FieldSpec::new("account", "account number or IBAN", SECRET, FILL, ISSUED),
411            FieldSpec::new(
412                "holder",
413                "whose name the account is in",
414                PUBLIC,
415                FILL,
416                UNCHECKED,
417            ),
418            FieldSpec::new("bank", "the bank", PUBLIC, FILL, UNCHECKED),
419            FieldSpec::new(
420                "routing",
421                "SWIFT/BIC, routing or sort code",
422                PUBLIC,
423                FILL,
424                UNCHECKED,
425            ),
426            FieldSpec::new(
427                "notes",
428                "branch, contact, anything else",
429                PUBLIC,
430                KEEP,
431                UNCHECKED,
432            ),
433        ],
434    },
435];
436
437/// One field of a stored record: a name, a value, and whether it is secret.
438///
439/// Secrecy travels with the value rather than being looked up in a template,
440/// so a field the template never heard of is still hidden when it should be,
441/// and a record written by another sefy keeps the secrecy it was written with.
442#[derive(Debug, Clone, PartialEq, Eq, Zeroize)]
443pub struct Field {
444    /// What the field is called; unique within a record.
445    pub name: String,
446    /// What it holds.
447    pub value: String,
448    /// Whether the value must stay off the screen and out of listings.
449    #[zeroize(skip)]
450    pub secret: bool,
451}
452
453impl Field {
454    /// A field holding something anyone may see.
455    pub fn public(name: impl Into<String>, value: impl Into<String>) -> Self {
456        Self {
457            name: name.into(),
458            value: value.into(),
459            secret: false,
460        }
461    }
462
463    /// A field holding a secret.
464    pub fn secret(name: impl Into<String>, value: impl Into<String>) -> Self {
465        Self {
466            name: name.into(),
467            value: value.into(),
468            secret: true,
469        }
470    }
471}
472
473/// The payload of an item, in the shape its kind implies.
474#[derive(Debug, Clone, PartialEq, Eq)]
475pub enum Payload {
476    /// Free-form text.
477    Note {
478        /// The text itself.
479        text: String,
480    },
481    /// A record made of named fields: a login, a card, an SSH key.
482    Fields {
483        /// Which kind of record this is.
484        kind: ItemKind,
485        /// Its fields, in the order they are meant to be read.
486        fields: Vec<Field>,
487    },
488    /// A stored file.
489    File {
490        /// Name the file had when it was added, used when extracting it.
491        filename: String,
492        /// File contents, kept byte for byte.
493        bytes: Vec<u8>,
494    },
495    /// An item whose kind this build does not know.
496    ///
497    /// The contents stay in the vault untouched; there is nothing here because
498    /// this build cannot say what shape they have. Carrying the name lets the
499    /// item be listed and passed along without being understood.
500    Unknown {
501        /// The kind name the item was stored under.
502        kind: String,
503    },
504}
505
506impl Payload {
507    /// A record of `kind` made of `fields`.
508    pub fn fields(kind: ItemKind, fields: impl IntoIterator<Item = Field>) -> Self {
509        Self::Fields {
510            kind,
511            fields: fields.into_iter().collect(),
512        }
513    }
514
515    /// Kind matching this payload.
516    pub fn kind(&self) -> ItemKind {
517        match self {
518            Self::Note { .. } => ItemKind::Note,
519            Self::Fields { kind, .. } => kind.clone(),
520            Self::File { .. } => ItemKind::File,
521            Self::Unknown { kind } => ItemKind::Unknown(kind.clone()),
522        }
523    }
524
525    /// Looks up one field of a record by name.
526    pub fn field(&self, name: &str) -> Option<&Field> {
527        match self {
528            Self::Fields { fields, .. } => fields.iter().find(|field| field.name == name),
529            _ => None,
530        }
531    }
532}
533
534impl Zeroize for Payload {
535    fn zeroize(&mut self) {
536        match self {
537            Self::Note { text } => text.zeroize(),
538            Self::Fields { fields, .. } => fields.zeroize(),
539            Self::File { filename, bytes } => {
540                filename.zeroize();
541                bytes.zeroize();
542            }
543            // Nothing secret is held here — only the kind's name, which is not
544            // a secret and is needed to describe the item.
545            Self::Unknown { .. } => {}
546        }
547    }
548}
549
550/// An item without its payload: enough to list and search, cheap to load.
551#[derive(Debug, Clone, PartialEq, Eq)]
552pub struct ItemSummary {
553    /// Identifier within this vault. Assigned by the database, so the same item
554    /// carries different ids in two vaults — use [`ItemSummary::uuid`] to
555    /// recognise it across them.
556    pub id: i64,
557    /// Identity that survives leaving this vault: stable across machines,
558    /// exports and imports, and what merging matches on.
559    pub uuid: String,
560    /// What the item is called.
561    pub title: String,
562    /// Kind of payload behind the summary.
563    pub kind: ItemKind,
564    /// Tags attached to the item, sorted.
565    pub tags: Vec<String>,
566    /// Creation time, seconds since the Unix epoch.
567    pub created_at: i64,
568    /// Time of the last change, seconds since the Unix epoch.
569    pub updated_at: i64,
570}
571
572/// A complete item: its summary and its payload.
573#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct Item {
575    /// Listing fields.
576    pub summary: ItemSummary,
577    /// The secret material.
578    pub payload: Payload,
579}
580
581/// A new item on its way into the vault.
582#[derive(Debug, Clone)]
583pub struct NewItem {
584    /// What to call it.
585    pub title: String,
586    /// What it holds.
587    pub payload: Payload,
588    /// Tags to attach; duplicates and empty strings are ignored.
589    pub tags: Vec<String>,
590}
591
592impl NewItem {
593    /// Builds an item with a title and a payload, no tags.
594    pub fn new(title: impl Into<String>, payload: Payload) -> Self {
595        Self {
596            title: title.into(),
597            payload,
598            tags: Vec::new(),
599        }
600    }
601
602    /// Attaches tags to the item under construction.
603    pub fn with_tags<I, S>(mut self, tags: I) -> Self
604    where
605        I: IntoIterator<Item = S>,
606        S: Into<String>,
607    {
608        self.tags = tags.into_iter().map(Into::into).collect();
609        self
610    }
611}
612
613/// Which items to return from a search.
614#[derive(Debug, Clone, Default)]
615pub struct Query {
616    /// Case-insensitive substring matched against titles, note text and the
617    /// non-secret fields of records. Secret values and file contents are never
618    /// scanned.
619    pub text: Option<String>,
620    /// Keep only items of this kind.
621    pub kind: Option<ItemKind>,
622    /// Keep only items carrying every one of these tags.
623    pub tags: Vec<String>,
624}
625
626impl Query {
627    /// A query matching every item in the vault.
628    pub fn all() -> Self {
629        Self::default()
630    }
631
632    /// Restricts the query to items matching `text`.
633    pub fn text(mut self, text: impl Into<String>) -> Self {
634        self.text = Some(text.into());
635        self
636    }
637
638    /// Restricts the query to one kind of item.
639    pub fn kind(mut self, kind: ItemKind) -> Self {
640        self.kind = Some(kind);
641        self
642    }
643
644    /// Restricts the query to items carrying all of `tags`.
645    pub fn tags<I, S>(mut self, tags: I) -> Self
646    where
647        I: IntoIterator<Item = S>,
648        S: Into<String>,
649    {
650        self.tags = tags.into_iter().map(Into::into).collect();
651        self
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    #[test]
660    fn kind_names_round_trip() {
661        for kind in ItemKind::known() {
662            assert_eq!(ItemKind::parse(kind.as_str()), kind);
663        }
664    }
665
666    #[test]
667    fn an_unheard_of_kind_keeps_its_name_instead_of_failing() {
668        let kind = ItemKind::parse("passport");
669        assert_eq!(kind, ItemKind::Unknown("passport".to_owned()));
670        assert_eq!(kind.as_str(), "passport");
671        assert!(!kind.is_known());
672        // It survives a round trip like any other name.
673        assert_eq!(ItemKind::parse(kind.as_str()), kind);
674    }
675
676    #[test]
677    fn the_old_name_for_a_login_still_reads() {
678        assert_eq!(ItemKind::parse(LEGACY_LOGIN_NAME), ItemKind::Login);
679        // But it is never what sefy writes.
680        assert_eq!(ItemKind::Login.as_str(), "login");
681    }
682
683    #[test]
684    fn only_field_backed_kinds_have_a_template() {
685        assert!(ItemKind::Login.template().is_some());
686        assert!(ItemKind::Card.template().is_some());
687        assert!(ItemKind::SshKey.template().is_some());
688        assert!(ItemKind::Wifi.template().is_some());
689        assert!(ItemKind::ApiToken.template().is_some());
690        assert!(ItemKind::Bank.template().is_some());
691        assert!(ItemKind::Note.template().is_none());
692        assert!(ItemKind::File.template().is_none());
693        assert!(
694            ItemKind::Unknown("passport".to_owned())
695                .template()
696                .is_none()
697        );
698    }
699
700    #[test]
701    fn every_template_names_its_fields_uniquely() {
702        for template in TEMPLATES {
703            let mut seen: Vec<&str> = Vec::new();
704            for field in template.fields {
705                assert!(
706                    !seen.contains(&field.name),
707                    "{} names {} twice",
708                    template.kind,
709                    field.name
710                );
711                seen.push(field.name);
712            }
713        }
714    }
715
716    #[test]
717    fn the_default_field_is_the_first_secret_one() {
718        assert_eq!(
719            ItemKind::Login
720                .template()
721                .unwrap()
722                .default_field()
723                .unwrap()
724                .name,
725            "password"
726        );
727        assert_eq!(
728            ItemKind::Card
729                .template()
730                .unwrap()
731                .default_field()
732                .unwrap()
733                .name,
734            "number"
735        );
736        assert_eq!(
737            ItemKind::SshKey
738                .template()
739                .unwrap()
740                .default_field()
741                .unwrap()
742                .name,
743            "private-key"
744        );
745    }
746
747    #[test]
748    fn every_kind_but_a_note_and_a_file_is_a_record_with_a_template_row() {
749        for kind in ItemKind::known() {
750            let expected = !matches!(kind, ItemKind::Note | ItemKind::File);
751            assert_eq!(kind.is_record(), expected, "{kind}");
752        }
753        // And every row describes a kind this build knows.
754        for template in TEMPLATES {
755            assert!(
756                ItemKind::known().contains(&template.kind),
757                "{}",
758                template.kind
759            );
760        }
761    }
762
763    #[test]
764    fn a_one_time_password_key_is_secret_wherever_a_template_has_one() {
765        for template in TEMPLATES {
766            if let Some(field) = template.field(crate::otp::FIELD) {
767                assert!(field.secret, "{} keeps its key in the open", template.kind);
768            }
769        }
770    }
771
772    #[test]
773    fn a_field_name_is_audited_the_same_way_in_every_template() {
774        // What lets a field outside its kind's template borrow the audit of a
775        // field of the same name elsewhere: the answer has to be one answer.
776        for template in TEMPLATES {
777            for field in template.fields {
778                for other in TEMPLATES {
779                    if let Some(same) = other.field(field.name) {
780                        assert_eq!(
781                            same.audit, field.audit,
782                            "{} in {} and {}",
783                            field.name, template.kind, other.kind
784                        );
785                    }
786                }
787            }
788        }
789    }
790
791    #[test]
792    fn only_a_secret_is_ever_audited() {
793        for template in TEMPLATES {
794            for field in template.fields {
795                if !field.secret {
796                    assert_eq!(field.audit, AuditAs::Nothing, "{}", field.name);
797                }
798            }
799        }
800    }
801
802    #[test]
803    fn a_field_outside_the_template_is_audited_as_its_name_is_elsewhere() {
804        let bank = ItemKind::Bank;
805        assert_eq!(
806            AuditAs::of(&bank, &Field::secret("password", "p")),
807            AuditAs::Password
808        );
809        assert_eq!(
810            AuditAs::of(&bank, &Field::secret("token", "t")),
811            AuditAs::Unique
812        );
813        // Public, it is not a secret to audit, whatever it is called.
814        assert_eq!(
815            AuditAs::of(&bank, &Field::public("password", "p")),
816            AuditAs::Nothing
817        );
818        // A name no template has.
819        assert_eq!(
820            AuditAs::of(&bank, &Field::secret("recovery", "r")),
821            AuditAs::Nothing
822        );
823        // Its own template answers first.
824        assert_eq!(
825            AuditAs::of(&ItemKind::Card, &Field::secret("pin", "1234")),
826            AuditAs::Nothing
827        );
828    }
829
830    #[test]
831    fn a_value_with_a_shape_is_checked_and_stored_in_it() {
832        assert_eq!(normalize_value("expires", "03/29").unwrap(), "2029-03");
833        assert!(normalize_value("expires", "soon").is_err());
834        assert_eq!(normalize_value("notes", " as is ").unwrap(), " as is ");
835        assert!(normalize_value(crate::otp::FIELD, "not a key!").is_err());
836    }
837
838    #[test]
839    fn a_login_fills_in_the_order_a_sign_in_form_asks() {
840        let order: Vec<&str> = ItemKind::Login
841            .template()
842            .unwrap()
843            .fill_order()
844            .map(|field| field.name)
845            .collect();
846        assert_eq!(order, ["login", "password", crate::otp::FIELD]);
847    }
848
849    #[test]
850    fn a_field_is_looked_up_by_name() {
851        let payload = Payload::fields(
852            ItemKind::Login,
853            [
854                Field::public("login", "ada"),
855                Field::secret("password", "s"),
856            ],
857        );
858        assert_eq!(payload.field("login").unwrap().value, "ada");
859        assert!(payload.field("password").unwrap().secret);
860        assert!(payload.field("url").is_none());
861    }
862}