keyroost 0.13.0

Desktop GUI for managing hardware security keys: FIDO2, OATH, OpenPGP, PIV, and Token2 programmable TOTP tokens.
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
// crates/keyroost/src/ui/device.rs
//
// View layer over the shared device model. The correlation/classification logic
// now lives in `keyroost-resolve` (consumed by the CLI too); here we keep only
// the GUI-specific capability-tab bar.
//
// Rows come from `keyroost_resolve::enumerate()`, the same matcher the CLI
// uses: USB topology, then the identity each side reports (#51,
// Windows/macOS), then the vendor fallback. On Linux topology settles every
// row, so the sidebar is unchanged there.

pub use keyroost_resolve::{enumerate, CapState, Caps, Device, DeviceId, DeviceKind};

/// Which capability pane is showing for the selected device.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CapTab {
    #[default]
    Overview,
    Fido2,
    Oath,
    Pgp,
    Piv,
    Otp,
}

/// The capability a tab manages, if it maps to one (`Overview` does not).
pub fn tab_cap(t: CapTab) -> Option<Caps> {
    match t {
        CapTab::Overview => None,
        CapTab::Fido2 => Some(Caps::FIDO2),
        CapTab::Oath => Some(Caps::OATH),
        CapTab::Pgp => Some(Caps::PGP),
        CapTab::Piv => Some(Caps::PIV),
        CapTab::Otp => Some(Caps::OTP),
    }
}

/// GUI view helpers on the shared [`Device`]. An extension trait because `Device`
/// is defined in another crate.
pub trait DeviceView {
    fn title(&self) -> &str;
    fn tabs(&self) -> Vec<CapTab>;
    /// True when the tab's capability is offered without device evidence
    /// ([`CapState::Unverified`]) — the tab still appears and works, it is
    /// only rendered with a quiet "not verified" affordance.
    fn tab_unverified(&self, t: CapTab) -> bool;
}

impl DeviceView for Device {
    fn title(&self) -> &str {
        self.name.as_deref().unwrap_or(&self.model)
    }

    fn tab_unverified(&self, t: CapTab) -> bool {
        tab_cap(t).is_some_and(|c| self.cap_state(c) == CapState::Unverified)
    }

    fn tabs(&self) -> Vec<CapTab> {
        if self.kind == DeviceKind::Token || self.kind == DeviceKind::ProgToken {
            return Vec::new();
        }
        let mut v = vec![CapTab::Overview];
        if self.caps.has(Caps::FIDO2) {
            v.push(CapTab::Fido2);
        }
        if self.caps.has(Caps::OATH) {
            v.push(CapTab::Oath);
        }
        if self.caps.has(Caps::PGP) {
            v.push(CapTab::Pgp);
        }
        if self.caps.has(Caps::PIV) {
            v.push(CapTab::Piv);
        }
        if self.caps.has(Caps::OTP) {
            v.push(CapTab::Otp);
        }
        v
    }
}

// --- Naming a key (#166) ---------------------------------------------------

use keyroost_resolve::{KeyLabel, NameSource, Naming};

/// Where the naming dialog saves a name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NameStoreChoice {
    /// This computer's keys.json.
    Computer,
    /// The key's own large-blob storage.
    Key,
}

/// The places the naming dialog offers for `d`: this computer always; the
/// key too when it is a FIDO2 key on USB whose scan found large-blob
/// storage (with or without a name in it; an unreadable name counts as
/// none).
pub fn store_choices(d: &Device) -> Vec<NameStoreChoice> {
    let mut v = vec![NameStoreChoice::Computer];
    let has_storage = matches!(
        d.naming.on_key,
        KeyLabel::Absent | KeyLabel::Present(_) | KeyLabel::Unreadable
    );
    if d.caps.has(Caps::FIDO2) && d.hid_path.is_some() && has_storage {
        v.push(NameStoreChoice::Key);
    }
    v
}

