bssh 3.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
// 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.

//! Server configuration module.
//!
//! This module provides both the original builder-based configuration API
//! and a new comprehensive YAML file-based configuration system.
//!
//! # Configuration Systems
//!
//! ## Builder-Based Configuration (Original)
//!
//! The [`ServerConfig`] and [`ServerConfigBuilder`] provide a programmatic
//! way to configure the server:
//!
//! ```
//! use bssh::server::config::{ServerConfig, ServerConfigBuilder};
//!
//! let config = ServerConfig::builder()
//!     .host_key("/etc/ssh/ssh_host_ed25519_key")
//!     .listen_address("0.0.0.0:2222")
//!     .max_connections(100)
//!     .build();
//! ```
//!
//! ## File-Based Configuration (New)
//!
//! The new configuration system supports loading from YAML files with
//! environment variable and CLI argument overrides:
//!
//! ```no_run
//! use bssh::server::config::load_config;
//!
//! # fn main() -> anyhow::Result<()> {
//! // Load from default locations or environment
//! let file_config = load_config(None)?;
//!
//! // Convert to ServerConfig for use with BsshServer
//! let server_config = file_config.into_server_config();
//! # Ok(())
//! # }
//! ```
//!
//! # Configuration File Format
//!
//! Configuration files use YAML format. Generate a template with:
//!
//! ```
//! use bssh::server::config::generate_config_template;
//!
//! let template = generate_config_template();
//! println!("{}", template);
//! ```

mod loader;
mod types;

// Re-export the new configuration types and functions
pub use loader::{generate_config_template, load_config};
pub use types::*;

// Re-export the original config types for backward compatibility
use super::auth::{
    AuthProvider, CompositeAuthProvider, PasswordAuthConfig, PublicKeyAuthConfig, PublicKeyVerifier,
};
use super::exec::ExecConfig;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

