entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! SSH public key parsing and fingerprinting (RFC 4253 Section 6.6).
//!
//! Parses OpenSSH `authorized_keys` format lines and computes SHA-256
//! fingerprints matching `ssh-keygen -lf key.pub -E sha256` output.
//!
//! # Format
//!
//! An OpenSSH `authorized_keys` line has the form:
//!
//! ```text
//! algorithm base64data [comment]
//! ```
//!
//! The base64-decoded blob begins with a length-prefixed algorithm name
//! (wire format per RFC 4253 Section 6.6), followed by algorithm-specific
//! key material.
//!
//! # Example
//!
//! ```
//! use entropy_auth::ssh::SshPublicKey;
//!
//! let line = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHOFsslv7dDSMH6tOWIk2a+jKNOSNi05BQJBKP5HS4Le test@example";
//! let key = SshPublicKey::parse(line).unwrap();
//! assert_eq!(key.algorithm().to_string(), "ssh-ed25519");
//! assert_eq!(key.comment(), Some("test@example"));
//!
//! let fp = key.fingerprint_sha256();
//! assert!(fp.starts_with("SHA256:"));
//! ```

use core::fmt;

use crate::crypto::Sha256;
use crate::encoding::{Base64DecodeError, base64_decode, base64_encode};

// ---------------------------------------------------------------------------
// SshKeyAlgorithm
// ---------------------------------------------------------------------------

/// SSH public key algorithm identifier.
///
/// Corresponds to the algorithm name string in both the `authorized_keys`
/// line prefix and the wire-format blob header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SshKeyAlgorithm {
    /// Ed25519 (`ssh-ed25519`).
    Ed25519,
    /// RSA (`ssh-rsa`).
    Rsa,
    /// ECDSA with NIST P-256 (`ecdsa-sha2-nistp256`).
    EcdsaNistP256,
    /// ECDSA with NIST P-384 (`ecdsa-sha2-nistp384`).
    EcdsaNistP384,
    /// ECDSA with NIST P-521 (`ecdsa-sha2-nistp521`).
    EcdsaNistP521,
    /// An algorithm not explicitly recognised by this crate.
    Unknown(String),
}

impl SshKeyAlgorithm {
    /// Construct an algorithm from its SSH wire-format name.
    fn from_wire_name(name: &str) -> Self {
        match name {
            "ssh-ed25519" => Self::Ed25519,
            "ssh-rsa" => Self::Rsa,
            "ecdsa-sha2-nistp256" => Self::EcdsaNistP256,
            "ecdsa-sha2-nistp384" => Self::EcdsaNistP384,
            "ecdsa-sha2-nistp521" => Self::EcdsaNistP521,
            other => Self::Unknown(other.to_owned()),
        }
    }
}

impl fmt::Display for SshKeyAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ed25519 => f.write_str("ssh-ed25519"),
            Self::Rsa => f.write_str("ssh-rsa"),
            Self::EcdsaNistP256 => f.write_str("ecdsa-sha2-nistp256"),
            Self::EcdsaNistP384 => f.write_str("ecdsa-sha2-nistp384"),
            Self::EcdsaNistP521 => f.write_str("ecdsa-sha2-nistp521"),
            Self::Unknown(s) => f.write_str(s),
        }
    }
}

// ---------------------------------------------------------------------------
// SshKeyError
// ---------------------------------------------------------------------------

/// The kind of SSH key parsing error that occurred.
///
/// Private — callers inspect errors through [`SshKeyError`]'s `Display`
/// and `std::error::Error` implementations plus `is_*()` query methods.
#[derive(Debug, Clone, PartialEq, Eq)]
enum SshKeyErrorKind {
    /// The input exceeded the maximum accepted line length.
    InputTooLong,
    /// The input did not contain both an algorithm and base64 field.
    MissingFields,
    /// The base64 data could not be decoded.
    InvalidBase64,
    /// The decoded blob is too short to contain a length-prefixed algorithm.
    BlobTooShort,
    /// The algorithm length prefix points beyond the blob boundary.
    InvalidAlgorithmLength,
    /// The algorithm name bytes in the blob are not valid UTF-8.
    InvalidAlgorithmName,
    /// The wire-format algorithm does not match the line prefix.
    AlgorithmMismatch,
}

