bssh 2.0.1

Parallel SSH command execution tool for cluster management
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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH handler implementation for the russh server.
//!
//! This module implements the `russh::server::Handler` trait which handles
//! all SSH protocol events for a single connection.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;

use futures::FutureExt;
use russh::keys::ssh_key;
use russh::server::{Auth, Msg, Session};
use russh::{Channel, ChannelId, MethodKind, MethodSet, Pty};
use tokio::sync::RwLock;
use zeroize::Zeroizing;

use super::auth::AuthProvider;
use super::config::ServerConfig;
use super::exec::CommandExecutor;
use super::pty::PtyConfig as PtyMasterConfig;
use super::scp::{ScpCommand, ScpHandler};
use super::security::AuthRateLimiter;
use super::session::{
    ChannelState, PtyConfig, SessionError, SessionId, SessionInfo, SessionManager,
};
use super::sftp::SftpHandler;
use super::shell::ShellSession;
use crate::shared::rate_limit::RateLimiter;

/// SSH handler for a single client connection.
///
/// This struct implements the `russh::server::Handler` trait to handle
/// SSH protocol events such as authentication, channel operations, and data transfer.
pub struct SshHandler {
    /// Remote address of the connected client.
    peer_addr: Option<SocketAddr>,

    /// Server configuration.
    config: Arc<ServerConfig>,

    /// Shared session manager.
    sessions: Arc<RwLock<SessionManager>>,

    /// Authentication provider for verifying credentials.
    auth_provider: Arc<dyn AuthProvider>,

    /// Rate limiter for authentication attempts.
    rate_limiter: RateLimiter<String>,

    /// Auth rate limiter with ban support (fail2ban-like).
    auth_rate_limiter: Option<AuthRateLimiter>,

    /// Session information for this connection.
    session_info: Option<SessionInfo>,

    /// Active channels for this connection.
    channels: HashMap<ChannelId, ChannelState>,

    /// Whether this connection should be immediately rejected.
    /// Set when IP access control denies the connection.
    rejected: bool,
}

impl SshHandler {
    /// Create a new SSH handler for a client connection.
    pub fn new(
        peer_addr: Option<SocketAddr>,
        config: Arc<ServerConfig>,
        sessions: Arc<RwLock<SessionManager>>,
    ) -> Self {
        let auth_provider = config.create_auth_provider();
        // Rate limiter: allow burst of 5 attempts, refill 1 attempt per second
        // Note: This creates a per-handler rate limiter. For production use,
        // prefer with_rate_limiter() to share a rate limiter across handlers.
        let rate_limiter = RateLimiter::with_simple_config(5, 1.0);

        Self {
            peer_addr,
            config,
            sessions,
            auth_provider,
            rate_limiter,
            auth_rate_limiter: None,
            session_info: Some(SessionInfo::new(peer_addr)),
            channels: HashMap::new(),
            rejected: false,
        }
    }

    /// Create a new SSH handler with a shared rate limiter.
    ///
    /// This is the preferred constructor for production use as it shares
    /// the rate limiter across all handlers, providing server-wide rate limiting.
    pub fn with_rate_limiter(
        peer_addr: Option<SocketAddr>,
        config: Arc<ServerConfig>,
        sessions: Arc<RwLock<SessionManager>>,
        rate_limiter: RateLimiter<String>,
    ) -> Self {
        let auth_provider = config.create_auth_provider();

        Self {
            peer_addr,
            config,
            sessions,
            auth_provider,
            rate_limiter,
            auth_rate_limiter: None,
            session_info: Some(SessionInfo::new(peer_addr)),
            channels: HashMap::new(),
            rejected: false,
        }
    }

    /// Create a new SSH handler with shared rate limiters including auth ban support.
    ///
    /// This is the preferred constructor for production use as it shares
    /// both rate limiters across all handlers, providing server-wide rate limiting
    /// and fail2ban-like functionality.
    pub fn with_rate_limiters(
        peer_addr: Option<SocketAddr>,
        config: Arc<ServerConfig>,
        sessions: Arc<RwLock<SessionManager>>,
        rate_limiter: RateLimiter<String>,
        auth_rate_limiter: AuthRateLimiter,
    ) -> Self {
        let auth_provider = config.create_auth_provider();

        Self {
            peer_addr,
            config,
            sessions,
            auth_provider,
            rate_limiter,
            auth_rate_limiter: Some(auth_rate_limiter),
            session_info: Some(SessionInfo::new(peer_addr)),
            channels: HashMap::new(),
            rejected: false,
        }
    }

    /// Create a new SSH handler with a custom auth provider.
    ///
    /// This is useful for testing or when you need a different auth provider.
    pub fn with_auth_provider(
        peer_addr: Option<SocketAddr>,
        config: Arc<ServerConfig>,
        sessions: Arc<RwLock<SessionManager>>,
        auth_provider: Arc<dyn AuthProvider>,
    ) -> Self {
        let rate_limiter = RateLimiter::with_simple_config(5, 1.0);

        Self {
            peer_addr,
            config,
            sessions,
            auth_provider,
            rate_limiter,
            auth_rate_limiter: None,
            session_info: Some(SessionInfo::new(peer_addr)),
            channels: HashMap::new(),
            rejected: false,
        }
    }

