Skip to main content

fynx_proto/ssh/
auth.rs

1//! SSH authentication protocol (RFC 4252).
2//!
3//! This module implements user authentication for SSH:
4//! - "publickey" - Public key authentication (Ed25519, RSA)
5//! - "password" - Password authentication
6//! - "none" - Test authentication state
7//!
8//! # Security
9//!
10//! - **Constant-time password comparison** - Prevents timing attacks
11//! - **Partial success handling** - Supports multi-factor authentication
12//! - **Public key signature verification** - Uses cryptographically secure libraries
13//!
14//! # Example
15//!
16//! ```rust
17//! use fynx_proto::ssh::auth::{AuthRequest, AuthMethod};
18//!
19//! // Create password authentication request
20//! let auth = AuthRequest::new(
21//!     "user",
22//!     "ssh-connection",
23//!     AuthMethod::Password("secret".to_string()),
24//! );
25//! ```
26
27use bytes::{BufMut, BytesMut};
28use fynx_platform::{FynxError, FynxResult};
29use sha2::{Digest, Sha256};
30use subtle::ConstantTimeEq;
31use zeroize::Zeroize;
32
33/// SSH authentication method.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum AuthMethod {
36    /// No authentication (test only).
37    None,
38    /// Password authentication.
39    Password(String),
40    /// Public key authentication.
41    PublicKey {
42        /// Algorithm name (e.g., "ssh-ed25519", "rsa-sha2-256")
43        algorithm: String,
44        /// Public key blob
45        public_key: Vec<u8>,
46        /// Signature (if present)
47        signature: Option<Vec<u8>>,
48    },
49}
50
51impl AuthMethod {
52    /// Returns the method name.
53    pub fn name(&self) -> &str {
54        match self {
55            AuthMethod::None => "none",
56            AuthMethod::Password(_) => "password",
57            AuthMethod::PublicKey { .. } => "publickey",
58        }
59    }
60}
61
62impl Drop for AuthMethod {
63    fn drop(&mut self) {
64        // Zeroize sensitive data
65        if let AuthMethod::Password(ref mut password) = self {
66            password.zeroize();
67        }
68    }
69}
70
71/// SSH_MSG_USERAUTH_REQUEST message (RFC 4252 Section 5).
72///
73/// This message is sent by the client to request authentication.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct AuthRequest {
76    /// User name
77    user_name: String,
78    /// Service name (usually "ssh-connection")
79    service_name: String,
80    /// Authentication method
81    method: AuthMethod,
82}
83
84impl AuthRequest {
85    /// Creates a new authentication request.
86    ///
87    /// # Arguments
88    ///
89    /// * `user_name` - User name to authenticate as
90    /// * `service_name` - Service to start after authentication (usually "ssh-connection")
91    /// * `method` - Authentication method
92    ///
93    /// # Example
94    ///
95    /// ```rust
96    /// use fynx_proto::ssh::auth::{AuthRequest, AuthMethod};
97    ///
98    /// let auth = AuthRequest::new(
99    ///     "alice",
100    ///     "ssh-connection",
101    ///     AuthMethod::Password("secret".to_string()),
102    /// );
103    /// ```
104    pub fn new(user_name: &str, service_name: &str, method: AuthMethod) -> Self {
105        Self {
106            user_name: user_name.to_string(),
107            service_name: service_name.to_string(),
108            method,
109        }
110    }
111
112    /// Returns the user name.
113    pub fn user_name(&self) -> &str {
114        &self.user_name
115    }
116
117    /// Returns the service name.
118    pub fn service_name(&self) -> &str {
119        &self.service_name
120    }
121
122    /// Returns the authentication method.
123    pub fn method(&self) -> &AuthMethod {
124        &self.method
125    }
126
127    /// Serializes the authentication request to bytes.
128    ///
129    /// Format (RFC 4252 Section 5):
130    /// ```text
131    /// byte      SSH_MSG_USERAUTH_REQUEST (50)
132    /// string    user name
133    /// string    service name
134    /// string    method name
135    /// ....      method specific fields
136    /// ```
137    pub fn to_bytes(&self) -> Vec<u8> {
138        let mut buf = BytesMut::new();
139
140        // byte SSH_MSG_USERAUTH_REQUEST (50)
141        buf.put_u8(50);
142
143        // string user name
144        write_string(&mut buf, &self.user_name);
145
146        // string service name
147        write_string(&mut buf, &self.service_name);
148
149        // string method name
150        write_string(&mut buf, self.method.name());
151
152        // Method-specific fields
153        match &self.method {
154            AuthMethod::None => {
155                // No additional fields
156            }
157            AuthMethod::Password(password) => {
158                // boolean FALSE (not changing password)
159                buf.put_u8(0);
160                // string plaintext password
161                write_string(&mut buf, password);
162            }
163            AuthMethod::PublicKey {
164                algorithm,
165                public_key,
166                signature,
167            } => {
168                // boolean (TRUE if signature present)
169                buf.put_u8(if signature.is_some() { 1 } else { 0 });
170                // string public key algorithm name
171                write_string(&mut buf, algorithm);
172                // string public key blob
173                write_bytes(&mut buf, public_key);
174                // string signature (if present)
175                if let Some(sig) = signature {
176                    write_bytes(&mut buf, sig);
177                }
178            }
179        }
180
181        buf.to_vec()
182    }
183
184    /// Parses an authentication request from bytes.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`FynxError::Protocol`] if the data is invalid.
189    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
190        if data.is_empty() {
191            return Err(FynxError::Protocol(
192                "USERAUTH_REQUEST message is empty".to_string(),
193            ));
194        }
195
196        // Check message type
197        if data[0] != 50 {
198            return Err(FynxError::Protocol(format!(
199                "Invalid message type: expected 50 (SSH_MSG_USERAUTH_REQUEST), got {}",
200                data[0]
201            )));
202        }
203
204        let mut offset = 1;
205
206        // Parse user name
207        let user_name = read_string(data, &mut offset)?;
208
209        // Parse service name
210        let service_name = read_string(data, &mut offset)?;
211
212        // Parse method name
213        let method_name = read_string(data, &mut offset)?;
214
215        // Parse method-specific fields
216        let method = match method_name.as_str() {
217            "none" => AuthMethod::None,
218            "password" => {
219                // boolean (changing password flag)
220                if offset >= data.len() {
221                    return Err(FynxError::Protocol(
222                        "USERAUTH_REQUEST truncated (missing password change flag)".to_string(),
223                    ));
224                }
225                let _changing = data[offset] != 0;
226                offset += 1;
227
228                // string password
229                let password = read_string(data, &mut offset)?;
230                AuthMethod::Password(password)
231            }
232            "publickey" => {
233                // boolean (has signature)
234                if offset >= data.len() {
235                    return Err(FynxError::Protocol(
236                        "USERAUTH_REQUEST truncated (missing publickey signature flag)".to_string(),
237                    ));
238                }
239                let has_signature = data[offset] != 0;
240                offset += 1;
241
242                // string algorithm name
243                let algorithm = read_string(data, &mut offset)?;
244
245                // string public key blob
246                let public_key = read_bytes(data, &mut offset)?;
247
248                // string signature (if present)
249                let signature = if has_signature {
250                    Some(read_bytes(data, &mut offset)?)
251                } else {
252                    None
253                };
254
255                AuthMethod::PublicKey {
256                    algorithm,
257                    public_key,
258                    signature,
259                }
260            }
261            _ => {
262                return Err(FynxError::Protocol(format!(
263                    "Unsupported authentication method: '{}'",
264                    method_name
265                )))
266            }
267        };
268
269        Ok(Self {
270            user_name,
271            service_name,
272            method,
273        })
274    }
275}
276
277/// SSH_MSG_USERAUTH_FAILURE message (RFC 4252 Section 5.1).
278///
279/// Sent by the server when authentication fails.
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct AuthFailure {
282    /// Authentications that can continue
283    methods_can_continue: Vec<String>,
284    /// Partial success flag
285    partial_success: bool,
286}
287
288impl AuthFailure {
289    /// Creates a new authentication failure message.
290    ///
291    /// # Arguments
292    ///
293    /// * `methods` - Methods that can continue
294    /// * `partial_success` - Whether partial success was achieved
295    ///
296    /// # Example
297    ///
298    /// ```rust
299    /// use fynx_proto::ssh::auth::AuthFailure;
300    ///
301    /// let failure = AuthFailure::new(
302    ///     vec!["publickey".to_string(), "password".to_string()],
303    ///     false,
304    /// );
305    /// ```
306    pub fn new(methods: Vec<String>, partial_success: bool) -> Self {
307        Self {
308            methods_can_continue: methods,
309            partial_success,
310        }
311    }
312
313    /// Returns the methods that can continue.
314    pub fn methods_can_continue(&self) -> &[String] {
315        &self.methods_can_continue
316    }
317
318    /// Returns whether partial success was achieved.
319    pub fn partial_success(&self) -> bool {
320        self.partial_success
321    }
322
323    /// Serializes to bytes.
324    pub fn to_bytes(&self) -> Vec<u8> {
325        let mut buf = BytesMut::new();
326
327        // byte SSH_MSG_USERAUTH_FAILURE (51)
328        buf.put_u8(51);
329
330        // name-list authentications that can continue
331        let methods_str = self.methods_can_continue.join(",");
332        write_string(&mut buf, &methods_str);
333
334        // boolean partial success
335        buf.put_u8(if self.partial_success { 1 } else { 0 });
336
337        buf.to_vec()
338    }
339
340    /// Parses from bytes.
341    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
342        if data.is_empty() {
343            return Err(FynxError::Protocol(
344                "USERAUTH_FAILURE message is empty".to_string(),
345            ));
346        }
347
348        if data[0] != 51 {
349            return Err(FynxError::Protocol(format!(
350                "Invalid message type: expected 51 (SSH_MSG_USERAUTH_FAILURE), got {}",
351                data[0]
352            )));
353        }
354
355        let mut offset = 1;
356
357        // name-list methods
358        let methods_str = read_string(data, &mut offset)?;
359        let methods_can_continue: Vec<String> = if methods_str.is_empty() {
360            vec![]
361        } else {
362            methods_str.split(',').map(String::from).collect()
363        };
364
365        // boolean partial success
366        if offset >= data.len() {
367            return Err(FynxError::Protocol(
368                "USERAUTH_FAILURE truncated (missing partial success flag)".to_string(),
369            ));
370        }
371        let partial_success = data[offset] != 0;
372
373        Ok(Self {
374            methods_can_continue,
375            partial_success,
376        })
377    }
378}
379
380/// SSH_MSG_USERAUTH_SUCCESS message (RFC 4252 Section 5.1).
381///
382/// Sent by the server when authentication succeeds.
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub struct AuthSuccess;
385
386impl AuthSuccess {
387    /// Creates a new authentication success message.
388    pub fn new() -> Self {
389        Self
390    }
391
392    /// Serializes to bytes.
393    pub fn to_bytes(&self) -> Vec<u8> {
394        vec![52] // SSH_MSG_USERAUTH_SUCCESS (52)
395    }
396
397    /// Parses from bytes.
398    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
399        if data.is_empty() || data[0] != 52 {
400            return Err(FynxError::Protocol(
401                "Invalid USERAUTH_SUCCESS message".to_string(),
402            ));
403        }
404        Ok(Self)
405    }
406}
407
408impl Default for AuthSuccess {
409    fn default() -> Self {
410        Self::new()
411    }
412}
413
414/// SSH_MSG_USERAUTH_BANNER message (RFC 4252 Section 5.4).
415///
416/// Sent by the server to display a banner message.
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct AuthBanner {
419    /// Banner message
420    message: String,
421    /// Language tag (usually "")
422    language_tag: String,
423}
424
425impl AuthBanner {
426    /// Creates a new banner message.
427    pub fn new(message: String) -> Self {
428        Self {
429            message,
430            language_tag: String::new(),
431        }
432    }
433
434    /// Returns the banner message.
435    pub fn message(&self) -> &str {
436        &self.message
437    }
438
439    /// Serializes to bytes.
440    pub fn to_bytes(&self) -> Vec<u8> {
441        let mut buf = BytesMut::new();
442
443        // byte SSH_MSG_USERAUTH_BANNER (53)
444        buf.put_u8(53);
445
446        // string message
447        write_string(&mut buf, &self.message);
448
449        // string language tag
450        write_string(&mut buf, &self.language_tag);
451
452        buf.to_vec()
453    }
454
455    /// Parses from bytes.
456    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
457        if data.is_empty() {
458            return Err(FynxError::Protocol(
459                "USERAUTH_BANNER message is empty".to_string(),
460            ));
461        }
462
463        if data[0] != 53 {
464            return Err(FynxError::Protocol(format!(
465                "Invalid message type: expected 53 (SSH_MSG_USERAUTH_BANNER), got {}",
466                data[0]
467            )));
468        }
469
470        let mut offset = 1;
471
472        let message = read_string(data, &mut offset)?;
473        let language_tag = read_string(data, &mut offset)?;
474
475        Ok(Self {
476            message,
477            language_tag,
478        })
479    }
480}
481
482/// SSH_MSG_USERAUTH_PK_OK message (RFC 4252 Section 7).
483///
484/// Sent by the server to indicate that the public key is acceptable
485/// for authentication (in response to a try-then-sign query).
486#[derive(Debug, Clone, PartialEq, Eq)]
487pub struct AuthPkOk {
488    /// Public key algorithm name
489    algorithm: String,
490    /// Public key blob
491    public_key: Vec<u8>,
492}
493
494impl AuthPkOk {
495    /// Creates a new SSH_MSG_USERAUTH_PK_OK message.
496    ///
497    /// # Arguments
498    ///
499    /// * `algorithm` - Public key algorithm name (e.g., "ssh-ed25519")
500    /// * `public_key` - Public key blob
501    ///
502    /// # Example
503    ///
504    /// ```rust
505    /// use fynx_proto::ssh::auth::AuthPkOk;
506    ///
507    /// let pk_ok = AuthPkOk::new("ssh-ed25519", vec![1, 2, 3, 4]);
508    /// ```
509    pub fn new(algorithm: impl Into<String>, public_key: Vec<u8>) -> Self {
510        Self {
511            algorithm: algorithm.into(),
512            public_key,
513        }
514    }
515
516    /// Returns the algorithm name.
517    pub fn algorithm(&self) -> &str {
518        &self.algorithm
519    }
520
521    /// Returns the public key blob.
522    pub fn public_key(&self) -> &[u8] {
523        &self.public_key
524    }
525
526    /// Serializes to bytes.
527    ///
528    /// Format (RFC 4252 Section 7):
529    /// ```text
530    /// byte      SSH_MSG_USERAUTH_PK_OK (60)
531    /// string    public key algorithm name
532    /// string    public key blob
533    /// ```
534    pub fn to_bytes(&self) -> Vec<u8> {
535        let mut buf = BytesMut::new();
536
537        // byte SSH_MSG_USERAUTH_PK_OK (60)
538        buf.put_u8(60);
539
540        // string algorithm name
541        write_string(&mut buf, &self.algorithm);
542
543        // string public key blob
544        write_bytes(&mut buf, &self.public_key);
545
546        buf.to_vec()
547    }
548
549    /// Parses from bytes.
550    ///
551    /// # Errors
552    ///
553    /// Returns [`FynxError::Protocol`] if the data is invalid.
554    pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
555        if data.is_empty() {
556            return Err(FynxError::Protocol(
557                "USERAUTH_PK_OK message is empty".to_string(),
558            ));
559        }
560
561        if data[0] != 60 {
562            return Err(FynxError::Protocol(format!(
563                "Invalid message type: expected 60 (SSH_MSG_USERAUTH_PK_OK), got {}",
564                data[0]
565            )));
566        }
567
568        let mut offset = 1;
569
570        // string algorithm name
571        let algorithm = read_string(data, &mut offset)?;
572
573        // string public key blob
574        let public_key = read_bytes(data, &mut offset)?;
575
576        Ok(Self {
577            algorithm,
578            public_key,
579        })
580    }
581}
582
583/// Constructs the data to be signed for public key authentication (RFC 4252 Section 7).
584///
585/// # Arguments
586///
587/// * `session_id` - Session identifier from key exchange
588/// * `user_name` - User name for authentication
589/// * `service_name` - Service name (usually "ssh-connection")
590/// * `algorithm` - Public key algorithm name
591/// * `public_key_blob` - Public key in SSH wire format
592///
593/// # Returns
594///
595/// Bytes to be signed
596///
597/// # Format
598///
599/// ```text
600/// string    session identifier
601/// byte      SSH_MSG_USERAUTH_REQUEST (50)
602/// string    user name
603/// string    service name
604/// string    "publickey"
605/// boolean   TRUE (has signature)
606/// string    public key algorithm name
607/// string    public key blob
608/// ```
609pub fn construct_signature_data(
610    session_id: &[u8],
611    user_name: &str,
612    service_name: &str,
613    algorithm: &str,
614    public_key_blob: &[u8],
615) -> Vec<u8> {
616    let mut buf = BytesMut::new();
617
618    // string session identifier
619    write_bytes(&mut buf, session_id);
620
621    // byte SSH_MSG_USERAUTH_REQUEST (50)
622    buf.put_u8(50);
623
624    // string user name
625    write_string(&mut buf, user_name);
626
627    // string service name
628    write_string(&mut buf, service_name);
629
630    // string "publickey"
631    write_string(&mut buf, "publickey");
632
633    // boolean TRUE (has signature)
634    buf.put_u8(1);
635
636    // string public key algorithm name
637    write_string(&mut buf, algorithm);
638
639    // string public key blob
640    write_bytes(&mut buf, public_key_blob);
641
642    buf.to_vec()
643}
644
645/// Compares two passwords in constant time to prevent timing attacks.
646///
647/// # Arguments
648///
649/// * `a` - First password
650/// * `b` - Second password
651///
652/// # Returns
653///
654/// `true` if passwords match, `false` otherwise
655///
656/// # Security
657///
658/// This function uses constant-time comparison to prevent timing attacks
659/// that could reveal information about the password.
660///
661/// # Example
662///
663/// ```rust
664/// use fynx_proto::ssh::auth::constant_time_compare;
665///
666/// assert!(constant_time_compare("secret", "secret"));
667/// assert!(!constant_time_compare("secret", "wrong"));
668/// ```
669pub fn constant_time_compare(a: &str, b: &str) -> bool {
670    // Hash both passwords first to ensure constant-time comparison
671    // even if lengths differ
672    let hash_a = Sha256::digest(a.as_bytes());
673    let hash_b = Sha256::digest(b.as_bytes());
674
675    // Use constant-time comparison
676    hash_a.ct_eq(&hash_b).into()
677}
678
679// Helper functions for string encoding/decoding
680
681fn write_string(buf: &mut BytesMut, s: &str) {
682    let bytes = s.as_bytes();
683    buf.put_u32(bytes.len() as u32);
684    buf.put_slice(bytes);
685}
686
687fn write_bytes(buf: &mut BytesMut, bytes: &[u8]) {
688    buf.put_u32(bytes.len() as u32);
689    buf.put_slice(bytes);
690}
691
692fn read_string(data: &[u8], offset: &mut usize) -> FynxResult<String> {
693    let bytes = read_bytes(data, offset)?;
694    String::from_utf8(bytes)
695        .map_err(|_| FynxError::Protocol("String contains invalid UTF-8".to_string()))
696}
697
698fn read_bytes(data: &[u8], offset: &mut usize) -> FynxResult<Vec<u8>> {
699    if *offset + 4 > data.len() {
700        return Err(FynxError::Protocol(format!(
701            "Cannot read length at offset {}",
702            offset
703        )));
704    }
705
706    let length = u32::from_be_bytes([
707        data[*offset],
708        data[*offset + 1],
709        data[*offset + 2],
710        data[*offset + 3],
711    ]) as usize;
712    *offset += 4;
713
714    if *offset + length > data.len() {
715        return Err(FynxError::Protocol(format!(
716            "Data truncated: expected {} bytes at offset {}",
717            length, offset
718        )));
719    }
720
721    let bytes = data[*offset..*offset + length].to_vec();
722    *offset += length;
723
724    Ok(bytes)
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn test_auth_request_password() {
733        let auth = AuthRequest::new(
734            "alice",
735            "ssh-connection",
736            AuthMethod::Password("secret".to_string()),
737        );
738
739        assert_eq!(auth.user_name(), "alice");
740        assert_eq!(auth.service_name(), "ssh-connection");
741        assert_eq!(auth.method().name(), "password");
742
743        let bytes = auth.to_bytes();
744        let parsed = AuthRequest::from_bytes(&bytes).unwrap();
745
746        assert_eq!(parsed.user_name(), "alice");
747        assert_eq!(parsed.service_name(), "ssh-connection");
748        if let AuthMethod::Password(pw) = parsed.method() {
749            assert_eq!(pw, "secret");
750        } else {
751            panic!("Expected Password method");
752        }
753    }
754
755    #[test]
756    fn test_auth_request_publickey() {
757        let public_key = vec![1, 2, 3, 4];
758        let auth = AuthRequest::new(
759            "bob",
760            "ssh-connection",
761            AuthMethod::PublicKey {
762                algorithm: "ssh-ed25519".to_string(),
763                public_key: public_key.clone(),
764                signature: None,
765            },
766        );
767
768        let bytes = auth.to_bytes();
769        let parsed = AuthRequest::from_bytes(&bytes).unwrap();
770
771        if let AuthMethod::PublicKey {
772            algorithm,
773            public_key: pk,
774            signature,
775        } = parsed.method()
776        {
777            assert_eq!(algorithm, "ssh-ed25519");
778            assert_eq!(pk, &public_key);
779            assert!(signature.is_none());
780        } else {
781            panic!("Expected PublicKey method");
782        }
783    }
784
785    #[test]
786    fn test_auth_request_none() {
787        let auth = AuthRequest::new("test", "ssh-connection", AuthMethod::None);
788
789        let bytes = auth.to_bytes();
790        let parsed = AuthRequest::from_bytes(&bytes).unwrap();
791
792        assert_eq!(parsed.method(), &AuthMethod::None);
793    }
794
795    #[test]
796    fn test_auth_failure() {
797        let failure =
798            AuthFailure::new(vec!["publickey".to_string(), "password".to_string()], false);
799
800        assert_eq!(
801            failure.methods_can_continue(),
802            &["publickey".to_string(), "password".to_string()]
803        );
804        assert!(!failure.partial_success());
805
806        let bytes = failure.to_bytes();
807        let parsed = AuthFailure::from_bytes(&bytes).unwrap();
808
809        assert_eq!(
810            parsed.methods_can_continue(),
811            failure.methods_can_continue()
812        );
813        assert_eq!(parsed.partial_success(), failure.partial_success());
814    }
815
816    #[test]
817    fn test_auth_success() {
818        let success = AuthSuccess::new();
819        let bytes = success.to_bytes();
820        let parsed = AuthSuccess::from_bytes(&bytes).unwrap();
821        assert_eq!(parsed, success);
822    }
823
824    #[test]
825    fn test_auth_banner() {
826        let banner = AuthBanner::new("Welcome to SSH Server".to_string());
827        assert_eq!(banner.message(), "Welcome to SSH Server");
828
829        let bytes = banner.to_bytes();
830        let parsed = AuthBanner::from_bytes(&bytes).unwrap();
831        assert_eq!(parsed.message(), banner.message());
832    }
833
834    #[test]
835    fn test_constant_time_compare() {
836        assert!(constant_time_compare("password123", "password123"));
837        assert!(!constant_time_compare("password123", "password124"));
838        assert!(!constant_time_compare("short", "verylongpassword"));
839    }
840
841    #[test]
842    fn test_auth_method_zeroize() {
843        let method = AuthMethod::Password("secret".to_string());
844        drop(method);
845        // Password should be zeroized (can't test directly, but ensures no panic)
846    }
847
848    #[test]
849    fn test_auth_pk_ok() {
850        let public_key = vec![1, 2, 3, 4, 5, 6, 7, 8];
851        let pk_ok = AuthPkOk::new("ssh-ed25519", public_key.clone());
852
853        assert_eq!(pk_ok.algorithm(), "ssh-ed25519");
854        assert_eq!(pk_ok.public_key(), &public_key);
855
856        let bytes = pk_ok.to_bytes();
857        assert_eq!(bytes[0], 60); // SSH_MSG_USERAUTH_PK_OK
858
859        let parsed = AuthPkOk::from_bytes(&bytes).unwrap();
860        assert_eq!(parsed.algorithm(), "ssh-ed25519");
861        assert_eq!(parsed.public_key(), &public_key);
862    }
863
864    #[test]
865    fn test_auth_pk_ok_invalid_message_type() {
866        let data = vec![50, 0, 0, 0, 0]; // Wrong message type (50 instead of 60)
867        let result = AuthPkOk::from_bytes(&data);
868        assert!(result.is_err());
869    }
870
871    #[test]
872    fn test_construct_signature_data() {
873        let session_id = vec![1, 2, 3, 4];
874        let user_name = "alice";
875        let service_name = "ssh-connection";
876        let algorithm = "ssh-ed25519";
877        let public_key_blob = vec![5, 6, 7, 8];
878
879        let data = construct_signature_data(
880            &session_id,
881            user_name,
882            service_name,
883            algorithm,
884            &public_key_blob,
885        );
886
887        // Should contain all required fields
888        assert!(!data.is_empty());
889
890        // Check that session_id is at the beginning
891        let sid_len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
892        assert_eq!(sid_len, session_id.len());
893        assert_eq!(&data[4..4 + sid_len], &session_id[..]);
894
895        // Check SSH_MSG_USERAUTH_REQUEST (50)
896        let msg_type_offset = 4 + sid_len;
897        assert_eq!(data[msg_type_offset], 50);
898    }
899}