/// The place the dialog starts on: where the current name lives, else this
/// computer.
pub fn default_store(d: &Device) -> NameStoreChoice {
    if d.naming.source == Some(NameSource::Key) {
        NameStoreChoice::Key
    } else {
        NameStoreChoice::Computer
    }
}

/// Whether the scan found that `d` has no large-blob storage (the dialog
/// then says so instead of offering the key).
pub fn lacks_key_storage(d: &Device) -> bool {
    d.naming.on_key == KeyLabel::Unsupported
}

/// What saving the naming dialog does.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NameSave {
    /// The name is already what and where the dialog asks.
    Unchanged,
    /// Set (`Some`) or clear (`None`) the name on this computer.
    Local(Option<String>),
    /// Set or clear the name on the key, first asking `question` when it
    /// replaces or removes a name the key carries.
    OnKey {
        name: Option<String>,
        question: Option<String>,
    },
}

/// Why a rename can't go to this computer: the key carries its name.
pub const NAME_IS_ON_THE_KEY: &str =
    "This key's name is stored on the key. Rename it there, or clear the name first.";

/// Plan saving `input` (trimmed; empty clears the name wherever it lives)
/// to `choice` for a key named as `naming` says. Same rules as
/// `keyroostctl name set|clear`: a rename stays where the name is, and a
/// name on the key is never left there behind a new local one.
pub fn plan_name_save(
    naming: &Naming,
    choice: NameStoreChoice,
    input: &str,
) -> Result<NameSave, &'static str> {
    let on_key = match &naming.on_key {
        KeyLabel::Present(l) if naming.source == Some(NameSource::Key) => Some(l.as_str()),
        _ => None,
    };
    if input.is_empty() {
        return Ok(match on_key {
            Some(old) => NameSave::OnKey {
                name: None,
                question: Some(format!("Remove the name \"{old}\" stored on the key?")),
            },
            None => NameSave::Local(None),
        });
    }
    match (choice, on_key) {
        (NameStoreChoice::Computer, Some(_)) => Err(NAME_IS_ON_THE_KEY),
        (NameStoreChoice::Key, Some(old)) if old == input => Ok(NameSave::Unchanged),
        (NameStoreChoice::Key, old) => Ok(NameSave::OnKey {
            name: Some(input.to_string()),
            question: old.map(|old| {
                format!("Replace the name \"{old}\" stored on the key with \"{input}\"?")
            }),
        }),
        (NameStoreChoice::Computer, None) => {
            if naming.source == Some(NameSource::Computer) && naming.plain.as_deref() == Some(input)
            {
                Ok(NameSave::Unchanged)
            } else {
                Ok(NameSave::Local(Some(input.to_string())))
            }
        }
    }
}

/// The name to offer writing back onto `d`: one this computer recorded as
/// stored on the key, which the key no longer carries. `None` once the
/// person dismissed the offer, or when the key can't hold a name now.
pub fn write_back_offer(d: &Device, dismissed: bool) -> Option<&str> {
    if dismissed || !store_choices(d).contains(&NameStoreChoice::Key) {
        return None;
    }
    d.naming.missing_on_key.as_deref()
}

/// Whether this computer already records the key with `serials` as
/// carrying `name` on the key.
pub fn has_key_record(keyring: &keyroost_keyring::Keyring, serials: &[&str], name: &str) -> bool {
    serials.iter().any(|s| {
        keyring
            .records_for(s)
            .iter()
            .any(|r| r.name == name && r.stored == keyroost_keyring::NameStore::Key)
    })
}

/// The large-blob row text for the key's name entry. A name that fails the
/// name rules is never shown.
pub fn key_name_row_text(label: &str) -> String {
    if keyroost_keyring::validate_name(label).is_ok() {
        format!("key name: \"{label}\"")
    } else {
        "key name (not shown)".to_string()
    }
}

