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

//! Configuration loader for bssh-server.
//!
//! This module handles loading configuration from multiple sources with
//! the following precedence (highest to lowest):
//! 1. CLI arguments
//! 2. Environment variables
//! 3. Configuration file (YAML)
//! 4. Default values

use super::types::ServerFileConfig;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Load configuration from file, environment, and CLI arguments.
///
/// # Configuration Precedence
///
/// Configuration is loaded with the following precedence (highest to lowest):
/// 1. CLI arguments (when supported)
/// 2. Environment variables (BSSH_* prefix)
/// 3. Configuration file (YAML)
/// 4. Default values
///
/// # Arguments
///
/// * `config_path` - Optional path to configuration file. If None, searches default locations.
///
/// # Default Locations
///
/// If no config path is specified, searches in order:
/// 1. `./bssh-server.yaml` (current directory)
/// 2. `/etc/bssh/server.yaml` (system-wide)
/// 3. `$XDG_CONFIG_HOME/bssh/server.yaml` or `~/.config/bssh/server.yaml` (user-specific)
///
/// # Environment Variables
///
/// The following environment variables can override config file settings:
///
/// - `BSSH_PORT` - Server port (e.g., "2222")
/// - `BSSH_BIND_ADDRESS` - Bind address (e.g., "0.0.0.0")
/// - `BSSH_HOST_KEY` - Comma-separated host key paths
/// - `BSSH_MAX_CONNECTIONS` - Maximum concurrent connections
/// - `BSSH_KEEPALIVE_INTERVAL` - Keepalive interval in seconds
/// - `BSSH_AUTH_METHODS` - Comma-separated auth methods (e.g., "publickey,password")
/// - `BSSH_AUTHORIZED_KEYS_DIR` - Directory for authorized_keys files
/// - `BSSH_AUTHORIZED_KEYS_PATTERN` - Pattern for authorized_keys paths
/// - `BSSH_SHELL` - Default shell path
/// - `BSSH_COMMAND_TIMEOUT` - Command timeout in seconds
///
/// # Example
///
/// ```no_run
/// use bssh::server::config::load_config;
///
/// # fn main() -> anyhow::Result<()> {
/// // Load from default locations
/// let config = load_config(None)?;
///
/// // Load from specific file
/// let config = load_config(Some("/etc/bssh/custom.yaml".as_ref()))?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - Configuration file cannot be read or parsed
/// - Environment variables have invalid values
/// - Configuration validation fails
pub fn load_config(config_path: Option<&Path>) -> Result<ServerFileConfig> {
    // Start with defaults
    let mut config = ServerFileConfig::default();

    // Load from file if specified or found in default locations
    if let Some(path) = config_path {
        config = load_config_file(path).context("Failed to load configuration file")?;
        tracing::info!(path = %path.display(), "Loaded configuration from file");
    } else {
        // Try default locations
        for path in default_config_paths() {
            if path.exists() {
                config = load_config_file(&path).context("Failed to load configuration file")?;
                tracing::info!(path = %path.display(), "Loaded configuration from file");
                break;
            }
        }
    }

    // Apply environment variable overrides
    config = apply_env_overrides(config)?;

    // Validate configuration
    validate_config(&config)?;

    Ok(config)
}

/// Generate a configuration template as YAML string.
///
/// This generates a fully documented configuration file template with
/// all available options and their default values.
///
/// # Example
///
/// ```
/// use bssh::server::config::generate_config_template;
///
/// let template = generate_config_template();
/// std::fs::write("bssh-server.yaml", template).unwrap();
/// ```
pub fn generate_config_template() -> String {
    let config = ServerFileConfig::default();
    let mut yaml = String::new();

    // Add header comment
    yaml.push_str("# bssh-server configuration file\n");
    yaml.push_str("#\n");
    yaml.push_str(
        "# This is a comprehensive configuration template showing all available options.\n",
    );
    yaml.push_str("# Uncomment and modify options as needed.\n");
    yaml.push_str("#\n");
    yaml.push_str("# Configuration hierarchy (highest to lowest precedence):\n");
    yaml.push_str("# 1. CLI arguments\n");
    yaml.push_str("# 2. Environment variables (BSSH_* prefix)\n");
    yaml.push_str("# 3. This configuration file\n");
    yaml.push_str("# 4. Default values\n\n");

    // Serialize config with defaults
    yaml.push_str(&serde_yaml::to_string(&config).unwrap_or_default());

    yaml
}