    /// Create a handler for a rejected connection.
    ///
    /// This handler will immediately reject all authentication attempts.
    /// Used when IP access control denies a connection.
    pub fn rejected(
        peer_addr: Option<SocketAddr>,
        config: Arc<ServerConfig>,
        sessions: Arc<RwLock<SessionManager>>,
    ) -> Self {
        let auth_provider = config.create_auth_provider();
        let rate_limiter = RateLimiter::with_simple_config(1, 0.1);

        Self {
            peer_addr,
            config,
            sessions,
            auth_provider,
            rate_limiter,
            auth_rate_limiter: None,
            session_info: None, // No session for rejected connections
            channels: HashMap::new(),
            rejected: true,
        }
    }

    /// Get the peer address of the connected client.
    pub fn peer_addr(&self) -> Option<SocketAddr> {
        self.peer_addr
    }

    /// Get the session ID, if the session has been created.
    pub fn session_id(&self) -> Option<SessionId> {
        self.session_info.as_ref().map(|s| s.id)
    }

    /// Check if the connection is authenticated.
    pub fn is_authenticated(&self) -> bool {
        self.session_info.as_ref().is_some_and(|s| s.authenticated)
    }

    /// Get the authenticated username, if any.
    pub fn username(&self) -> Option<&str> {
        self.session_info.as_ref().and_then(|s| s.user.as_deref())
    }

    /// Build the method set of allowed authentication methods.
    fn allowed_methods(&self) -> MethodSet {
        let mut methods = MethodSet::empty();

        if self.config.allow_publickey_auth {
            methods.push(MethodKind::PublicKey);
        }
        if self.config.allow_password_auth {
            methods.push(MethodKind::Password);
        }
        if self.config.allow_keyboard_interactive {
            methods.push(MethodKind::KeyboardInteractive);
        }

        methods
    }

    /// Check if the maximum authentication attempts has been exceeded.
    fn auth_attempts_exceeded(&self) -> bool {
        self.session_info
            .as_ref()
            .is_some_and(|s| s.auth_attempts >= self.config.max_auth_attempts)
    }
}

impl russh::server::Handler for SshHandler {
    type Error = anyhow::Error;

    /// Called when a new session channel is created.
    fn channel_open_session(
        &mut self,
        channel: Channel<Msg>,
        _session: &mut Session,
    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
        let channel_id = channel.id();
        tracing::debug!(
            peer = ?self.peer_addr,
            channel = ?channel_id,
            "Channel opened for session"
        );

        // Store the channel itself so we can use it for subsystems like SFTP
        self.channels
            .insert(channel_id, ChannelState::with_channel(channel));
        async { Ok(true) }
    }

    /// Handle 'none' authentication.
    ///
    /// Always rejects and advertises available authentication methods.
    fn auth_none(
        &mut self,
        user: &str,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        tracing::debug!(
            user = %user,
            peer = ?self.peer_addr,
            "Auth none attempt"
        );

        // If connection was rejected by IP access control, immediately reject
        if self.rejected {
            tracing::debug!(
                peer = ?self.peer_addr,
                "Rejecting auth for IP-blocked connection"
            );
            return std::future::ready(Ok(Auth::Reject {
                proceed_with_methods: None,
                partial_success: false,
            }))
            .left_future();
        }

        // Create session info if not already created
        let peer_addr = self.peer_addr;
        let sessions = Arc::clone(&self.sessions);
        let methods = self.allowed_methods();

        // We need to handle session creation
        let session_info_ref = &mut self.session_info;

        async move {
            if session_info_ref.is_none() {
                let mut sessions_guard = sessions.write().await;
                if let Some(info) = sessions_guard.create_session(peer_addr) {
                    tracing::info!(
                        session_id = %info.id,
                        peer = ?peer_addr,
                        "New session created"
                    );
                    *session_info_ref = Some(info);
                } else {
                    tracing::warn!(
                        peer = ?peer_addr,
                        "Session limit reached, rejecting connection"
                    );
                    return Ok(Auth::Reject {
                        proceed_with_methods: None,
                        partial_success: false,
                    });
                }
            }

            // Reject with available methods
            tracing::debug!(
                methods = ?methods,
                "Rejecting auth_none, advertising methods"
            );

            Ok(Auth::Reject {
                proceed_with_methods: Some(methods),
                partial_success: false,
            })
        }
        .right_future()
    }

