keyroost-keyring 0.5.1

Friendly-name registry and device-identity resolution for security keys.
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
//! Friendly-name registry for security keys, plus device-identity resolution.
//!
//! Lets a user attach a memorable label (e.g. `signing-yubikey`) to a physical
//! key, matched by its stable **serial number**, so commands can target a key
//! by `--name` instead of a `/dev/hidrawN` path that changes on every replug.
//!
//! This crate is pure config + matching logic: it has no hardware or PC/SC
//! dependencies and never enumerates devices itself. The caller supplies the
//! list of connected devices (as [`ConnectedKey`]) — for the CLI that's the
//! HID enumeration plus, for keys without a USB serial, a CCID-read serial.
//! Front-end concerns (interactive pickers, TTY handling, confirmations) live
//! in the caller, so both the CLI and the GUI reuse this same core.
//!
//! ## Privacy
//!
//! Persisting a key's serial to disk is **opt-in**: nothing is written unless
//! the caller explicitly invokes [`Keyring::save_to`] / [`Keyring::save_default`]
//! (i.e. the user ran an "add a name" action). Loading and in-memory matching
//! record nothing.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

/// How a key's serial is obtained — recorded for display/diagnostics. Matching
/// is always by serial-string equality regardless of source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum IdSource {
    /// USB `iSerialNumber` (read from sysfs; SoloKeys, Nitrokey, …).
    #[default]
    Usb,
    /// Serial read from a vendor management applet over CCID (e.g. YubiKey).
    Ccid,
}

/// One named key in the registry. `serial` is the match key; `name` is the
/// unique user-facing label.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyEntry {
    pub name: String,
    pub serial: String,
    #[serde(default)]
    pub source: IdSource,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vendor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aaguid: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// The on-disk registry (`keys.json`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Keyring {
    #[serde(default)]
    pub keys: Vec<KeyEntry>,
}

/// A currently-connected device as seen by the resolver. The caller builds
/// these from device enumeration; `serial` is the device's effective serial
/// (USB or CCID), `None` if it couldn't be determined.
#[derive(Debug, Clone)]
pub struct ConnectedKey {
    pub path: PathBuf,
    pub serial: Option<String>,
    pub label: String,
}

/// Errors loading, saving, or mutating the registry.
#[derive(Debug)]
pub enum KeyringError {
    Io(io::Error),
    Parse(String),
    NoConfigDir,
    DuplicateName(String),
    DuplicateSerial {
        serial: String,
        existing_name: String,
    },
    InvalidName(String),
}

impl fmt::Display for KeyringError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyringError::Io(e) => write!(f, "keyring I/O error: {}", e),
            KeyringError::Parse(s) => write!(f, "keyring config parse error: {}", s),
            KeyringError::NoConfigDir => {
                write!(
                    f,
                    "could not determine config dir (set HOME or XDG_CONFIG_HOME)"
                )
            }
            KeyringError::DuplicateName(n) => write!(f, "a key named '{}' already exists", n),
            KeyringError::DuplicateSerial {
                serial,
                existing_name,
            } => {
                write!(f, "serial {} is already named '{}'", serial, existing_name)
            }
            KeyringError::InvalidName(n) => {
                write!(f, "invalid key name '{}': use 1-64 chars of [a-z0-9_-]", n)
            }
        }
    }
}

impl std::error::Error for KeyringError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            KeyringError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for KeyringError {
    fn from(e: io::Error) -> Self {
        KeyringError::Io(e)
    }
}

/// Errors resolving a `--name` to a connected device.
#[derive(Debug)]
pub enum ResolveError {
    UnknownName { name: String, known: Vec<String> },
    NotConnected { name: String, serial: String },
}

impl fmt::Display for ResolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ResolveError::UnknownName { name, known } if known.is_empty() => write!(
                f,
                "no key named '{}': no named keys yet — add one with `keyroostctl key-name add`",
                name
            ),
            ResolveError::UnknownName { name, known } => {
                write!(
                    f,
                    "no key named '{}'. Known names: {}",
                    name,
                    known.join(", ")
                )
            }
            ResolveError::NotConnected { name, serial } => {
                write!(f, "key '{}' (serial {}) is not connected", name, serial)
            }
        }
    }
}

impl std::error::Error for ResolveError {}

/// Validate a friendly name: 1-64 chars of lowercase ASCII, digits, `-`, `_`.
pub fn validate_name(name: &str) -> Result<(), KeyringError> {
    let ok = !name.is_empty()
        && name.len() <= 64
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
    if ok {
        Ok(())
    } else {
        // The rejected name is echoed in the error message; sanitize it so a
        // hand-edited keys.json can't smuggle terminal escapes through the
        // very rejection meant to stop them.
        let mut shown = name.to_string();
        strip_control_chars(&mut shown);
        Err(KeyringError::InvalidName(shown))
    }
}