/// Configuration for the SSH server (original builder-based API).
///
/// This is the original configuration type used by [`BsshServer`].
/// For file-based configuration, use [`ServerFileConfig`] and convert
/// it using [`into_server_config()`](ServerFileConfig::into_server_config).
///
/// # Example
///
/// ```
/// use bssh::server::config::ServerConfig;
///
/// let config = ServerConfig::builder()
///     .host_key("/etc/ssh/ssh_host_ed25519_key")
///     .listen_address("0.0.0.0:2222")
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    /// Paths to host key files (e.g., SSH private keys).
    #[serde(default)]
    pub host_keys: Vec<PathBuf>,

    /// Address to listen on (e.g., "0.0.0.0:2222").
    #[serde(default = "default_listen_address")]
    pub listen_address: String,

    /// Maximum number of concurrent connections.
    #[serde(default = "default_max_connections")]
    pub max_connections: usize,

    /// Maximum number of authentication attempts per connection.
    #[serde(default = "default_max_auth_attempts")]
    pub max_auth_attempts: u32,

    /// Timeout for authentication in seconds.
    #[serde(default = "default_auth_timeout_secs")]
    pub auth_timeout_secs: u64,

    /// Connection idle timeout in seconds.
    #[serde(default = "default_idle_timeout_secs")]
    pub idle_timeout_secs: u64,

    /// Enable password authentication.
    #[serde(default)]
    pub allow_password_auth: bool,

    /// Enable public key authentication.
    #[serde(default = "default_true")]
    pub allow_publickey_auth: bool,

    /// Enable keyboard-interactive authentication.
    #[serde(default)]
    pub allow_keyboard_interactive: bool,

    /// Banner message displayed to clients before authentication.
    #[serde(default)]
    pub banner: Option<String>,

    /// Configuration for public key authentication.
    #[serde(default)]
    pub publickey_auth: PublicKeyAuthConfigSerde,

    /// Configuration for password authentication.
    #[serde(default)]
    pub password_auth: PasswordAuthConfigSerde,

    /// Configuration for command execution.
    #[serde(default)]
    pub exec: ExecConfig,

    /// Enable SCP protocol support.
    #[serde(default = "default_true")]
    pub scp_enabled: bool,

    /// Optional chroot directory for SFTP operations.
    ///
    /// When `None` (default), SFTP runs without chroot: absolute client paths
    /// are used verbatim and relative paths resolve from the user's home
    /// directory, matching OpenSSH `sftp-server` semantics.
    ///
    /// When set, SFTP clients are confined to this directory. The client's `/`
    /// is the chroot root, so absolute and relative paths are re-anchored under
    /// it (a host-looking `/etc/passwd` is confined to `<root>/etc/passwd`) and
    /// `..` cannot escape.
    #[serde(default)]
    pub sftp_root: Option<PathBuf>,

    /// Optional chroot directory for SCP transfers.
    ///
    /// Has the same semantics as [`Self::sftp_root`]. When `None` and
    /// `sftp_root` is set, SCP falls back to `sftp_root`. Configure both
    /// fields only if SCP and SFTP need different chroots.
    #[serde(default)]
    pub scp_root: Option<PathBuf>,

    /// Time window for counting authentication attempts in seconds.
    ///
    /// Default: 300 (5 minutes)
    #[serde(default = "default_auth_window_secs")]
    pub auth_window_secs: u64,

    /// Ban duration in seconds after exceeding max auth attempts.
    ///
    /// Default: 300 (5 minutes)
    #[serde(default = "default_ban_time_secs")]
    pub ban_time_secs: u64,

    /// IP addresses that are never banned (whitelist).
    #[serde(default)]
    pub whitelist_ips: Vec<String>,

    /// Allowed IP ranges in CIDR notation for connection filtering.
    ///
    /// If non-empty, only connections from these ranges are allowed.
    /// Empty list means all IPs are allowed (subject to blocked_ips).
    #[serde(default)]
    pub allowed_ips: Vec<String>,

    /// Blocked IP ranges in CIDR notation for connection filtering.
    ///
    /// Connections from these ranges are always denied.
    /// Blocked IPs take priority over allowed IPs.
    #[serde(default)]
    pub blocked_ips: Vec<String>,

    /// Maximum number of concurrent sessions per user.
    ///
    /// Default: 10
    #[serde(default = "default_max_sessions_per_user")]
    pub max_sessions_per_user: usize,

    /// Maximum session duration in seconds (optional).
    ///
    /// If set to 0, sessions have no maximum duration.
    /// Default: 0 (disabled)
    #[serde(default)]
    pub session_timeout_secs: u64,

    /// Advertise SSH transport compression (`zlib`, `zlib@openssh.com`).
    ///
    /// When `false` (default), the server advertises only `none` so clients
    /// fall back to the uncompressed transport. This is the safe default:
    /// russh's delayed-zlib (`zlib@openssh.com`) transport desyncs a few
    /// packets after compression activates post-auth, dropping clients that
    /// negotiate it (Cyberduck, `sftp -C`) mid-session. Enable only after
    /// verifying compression interoperability with every deployed client.
    #[serde(default)]
    pub compression: bool,

    /// Maximum SSH channel packet size in bytes advertised to clients.
    ///
    /// Larger packets amortize per-packet cipher and copy overhead; russh's
    /// library default of 32768 fragments a 256 KiB SFTP write into 8
    /// CHANNEL_DATA packets. Clamped to at most 65535, which russh requires.
    /// Default: 65535.
    #[serde(default = "default_maximum_packet_size")]
    pub maximum_packet_size: u32,

    /// SSH channel flow-control window size in bytes advertised to clients.
    ///
    /// Bounds in-flight client data per channel (and thus per-channel
    /// buffering). Default: 8 MiB, four times the russh library default, so
    /// bulk uploads do not stall on window-adjust round trips.
    #[serde(default = "default_window_size")]
    pub window_size: u32,
}

fn default_max_sessions_per_user() -> usize {
    10
}

/// Serializable configuration for public key authentication.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PublicKeyAuthConfigSerde {
    /// Directory containing authorized_keys files.
    pub authorized_keys_dir: Option<PathBuf>,

    /// Alternative: file path pattern with `{user}` placeholder.
    pub authorized_keys_pattern: Option<String>,
}