    /// Handle public key authentication.
    ///
    /// Verifies the public key against the user's authorized_keys file.
    fn auth_publickey(
        &mut self,
        user: &str,
        public_key: &ssh_key::PublicKey,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        tracing::debug!(
            user = %user,
            peer = ?self.peer_addr,
            key_type = %public_key.algorithm(),
            "Public key authentication attempt"
        );

        // Increment auth attempts
        if let Some(ref mut info) = self.session_info {
            info.increment_auth_attempts();
        }

        // Check if max attempts exceeded
        let exceeded = self.auth_attempts_exceeded();
        let mut methods = self.allowed_methods();
        methods.remove(MethodKind::PublicKey);

        // Clone what we need for the async block
        let auth_provider = Arc::clone(&self.auth_provider);
        let sessions = Arc::clone(&self.sessions);
        let rate_limiter = self.rate_limiter.clone();
        let auth_rate_limiter = self.auth_rate_limiter.clone();
        let peer_addr = self.peer_addr;
        let user = user.to_string();
        let public_key = public_key.clone();

        // Get mutable reference to session_info for authentication update
        let session_info = &mut self.session_info;

        async move {
            // Check if IP is banned (fail2ban-like check)
            if let Some(ref limiter) = auth_rate_limiter {
                if let Some(ip) = peer_addr.map(|a| a.ip()) {
                    if limiter.is_banned(&ip).await {
                        tracing::warn!(
                            user = %user,
                            peer = ?peer_addr,
                            "Rejected auth from banned IP"
                        );
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }
                }
            }

            if exceeded {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Max authentication attempts exceeded"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Check rate limiting based on peer address
            let rate_key = peer_addr
                .map(|addr| addr.ip().to_string())
                .unwrap_or_else(|| "unknown".to_string());

            if rate_limiter.is_rate_limited(&rate_key).await {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Rate limited authentication attempt"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Try to acquire a rate limit token
            if rate_limiter.try_acquire(&rate_key).await.is_err() {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Rate limit exceeded"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Verify public key using auth provider
            match auth_provider.verify_publickey(&user, &public_key).await {
                Ok(result) if result.is_accepted() => {
                    tracing::info!(
                        user = %user,
                        peer = ?peer_addr,
                        key_type = %public_key.algorithm(),
                        "Public key authentication successful"
                    );

                    // Try to authenticate session with per-user limits
                    if let Some(ref info) = session_info {
                        let mut sessions_guard = sessions.write().await;
                        match sessions_guard.authenticate_session(info.id, &user) {
                            Ok(()) => {
                                // Also update local session info
                                drop(sessions_guard);
                                if let Some(ref mut local_info) = session_info {
                                    local_info.authenticate(&user);
                                }
                            }
                            Err(SessionError::TooManyUserSessions { user: u, limit }) => {
                                tracing::warn!(
                                    user = %u,
                                    limit = limit,
                                    peer = ?peer_addr,
                                    "Per-user session limit reached, rejecting authentication"
                                );
                                return Ok(Auth::Reject {
                                    proceed_with_methods: None,
                                    partial_success: false,
                                });
                            }
                            Err(e) => {
                                tracing::error!(
                                    user = %user,
                                    error = %e,
                                    "Failed to authenticate session"
                                );
                                return Ok(Auth::Reject {
                                    proceed_with_methods: None,
                                    partial_success: false,
                                });
                            }
                        }
                    }

                    // Record success to reset failure counter
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            limiter.record_success(&ip).await;
                        }
                    }

                    Ok(Auth::Accept)
                }
                Ok(_) => {
                    tracing::debug!(
                        user = %user,
                        peer = ?peer_addr,
                        key_type = %public_key.algorithm(),
                        "Public key authentication rejected"
                    );

                    // Record failure for ban tracking
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            let banned = limiter.record_failure(ip).await;
                            if banned {
                                tracing::warn!(
                                    user = %user,
                                    peer = ?peer_addr,
                                    "IP banned due to too many failed auth attempts"
                                );
                            }
                        }
                    }

                    let proceed = if methods.is_empty() {
                        None
                    } else {
                        Some(methods)
                    };

                    Ok(Auth::Reject {
                        proceed_with_methods: proceed,
                        partial_success: false,
                    })
                }
                Err(e) => {
                    tracing::error!(
                        user = %user,
                        peer = ?peer_addr,
                        error = %e,
                        "Error during public key verification"
                    );

                    // Record failure for ban tracking
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            limiter.record_failure(ip).await;
                        }
                    }

                    let proceed = if methods.is_empty() {
                        None
                    } else {
                        Some(methods)
                    };

                    Ok(Auth::Reject {
                        proceed_with_methods: proceed,
                        partial_success: false,
                    })
                }
            }
        }
    }

    /// Handle password authentication.
    ///
    /// Verifies the password against configured users using the auth provider.
    /// Implements rate limiting and tracks failed authentication attempts.
    fn auth_password(
        &mut self,
        user: &str,
        password: &str,
    ) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
        tracing::debug!(
            user = %user,
            peer = ?self.peer_addr,
            "Password authentication attempt"
        );

        // Increment auth attempts
        if let Some(ref mut info) = self.session_info {
            info.increment_auth_attempts();
        }

        // Check if max attempts exceeded
        let exceeded = self.auth_attempts_exceeded();
        let mut methods = self.allowed_methods();
        methods.remove(MethodKind::Password);

        // Clone what we need for the async block
        let auth_provider = Arc::clone(&self.auth_provider);
        let sessions = Arc::clone(&self.sessions);
        let rate_limiter = self.rate_limiter.clone();
        let auth_rate_limiter = self.auth_rate_limiter.clone();
        let peer_addr = self.peer_addr;
        let user = user.to_string();
        // Use Zeroizing to ensure password is securely cleared from memory when dropped
        let password = Zeroizing::new(password.to_string());
        let allow_password = self.config.allow_password_auth;

        // Get mutable reference to session_info for authentication update
        let session_info = &mut self.session_info;

        async move {
            // Check if IP is banned (fail2ban-like check)
            if let Some(ref limiter) = auth_rate_limiter {
                if let Some(ip) = peer_addr.map(|a| a.ip()) {
                    if limiter.is_banned(&ip).await {
                        tracing::warn!(
                            user = %user,
                            peer = ?peer_addr,
                            "Rejected password auth from banned IP"
                        );
                        return Ok(Auth::Reject {
                            proceed_with_methods: None,
                            partial_success: false,
                        });
                    }
                }
            }

            // Check if password auth is enabled
            if !allow_password {
                tracing::debug!(
                    user = %user,
                    "Password authentication disabled"
                );
                let proceed = if methods.is_empty() {
                    None
                } else {
                    Some(methods)
                };
                return Ok(Auth::Reject {
                    proceed_with_methods: proceed,
                    partial_success: false,
                });
            }

            if exceeded {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Max authentication attempts exceeded"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Check rate limiting based on peer address
            let rate_key = peer_addr
                .map(|addr| addr.ip().to_string())
                .unwrap_or_else(|| "unknown".to_string());

            if rate_limiter.is_rate_limited(&rate_key).await {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Rate limited password authentication attempt"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Try to acquire a rate limit token
            if rate_limiter.try_acquire(&rate_key).await.is_err() {
                tracing::warn!(
                    user = %user,
                    peer = ?peer_addr,
                    "Rate limit exceeded for password authentication"
                );
                return Ok(Auth::Reject {
                    proceed_with_methods: None,
                    partial_success: false,
                });
            }

            // Verify password using auth provider
            match auth_provider.verify_password(&user, &password).await {
                Ok(result) if result.is_accepted() => {
                    tracing::info!(
                        user = %user,
                        peer = ?peer_addr,
                        "Password authentication successful"
                    );

                    // Try to authenticate session with per-user limits
                    if let Some(ref info) = session_info {
                        let mut sessions_guard = sessions.write().await;
                        match sessions_guard.authenticate_session(info.id, &user) {
                            Ok(()) => {
                                // Also update local session info
                                drop(sessions_guard);
                                if let Some(ref mut local_info) = session_info {
                                    local_info.authenticate(&user);
                                }
                            }
                            Err(SessionError::TooManyUserSessions { user: u, limit }) => {
                                tracing::warn!(
                                    user = %u,
                                    limit = limit,
                                    peer = ?peer_addr,
                                    "Per-user session limit reached, rejecting authentication"
                                );
                                return Ok(Auth::Reject {
                                    proceed_with_methods: None,
                                    partial_success: false,
                                });
                            }
                            Err(e) => {
                                tracing::error!(
                                    user = %user,
                                    error = %e,
                                    "Failed to authenticate session"
                                );
                                return Ok(Auth::Reject {
                                    proceed_with_methods: None,
                                    partial_success: false,
                                });
                            }
                        }
                    }

                    // Record success to reset failure counter
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            limiter.record_success(&ip).await;
                        }
                    }

                    Ok(Auth::Accept)
                }
                Ok(_) => {
                    tracing::debug!(
                        user = %user,
                        peer = ?peer_addr,
                        "Password authentication rejected"
                    );

                    // Record failure for ban tracking
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            let banned = limiter.record_failure(ip).await;
                            if banned {
                                tracing::warn!(
                                    user = %user,
                                    peer = ?peer_addr,
                                    "IP banned due to too many failed password auth attempts"
                                );
                            }
                        }
                    }

                    let proceed = if methods.is_empty() {
                        None
                    } else {
                        Some(methods)
                    };

                    Ok(Auth::Reject {
                        proceed_with_methods: proceed,
                        partial_success: false,
                    })
                }
                Err(e) => {
                    tracing::error!(
                        user = %user,
                        peer = ?peer_addr,
                        error = %e,
                        "Error during password verification"
                    );

                    // Record failure for ban tracking
                    if let Some(ref limiter) = auth_rate_limiter {
                        if let Some(ip) = peer_addr.map(|a| a.ip()) {
                            limiter.record_failure(ip).await;
                        }
                    }

                    let proceed = if methods.is_empty() {
                        None
                    } else {
                        Some(methods)
                    };

                    Ok(Auth::Reject {
                        proceed_with_methods: proceed,
                        partial_success: false,
                    })
                }
            }
        }
    }

    /// Handle PTY request.
    ///
    /// Stores the PTY configuration for the channel.
    #[allow(clippy::too_many_arguments)]
    fn pty_request(
        &mut self,
        channel_id: ChannelId,
        term: &str,
        col_width: u32,
        row_height: u32,
        pix_width: u32,
        pix_height: u32,
        _modes: &[(Pty, u32)],
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!(
            term = %term,
            cols = %col_width,
            rows = %row_height,
            "PTY request"
        );

        if let Some(channel_state) = self.channels.get_mut(&channel_id) {
            let pty_config = PtyConfig::new(
                term.to_string(),
                col_width,
                row_height,
                pix_width,
                pix_height,
            );
            channel_state.set_pty(pty_config);
            let _ = session.channel_success(channel_id);
        } else {
            tracing::warn!("PTY request for unknown channel");
            let _ = session.channel_failure(channel_id);
        }

        async { Ok(()) }
    }

    /// Handle exec request.
    ///
    /// Executes the requested command and streams output back to the client.
    /// The command is executed via the configured shell with proper environment
    /// setup based on the authenticated user.
    ///
    /// Special handling is provided for SCP commands, which require bidirectional
    /// communication with the client.
    fn exec_request(
        &mut self,
        channel_id: ChannelId,
        data: &[u8],
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        // Parse command from data
        let command = match std::str::from_utf8(data) {
            Ok(cmd) => cmd.to_string(),
            Err(e) => {
                tracing::warn!(
                    channel = ?channel_id,
                    error = %e,
                    "Invalid UTF-8 in exec command"
                );
                let _ = session.channel_failure(channel_id);
                return async { Ok(()) }.boxed();
            }
        };

        tracing::debug!(
            channel = ?channel_id,
            command = %command,
            "Exec request received"
        );

        // Update channel state
        if let Some(channel_state) = self.channels.get_mut(&channel_id) {
            channel_state.set_exec(command.clone());
        }

        // Get authenticated user info
        let username = match self.session_info.as_ref().and_then(|s| s.user.clone()) {
            Some(user) => user,
            None => {
                tracing::warn!(
                    channel = ?channel_id,
                    "Exec request without authenticated user"
                );
                let _ = session.channel_failure(channel_id);
                return async { Ok(()) }.boxed();
            }
        };

        // Clone what we need for the async block
        let auth_provider = Arc::clone(&self.auth_provider);
        let exec_config = self.config.exec.clone();
        let scp_enabled = self.config.scp_enabled;
        let handle = session.handle();
        let peer_addr = self.peer_addr;

        // Check if this is an SCP command
        let scp_command = if scp_enabled && ScpCommand::is_scp_command(&command) {
            ScpCommand::parse(&command).ok()
        } else {
            None
        };

        // If SCP, we need to set up data forwarding
        let scp_data_rx = if scp_command.is_some() {
            let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1024);
            // Store the sender in channel state for data forwarding
            if let Some(state) = self.channels.get_mut(&channel_id) {
                state.shell_data_tx = Some(tx);
            }
            Some(rx)
        } else {
            None
        };

        // Signal channel success before executing
        let _ = session.channel_success(channel_id);

        async move {
            // Get user info from auth provider
            let user_info = match auth_provider.get_user_info(&username).await {
                Ok(Some(info)) => info,
                Ok(None) => {
                    tracing::error!(
                        user = %username,
                        "User not found after authentication"
                    );
                    let _ = handle.exit_status_request(channel_id, 1).await;
                    let _ = handle.eof(channel_id).await;
                    let _ = handle.close(channel_id).await;
                    return Ok(());
                }
                Err(e) => {
                    tracing::error!(
                        user = %username,
                        error = %e,
                        "Failed to get user info"
                    );
                    let _ = handle.exit_status_request(channel_id, 1).await;
                    let _ = handle.eof(channel_id).await;
                    let _ = handle.close(channel_id).await;
                    return Ok(());
                }
            };

            // Handle SCP commands specially
            if let Some(scp_cmd) = scp_command {
                tracing::info!(
                    user = %username,
                    peer = ?peer_addr,
                    mode = %scp_cmd.mode,
                    path = %scp_cmd.path.display(),
                    recursive = %scp_cmd.recursive,
                    "Executing SCP command"
                );

                // Get the receiver that was set up earlier
                let data_rx = match scp_data_rx {
                    Some(rx) => rx,
                    None => {
                        tracing::error!("SCP data receiver not set up");
                        let _ = handle.exit_status_request(channel_id, 1).await;
                        let _ = handle.eof(channel_id).await;
                        let _ = handle.close(channel_id).await;
                        return Ok(());
                    }
                };

                let handle_clone = handle.clone();

                // Create SCP handler with user's home directory as root
                let scp_handler = ScpHandler::from_command(
                    &scp_cmd,
                    user_info.clone(),
                    Some(user_info.home_dir.clone()),
                );

                // Run SCP in a spawned task so the session loop can process incoming data
                // The data() handler will forward data to shell_data_tx which the SCP handler
                // will receive via data_rx
                tokio::spawn(async move {
                    let exit_code = scp_handler
                        .run(channel_id, handle_clone.clone(), data_rx)
                        .await;

                    // Send exit status, EOF, and close channel
                    let _ = handle_clone
                        .exit_status_request(channel_id, exit_code as u32)
                        .await;
                    let _ = handle_clone.eof(channel_id).await;
                    let _ = handle_clone.close(channel_id).await;
                });

                return Ok(());
            }

            tracing::info!(
                user = %username,
                peer = ?peer_addr,
                command = %command,
                "Executing command"
            );

            // Create executor and run command
            let executor = CommandExecutor::new(exec_config);
            let exit_code = match executor
                .execute(&command, &user_info, channel_id, handle.clone())
                .await
            {
                Ok(code) => code,
                Err(e) => {
                    tracing::error!(
                        user = %username,
                        command = %command,
                        error = %e,
                        "Command execution failed"
                    );
                    1 // Default error exit code
                }
            };

            tracing::debug!(
                user = %username,
                command = %command,
                exit_code = %exit_code,
                "Command completed"
            );

            // Send exit status, EOF, and close channel
            let _ = handle
                .exit_status_request(channel_id, exit_code as u32)
                .await;
            let _ = handle.eof(channel_id).await;
            let _ = handle.close(channel_id).await;

            Ok(())
        }
        .boxed()
    }

    /// Handle shell request.
    ///
    /// Starts an interactive shell session for the authenticated user.
    /// Uses Handle-based I/O for PTY output to avoid notify_waiters() race conditions.
    /// The key insight is that Handle::data() uses notify_one() which stores a permit
    /// if no task is waiting, while ChannelTx uses notify_waiters() which only wakes
    /// tasks that are currently waiting. This causes intermittent failures with rapid
    /// connections when using ChannelStream-based I/O.
    fn shell_request(
        &mut self,
        channel_id: ChannelId,
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!(channel = ?channel_id, "Shell request");

        // Get authenticated user info
        let username = match self.session_info.as_ref().and_then(|s| s.user.clone()) {
            Some(user) => user,
            None => {
                tracing::warn!(
                    channel = ?channel_id,
                    "Shell request without authenticated user"
                );
                let _ = session.channel_failure(channel_id);
                return async { Ok(()) }.boxed();
            }
        };

        // Get PTY configuration
        let pty_config = match self.channels.get_mut(&channel_id) {
            Some(state) => {
                let config = state
                    .pty
                    .as_ref()
                    .map(|pty| {
                        PtyMasterConfig::new(
                            pty.term.clone(),
                            pty.col_width,
                            pty.row_height,
                            pty.pix_width,
                            pty.pix_height,
                        )
                    })
                    .unwrap_or_default();
                state.set_shell();
                config
            }
            None => {
                tracing::warn!(
                    channel = ?channel_id,
                    "Shell request but channel state not found"
                );
                let _ = session.channel_failure(channel_id);
                return async { Ok(()) }.boxed();
            }
        };

        // Create shell session (sync) to get the PTY
        let shell_session = match ShellSession::new(channel_id, pty_config.clone()) {
            Ok(session) => session,
            Err(e) => {
                tracing::error!(
                    channel = ?channel_id,
                    error = %e,
                    "Failed to create shell session"
                );
                let _ = session.channel_failure(channel_id);
                return async { Ok(()) }.boxed();
            }
        };

        // Get PTY reference for window_change_request
        let pty = Arc::clone(shell_session.pty());

        // Create channel for SSH -> PTY data (client input)
        let (data_tx, data_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1024);

        // Store handles in channel state for window_change callbacks and data forwarding
        if let Some(state) = self.channels.get_mut(&channel_id) {
            state.set_shell_handles(data_tx, Arc::clone(&pty));
        }

        // Clone what we need for the async block
        let auth_provider = Arc::clone(&self.auth_provider);
        let peer_addr = self.peer_addr;
        let handle = session.handle();

        // Signal success before starting shell
        let _ = session.channel_success(channel_id);

        async move {
            // Get user info from auth provider
            let user_info = match auth_provider.get_user_info(&username).await {
                Ok(Some(info)) => info,
                Ok(None) => {
                    tracing::error!(
                        user = %username,
                        "User not found after authentication for shell"
                    );
                    return Ok(());
                }
                Err(e) => {
                    tracing::error!(
                        user = %username,
                        error = %e,
                        "Failed to get user info for shell"
                    );
                    return Ok(());
                }
            };

            tracing::info!(
                user = %username,
                peer = ?peer_addr,
                term = %pty_config.term,
                size = %format!("{}x{}", pty_config.col_width, pty_config.row_height),
                "Starting shell session"
            );

            // Spawn shell process (async part)
            let mut shell_session = shell_session;
            if let Err(e) = shell_session.spawn_shell_process(&user_info).await {
                tracing::error!(
                    user = %username,
                    error = %e,
                    "Failed to spawn shell process"
                );
                return Ok(());
            }

            // Get child process for the I/O loop
            let child = shell_session.take_child();

            tracing::debug!(
                channel = ?channel_id,
                "Spawning shell I/O task with Handle-based approach"
            );

            // IMPORTANT: Spawn the I/O loop instead of awaiting it!
            // The session loop needs to keep running to flush Handle::data() messages
            // to the network. If we await here, the session loop is blocked.
            tokio::spawn(async move {
                let exit_code = crate::server::shell::run_shell_io_loop_with_handle(
                    channel_id,
                    pty,
                    child,
                    handle.clone(),
                    data_rx,
                )
                .await;

                tracing::info!(
                    channel = ?channel_id,
                    exit_code = exit_code,
                    "Shell session completed"
                );

                // Send exit status, EOF, and close channel (same as exec_request)
                // This is critical - without these, the SSH client waits indefinitely
                let _ = handle
                    .exit_status_request(channel_id, exit_code as u32)
                    .await;
                let _ = handle.eof(channel_id).await;
                let _ = handle.close(channel_id).await;
            });

            tracing::debug!(
                channel = ?channel_id,
                "Shell I/O task spawned, handler returning"
            );

            Ok(())
        }
        .boxed()
    }

    /// Handle subsystem request.
    ///
    /// Handles SFTP subsystem requests by creating an SftpHandler and running
    /// the SFTP server on the channel stream.
    fn subsystem_request(
        &mut self,
        channel_id: ChannelId,
        name: &str,
        session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!(
            subsystem = %name,
            channel = ?channel_id,
            peer = ?self.peer_addr,
            "Subsystem request"
        );

        // Handle SFTP subsystem
        if name == "sftp" {
            // Check if SFTP is enabled (default: enabled)
            // In future, this should check config.sftp.enabled

            // Get the channel from our stored channels
            let channel = self.channels.get_mut(&channel_id).and_then(|state| {
                state.set_sftp();
                state.take_channel()
            });

            let channel = match channel {
                Some(ch) => ch,
                None => {
                    tracing::warn!(
                        channel = ?channel_id,
                        "SFTP request but channel not found or already taken"
                    );
                    let _ = session.channel_failure(channel_id);
                    return async { Ok(()) }.boxed();
                }
            };

            // Get authenticated user info
            let username = match self.session_info.as_ref().and_then(|s| s.user.clone()) {
                Some(user) => user,
                None => {
                    tracing::warn!(
                        channel = ?channel_id,
                        "SFTP request without authenticated user"
                    );
                    let _ = session.channel_failure(channel_id);
                    return async { Ok(()) }.boxed();
                }
            };

            // Clone what we need for the async block
            let auth_provider = Arc::clone(&self.auth_provider);
            let peer_addr = self.peer_addr;

            // Signal success before spawning the SFTP handler
            let _ = session.channel_success(channel_id);

            return async move {
                // Get user info from auth provider
                let user_info = match auth_provider.get_user_info(&username).await {
                    Ok(Some(info)) => info,
                    Ok(None) => {
                        tracing::error!(
                            user = %username,
                            "User not found after authentication for SFTP"
                        );
                        return Ok(());
                    }
                    Err(e) => {
                        tracing::error!(
                            user = %username,
                            error = %e,
                            "Failed to get user info for SFTP"
                        );
                        return Ok(());
                    }
                };

                tracing::info!(
                    user = %username,
                    peer = ?peer_addr,
                    home = %user_info.home_dir.display(),
                    "Starting SFTP session"
                );

                // Create SFTP handler with user's home directory as root
                let sftp_handler = SftpHandler::new(user_info.clone(), Some(user_info.home_dir));

                // Run SFTP server on the channel stream
                russh_sftp::server::run(channel.into_stream(), sftp_handler).await;

                tracing::info!(
                    user = %username,
                    peer = ?peer_addr,
                    "SFTP session ended"
                );

                Ok(())
            }
            .boxed();
        }

        // Unknown subsystem - reject
        tracing::debug!(
            subsystem = %name,
            "Unknown subsystem, rejecting"
        );
        let _ = session.channel_failure(channel_id);
        async { Ok(()) }.boxed()
    }

    /// Handle incoming data from the client.
    ///
    /// Forwards data to the active shell session if one exists.
    fn data(
        &mut self,
        channel_id: ChannelId,
        data: &[u8],
        _session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!(
            channel = ?channel_id,
            bytes = %data.len(),
            "Received data from client"
        );

        // Get the data sender if there's an active shell session
        let data_sender = self
            .channels
            .get(&channel_id)
            .and_then(|state| state.shell_data_tx.clone());

        if let Some(tx) = data_sender {
            tracing::debug!(
                channel = ?channel_id,
                bytes = %data.len(),
                "Forwarding data to shell via mpsc"
            );
            let data = data.to_vec();
            return async move {
                if let Err(e) = tx.send(data).await {
                    tracing::debug!(
                        channel = ?channel_id,
                        error = %e,
                        "Error forwarding data to shell"
                    );
                } else {
                    tracing::debug!(
                        channel = ?channel_id,
                        "Data forwarded to shell successfully"
                    );
                }
                Ok(())
            }
            .boxed();
        } else {
            tracing::debug!(
                channel = ?channel_id,
                "No shell_data_tx found for channel, dropping data"
            );
        }

        async { Ok(()) }.boxed()
    }

    /// Handle window size change request.
    ///
    /// Updates the PTY window size for active shell sessions.
    #[allow(clippy::too_many_arguments)]
    fn window_change_request(
        &mut self,
        channel_id: ChannelId,
        col_width: u32,
        row_height: u32,
        pix_width: u32,
        pix_height: u32,
        _session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!(
            channel = ?channel_id,
            cols = col_width,
            rows = row_height,
            "Window change request"
        );

        // Update stored PTY config
        if let Some(state) = self.channels.get_mut(&channel_id) {
            if let Some(ref mut pty) = state.pty {
                pty.col_width = col_width;
                pty.row_height = row_height;
                pty.pix_width = pix_width;
                pty.pix_height = pix_height;
            }
        }

        // Get the PTY mutex if there's an active shell session
        let pty_mutex = self
            .channels
            .get(&channel_id)
            .and_then(|state| state.shell_pty.clone());

        if let Some(pty) = pty_mutex {
            return async move {
                let mut pty_guard = pty.write().await;
                if let Err(e) = pty_guard.resize(col_width, row_height) {
                    tracing::debug!(
                        channel = ?channel_id,
                        error = %e,
                        "Error resizing shell PTY"
                    );
                }
                Ok(())
            }
            .boxed();
        }

        async { Ok(()) }.boxed()
    }

    /// Handle channel EOF from the client.
    fn channel_eof(
        &mut self,
        channel_id: ChannelId,
        _session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!("Channel EOF received");

        if let Some(channel_state) = self.channels.get_mut(&channel_id) {
            channel_state.mark_eof();
        }

        async { Ok(()) }
    }

    /// Handle channel close from the client.
    fn channel_close(
        &mut self,
        channel_id: ChannelId,
        _session: &mut Session,
    ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
        tracing::debug!("Channel closed");

        self.channels.remove(&channel_id);
        async { Ok(()) }
    }
}