/// Error returned when parsing an SSH public key fails.
///
/// Use the `is_*()` methods to query which kind of error occurred, and
/// `Display` for human-readable messages prefixed with `"ssh_key: "`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SshKeyError {
    kind: SshKeyErrorKind,
}

impl SshKeyError {
    /// Creates a new error of the given kind.
    const fn new(kind: SshKeyErrorKind) -> Self {
        Self { kind }
    }

    /// Returns `true` if the input exceeded the maximum line length.
    #[must_use]
    pub fn is_input_too_long(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::InputTooLong)
    }

    /// Returns `true` if the input was missing required fields.
    #[must_use]
    pub fn is_missing_fields(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::MissingFields)
    }

    /// Returns `true` if the base64 data was invalid.
    #[must_use]
    pub fn is_invalid_base64(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::InvalidBase64)
    }

    /// Returns `true` if the decoded blob was too short.
    #[must_use]
    pub fn is_blob_too_short(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::BlobTooShort)
    }

    /// Returns `true` if the algorithm length was out of bounds.
    #[must_use]
    pub fn is_invalid_algorithm_length(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::InvalidAlgorithmLength)
    }

    /// Returns `true` if the algorithm name was not valid UTF-8.
    #[must_use]
    pub fn is_invalid_algorithm_name(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::InvalidAlgorithmName)
    }

    /// Returns `true` if the wire-format algorithm did not match the
    /// line prefix.
    #[must_use]
    pub fn is_algorithm_mismatch(&self) -> bool {
        matches!(self.kind, SshKeyErrorKind::AlgorithmMismatch)
    }
}

impl fmt::Display for SshKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            SshKeyErrorKind::InputTooLong => {
                f.write_str("ssh_key: input exceeds maximum line length")
            }
            SshKeyErrorKind::MissingFields => {
                f.write_str("ssh_key: missing algorithm or key data fields")
            }
            SshKeyErrorKind::InvalidBase64 => f.write_str("ssh_key: invalid base64 in key data"),
            SshKeyErrorKind::BlobTooShort => {
                f.write_str("ssh_key: key blob too short for algorithm header")
            }
            SshKeyErrorKind::InvalidAlgorithmLength => {
                f.write_str("ssh_key: algorithm length exceeds blob size")
            }
            SshKeyErrorKind::InvalidAlgorithmName => {
                f.write_str("ssh_key: algorithm name is not valid UTF-8")
            }
            SshKeyErrorKind::AlgorithmMismatch => {
                f.write_str("ssh_key: algorithm prefix does not match wire format")
            }
        }
    }
}

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

// ---------------------------------------------------------------------------
// SshPublicKey
// ---------------------------------------------------------------------------

/// Maximum accepted `authorized_keys` line length (16 KiB). Bounds work on
/// hostile input before base64 decoding; real public keys are well under
/// 1 KiB even for RSA-4096.
const MAX_LINE_LEN: usize = 16 * 1024;

/// A parsed OpenSSH public key.
///
/// Holds the algorithm, the full wire-format key blob, and an optional
/// comment. Supports computing SHA-256 fingerprints compatible with
/// `ssh-keygen -lf key.pub -E sha256`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SshPublicKey {
    /// The key algorithm.
    algorithm: SshKeyAlgorithm,
    /// The full base64-decoded wire-format blob.
    key_blob: Vec<u8>,
    /// Optional trailing comment from the `authorized_keys` line.
    comment: Option<String>,
}