/// Load configuration from a YAML file.
fn load_config_file(path: &Path) -> Result<ServerFileConfig> {
    // MEDIUM: Check config file permissions on Unix
    #[cfg(unix)]
    check_config_file_permissions(path)?;

    let content =
        std::fs::read_to_string(path).context(format!("Failed to read {}", path.display()))?;

    serde_yaml::from_str(&content).context(format!("Failed to parse {}", path.display()))
}

/// Check configuration file permissions on Unix systems.
///
/// Warns if the config file is readable by group or others, as configuration
/// files may contain sensitive information.
#[cfg(unix)]
fn check_config_file_permissions(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    let metadata = std::fs::metadata(path)
        .context(format!("Failed to read metadata for {}", path.display()))?;
    let permissions = metadata.permissions();
    let mode = permissions.mode();

    // Check if file is readable by group or others (mode & 0o077 != 0)
    if mode & 0o077 != 0 {
        tracing::warn!(
            path = %path.display(),
            mode = format!("{:o}", mode & 0o777),
            "Configuration file is readable by group or others. \
             Consider using 'chmod 600 {}' to restrict access.",
            path.display()
        );
    }

    Ok(())
}

/// Get default configuration file search paths.
fn default_config_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();

    // Current directory
    paths.push(PathBuf::from("./bssh-server.yaml"));

    // System-wide config
    paths.push(PathBuf::from("/etc/bssh/server.yaml"));

    // User config directory
    if let Some(config_dir) = dirs::config_dir() {
        paths.push(config_dir.join("bssh/server.yaml"));
    }

    paths
}