impl From<PublicKeyAuthConfigSerde> for PublicKeyAuthConfig {
    fn from(serde_config: PublicKeyAuthConfigSerde) -> Self {
        if let Some(dir) = serde_config.authorized_keys_dir {
            PublicKeyAuthConfig::with_directory(dir)
        } else if let Some(pattern) = serde_config.authorized_keys_pattern {
            PublicKeyAuthConfig::with_pattern(pattern)
        } else {
            PublicKeyAuthConfig::default()
        }
    }
}

/// Serializable configuration for password authentication.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PasswordAuthConfigSerde {
    /// Path to YAML file containing user definitions.
    pub users_file: Option<PathBuf>,

    /// Inline user definitions.
    #[serde(default)]
    pub users: Vec<UserDefinition>,
}

impl From<PasswordAuthConfigSerde> for PasswordAuthConfig {
    fn from(serde_config: PasswordAuthConfigSerde) -> Self {
        PasswordAuthConfig {
            users_file: serde_config.users_file,
            users: serde_config.users,
        }
    }
}

fn default_listen_address() -> String {
    "0.0.0.0:2222".to_string()
}

fn default_max_connections() -> usize {
    100
}

fn default_max_auth_attempts() -> u32 {
    5
}

fn default_auth_timeout_secs() -> u64 {
    120
}

fn default_idle_timeout_secs() -> u64 {
    0 // 0 means no timeout
}

fn default_auth_window_secs() -> u64 {
    300 // 5 minutes
}

fn default_ban_time_secs() -> u64 {
    300 // 5 minutes
}

fn default_true() -> bool {
    true
}

fn default_maximum_packet_size() -> u32 {
    // russh rejects channel packets larger than a TCP frame (65535);
    // advertise the cap to minimize SFTP write fragmentation (issue #187).
    65535
}

fn default_window_size() -> u32 {
    // 8 MiB: four times the russh default; see ServerSettings::window_size.
    8 * 1024 * 1024
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host_keys: Vec::new(),
            listen_address: default_listen_address(),
            max_connections: default_max_connections(),
            max_auth_attempts: default_max_auth_attempts(),
            auth_timeout_secs: default_auth_timeout_secs(),
            idle_timeout_secs: default_idle_timeout_secs(),
            allow_password_auth: false,
            allow_publickey_auth: true,
            allow_keyboard_interactive: false,
            banner: None,
            publickey_auth: PublicKeyAuthConfigSerde::default(),
            password_auth: PasswordAuthConfigSerde::default(),
            exec: ExecConfig::default(),
            scp_enabled: true,
            sftp_root: None,
            scp_root: None,
            auth_window_secs: default_auth_window_secs(),
            ban_time_secs: default_ban_time_secs(),
            whitelist_ips: Vec::new(),
            allowed_ips: Vec::new(),
            blocked_ips: Vec::new(),
            max_sessions_per_user: default_max_sessions_per_user(),
            session_timeout_secs: 0,
            compression: false,
            maximum_packet_size: default_maximum_packet_size(),
            window_size: default_window_size(),
        }
    }
}

impl ServerConfig {
    /// Create a new server configuration with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for constructing server configuration.
    pub fn builder() -> ServerConfigBuilder {
        ServerConfigBuilder::default()
    }

    /// Get the authentication timeout as a Duration.
    pub fn auth_timeout(&self) -> Duration {
        Duration::from_secs(self.auth_timeout_secs)
    }

    /// Get the idle timeout as a Duration.
    ///
    /// Returns `None` if idle timeout is disabled (set to 0).
    pub fn idle_timeout(&self) -> Option<Duration> {
        if self.idle_timeout_secs == 0 {
            None
        } else {
            Some(Duration::from_secs(self.idle_timeout_secs))
        }
    }

    /// Get the session timeout as a Duration.
    ///
    /// Returns `None` if session timeout is disabled (set to 0).
    pub fn session_timeout(&self) -> Option<Duration> {
        if self.session_timeout_secs == 0 {
            None
        } else {
            Some(Duration::from_secs(self.session_timeout_secs))
        }
    }

    /// Create a SessionConfig from the server configuration.
    pub fn session_config(&self) -> super::session::SessionConfig {
        let mut config = super::session::SessionConfig::new()
            .with_max_sessions_per_user(self.max_sessions_per_user)
            .with_max_total_sessions(self.max_connections);

        if self.idle_timeout_secs > 0 {
            config = config.with_idle_timeout(Duration::from_secs(self.idle_timeout_secs));
        }

        if self.session_timeout_secs > 0 {
            config = config.with_session_timeout(Duration::from_secs(self.session_timeout_secs));
        }

        config
    }