impl SshPublicKey {
    /// Parse an OpenSSH `authorized_keys` format line.
    ///
    /// The expected format is:
    ///
    /// ```text
    /// algorithm base64data [comment]
    /// ```
    ///
    /// Validates that the algorithm prefix matches the wire-format
    /// algorithm embedded in the base64-decoded blob.
    ///
    /// Fields are separated by runs of whitespace (matching OpenSSH), so
    /// keys pasted with tabs or multiple spaces parse correctly. Any text
    /// after the base64 field is taken verbatim as the comment.
    ///
    /// # Security
    ///
    /// Only the algorithm name embedded at the front of the wire blob is
    /// validated (against the line prefix). The remaining key fields are
    /// **not** structurally parsed, and trailing bytes are not rejected, so
    /// two blobs sharing an algorithm header but differing in their
    /// remaining bytes are accepted as distinct keys (with distinct
    /// fingerprints). This type is intended for fingerprinting and
    /// algorithm classification, not for cryptographic key validation.
    ///
    /// # Errors
    ///
    /// Returns [`SshKeyError`] if the input exceeds 16 KiB, is malformed,
    /// the base64 data is invalid, the blob is truncated, or the algorithm
    /// names do not match.
    pub fn parse(input: &str) -> Result<Self, SshKeyError> {
        let input = input.trim();
        // Bound work on hostile input before the base64 decode. Real public
        // keys are a few hundred bytes; the cap sits far above any
        // legitimate key (RSA-4096 is ~740 B base64).
        if input.len() > MAX_LINE_LEN {
            return Err(SshKeyError::new(SshKeyErrorKind::InputTooLong));
        }

        // OpenSSH treats any run of whitespace as a single field separator.
        // `splitn(_, char::is_whitespace)` would yield an empty middle field
        // for the common tab- or multi-space-separated paste, so split on the
        // first whitespace run for each mandatory field and keep the
        // remainder (which may contain spaces) as the comment.
        let (algo_prefix, rest) = input
            .split_once(char::is_whitespace)
            .ok_or(SshKeyError::new(SshKeyErrorKind::MissingFields))?;
        let (b64_data, comment) = match rest.trim_start().split_once(char::is_whitespace) {
            Some((b64, comment)) => {
                let comment = comment.trim();
                (b64, (!comment.is_empty()).then(|| comment.to_owned()))
            }
            None => (rest.trim_start(), None),
        };
        if algo_prefix.is_empty() || b64_data.is_empty() {
            return Err(SshKeyError::new(SshKeyErrorKind::MissingFields));
        }

        let blob = base64_decode(b64_data)
            .map_err(|_: Base64DecodeError| SshKeyError::new(SshKeyErrorKind::InvalidBase64))?;

        if blob.len() < 4 {
            return Err(SshKeyError::new(SshKeyErrorKind::BlobTooShort));
        }

        let algo_len = u32::from_be_bytes([blob[0], blob[1], blob[2], blob[3]]) as usize;
        // `blob.len() >= 4` is checked above, so `blob.len() - 4` cannot
        // underflow; comparing this way (rather than `4 + algo_len`) avoids a
        // `usize` overflow on 32-bit targets when `algo_len` is near `u32::MAX`.
        if algo_len > blob.len() - 4 {
            return Err(SshKeyError::new(SshKeyErrorKind::InvalidAlgorithmLength));
        }

        let wire_algo = std::str::from_utf8(&blob[4..4 + algo_len])
            .map_err(|_| SshKeyError::new(SshKeyErrorKind::InvalidAlgorithmName))?;

        if wire_algo != algo_prefix {
            return Err(SshKeyError::new(SshKeyErrorKind::AlgorithmMismatch));
        }

        Ok(Self {
            algorithm: SshKeyAlgorithm::from_wire_name(wire_algo),
            key_blob: blob,
            comment,
        })
    }

    /// Computes the SHA-256 fingerprint of this key.
    ///
    /// The returned string matches the output of
    /// `ssh-keygen -lf key.pub -E sha256`, i.e. `"SHA256:{base64_no_padding}"`.
    /// The digest is encoded with the **standard** Base64 alphabet (`+`/`/`),
    /// as ssh-keygen does — not the URL-safe alphabet — with padding stripped.
    #[must_use]
    pub fn fingerprint_sha256(&self) -> String {
        let hash = Sha256::digest(&self.key_blob);
        let encoded = base64_encode(&hash);
        let trimmed = encoded.trim_end_matches('=');
        format!("SHA256:{trimmed}")
    }

    /// Returns the key algorithm.
    #[must_use]
    pub fn algorithm(&self) -> &SshKeyAlgorithm {
        &self.algorithm
    }

    /// Returns the optional comment, if present.
    #[must_use]
    pub fn comment(&self) -> Option<&str> {
        self.comment.as_deref()
    }

    /// Returns the raw wire-format key blob.
    #[must_use]
    pub fn key_blob(&self) -> &[u8] {
        &self.key_blob
    }