/// Apply environment variable overrides to configuration.
fn apply_env_overrides(mut config: ServerFileConfig) -> Result<ServerFileConfig> {
    // BSSH_PORT
    if let Ok(port_str) = std::env::var("BSSH_PORT") {
        config.server.port = port_str
            .parse()
            .context(format!("Invalid BSSH_PORT value: {port_str}"))?;
        tracing::debug!(port = config.server.port, "Applied BSSH_PORT override");
    }

    // BSSH_BIND_ADDRESS
    if let Ok(addr) = std::env::var("BSSH_BIND_ADDRESS") {
        config.server.bind_address = addr.clone();
        tracing::debug!(address = %addr, "Applied BSSH_BIND_ADDRESS override");
    }

    // BSSH_HOST_KEY (comma-separated list)
    if let Ok(keys) = std::env::var("BSSH_HOST_KEY") {
        config.server.host_keys = keys.split(',').map(|s| PathBuf::from(s.trim())).collect();
        tracing::debug!(
            key_count = config.server.host_keys.len(),
            "Applied BSSH_HOST_KEY override"
        );
    }

    // BSSH_MAX_CONNECTIONS
    if let Ok(max_str) = std::env::var("BSSH_MAX_CONNECTIONS") {
        config.server.max_connections = max_str
            .parse()
            .context(format!("Invalid BSSH_MAX_CONNECTIONS value: {max_str}"))?;
        tracing::debug!(
            max = config.server.max_connections,
            "Applied BSSH_MAX_CONNECTIONS override"
        );
    }

    // BSSH_KEEPALIVE_INTERVAL
    if let Ok(interval_str) = std::env::var("BSSH_KEEPALIVE_INTERVAL") {
        config.server.keepalive_interval = interval_str.parse().context(format!(
            "Invalid BSSH_KEEPALIVE_INTERVAL value: {interval_str}"
        ))?;
        tracing::debug!(
            interval = config.server.keepalive_interval,
            "Applied BSSH_KEEPALIVE_INTERVAL override"
        );
    }

    // BSSH_AUTH_METHODS (comma-separated: "publickey,password")
    if let Ok(methods_str) = std::env::var("BSSH_AUTH_METHODS") {
        use super::types::AuthMethod;
        let mut methods = Vec::new();
        for method in methods_str.split(',') {
            let method = method.trim().to_lowercase();
            match method.as_str() {
                "publickey" => methods.push(AuthMethod::PublicKey),
                "password" => methods.push(AuthMethod::Password),
                _ => {
                    anyhow::bail!("Unknown auth method in BSSH_AUTH_METHODS: {}", method);
                }
            }
        }
        config.auth.methods = methods;
        tracing::debug!(
            methods = ?config.auth.methods,
            "Applied BSSH_AUTH_METHODS override"
        );
    }

    // BSSH_AUTHORIZED_KEYS_DIR
    if let Ok(dir) = std::env::var("BSSH_AUTHORIZED_KEYS_DIR") {
        config.auth.publickey.authorized_keys_dir = Some(PathBuf::from(dir.clone()));
        config.auth.publickey.authorized_keys_pattern = None;
        tracing::debug!(dir = %dir, "Applied BSSH_AUTHORIZED_KEYS_DIR override");
    }

    // BSSH_AUTHORIZED_KEYS_PATTERN
    if let Ok(pattern) = std::env::var("BSSH_AUTHORIZED_KEYS_PATTERN") {
        config.auth.publickey.authorized_keys_pattern = Some(pattern.clone());
        config.auth.publickey.authorized_keys_dir = None;
        tracing::debug!(
            pattern = %pattern,
            "Applied BSSH_AUTHORIZED_KEYS_PATTERN override"
        );
    }

    // BSSH_SHELL
    if let Ok(shell) = std::env::var("BSSH_SHELL") {
        config.shell.default = PathBuf::from(shell.clone());
        tracing::debug!(shell = %shell, "Applied BSSH_SHELL override");
    }

    // BSSH_COMMAND_TIMEOUT
    if let Ok(timeout_str) = std::env::var("BSSH_COMMAND_TIMEOUT") {
        config.shell.command_timeout = timeout_str
            .parse()
            .context(format!("Invalid BSSH_COMMAND_TIMEOUT value: {timeout_str}"))?;
        tracing::debug!(
            timeout = config.shell.command_timeout,
            "Applied BSSH_COMMAND_TIMEOUT override"
        );
    }

    Ok(config)
}