/// Whether "Keep the key's name" starts checked in the clear confirmation:
/// when the array carries a name.
pub fn keep_name_default(array: &keyroost_ctap::large_blobs::LargeBlobArray) -> bool {
    array.label().is_some()
}

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

    fn dev(fido: bool, hid: bool, on_key: KeyLabel) -> Device {
        let mut caps = Caps::default();
        if fido {
            caps.insert(Caps::FIDO2);
        }
        Device {
            id: "serial:12345678".into(),
            name: None,
            vendor: "Vendor".into(),
            model: "Model".into(),
            serial: "12345678".into(),
            transport: "USB".into(),
            firmware: String::new(),
            caps,
            unverified: Caps::default(),
            kind: DeviceKind::Key,
            hid_path: hid.then(|| "/dev/hidraw0".into()),
            reader: None,
            hid_serial: None,
            naming: Naming {
                on_key,
                ..Naming::default()
            },
        }
    }

    fn on_key(name: &str) -> Naming {
        Naming {
            plain: Some(name.into()),
            source: Some(NameSource::Key),
            selectable: true,
            on_key: KeyLabel::Present(name.into()),
            missing_on_key: None,
        }
    }

    use NameStoreChoice::{Computer, Key};

    #[test]
    fn store_choices_fido_with_large_blob_offers_both() {
        for l in [
            KeyLabel::Absent,
            KeyLabel::Present("Desk".into()),
            KeyLabel::Unreadable,
        ] {
            assert_eq!(store_choices(&dev(true, true, l)), vec![Computer, Key]);
        }
    }

    #[test]
    fn store_choices_fido_without_large_blob_is_this_computer_only() {
        let d = dev(true, true, KeyLabel::Unsupported);
        assert_eq!(store_choices(&d), vec![Computer]);
        assert!(lacks_key_storage(&d));
        // Not read (or no answer): nothing is known, so no key option and
        // no "can't store" line either.
        for l in [KeyLabel::NotRead, KeyLabel::ReadFailed] {
            let d = dev(true, true, l);
            assert_eq!(store_choices(&d), vec![Computer]);
            assert!(!lacks_key_storage(&d));
        }
    }

    #[test]
    fn store_choices_card_only_is_this_computer_only() {
        // FIDO over a reader, no HID path: the name can't be written there.
        let d = dev(true, false, KeyLabel::NotRead);
        assert_eq!(store_choices(&d), vec![Computer]);
        assert!(!lacks_key_storage(&d));
    }

    #[test]
    fn store_choices_molto2_is_this_computer_only() {
        let mut d = dev(false, false, KeyLabel::NotRead);
        d.kind = DeviceKind::Token;
        assert_eq!(store_choices(&d), vec![Computer]);
        assert!(!lacks_key_storage(&d));
    }

    #[test]
    fn default_store_follows_current_place() {
        let mut d = dev(true, true, KeyLabel::Absent);
        assert_eq!(default_store(&d), Computer);
        d.naming = Naming::local(Some("Desk"));
        assert_eq!(default_store(&d), Computer);
        d.naming = on_key("Desk");
        assert_eq!(default_store(&d), Key);
    }

    #[test]
    fn plan_name_save_follows_the_cli_rules() {
        let unnamed = Naming {
            on_key: KeyLabel::Absent,
            ..Naming::default()
        };
        let local = Naming::local(Some("Desk"));
        let key = on_key("Desk");
        // New names go where chosen.
        assert_eq!(
            plan_name_save(&unnamed, Computer, "A"),
            Ok(NameSave::Local(Some("A".into())))
        );
        assert_eq!(
            plan_name_save(&unnamed, Key, "A"),
            Ok(NameSave::OnKey {
                name: Some("A".into()),
                question: None
            })
        );
        // Moving a local name onto the key asks nothing (no name on the key).
        assert_eq!(
            plan_name_save(&local, Key, "Desk"),
            Ok(NameSave::OnKey {
                name: Some("Desk".into()),
                question: None
            })
        );
        assert_eq!(
            plan_name_save(&local, Computer, "Desk"),
            Ok(NameSave::Unchanged)
        );
        // A name on the key: rename there (asking), never behind a local one.
        assert_eq!(plan_name_save(&key, Key, "Desk"), Ok(NameSave::Unchanged));
        assert_eq!(
            plan_name_save(&key, Key, "Lab"),
            Ok(NameSave::OnKey {
                name: Some("Lab".into()),
                question: Some("Replace the name \"Desk\" stored on the key with \"Lab\"?".into())
            })
        );
        assert_eq!(
            plan_name_save(&key, Computer, "Lab"),
            Err(NAME_IS_ON_THE_KEY)
        );
        // Empty clears wherever the name lives, whatever is chosen.
        for c in [Computer, Key] {
            assert_eq!(
                plan_name_save(&key, c, ""),
                Ok(NameSave::OnKey {
                    name: None,
                    question: Some("Remove the name \"Desk\" stored on the key?".into())
                })
            );
            assert_eq!(plan_name_save(&local, c, ""), Ok(NameSave::Local(None)));
        }
        // An unreadable name on the key counts as no name.
        let unreadable = Naming {
            on_key: KeyLabel::Unreadable,
            ..Naming::default()
        };
        assert_eq!(
            plan_name_save(&unreadable, Key, "A"),
            Ok(NameSave::OnKey {
                name: Some("A".into()),
                question: None
            })
        );
    }

    #[test]
    fn write_back_offer_needs_a_missing_name_and_storage() {
        let mut d = dev(true, true, KeyLabel::Absent);
        assert_eq!(write_back_offer(&d, false), None);
        d.naming.missing_on_key = Some("Desk".into());
        assert_eq!(write_back_offer(&d, false), Some("Desk"));
        assert_eq!(write_back_offer(&d, true), None, "dismissed");
        d.naming.on_key = KeyLabel::ReadFailed;
        assert_eq!(write_back_offer(&d, false), None, "storage not known");
        let mut card = dev(true, false, KeyLabel::Absent);
        card.naming.missing_on_key = Some("Desk".into());
        assert_eq!(write_back_offer(&card, false), None, "no HID path");
    }

    #[test]
    fn has_key_record_needs_this_keys_on_key_record_of_that_name() {
        use keyroost_keyring::{Keyring, NameStore, RecordMeta};
        let mut k = Keyring::default();
        let serials = ["12345678", "ABCDEF01"];
        assert!(!has_key_record(&k, &serials, "Desk"));
        k.set_name(
            "ABCDEF01",
            "Desk",
            NameStore::Computer,
            RecordMeta::default(),
        )
        .unwrap();
        assert!(!has_key_record(&k, &serials, "Desk"), "a computer record");
        k.set_name("ABCDEF01", "Desk", NameStore::Key, RecordMeta::default())
            .unwrap();
        assert!(has_key_record(&k, &serials, "Desk"), "under the HID serial");
        assert!(!has_key_record(&k, &serials, "Lab"));
        assert!(!has_key_record(&k, &["99999999"], "Desk"), "another key");
    }

    #[test]
    fn key_name_row_text_hides_names_that_fail_the_rules() {
        assert_eq!(key_name_row_text("Desk"), "key name: \"Desk\"");
        assert_eq!(key_name_row_text("a\u{202E}b"), "key name (not shown)");
    }

    #[test]
    fn keep_name_defaults_on_only_with_a_name() {
        use keyroost_ctap::device_label::DeviceLabel;
        use keyroost_ctap::large_blobs::LargeBlobArray;
        let empty = LargeBlobArray::parse(&[0x80]).unwrap();
        assert!(!keep_name_default(&empty));
        let named = empty
            .with_label(
                Some(&DeviceLabel {
                    label: "Desk".into(),
                    writer: None,
                }),
                [0; 12],
            )
            .unwrap();
        assert!(keep_name_default(&named));
    }
}