    /// Check if any host keys are configured.
    pub fn has_host_keys(&self) -> bool {
        !self.host_keys.is_empty()
    }

    /// Add a host key path.
    pub fn add_host_key(&mut self, path: impl Into<PathBuf>) {
        self.host_keys.push(path.into());
    }

    /// Create an auth provider based on the configuration.
    ///
    /// This creates a composite auth provider that supports:
    /// - Public key authentication (if `allow_publickey_auth` is true)
    /// - Password authentication (if `allow_password_auth` is true)
    ///
    /// The provider is created synchronously using a blocking runtime.
    /// For async creation, use `create_auth_provider_async`.
    pub fn create_auth_provider(&self) -> Arc<dyn AuthProvider> {
        // If neither method is enabled, return a public key only provider (will reject all)
        if !self.allow_publickey_auth && !self.allow_password_auth {
            let config: PublicKeyAuthConfig = self.publickey_auth.clone().into();
            return Arc::new(PublicKeyVerifier::new(config));
        }

        // If only public key auth is enabled, use simple provider
        if self.allow_publickey_auth && !self.allow_password_auth {
            let config: PublicKeyAuthConfig = self.publickey_auth.clone().into();
            return Arc::new(PublicKeyVerifier::new(config));
        }

        // If password auth is enabled, we need to create a composite provider
        // Use blocking call since this is called during server startup
        let publickey_config = if self.allow_publickey_auth {
            Some(self.publickey_auth.clone().into())
        } else {
            None
        };

        let password_config = if self.allow_password_auth {
            Some(self.password_auth.clone().into())
        } else {
            None
        };

        // Create the composite provider using blocking runtime
        // This is safe because this is only called during server initialization
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                match tokio::task::block_in_place(|| {
                    handle.block_on(CompositeAuthProvider::new(
                        publickey_config,
                        password_config,
                    ))
                }) {
                    Ok(provider) => Arc::new(provider),
                    Err(e) => {
                        tracing::error!(error = %e, "Failed to create composite auth provider, falling back to publickey only");
                        let config: PublicKeyAuthConfig = self.publickey_auth.clone().into();
                        Arc::new(PublicKeyVerifier::new(config))
                    }
                }
            }
            Err(_) => {
                // No async runtime, create a new one
                let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime");
                match rt.block_on(CompositeAuthProvider::new(
                    publickey_config,
                    password_config,
                )) {
                    Ok(provider) => Arc::new(provider),
                    Err(e) => {
                        tracing::error!(error = %e, "Failed to create composite auth provider, falling back to publickey only");
                        let config: PublicKeyAuthConfig = self.publickey_auth.clone().into();
                        Arc::new(PublicKeyVerifier::new(config))
                    }
                }
            }
        }
    }
}

/// Builder for constructing ServerConfig.
#[derive(Debug, Default)]
pub struct ServerConfigBuilder {
    config: ServerConfig,
}

impl ServerConfigBuilder {
    /// Set the host key paths.
    pub fn host_keys(mut self, keys: Vec<PathBuf>) -> Self {
        self.config.host_keys = keys;
        self
    }

    /// Add a host key path.
    pub fn host_key(mut self, key: impl Into<PathBuf>) -> Self {
        self.config.host_keys.push(key.into());
        self
    }

    /// Set the listen address.
    pub fn listen_address(mut self, addr: impl Into<String>) -> Self {
        self.config.listen_address = addr.into();
        self
    }

    /// Set the maximum number of connections.
    pub fn max_connections(mut self, max: usize) -> Self {
        self.config.max_connections = max;
        self
    }

    /// Set the maximum authentication attempts.
    pub fn max_auth_attempts(mut self, max: u32) -> Self {
        self.config.max_auth_attempts = max;
        self
    }

    /// Set the authentication timeout in seconds.
    pub fn auth_timeout_secs(mut self, secs: u64) -> Self {
        self.config.auth_timeout_secs = secs;
        self
    }