    /// Reconstructs the `authorized_keys` format line.
    ///
    /// The output can be parsed back with [`SshPublicKey::parse`].
    #[must_use]
    pub fn to_authorized_keys_line(&self) -> String {
        let b64 = base64_encode(&self.key_blob);
        match &self.comment {
            Some(c) => format!("{} {} {}", self.algorithm, b64, c),
            None => format!("{} {}", self.algorithm, b64),
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // A real ssh-ed25519 public key generated with:
    //   ssh-keygen -t ed25519 -C "test@example"
    //
    // The blob structure for ed25519 is:
    //   [4 bytes: len("ssh-ed25519") = 11]
    //   [11 bytes: "ssh-ed25519"]
    //   [4 bytes: len(pubkey) = 32]
    //   [32 bytes: ed25519 public key]
    //
    // We use a well-known test vector. The base64 data below decodes to
    // a valid ssh-ed25519 wire-format blob.
    const ED25519_LINE: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHOFsslv7dDSMH6tOWIk2a+jKNOSNi05BQJBKP5HS4Le test@example";

    // Hard-coded fingerprint fixture captured from real ssh-keygen for
    // `ED25519_LINE`, verified with:
    //   ssh-keygen -lf key.pub -E sha256
    // This is an independent oracle (standard Base64, `+`/`/` alphabet, no
    // padding) — deliberately NOT re-derived from the crate's own encoder, so
    // it catches an alphabet regression that a circular fixture would miss.
    const EXPECTED_ED25519_FINGERPRINT: &str = "SHA256:35egQFxzIJm8xLYiDJBQhZLP+o9hhss8TGs41jDvg8g";

    // A minimal ssh-rsa key (real RSA keys are much longer, but this is
    // a structurally valid wire-format blob for parsing tests).
    // We construct one by hand: [len][ssh-rsa][len][exponent][len][modulus]
    fn make_rsa_line() -> String {
        // Build a minimal ssh-rsa blob:
        // algorithm string: "ssh-rsa" (7 bytes)
        // exponent: 65537 = 0x010001 (3 bytes)
        // modulus: 128 bytes of 0xFF (fake, but structurally valid)
        let mut blob = Vec::new();
        // algorithm length + name
        blob.extend_from_slice(&7u32.to_be_bytes());
        blob.extend_from_slice(b"ssh-rsa");
        // exponent
        blob.extend_from_slice(&3u32.to_be_bytes());
        blob.extend_from_slice(&[0x01, 0x00, 0x01]);
        // modulus (128 bytes)
        blob.extend_from_slice(&128u32.to_be_bytes());
        blob.extend_from_slice(&[0xFF; 128]);

        let b64 = crate::encoding::base64_encode(&blob);
        format!("ssh-rsa {b64} rsa@example")
    }

    // A minimal ecdsa-sha2-nistp256 blob.
    fn make_ecdsa_p256_line() -> String {
        let mut blob = Vec::new();
        // algorithm: "ecdsa-sha2-nistp256" (19 bytes)
        blob.extend_from_slice(&19u32.to_be_bytes());
        blob.extend_from_slice(b"ecdsa-sha2-nistp256");
        // curve identifier: "nistp256" (8 bytes)
        blob.extend_from_slice(&8u32.to_be_bytes());
        blob.extend_from_slice(b"nistp256");
        // public key point: 65 bytes (uncompressed, 0x04 + 32 + 32)
        blob.extend_from_slice(&65u32.to_be_bytes());
        blob.push(0x04);
        blob.extend_from_slice(&[0xAA; 32]);
        blob.extend_from_slice(&[0xBB; 32]);

        let b64 = crate::encoding::base64_encode(&blob);
        format!("ecdsa-sha2-nistp256 {b64} ecdsa@example")
    }

    // -----------------------------------------------------------------------
    // Algorithm detection
    // -----------------------------------------------------------------------

    #[test]
    fn parse_ed25519() {
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        assert_eq!(*key.algorithm(), SshKeyAlgorithm::Ed25519);
    }

    #[test]
    fn parse_rsa() {
        let line = make_rsa_line();
        let key = SshPublicKey::parse(&line).unwrap();
        assert_eq!(*key.algorithm(), SshKeyAlgorithm::Rsa);
    }

    #[test]
    fn parse_ecdsa_p256() {
        let line = make_ecdsa_p256_line();
        let key = SshPublicKey::parse(&line).unwrap();
        assert_eq!(*key.algorithm(), SshKeyAlgorithm::EcdsaNistP256);
    }

    // -----------------------------------------------------------------------
    // Fingerprint
    // -----------------------------------------------------------------------

    #[test]
    fn fingerprint_sha256_matches_expected() {
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        let fp = key.fingerprint_sha256();
        assert_eq!(fp, EXPECTED_ED25519_FINGERPRINT);
        assert!(fp.starts_with("SHA256:"));
        // Must not contain padding characters.
        assert!(!fp.contains('='), "fingerprint should not contain padding");
    }

    #[test]
    fn fingerprint_sha256_deterministic() {
        let key1 = SshPublicKey::parse(ED25519_LINE).unwrap();
        let key2 = SshPublicKey::parse(ED25519_LINE).unwrap();
        assert_eq!(key1.fingerprint_sha256(), key2.fingerprint_sha256());
    }

    #[test]
    fn trailing_bytes_change_the_fingerprint() {
        // The parser validates only the algorithm header and accepts trailing
        // bytes (documented in `parse`'s # Security note). Pin the consequence:
        // an attacker appending bytes after the real key material produces a
        // *distinct* fingerprint, so callers must not treat the fingerprint as
        // canonical key identity / a dedup key.
        let mut blob = Vec::new();
        blob.extend_from_slice(&7u32.to_be_bytes());
        blob.extend_from_slice(b"ssh-rsa");
        blob.extend_from_slice(&3u32.to_be_bytes());
        blob.extend_from_slice(&[0x01, 0x00, 0x01]);
        blob.extend_from_slice(&128u32.to_be_bytes());
        blob.extend_from_slice(&[0xFF; 128]);

        let mut padded = blob.clone();
        padded.push(0x00); // a single trailing byte after the key material

        let line = format!("ssh-rsa {} k", crate::encoding::base64_encode(&blob));
        let padded_line = format!("ssh-rsa {} k", crate::encoding::base64_encode(&padded));

        let key = SshPublicKey::parse(&line).unwrap();
        let padded_key = SshPublicKey::parse(&padded_line).unwrap();
        assert_ne!(
            key.fingerprint_sha256(),
            padded_key.fingerprint_sha256(),
            "trailing bytes must yield a different fingerprint"
        );
    }

    #[test]
    fn fingerprint_sha256_is_43_chars_after_prefix() {
        // SHA-256 produces 32 bytes. Base64 without padding for 32
        // bytes = ceil(32*4/3) = 43 characters.
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        let fp = key.fingerprint_sha256();
        let after_prefix = fp.strip_prefix("SHA256:").unwrap();
        assert_eq!(after_prefix.len(), 43);
    }

    // -----------------------------------------------------------------------
    // Round-trip
    // -----------------------------------------------------------------------

    #[test]
    fn round_trip_ed25519() {
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        let line = key.to_authorized_keys_line();
        let reparsed = SshPublicKey::parse(&line).unwrap();
        assert_eq!(key, reparsed);
    }

    #[test]
    fn round_trip_rsa() {
        let line = make_rsa_line();
        let key = SshPublicKey::parse(&line).unwrap();
        let reconstructed = key.to_authorized_keys_line();
        let reparsed = SshPublicKey::parse(&reconstructed).unwrap();
        assert_eq!(key, reparsed);
    }

    #[test]
    fn round_trip_ecdsa() {
        let line = make_ecdsa_p256_line();
        let key = SshPublicKey::parse(&line).unwrap();
        let reconstructed = key.to_authorized_keys_line();
        let reparsed = SshPublicKey::parse(&reconstructed).unwrap();
        assert_eq!(key, reparsed);
    }

    // -----------------------------------------------------------------------
    // Comment parsing
    // -----------------------------------------------------------------------

    #[test]
    fn comment_present() {
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        assert_eq!(key.comment(), Some("test@example"));
    }

    #[test]
    fn comment_absent() {
        // Strip the comment from the line.
        let parts: Vec<&str> = ED25519_LINE.splitn(3, ' ').collect();
        let no_comment = format!("{} {}", parts[0], parts[1]);
        let key = SshPublicKey::parse(&no_comment).unwrap();
        assert_eq!(key.comment(), None);
    }

    #[test]
    fn comment_with_spaces() {
        let parts: Vec<&str> = ED25519_LINE.splitn(3, ' ').collect();
        let line = format!("{} {} multi word comment here", parts[0], parts[1]);
        let key = SshPublicKey::parse(&line).unwrap();
        assert_eq!(key.comment(), Some("multi word comment here"));
    }

    #[test]
    fn parse_tolerates_whitespace_runs() {
        // OpenSSH treats tabs and runs of spaces as a single separator;
        // pasted keys frequently carry these. The old `splitn` approach
        // produced an empty middle field here and failed with MissingFields.
        let parts: Vec<&str> = ED25519_LINE.splitn(3, ' ').collect();
        let line = format!("{}  \t {}\t{}", parts[0], parts[1], parts[2]);
        let key = SshPublicKey::parse(&line).unwrap();
        assert_eq!(*key.algorithm(), SshKeyAlgorithm::Ed25519);
        assert_eq!(key.comment(), Some("test@example"));
    }

    #[test]
    fn parse_rejects_overlong_input() {
        let line = format!("ssh-ed25519 {}", "A".repeat(MAX_LINE_LEN));
        let err = SshPublicKey::parse(&line).unwrap_err();
        assert!(err.is_input_too_long(), "got: {err}");
    }

    // -----------------------------------------------------------------------
    // Key blob accessor
    // -----------------------------------------------------------------------

    #[test]
    fn key_blob_matches_decoded_base64() {
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        let parts: Vec<&str> = ED25519_LINE.splitn(3, ' ').collect();
        let expected_blob = crate::encoding::base64_decode(parts[1]).unwrap();
        assert_eq!(key.key_blob(), expected_blob.as_slice());
    }

    // -----------------------------------------------------------------------
    // Error cases
    // -----------------------------------------------------------------------

    #[test]
    fn error_empty_input() {
        let err = SshPublicKey::parse("").unwrap_err();
        assert!(err.is_missing_fields());
    }

    #[test]
    fn error_whitespace_only() {
        let err = SshPublicKey::parse("   ").unwrap_err();
        assert!(err.is_missing_fields());
    }

    #[test]
    fn error_single_field() {
        let err = SshPublicKey::parse("ssh-ed25519").unwrap_err();
        assert!(err.is_missing_fields());
    }

    #[test]
    fn error_invalid_base64() {
        let err = SshPublicKey::parse("ssh-ed25519 !!!invalid!!!").unwrap_err();
        assert!(err.is_invalid_base64());
    }

    #[test]
    fn error_blob_too_short() {
        // base64 for 3 bytes [0x00, 0x00, 0x01] = "AAAB"
        let err = SshPublicKey::parse("ssh-ed25519 AAAB").unwrap_err();
        assert!(err.is_blob_too_short());
    }

    #[test]
    fn error_algorithm_length_exceeds_blob() {
        // Build a blob where the algorithm length is larger than remaining data.
        // 4 bytes: length = 255, then 1 byte of data (too short).
        let mut blob = Vec::new();
        blob.extend_from_slice(&255u32.to_be_bytes());
        blob.push(0x41); // 'A'
        let b64 = crate::encoding::base64_encode(&blob);
        let line = format!("ssh-ed25519 {b64}");
        let err = SshPublicKey::parse(&line).unwrap_err();
        assert!(err.is_invalid_algorithm_length());
    }

    #[test]
    fn error_algorithm_mismatch() {
        // Use a valid ed25519 blob but claim it's ssh-rsa.
        let parts: Vec<&str> = ED25519_LINE.splitn(3, ' ').collect();
        let line = format!("ssh-rsa {}", parts[1]);
        let err = SshPublicKey::parse(&line).unwrap_err();
        assert!(err.is_algorithm_mismatch());
    }

    #[test]
    fn error_truncated_blob_exactly_4_bytes() {
        // A blob of exactly 4 bytes with algo_len = 0 is technically valid
        // for the length check, but the algorithm will be empty and won't
        // match any prefix. Let's test a blob with algo_len = 1 but only
        // 4 bytes total.
        let mut blob = Vec::new();
        blob.extend_from_slice(&1u32.to_be_bytes());
        // No algorithm byte follows — blob is only 4 bytes.
        let b64 = crate::encoding::base64_encode(&blob);
        let line = format!("x {b64}");
        let err = SshPublicKey::parse(&line).unwrap_err();
        assert!(err.is_invalid_algorithm_length());
    }

    // -----------------------------------------------------------------------
    // Display on SshKeyAlgorithm
    // -----------------------------------------------------------------------

    #[test]
    fn algorithm_display_wire_names() {
        assert_eq!(SshKeyAlgorithm::Ed25519.to_string(), "ssh-ed25519");
        assert_eq!(SshKeyAlgorithm::Rsa.to_string(), "ssh-rsa");
        assert_eq!(
            SshKeyAlgorithm::EcdsaNistP256.to_string(),
            "ecdsa-sha2-nistp256"
        );
        assert_eq!(
            SshKeyAlgorithm::EcdsaNistP384.to_string(),
            "ecdsa-sha2-nistp384"
        );
        assert_eq!(
            SshKeyAlgorithm::EcdsaNistP521.to_string(),
            "ecdsa-sha2-nistp521"
        );
        assert_eq!(
            SshKeyAlgorithm::Unknown("custom-algo".to_owned()).to_string(),
            "custom-algo"
        );
    }

    // -----------------------------------------------------------------------
    // Display on SshKeyError
    // -----------------------------------------------------------------------

    #[test]
    fn error_display_messages_start_with_ssh_key() {
        let cases = [
            (
                SshKeyErrorKind::MissingFields,
                "ssh_key: missing algorithm or key data fields",
            ),
            (
                SshKeyErrorKind::InvalidBase64,
                "ssh_key: invalid base64 in key data",
            ),
            (
                SshKeyErrorKind::BlobTooShort,
                "ssh_key: key blob too short for algorithm header",
            ),
            (
                SshKeyErrorKind::InvalidAlgorithmLength,
                "ssh_key: algorithm length exceeds blob size",
            ),
            (
                SshKeyErrorKind::InvalidAlgorithmName,
                "ssh_key: algorithm name is not valid UTF-8",
            ),
            (
                SshKeyErrorKind::AlgorithmMismatch,
                "ssh_key: algorithm prefix does not match wire format",
            ),
        ];
        for (kind, expected) in &cases {
            let err = SshKeyError::new(kind.clone());
            let msg = err.to_string();
            assert!(
                msg.starts_with("ssh_key:"),
                "expected Display to start with 'ssh_key:', got: {msg}",
            );
            assert_eq!(&msg, expected);
        }
    }

    // -----------------------------------------------------------------------
    // std::error::Error
    // -----------------------------------------------------------------------

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(SshKeyError::new(SshKeyErrorKind::MissingFields));
        assert!(err.source().is_none());
        let _ = err.to_string();
    }

    // -----------------------------------------------------------------------
    // Fingerprint uses SHA-256 correctly
    // -----------------------------------------------------------------------

    #[test]
    fn fingerprint_sha256_matches_manual_computation() {
        // Manually compute: SHA-256 of the blob, then standard Base64 no-pad.
        let key = SshPublicKey::parse(ED25519_LINE).unwrap();
        let hash = Sha256::digest(key.key_blob());
        let hash_hex = hex_encode(&hash);

        let fp = key.fingerprint_sha256();
        // Decode the standard-Base64 part of the fingerprint and verify it
        // matches the raw SHA-256 hash. base64_decode requires padding, so
        // re-append the padding that fingerprint_sha256 strips (32 bytes ->
        // 44 chars with one '=').
        let fp_b64 = fp.strip_prefix("SHA256:").unwrap();
        let fp_bytes = crate::encoding::base64_decode(&format!("{fp_b64}=")).unwrap();
        assert_eq!(hex_encode(&fp_bytes), hash_hex);
    }

    // -----------------------------------------------------------------------
    // Whitespace handling
    // -----------------------------------------------------------------------

    #[test]
    fn parse_trims_leading_trailing_whitespace() {
        let padded = format!("  {ED25519_LINE}  ");
        let key = SshPublicKey::parse(&padded).unwrap();
        assert_eq!(*key.algorithm(), SshKeyAlgorithm::Ed25519);
    }

    // -----------------------------------------------------------------------
    // Unknown algorithm
    // -----------------------------------------------------------------------

    #[test]
    fn parse_unknown_algorithm() {
        // Build a blob with an unknown algorithm name.
        let algo = "custom-algo-v1";
        let mut blob = Vec::new();
        blob.extend_from_slice(&u32::try_from(algo.len()).unwrap().to_be_bytes());
        blob.extend_from_slice(algo.as_bytes());
        blob.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);

        let b64 = crate::encoding::base64_encode(&blob);
        let line = format!("{algo} {b64} custom comment");
        let key = SshPublicKey::parse(&line).unwrap();
        assert_eq!(
            *key.algorithm(),
            SshKeyAlgorithm::Unknown("custom-algo-v1".to_owned())
        );
        assert_eq!(key.comment(), Some("custom comment"));
    }
}