/// Remove control characters in place — terminal-escape hygiene for
/// hand-editable fields that get echoed back to the user. Also strips the
/// Unicode format characters used for display spoofing (`char::is_control`
/// covers only Cc): bidi overrides/isolates (RLO can render "key-live" out
/// of "evil-yek"), zero-width chars, BOM, and the soft/Arabic-letter marks.
fn strip_control_chars(s: &mut String) {
    fn spoofing(c: char) -> bool {
        c.is_control()
            || matches!(c,
                '\u{200B}'..='\u{200F}' // zero-width space/joiners, LRM/RLM
                | '\u{202A}'..='\u{202E}' // bidi embeddings + LRO/RLO
                | '\u{2066}'..='\u{2069}' // bidi isolates
                | '\u{FEFF}' // BOM / ZWNBSP
                | '\u{00AD}' // soft hyphen
                | '\u{061C}' // Arabic letter mark
            )
    }
    if s.chars().any(spoofing) {
        s.retain(|c| !spoofing(c));
    }
}

/// Default config path: `$XDG_CONFIG_HOME/keyroost/keys.json`, else
/// `$HOME/.config/keyroost/keys.json`.
pub fn config_path() -> Option<PathBuf> {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        if !xdg.is_empty() {
            return Some(PathBuf::from(xdg).join("keyroost").join("keys.json"));
        }
    }
    let home = std::env::var_os("HOME")?;
    if home.is_empty() {
        return None;
    }
    Some(
        PathBuf::from(home)
            .join(".config")
            .join("keyroost")
            .join("keys.json"),
    )
}

impl Keyring {
    /// Load from the default config path. A missing file yields an empty
    /// registry (reading records nothing).
    pub fn load_default() -> Result<Keyring, KeyringError> {
        let path = config_path().ok_or(KeyringError::NoConfigDir)?;
        Self::load_from(&path)
    }

    /// Load from a specific path. A missing file yields an empty registry.
    pub fn load_from(path: &Path) -> Result<Keyring, KeyringError> {
        match fs::read_to_string(path) {
            Ok(s) => {
                let mut ring: Keyring =
                    serde_json::from_str(&s).map_err(|e| KeyringError::Parse(e.to_string()))?;
                // `add` validates names before they ever reach disk; on the
                // way back in every field — including the name — is sanitized
                // rather than rejected. Rejecting would make one hand-edited
                // entry render the whole registry unloadable, and callers
                // that fall back to an empty registry on error would then
                // overwrite keys.json and destroy every other entry on the
                // next save.
                for entry in &mut ring.keys {
                    strip_control_chars(&mut entry.name);
                    strip_control_chars(&mut entry.serial);
                    for field in [&mut entry.vendor, &mut entry.aaguid, &mut entry.note]
                        .into_iter()
                        .flatten()
                    {
                        strip_control_chars(field);
                    }
                }
                Ok(ring)
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Keyring::default()),
            Err(e) => Err(KeyringError::Io(e)),
        }
    }

    /// Persist to the default config path, creating parent dirs. Opt-in: only
    /// call this from an explicit user action. Returns the path written.
    pub fn save_default(&self) -> Result<PathBuf, KeyringError> {
        let path = config_path().ok_or(KeyringError::NoConfigDir)?;
        self.save_to(&path)?;
        Ok(path)
    }