/// Validate configuration for correctness.
fn validate_config(config: &ServerFileConfig) -> Result<()> {
    // Validate host keys exist
    if config.server.host_keys.is_empty() {
        anyhow::bail!(
            "At least one host key must be configured (server.host_keys or BSSH_HOST_KEY)"
        );
    }

    for key_path in &config.server.host_keys {
        if !key_path.exists() {
            anyhow::bail!("Host key file not found: {}", key_path.display());
        }
    }

    // Validate authentication configuration
    if config.auth.methods.is_empty() {
        anyhow::bail!("At least one authentication method must be enabled (auth.methods)");
    }

    // HIGH: Validate bind_address is a valid IP address
    config
        .server
        .bind_address
        .parse::<std::net::IpAddr>()
        .context(format!(
            "Invalid bind_address: {}",
            config.server.bind_address
        ))?;

    // HIGH: Validate authorized_keys_pattern for path traversal
    if let Some(ref pattern) = config.auth.publickey.authorized_keys_pattern {
        // Ensure pattern doesn't contain ".." after substitution
        if pattern.contains("..") {
            anyhow::bail!(
                "authorized_keys_pattern contains '..' which could lead to path traversal: {}",
                pattern
            );
        }

        // For patterns with {user} placeholder, validate structure
        if pattern.contains("{user}") {
            // After removing {user}, the pattern should start with absolute path
            let without_placeholder = pattern.replace("{user}", "");
            if !without_placeholder.starts_with('/') && !without_placeholder.starts_with("./") {
                anyhow::bail!(
                    "authorized_keys_pattern must use absolute paths: {}",
                    pattern
                );
            }
        } else if !pattern.starts_with('/') {
            // If no placeholder, must be absolute path
            anyhow::bail!(
                "authorized_keys_pattern must use absolute paths: {}",
                pattern
            );
        }
    }

    // MEDIUM: Validate shell path exists
    if !config.shell.default.exists() {
        anyhow::bail!(
            "Default shell does not exist: {}",
            config.shell.default.display()
        );
    }

    // Validate IP ranges (CIDR notation)
    for cidr in &config.security.allowed_ips {
        cidr.parse::<ipnetwork::IpNetwork>()
            .context(format!("Invalid CIDR notation in allowed_ips: {cidr}"))?;
    }

    for cidr in &config.security.blocked_ips {
        cidr.parse::<ipnetwork::IpNetwork>()
            .context(format!("Invalid CIDR notation in blocked_ips: {cidr}"))?;
    }

    // Validate port number
    if config.server.port == 0 {
        anyhow::bail!("Server port cannot be 0");
    }

    // Validate max connections
    if config.server.max_connections == 0 {
        anyhow::bail!("max_connections must be greater than 0");
    }

    tracing::info!("Configuration validation passed");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_generate_config_template() {
        let template = generate_config_template();
        assert!(template.contains("bssh-server configuration"));
        assert!(template.contains("server:"));
        assert!(template.contains("auth:"));
        assert!(template.contains("shell:"));

        // Template should be valid YAML
        let parsed: Result<ServerFileConfig, _> = serde_yaml::from_str(&template);
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_load_config_from_file() {
        let yaml_content = r#"
server:
  port: 2223
  bind_address: "127.0.0.1"
  host_keys:
    - /tmp/test_key
auth:
  methods:
    - publickey
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(yaml_content.as_bytes()).unwrap();
        temp_file.flush().unwrap();

        let config = load_config_file(temp_file.path()).unwrap();
        assert_eq!(config.server.port, 2223);
        assert_eq!(config.server.bind_address, "127.0.0.1");
        assert_eq!(config.server.host_keys.len(), 1);
    }

    #[test]
    #[serial_test::serial]
    fn test_env_override_port() {
        // Clear any existing env vars
        std::env::remove_var("BSSH_PORT");

        std::env::set_var("BSSH_PORT", "3333");
        let config = apply_env_overrides(ServerFileConfig::default()).unwrap();
        assert_eq!(config.server.port, 3333);
        std::env::remove_var("BSSH_PORT");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_override_bind_address() {
        // Clear any existing env vars
        std::env::remove_var("BSSH_PORT");

        std::env::set_var("BSSH_BIND_ADDRESS", "192.168.1.1");
        let config = apply_env_overrides(ServerFileConfig::default()).unwrap();
        assert_eq!(config.server.bind_address, "192.168.1.1");
        std::env::remove_var("BSSH_BIND_ADDRESS");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_override_host_keys() {
        // Clear any existing env vars
        std::env::remove_var("BSSH_PORT");

        std::env::set_var("BSSH_HOST_KEY", "/key1,/key2,/key3");
        let config = apply_env_overrides(ServerFileConfig::default()).unwrap();
        assert_eq!(config.server.host_keys.len(), 3);
        assert_eq!(config.server.host_keys[0], PathBuf::from("/key1"));
        std::env::remove_var("BSSH_HOST_KEY");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_override_auth_methods() {
        // Clear any existing env vars
        std::env::remove_var("BSSH_PORT");

        std::env::set_var("BSSH_AUTH_METHODS", "publickey,password");
        let config = apply_env_overrides(ServerFileConfig::default()).unwrap();
        assert_eq!(config.auth.methods.len(), 2);
        std::env::remove_var("BSSH_AUTH_METHODS");
    }

    #[test]
    #[serial_test::serial]
    fn test_env_override_invalid_port() {
        // Clear any existing env vars first
        std::env::remove_var("BSSH_PORT");

        std::env::set_var("BSSH_PORT", "invalid");
        let result = apply_env_overrides(ServerFileConfig::default());
        assert!(result.is_err());
        std::env::remove_var("BSSH_PORT");
    }

    #[test]
    fn test_validate_config_no_host_keys() {
        let mut config = ServerFileConfig::default();
        config.server.host_keys.clear();

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("At least one host key"));
    }

    #[test]
    fn test_validate_config_no_auth_methods() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.auth.methods.clear();

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("authentication method"));
    }

    #[test]
    fn test_validate_config_invalid_cidr() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.security.allowed_ips.push("invalid-cidr".to_string());

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("CIDR"));
    }

    #[test]
    fn test_validate_config_valid_cidr() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config
            .security
            .allowed_ips
            .push("192.168.1.0/24".to_string());
        config.security.blocked_ips.push("10.0.0.0/8".to_string());

        // Should pass validation with valid CIDR
        let result = validate_config(&config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_config_zero_port() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.server.port = 0;

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("port cannot be 0"));
    }

    #[test]
    fn test_validate_config_zero_max_connections() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.server.max_connections = 0;

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("max_connections must be greater than 0"));
    }

    #[test]
    fn test_validate_config_invalid_bind_address() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.server.bind_address = "not-an-ip-address".to_string();

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid bind_address"));
    }

    #[test]
    fn test_validate_config_valid_bind_address() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());

        // Test IPv4
        config.server.bind_address = "127.0.0.1".to_string();
        assert!(validate_config(&config).is_ok());

        // Test IPv6
        config.server.bind_address = "::1".to_string();
        assert!(validate_config(&config).is_ok());

        // Test wildcard
        config.server.bind_address = "0.0.0.0".to_string();
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_config_authorized_keys_pattern_path_traversal() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());

        // Test pattern with ".."
        config.auth.publickey.authorized_keys_pattern = Some("/home/../etc/passwd".to_string());
        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("path traversal"));
    }

    #[test]
    fn test_validate_config_authorized_keys_pattern_relative_path() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());

        // Test relative path without placeholder
        config.auth.publickey.authorized_keys_pattern = Some("relative/path".to_string());
        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("absolute paths"));
    }

    #[test]
    fn test_validate_config_authorized_keys_pattern_valid() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());

        // Test valid absolute path with placeholder
        config.auth.publickey.authorized_keys_pattern =
            Some("/home/{user}/.ssh/authorized_keys".to_string());
        assert!(validate_config(&config).is_ok());

        // Test valid absolute path without placeholder
        config.auth.publickey.authorized_keys_pattern =
            Some("/etc/bssh/authorized_keys".to_string());
        assert!(validate_config(&config).is_ok());
    }

    #[test]
    fn test_validate_config_shell_not_exists() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"fake host key").unwrap();
        temp_file.flush().unwrap();

        let mut config = ServerFileConfig::default();
        config.server.host_keys.push(temp_file.path().to_path_buf());
        config.shell.default = PathBuf::from("/nonexistent/shell");

        let result = validate_config(&config);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Default shell does not exist"));
    }

    #[cfg(unix)]
    #[test]
    fn test_config_file_permissions_warning() {
        use std::os::unix::fs::PermissionsExt;

        let yaml_content = r#"
server:
  port: 2222
  host_keys:
    - /tmp/test_key
"#;

        // Create temp file with world-readable permissions
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(yaml_content.as_bytes()).unwrap();
        temp_file.flush().unwrap();

        // Set permissions to 0644 (world-readable)
        let mut permissions = temp_file.as_file().metadata().unwrap().permissions();
        permissions.set_mode(0o644);
        std::fs::set_permissions(temp_file.path(), permissions).unwrap();

        // This should succeed but log a warning
        let result = check_config_file_permissions(temp_file.path());
        assert!(result.is_ok());

        // Set permissions to 0600 (owner only)
        let mut permissions = temp_file.as_file().metadata().unwrap().permissions();
        permissions.set_mode(0o600);
        std::fs::set_permissions(temp_file.path(), permissions).unwrap();

        // This should succeed without warning
        let result = check_config_file_permissions(temp_file.path());
        assert!(result.is_ok());
    }
}