    /// Set the idle timeout in seconds.
    pub fn idle_timeout_secs(mut self, secs: u64) -> Self {
        self.config.idle_timeout_secs = secs;
        self
    }

    /// Enable or disable password authentication.
    pub fn allow_password_auth(mut self, allow: bool) -> Self {
        self.config.allow_password_auth = allow;
        self
    }

    /// Enable or disable public key authentication.
    pub fn allow_publickey_auth(mut self, allow: bool) -> Self {
        self.config.allow_publickey_auth = allow;
        self
    }

    /// Enable or disable keyboard-interactive authentication.
    pub fn allow_keyboard_interactive(mut self, allow: bool) -> Self {
        self.config.allow_keyboard_interactive = allow;
        self
    }

    /// Set the banner message.
    pub fn banner(mut self, banner: impl Into<String>) -> Self {
        self.config.banner = Some(banner.into());
        self
    }

    /// Set the authorized_keys directory.
    pub fn authorized_keys_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config.publickey_auth.authorized_keys_dir = Some(dir.into());
        self.config.publickey_auth.authorized_keys_pattern = None;
        self
    }

    /// Set the authorized_keys file pattern.
    pub fn authorized_keys_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.config.publickey_auth.authorized_keys_pattern = Some(pattern.into());
        self.config.publickey_auth.authorized_keys_dir = None;
        self
    }

    /// Set the password users file path.
    pub fn password_users_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.config.password_auth.users_file = Some(path.into());
        self
    }

    /// Set inline password users.
    pub fn password_users(mut self, users: Vec<UserDefinition>) -> Self {
        self.config.password_auth.users = users;
        self
    }

    /// Set the exec configuration.
    pub fn exec(mut self, exec_config: ExecConfig) -> Self {
        self.config.exec = exec_config;
        self
    }

    /// Set the command execution timeout in seconds.
    pub fn exec_timeout_secs(mut self, secs: u64) -> Self {
        self.config.exec.timeout_secs = secs;
        self
    }

    /// Set the default shell for command execution.
    pub fn exec_shell(mut self, shell: impl Into<PathBuf>) -> Self {
        self.config.exec.default_shell = shell.into();
        self
    }

    /// Enable or disable SCP protocol support.
    pub fn scp_enabled(mut self, enabled: bool) -> Self {
        self.config.scp_enabled = enabled;
        self
    }

    /// Set the SFTP chroot directory.
    ///
    /// When `None`, SFTP runs without chroot (OpenSSH-compatible default).
    /// When set, SFTP clients are confined to this directory.
    pub fn sftp_root(mut self, root: Option<PathBuf>) -> Self {
        self.config.sftp_root = root;
        self
    }

    /// Set the SCP chroot directory.
    ///
    /// When `None`, SCP falls back to [`sftp_root`](Self::sftp_root) if set,
    /// otherwise runs without chroot. Set both fields only when SCP and SFTP
    /// need different chroots.
    pub fn scp_root(mut self, root: Option<PathBuf>) -> Self {
        self.config.scp_root = root;
        self
    }

    /// Set the maximum sessions per user.
    pub fn max_sessions_per_user(mut self, max: usize) -> Self {
        self.config.max_sessions_per_user = max;
        self
    }

    /// Set the session timeout in seconds.
    pub fn session_timeout_secs(mut self, secs: u64) -> Self {
        self.config.session_timeout_secs = secs;
        self
    }

    /// Enable or disable SSH transport compression negotiation.
    ///
    /// Disabled by default: russh's delayed-zlib (`zlib@openssh.com`)
    /// transport desyncs mid-session, so the server advertises only `none`
    /// unless this is explicitly enabled. Test interoperability with every
    /// deployed client before enabling it.
    pub fn compression(mut self, enabled: bool) -> Self {
        self.config.compression = enabled;
        self
    }

    /// Set the maximum SSH channel packet size in bytes.
    ///
    /// Values above 65535 are clamped when the russh config is built.
    pub fn maximum_packet_size(mut self, size: u32) -> Self {
        self.config.maximum_packet_size = size;
        self
    }

    /// Set the SSH channel flow-control window size in bytes.
    pub fn window_size(mut self, size: u32) -> Self {
        self.config.window_size = size;
        self
    }

    /// Build the ServerConfig.
    pub fn build(self) -> ServerConfig {
        self.config
    }
}