impl Drop for SshHandler {
    fn drop(&mut self) {
        if let Some(ref info) = self.session_info {
            let session_id = info.id;

            tracing::info!(
                session_id = %session_id,
                peer = ?self.peer_addr,
                duration_secs = %info.duration_secs(),
                authenticated = %info.authenticated,
                "Session ended"
            );

            // Remove session from manager with retry mechanism
            // We use try_write with retries to ensure cleanup even under contention.
            // This is important to prevent session leaks that could exhaust limits.
            let mut retries = 0;
            const MAX_RETRIES: u32 = 5;

            loop {
                if let Ok(mut sessions_guard) = self.sessions.try_write() {
                    sessions_guard.remove(session_id);
                    tracing::debug!(
                        session_id = %session_id,
                        retries = retries,
                        "Session removed from manager"
                    );
                    break;
                }

                retries += 1;
                if retries >= MAX_RETRIES {
                    tracing::error!(
                        session_id = %session_id,
                        retries = retries,
                        "Failed to remove session after max retries - session may leak"
                    );
                    break;
                }

                // Brief delay before retry (exponential backoff in microseconds)
                // This is safe in Drop as we're in a sync context
                std::thread::sleep(std::time::Duration::from_micros(100 * (1 << retries)));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::auth_types::{AuthResult, UserInfo};
    use async_trait::async_trait;
    use std::net::{IpAddr, Ipv4Addr};

    fn test_addr() -> SocketAddr {
        SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 22222)
    }

    fn test_config() -> Arc<ServerConfig> {
        Arc::new(
            ServerConfig::builder()
                .allow_password_auth(true)
                .allow_publickey_auth(true)
                .build(),
        )
    }

    fn test_sessions() -> Arc<RwLock<SessionManager>> {
        Arc::new(RwLock::new(SessionManager::new()))
    }

    /// Test auth provider that always accepts
    struct AcceptAllAuthProvider;

    #[async_trait]
    impl AuthProvider for AcceptAllAuthProvider {
        async fn verify_publickey(
            &self,
            _username: &str,
            _key: &ssh_key::PublicKey,
        ) -> anyhow::Result<AuthResult> {
            Ok(AuthResult::Accept)
        }

        async fn verify_password(
            &self,
            _username: &str,
            _password: &str,
        ) -> anyhow::Result<AuthResult> {
            Ok(AuthResult::Accept)
        }

        async fn get_user_info(&self, username: &str) -> anyhow::Result<Option<UserInfo>> {
            Ok(Some(UserInfo::new(username)))
        }

        async fn user_exists(&self, _username: &str) -> anyhow::Result<bool> {
            Ok(true)
        }
    }

    /// Test auth provider that always rejects
    #[allow(dead_code)] // May be used in future tests
    struct RejectAllAuthProvider;

    #[async_trait]
    impl AuthProvider for RejectAllAuthProvider {
        async fn verify_publickey(
            &self,
            _username: &str,
            _key: &ssh_key::PublicKey,
        ) -> anyhow::Result<AuthResult> {
            Ok(AuthResult::Reject)
        }

        async fn verify_password(
            &self,
            _username: &str,
            _password: &str,
        ) -> anyhow::Result<AuthResult> {
            Ok(AuthResult::Reject)
        }

        async fn get_user_info(&self, _username: &str) -> anyhow::Result<Option<UserInfo>> {
            Ok(None)
        }

        async fn user_exists(&self, _username: &str) -> anyhow::Result<bool> {
            Ok(false)
        }
    }

    #[test]
    fn test_handler_creation() {
        let handler = SshHandler::new(Some(test_addr()), test_config(), test_sessions());

        assert_eq!(handler.peer_addr(), Some(test_addr()));
        // Session ID is assigned at creation time
        assert!(handler.session_id().is_some());
        assert!(!handler.is_authenticated());
        assert!(handler.username().is_none());
    }

    #[test]
    fn test_handler_with_custom_auth_provider() {
        let handler = SshHandler::with_auth_provider(
            Some(test_addr()),
            test_config(),
            test_sessions(),
            Arc::new(AcceptAllAuthProvider),
        );

        assert_eq!(handler.peer_addr(), Some(test_addr()));
    }

    #[test]
    fn test_allowed_methods_all() {
        let config = Arc::new(
            ServerConfig::builder()
                .allow_password_auth(true)
                .allow_publickey_auth(true)
                .allow_keyboard_interactive(true)
                .build(),
        );
        let handler = SshHandler::new(Some(test_addr()), config, test_sessions());
        let methods = handler.allowed_methods();

        assert!(methods.contains(&MethodKind::Password));
        assert!(methods.contains(&MethodKind::PublicKey));
        assert!(methods.contains(&MethodKind::KeyboardInteractive));
    }

    #[test]
    fn test_allowed_methods_none() {
        let config = Arc::new(
            ServerConfig::builder()
                .allow_password_auth(false)
                .allow_publickey_auth(false)
                .allow_keyboard_interactive(false)
                .build(),
        );
        let handler = SshHandler::new(Some(test_addr()), config, test_sessions());
        let methods = handler.allowed_methods();

        assert!(methods.is_empty());
    }

    #[test]
    fn test_auth_attempts_not_exceeded() {
        let config = Arc::new(ServerConfig::builder().max_auth_attempts(3).build());
        let handler = SshHandler::new(Some(test_addr()), config, test_sessions());

        assert!(!handler.auth_attempts_exceeded());
    }

    #[test]
    fn test_handler_no_peer_addr() {
        let handler = SshHandler::new(None, test_config(), test_sessions());

        assert!(handler.peer_addr().is_none());
        // Session ID is assigned at creation time even without peer address
        assert!(handler.session_id().is_some());
        assert!(!handler.is_authenticated());
    }

    #[test]
    fn test_allowed_methods_publickey_only() {
        let config = Arc::new(
            ServerConfig::builder()
                .allow_password_auth(false)
                .allow_publickey_auth(true)
                .allow_keyboard_interactive(false)
                .build(),
        );
        let handler = SshHandler::new(Some(test_addr()), config, test_sessions());
        let methods = handler.allowed_methods();

        assert!(methods.contains(&MethodKind::PublicKey));
        assert!(!methods.contains(&MethodKind::Password));
        assert!(!methods.contains(&MethodKind::KeyboardInteractive));
    }

    #[test]
    fn test_allowed_methods_password_only() {
        let config = Arc::new(
            ServerConfig::builder()
                .allow_password_auth(true)
                .allow_publickey_auth(false)
                .allow_keyboard_interactive(false)
                .build(),
        );
        let handler = SshHandler::new(Some(test_addr()), config, test_sessions());
        let methods = handler.allowed_methods();

        assert!(!methods.contains(&MethodKind::PublicKey));
        assert!(methods.contains(&MethodKind::Password));
        assert!(!methods.contains(&MethodKind::KeyboardInteractive));
    }
}