    /// Persist to a specific path, creating parent dirs. Opt-in.
    pub fn save_to(&self, path: &Path) -> Result<(), KeyringError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
            // Owner-only on the directory too, matching the file below. Only
            // tightened when we (may have) just created it — an existing dir
            // the user deliberately opened up is left alone.
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Ok(meta) = fs::metadata(parent) {
                    let mut perms = meta.permissions();
                    if perms.mode() & 0o077 != 0 && parent.ends_with("keyroost") {
                        perms.set_mode(0o700);
                        let _ = fs::set_permissions(parent, perms);
                    }
                }
            }
        }
        let json =
            serde_json::to_string_pretty(self).map_err(|e| KeyringError::Parse(e.to_string()))?;
        // Write a sibling temp file and rename into place: a crash mid-write
        // can no longer corrupt the registry, and the file is created
        // owner-only — which security keys a person owns is their business —
        // instead of inheriting the umask default (typically world-readable).
        let tmp = path.with_extension("json.tmp");
        // Remove any stale temp file so `create_new` below can succeed.
        // `create_new` (not `create`) matters twice over: a pre-existing file
        // would keep its old permissions (the 0o600 applies only at creation),
        // and a symlink planted at the temp path would otherwise be followed.
        let _ = fs::remove_file(&tmp);
        {
            let mut opts = fs::OpenOptions::new();
            opts.write(true).create_new(true);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt;
                opts.mode(0o600);
            }
            use std::io::Write;
            let mut f = opts.open(&tmp)?;
            f.write_all(json.as_bytes())?;
            f.write_all(b"\n")?;
            f.sync_all()?;
        }
        fs::rename(&tmp, path)?;
        Ok(())
    }

    /// Add a new entry. Rejects duplicate names and duplicate serials.
    pub fn add(&mut self, mut entry: KeyEntry) -> Result<(), KeyringError> {
        validate_name(&entry.name)?;
        // Sanitize on the way in with the same rules `load_from` applies on
        // the way out, so a device-reported serial (or note) containing
        // control characters is stored exactly as it will round-trip —
        // otherwise the value would silently mutate on the next load, and
        // duplicate-serial detection would compare against a phantom.
        strip_control_chars(&mut entry.serial);
        for field in [&mut entry.vendor, &mut entry.aaguid, &mut entry.note]
            .into_iter()
            .flatten()
        {
            strip_control_chars(field);
        }
        if self.keys.iter().any(|k| k.name == entry.name) {
            return Err(KeyringError::DuplicateName(entry.name));
        }
        if let Some(existing) = self.keys.iter().find(|k| k.serial == entry.serial) {
            return Err(KeyringError::DuplicateSerial {
                serial: entry.serial.clone(),
                existing_name: existing.name.clone(),
            });
        }
        self.keys.push(entry);
        Ok(())
    }

    /// Remove the entry with `name`. Returns true if one was removed.
    pub fn remove(&mut self, name: &str) -> bool {
        let before = self.keys.len();
        self.keys.retain(|k| k.name != name);
        self.keys.len() != before
    }

    pub fn by_name(&self, name: &str) -> Option<&KeyEntry> {
        self.keys.iter().find(|k| k.name == name)
    }

    pub fn by_serial(&self, serial: &str) -> Option<&KeyEntry> {
        self.keys.iter().find(|k| k.serial == serial)
    }

    /// The friendly name for a connected device's serial, if one is registered.
    /// Used by `list` to annotate devices.
    pub fn name_for(&self, serial: Option<&str>) -> Option<&str> {
        let serial = serial?;
        self.by_serial(serial).map(|k| k.name.as_str())
    }

    /// Resolve a `--name` to a connected device by matching serials.
    pub fn resolve<'a>(
        &self,
        name: &str,
        connected: &'a [ConnectedKey],
    ) -> Result<&'a ConnectedKey, ResolveError> {
        let entry = self
            .by_name(name)
            .ok_or_else(|| ResolveError::UnknownName {
                name: name.to_string(),
                known: self.keys.iter().map(|k| k.name.clone()).collect(),
            })?;
        connected
            .iter()
            .find(|d| d.serial.as_deref() == Some(entry.serial.as_str()))
            .ok_or_else(|| ResolveError::NotConnected {
                name: name.to_string(),
                serial: entry.serial.clone(),
            })
    }
}

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

    fn entry(name: &str, serial: &str) -> KeyEntry {
        KeyEntry {
            name: name.into(),
            serial: serial.into(),
            source: IdSource::Usb,
            vendor: None,
            aaguid: None,
            note: None,
        }
    }

    #[test]
    fn name_validation() {
        assert!(validate_name("signing-yubikey").is_ok());
        assert!(validate_name("test_solo2").is_ok());
        assert!(validate_name("").is_err());
        assert!(validate_name("Bad Name").is_err());
        assert!(validate_name("UPPER").is_err());
    }

    #[test]
    fn add_rejects_duplicates() {
        let mut k = Keyring::default();
        k.add(entry("a", "111")).unwrap();
        assert!(matches!(
            k.add(entry("a", "222")),
            Err(KeyringError::DuplicateName(_))
        ));
        assert!(matches!(
            k.add(entry("b", "111")),
            Err(KeyringError::DuplicateSerial { .. })
        ));
        k.add(entry("b", "222")).unwrap();
        assert_eq!(k.keys.len(), 2);
    }

    #[test]
    fn remove_and_lookup() {
        let mut k = Keyring::default();
        k.add(entry("solo", "ABC")).unwrap();
        assert_eq!(k.by_name("solo").map(|e| e.serial.as_str()), Some("ABC"));
        assert_eq!(k.name_for(Some("ABC")), Some("solo"));
        assert_eq!(k.name_for(Some("XYZ")), None);
        assert_eq!(k.name_for(None), None);
        assert!(k.remove("solo"));
        assert!(!k.remove("solo"));
    }

    #[test]
    fn resolve_matches_by_serial() {
        let mut k = Keyring::default();
        k.add(entry("solo", "ABC")).unwrap();
        let connected = vec![
            ConnectedKey {
                path: "/dev/hidraw5".into(),
                serial: Some("ABC".into()),
                label: "Solo 2".into(),
            },
            ConnectedKey {
                path: "/dev/hidraw9".into(),
                serial: None,
                label: "YubiKey".into(),
            },
        ];
        assert_eq!(
            k.resolve("solo", &connected).unwrap().path,
            PathBuf::from("/dev/hidraw5")
        );
        assert!(matches!(
            k.resolve("nope", &connected),
            Err(ResolveError::UnknownName { .. })
        ));
        assert!(matches!(
            k.resolve("solo", &[]),
            Err(ResolveError::NotConnected { .. })
        ));
    }

    #[test]
    fn json_round_trip_and_defaults() {
        let mut k = Keyring::default();
        k.add(KeyEntry {
            name: "signing-yubikey".into(),
            serial: "37806840".into(),
            source: IdSource::Ccid,
            vendor: Some("yubico".into()),
            aaguid: None,
            note: Some("daily".into()),
        })
        .unwrap();
        let json = serde_json::to_string_pretty(&k).unwrap();
        let back: Keyring = serde_json::from_str(&json).unwrap();
        assert_eq!(back.keys[0].name, "signing-yubikey");
        assert_eq!(back.keys[0].source, IdSource::Ccid);
        assert_eq!(back.keys[0].vendor.as_deref(), Some("yubico"));

        // `source` defaults to Usb when absent in JSON.
        let minimal: Keyring =
            serde_json::from_str(r#"{"keys":[{"name":"x","serial":"S1"}]}"#).unwrap();
        assert_eq!(minimal.keys[0].source, IdSource::Usb);
    }

    #[test]
    fn load_missing_is_empty() {
        let k = Keyring::load_from(Path::new("/nonexistent/keyroost/keys.json")).unwrap();
        assert!(k.keys.is_empty());
    }

    #[test]
    fn load_sanitizes_invalid_names_and_strips_control_chars() {
        let dir = std::env::temp_dir().join(format!("keyroost-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("keys.json");

        // A name with an ANSI escape is sanitized, not fatal: one bad
        // hand-edited entry must never make the whole registry unloadable
        // (an unwrap_or_default + save would wipe every other entry).
        std::fs::write(
            &path,
            "{\"keys\":[{\"name\":\"evil\\u001b[31m\",\"serial\":\"S1\"},{\"name\":\"good\",\"serial\":\"S2\"}]}",
        )
        .unwrap();
        let k = Keyring::load_from(&path).unwrap();
        assert_eq!(k.keys[0].name, "evil[31m");
        assert_eq!(k.keys[1].name, "good");

        // Control chars in free-text fields are stripped, not fatal.
        std::fs::write(
            &path,
            "{\"keys\":[{\"name\":\"ok\",\"serial\":\"S\\u001b[2J1\",\"note\":\"a\\u0007b\"}]}",
        )
        .unwrap();
        let k = Keyring::load_from(&path).unwrap();
        assert_eq!(k.keys[0].serial, "S[2J1");
        assert_eq!(k.keys[0].note.as_deref(), Some("ab"));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn add_sanitizes_device_supplied_fields() {
        // A device-reported serial with control chars must be stored in the
        // same form load_from would produce, or the entry mutates on reload.
        let mut k = Keyring::default();
        k.add(KeyEntry {
            name: "weird".into(),
            serial: "AB\u{1b}[31mCD".into(),
            source: IdSource::Usb,
            vendor: None,
            aaguid: None,
            note: Some("x\u{7}y".into()),
        })
        .unwrap();
        assert_eq!(k.keys[0].serial, "AB[31mCD");
        assert_eq!(k.keys[0].note.as_deref(), Some("xy"));

        // Unicode format chars (Cf) used for display spoofing go too: RLO
        // would render "evil-yek" as "key-live" in a terminal listing.
        let mut k2 = Keyring::default();
        k2.add(KeyEntry {
            name: "bidi".into(),
            serial: "S\u{202E}9\u{200B}9".into(),
            source: IdSource::Usb,
            vendor: None,
            aaguid: None,
            note: None,
        })
        .unwrap();
        assert_eq!(k2.keys[0].serial, "S99");
    }

    #[cfg(unix)]
    #[test]
    fn save_creates_owner_only_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("keyroost-perm-{}", std::process::id()));
        let path = dir.join("keys.json");
        let mut k = Keyring::default();
        k.add(KeyEntry {
            name: "test-key".into(),
            serial: "S1".into(),
            source: IdSource::Usb,
            vendor: None,
            aaguid: None,
            note: None,
        })
        .unwrap();
        k.save_to(&path).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600, "keys.json must be owner-only");
        // No temp file left behind.
        assert!(!path.with_extension("json.tmp").exists());
        std::fs::remove_dir_all(&dir).ok();
    }
}