/// Extension trait for converting file-based config to builder-based config.
impl ServerFileConfig {
    /// Convert a file-based configuration to a builder-based ServerConfig.
    ///
    /// This enables using file-based configuration with the existing BsshServer API.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bssh::server::{BsshServer, config::load_config};
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let file_config = load_config(None)?;
    /// let server_config = file_config.into_server_config();
    /// let server = BsshServer::new(server_config);
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_server_config(self) -> ServerConfig {
        let listen_address = format!("{}:{}", self.server.bind_address, self.server.port);

        // Determine which auth methods are enabled
        let allow_publickey = self.auth.methods.contains(&AuthMethod::PublicKey);
        let allow_password = self.auth.methods.contains(&AuthMethod::Password);

        ServerConfig {
            host_keys: self.server.host_keys,
            listen_address,
            max_connections: self.server.max_connections,
            max_auth_attempts: self.security.max_auth_attempts,
            auth_timeout_secs: self.server.timeout,
            idle_timeout_secs: self.security.idle_timeout,
            allow_password_auth: allow_password,
            allow_publickey_auth: allow_publickey,
            allow_keyboard_interactive: false,
            banner: None,
            publickey_auth: PublicKeyAuthConfigSerde {
                authorized_keys_dir: self.auth.publickey.authorized_keys_dir,
                authorized_keys_pattern: self.auth.publickey.authorized_keys_pattern,
            },
            password_auth: PasswordAuthConfigSerde {
                users_file: self.auth.password.users_file,
                users: self.auth.password.users,
            },
            exec: ExecConfig {
                default_shell: self.shell.default,
                timeout_secs: self.shell.command_timeout,
                env: self.shell.env,
                working_dir: None,
                allowed_commands: None,
                blocked_commands: Vec::new(),
            },
            scp_enabled: self.scp.enabled,
            // SCP falls back to sftp.root when scp.root is unset so a single
            // top-level chroot setting governs both subsystems.
            scp_root: self.scp.root.or_else(|| self.sftp.root.clone()),
            sftp_root: self.sftp.root,
            auth_window_secs: self.security.auth_window,
            ban_time_secs: self.security.ban_time,
            whitelist_ips: self.security.whitelist_ips,
            allowed_ips: self.security.allowed_ips,
            blocked_ips: self.security.blocked_ips,
            max_sessions_per_user: self.security.max_sessions_per_user,
            session_timeout_secs: self.security.session_timeout,
            compression: self.server.compression,
            maximum_packet_size: self.server.maximum_packet_size,
            window_size: self.server.window_size,
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = ServerConfig::default();
        assert!(config.host_keys.is_empty());
        assert_eq!(config.listen_address, "0.0.0.0:2222");
        assert_eq!(config.max_connections, 100);
        assert_eq!(config.max_auth_attempts, 5);
        assert!(!config.allow_password_auth);
        assert!(config.allow_publickey_auth);
        assert!(config.scp_enabled);
    }

    #[test]
    fn test_config_builder() {
        let config = ServerConfig::builder()
            .host_key("/etc/ssh/ssh_host_ed25519_key")
            .listen_address("127.0.0.1:22")
            .max_connections(50)
            .max_auth_attempts(3)
            .allow_password_auth(true)
            .banner("Welcome to bssh server!")
            .build();

        assert_eq!(config.host_keys.len(), 1);
        assert_eq!(config.listen_address, "127.0.0.1:22");
        assert_eq!(config.max_connections, 50);
        assert_eq!(config.max_auth_attempts, 3);
        assert!(config.allow_password_auth);
        assert_eq!(config.banner, Some("Welcome to bssh server!".to_string()));
    }

    #[test]
    fn test_file_config_to_server_config_conversion() {
        let mut file_config = ServerFileConfig::default();
        file_config.server.bind_address = "127.0.0.1".to_string();
        file_config.server.port = 2223;
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];
        file_config.auth.methods = vec![AuthMethod::PublicKey, AuthMethod::Password];
        file_config.security.max_auth_attempts = 3;
        file_config.security.idle_timeout = 600;

        let server_config = file_config.into_server_config();

        assert_eq!(server_config.listen_address, "127.0.0.1:2223");
        assert_eq!(server_config.host_keys.len(), 1);
        assert_eq!(server_config.max_auth_attempts, 3);
        assert_eq!(server_config.idle_timeout_secs, 600);
        assert!(server_config.allow_publickey_auth);
        assert!(server_config.allow_password_auth);
    }

    #[test]
    fn sftp_root_threads_into_server_config() {
        // Setting sftp.root should propagate to ServerConfig.sftp_root, and
        // scp_root should fall back to it when scp.root is unset.
        let mut file_config = ServerFileConfig::default();
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];
        file_config.sftp.root = Some(PathBuf::from("/srv/sftp"));

        let server_config = file_config.into_server_config();

        assert_eq!(server_config.sftp_root, Some(PathBuf::from("/srv/sftp")));
        assert_eq!(server_config.scp_root, Some(PathBuf::from("/srv/sftp")));
    }

    #[test]
    fn scp_root_overrides_sftp_root_fallback() {
        // When scp.root is explicitly set, it takes precedence over the
        // sftp.root fallback so admins can split the two chroots.
        let mut file_config = ServerFileConfig::default();
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];
        file_config.sftp.root = Some(PathBuf::from("/srv/sftp"));
        file_config.scp.root = Some(PathBuf::from("/srv/scp"));

        let server_config = file_config.into_server_config();

        assert_eq!(server_config.sftp_root, Some(PathBuf::from("/srv/sftp")));
        assert_eq!(server_config.scp_root, Some(PathBuf::from("/srv/scp")));
    }

    #[test]
    fn no_chroot_by_default() {
        // The new default: both scp_root and sftp_root are None when no
        // configuration is provided. This is the OpenSSH-compatible default
        // documented for issue #186.
        let mut file_config = ServerFileConfig::default();
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];

        let server_config = file_config.into_server_config();

        assert!(server_config.sftp_root.is_none());
        assert!(server_config.scp_root.is_none());
    }

    #[test]
    fn compression_defaults_to_off_and_threads_into_server_config() {
        // #220: compression must default to off (preserving the #215
        // workaround) and the file-config `server.compression` flag must
        // propagate into ServerConfig.
        let mut file_config = ServerFileConfig::default();
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];
        assert!(!file_config.server.compression);

        let server_config = file_config.clone().into_server_config();
        assert!(!server_config.compression);

        file_config.server.compression = true;
        let server_config = file_config.into_server_config();
        assert!(server_config.compression);
    }

    #[test]
    fn channel_sizing_defaults_and_threads_into_server_config() {
        // #187: tuned channel-sizing defaults, overridable via the file
        // config, must propagate into ServerConfig.
        let mut file_config = ServerFileConfig::default();
        file_config.server.host_keys = vec![PathBuf::from("/test/key")];
        assert_eq!(file_config.server.maximum_packet_size, 65535);
        assert_eq!(file_config.server.window_size, 8 * 1024 * 1024);

        file_config.server.maximum_packet_size = 32768;
        file_config.server.window_size = 4 * 1024 * 1024;
        let server_config = file_config.into_server_config();
        assert_eq!(server_config.maximum_packet_size, 32768);
        assert_eq!(server_config.window_size, 4 * 1024 * 1024);
    }

    #[test]
    fn test_config_new() {
        let config = ServerConfig::new();
        assert!(config.host_keys.is_empty());
        assert_eq!(config.listen_address, "0.0.0.0:2222");
    }

    #[test]
    fn test_auth_timeout() {
        let config = ServerConfig::default();
        assert_eq!(config.auth_timeout(), Duration::from_secs(120));
    }

    #[test]
    fn test_idle_timeout() {
        let mut config = ServerConfig::default();
        assert!(config.idle_timeout().is_none());

        config.idle_timeout_secs = 300;
        assert_eq!(config.idle_timeout(), Some(Duration::from_secs(300)));
    }

    #[test]
    fn test_has_host_keys() {
        let mut config = ServerConfig::default();
        assert!(!config.has_host_keys());

        config.add_host_key("/path/to/key");
        assert!(config.has_host_keys());
    }
}