synapse-waf 0.9.1

High-performance WAF and reverse proxy with embedded intelligence — built on Cloudflare Pingora
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
//! Configuration loading and validation for Synapse-Pingora.
//!
//! This module handles YAML configuration parsing with security validations
//! including file size limits, path validation, and schema verification.

use crate::shadow::ShadowMirrorConfig;
use crate::trap::TrapConfig;
use crate::vhost::SiteConfig;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fmt;
use std::fs;
use std::path::Path;
use tracing::{debug, info, warn};

/// Maximum configuration file size (10MB).
const MAX_CONFIG_SIZE: u64 = 10 * 1024 * 1024;

/// Global server configuration.
#[derive(Clone, Serialize, Deserialize, JsonSchema)]
pub struct GlobalConfig {
    /// HTTP listen address (default: 0.0.0.0:80)
    #[serde(default = "default_http_addr")]
    pub http_addr: String,
    /// HTTPS listen address (default: 0.0.0.0:443)
    #[serde(default = "default_https_addr")]
    pub https_addr: String,
    /// Number of worker threads (0 = auto-detect)
    #[serde(default)]
    pub workers: usize,
    /// Graceful shutdown timeout in seconds
    #[serde(default = "default_shutdown_timeout")]
    pub shutdown_timeout_secs: u64,
    /// Global WAF threshold (0-100)
    #[serde(default = "default_waf_threshold")]
    pub waf_threshold: u8,
    /// Whether WAF is globally enabled
    #[serde(default = "default_true")]
    pub waf_enabled: bool,
    /// Log level (trace, debug, info, warn, error)
    #[serde(default = "default_log_level")]
    pub log_level: String,
    /// API key for the admin server (if unset, a secure random key is generated at startup)
    #[serde(default)]
    pub admin_api_key: Option<String>,
    /// Honeypot trap endpoint configuration
    #[serde(default)]
    pub trap_config: Option<TrapConfig>,
    /// WAF regex evaluation timeout in milliseconds (prevents ReDoS attacks).
    /// Default: 100ms. Maximum: 500ms (capped to prevent disabling protection).
    #[serde(default = "default_waf_regex_timeout_ms")]
    pub waf_regex_timeout_ms: u64,
}

fn default_waf_regex_timeout_ms() -> u64 {
    100 // 100ms default, matching issue requirement
}

fn default_http_addr() -> String {
    "0.0.0.0:80".to_string()
}

fn default_https_addr() -> String {
    "0.0.0.0:443".to_string()
}

fn default_shutdown_timeout() -> u64 {
    30
}

fn default_waf_threshold() -> u8 {
    70
}

fn default_true() -> bool {
    true
}

fn default_log_level() -> String {
    "info".to_string()
}

impl fmt::Debug for GlobalConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlobalConfig")
            .field("http_addr", &self.http_addr)
            .field("https_addr", &self.https_addr)
            .field("workers", &self.workers)
            .field("shutdown_timeout_secs", &self.shutdown_timeout_secs)
            .field("waf_threshold", &self.waf_threshold)
            .field("waf_enabled", &self.waf_enabled)
            .field("log_level", &self.log_level)
            .field(
                "admin_api_key",
                &self.admin_api_key.as_ref().map(|_| "[REDACTED]"),
            )
            .field("trap_config", &self.trap_config)
            .field("waf_regex_timeout_ms", &self.waf_regex_timeout_ms)
            .finish()
    }
}

impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            http_addr: default_http_addr(),
            https_addr: default_https_addr(),
            workers: 0,
            shutdown_timeout_secs: default_shutdown_timeout(),
            waf_threshold: default_waf_threshold(),
            waf_enabled: true,
            log_level: default_log_level(),
            admin_api_key: None,
            trap_config: None,
            waf_regex_timeout_ms: default_waf_regex_timeout_ms(),
        }
    }
}

/// Rate limiting configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RateLimitConfig {
    /// Requests per second limit
    pub rps: u32,
    /// Whether rate limiting is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Burst capacity (defaults to rps * 2)
    pub burst: Option<u32>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            rps: 10000,
            enabled: true,
            burst: None,
        }
    }
}

/// Upstream backend configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct UpstreamConfig {
    /// Backend host
    pub host: String,
    /// Backend port
    pub port: u16,
    /// Weight for load balancing (default: 1)
    #[serde(default = "default_weight")]
    pub weight: u32,
    /// Whether this backend is healthy
    #[serde(skip)]
    pub healthy: bool,
}

fn default_weight() -> u32 {
    1
}

/// TLS configuration for a site.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TlsConfig {
    /// Path to certificate file (PEM format)
    pub cert_path: String,
    /// Path to private key file (PEM format)
    pub key_path: String,
    /// Minimum TLS version (1.2 or 1.3)
    #[serde(default = "default_min_tls")]
    pub min_version: String,
}

fn default_min_tls() -> String {
    "1.2".to_string()
}

/// Access control configuration for a site.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
pub struct AccessControlConfig {
    /// List of CIDR ranges to allow
    #[serde(default)]
    pub allow: Vec<String>,
    /// List of CIDR ranges to deny
    #[serde(default)]
    pub deny: Vec<String>,
    /// Default action if no rule matches (allow or deny)
    #[serde(default)]
    pub default_action: String,
}

/// Header manipulation configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
pub struct HeaderConfig {
    /// Headers to add/set/remove on the request
    #[serde(default)]
    pub request: HeaderOps,
    /// Headers to add/set/remove on the response
    #[serde(default)]
    pub response: HeaderOps,
}

/// Header operations (add, set, remove).
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
pub struct HeaderOps {
    /// Headers to add (appends if already exists)
    #[serde(default)]
    pub add: std::collections::HashMap<String, String>,
    /// Headers to set (replaces if already exists)
    #[serde(default)]
    pub set: std::collections::HashMap<String, String>,
    /// Headers to remove
    #[serde(default)]
    pub remove: Vec<String>,
}

/// Site-specific WAF configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SiteWafConfig {
    /// Whether WAF is enabled for this site
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Risk threshold (0-100)
    pub threshold: Option<u8>,
    /// Rule overrides (rule_id -> action)
    #[serde(default)]
    pub rule_overrides: std::collections::HashMap<String, String>,
}

impl Default for SiteWafConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold: None,
            rule_overrides: std::collections::HashMap::new(),
        }
    }
}

/// Site configuration from YAML.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SiteYamlConfig {
    /// Hostname or wildcard pattern
    pub hostname: String,
    /// Upstream backends
    pub upstreams: Vec<UpstreamConfig>,
    /// TLS configuration (optional)
    pub tls: Option<TlsConfig>,
    /// WAF configuration (optional)
    pub waf: Option<SiteWafConfig>,
    /// Rate limiting configuration (optional)
    pub rate_limit: Option<RateLimitConfig>,
    /// Access control (optional)
    pub access_control: Option<AccessControlConfig>,
    /// Header manipulation (optional)
    pub headers: Option<HeaderConfig>,
    /// Shadow mirroring configuration (optional)
    #[serde(default)]
    pub shadow_mirror: Option<ShadowMirrorConfig>,
}

/// Profiler configuration for endpoint behavior learning.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProfilerConfig {
    /// Whether profiling is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Maximum number of endpoint profiles to maintain
    #[serde(default = "default_max_profiles")]
    pub max_profiles: usize,
    /// Maximum number of learned schemas to maintain
    #[serde(default = "default_max_schemas")]
    pub max_schemas: usize,
    /// Minimum samples required before validating against profile
    #[serde(default = "default_min_samples")]
    pub min_samples_for_validation: u32,

    // ========================================================================
    // Anomaly Detection Thresholds
    // ========================================================================
    /// Z-score threshold for payload size anomaly detection (default: 3.0)
    #[serde(default = "default_payload_z_threshold")]
    pub payload_z_threshold: f64,

    /// Z-score threshold for parameter value anomaly detection (default: 4.0)
    #[serde(default = "default_param_z_threshold")]
    pub param_z_threshold: f64,

    /// Z-score threshold for response size anomaly detection (default: 4.0)
    #[serde(default = "default_response_z_threshold")]
    pub response_z_threshold: f64,

    /// Minimum standard deviation for z-score calculation (avoids div/0) (default: 0.01)
    #[serde(default = "default_min_stddev")]
    pub min_stddev: f64,

    /// Ratio threshold for type-based anomaly detection (default: 0.9)
    /// If >90% of values are numeric, flag non-numeric as anomaly
    #[serde(default = "default_type_ratio_threshold")]
    pub type_ratio_threshold: f64,

    // ========================================================================
    // Security Controls
    // ========================================================================
    /// Maximum number of type categories per parameter (prevents memory exhaustion)
    #[serde(default = "default_max_type_counts")]
    pub max_type_counts: usize,

    /// Redact PII values in anomaly descriptions (default: true)
    #[serde(default = "default_true")]
    pub redact_pii: bool,

    /// Freeze baseline after this many samples (prevents model poisoning)
    /// Set to 0 to disable (continuous learning). Default: 0 (disabled)
    #[serde(default)]
    pub freeze_after_samples: u32,
}

fn default_max_profiles() -> usize {
    1000
}

fn default_max_schemas() -> usize {
    500
}

fn default_min_samples() -> u32 {
    100
}

fn default_payload_z_threshold() -> f64 {
    3.0
}

fn default_param_z_threshold() -> f64 {
    4.0
}

fn default_response_z_threshold() -> f64 {
    4.0
}

fn default_min_stddev() -> f64 {
    0.01
}

fn default_type_ratio_threshold() -> f64 {
    0.9
}

fn default_max_type_counts() -> usize {
    10
}

impl Default for ProfilerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_profiles: default_max_profiles(),
            max_schemas: default_max_schemas(),
            min_samples_for_validation: default_min_samples(),
            payload_z_threshold: default_payload_z_threshold(),
            param_z_threshold: default_param_z_threshold(),
            response_z_threshold: default_response_z_threshold(),
            min_stddev: default_min_stddev(),
            type_ratio_threshold: default_type_ratio_threshold(),
            max_type_counts: default_max_type_counts(),
            redact_pii: true,
            freeze_after_samples: 0,
        }
    }
}

/// Complete configuration file structure.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ConfigFile {
    /// Global server settings
    #[serde(default)]
    pub server: GlobalConfig,
    /// Site configurations
    pub sites: Vec<SiteYamlConfig>,
    /// Global rate limiting
    #[serde(default)]
    pub rate_limit: RateLimitConfig,
    /// Profiler configuration
    #[serde(default)]
    pub profiler: ProfilerConfig,
}

/// Errors that can occur during configuration loading.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("configuration file not found: {path} (check the path or mount the file into the container)")]
    NotFound { path: String },

    #[error("configuration file too large: {size} bytes (max {max} bytes). Reduce size or split the configuration")]
    FileTooLarge { size: u64, max: u64 },

    #[error("failed to read configuration: {0}")]
    IoError(#[from] std::io::Error),

    #[error("failed to parse configuration: {0}")]
    ParseError(#[from] serde_yaml::Error),

    #[error("validation error: {0}")]
    ValidationError(String),

    #[error("TLS certificate not found: {path} (set tls.cert_path to a valid PEM file)")]
    CertNotFound { path: String },

    #[error("TLS key not found: {path} (set tls.key_path to a valid PEM file)")]
    KeyNotFound { path: String },

    #[error("duplicate hostname: {hostname} (hostnames must be unique; consider a wildcard like '*.example.com')")]
    DuplicateHostname { hostname: String },

    #[error("invalid TLS version: {version} (set min_version to '1.2' or '1.3')")]
    InvalidTlsVersion { version: String },

    #[error("path traversal detected in: {path} (remove '..' or encoded traversal sequences)")]
    PathTraversal { path: String },
}

/// Check if a path contains path traversal sequences.
///
/// Detects:
/// - Literal `..` sequences
/// - URL-encoded variants: `%2e%2e`, `%2E%2E`, mixed case
/// - Double-URL-encoded: `%252e%252e`
/// - Backslash variants: `..\`, `..\\`
fn contains_path_traversal(path: &str) -> bool {
    // Check literal parent directory reference
    if path.contains("..") {
        return true;
    }

    // Check URL-encoded variants (case-insensitive)
    let path_lower = path.to_lowercase();
    if path_lower.contains("%2e%2e") || path_lower.contains("%2e.") || path_lower.contains(".%2e") {
        return true;
    }

    // Check double-URL-encoded
    if path_lower.contains("%252e") {
        return true;
    }

    // Check for null bytes (path truncation attack)
    if path.contains('\0') || path_lower.contains("%00") {
        return true;
    }

    false
}

/// Configuration loader with security validations.
pub struct ConfigLoader;

impl ConfigLoader {
    /// Loads configuration from a YAML file.
    ///
    /// # Security
    /// - Enforces 10MB file size limit
    /// - Validates TLS certificate/key paths exist
    /// - Checks for path traversal attempts
    /// - Validates hostnames for duplicates
    pub fn load<P: AsRef<Path>>(path: P) -> Result<ConfigFile, ConfigError> {
        let path = path.as_ref();
        info!("Loading configuration from: {}", path.display());

        // Check file exists
        if !path.exists() {
            return Err(ConfigError::NotFound {
                path: path.display().to_string(),
            });
        }

        // Check file size (security: prevent memory exhaustion)
        let metadata = fs::metadata(path)?;
        if metadata.len() > MAX_CONFIG_SIZE {
            return Err(ConfigError::FileTooLarge {
                size: metadata.len(),
                max: MAX_CONFIG_SIZE,
            });
        }

        // Read and parse
        let contents = fs::read_to_string(path)?;
        let config: ConfigFile = serde_yaml::from_str(&contents)?;

        // Validate
        Self::validate(&config)?;

        info!("Loaded configuration with {} sites", config.sites.len());
        Ok(config)
    }

    /// Validates the configuration.
    fn validate(config: &ConfigFile) -> Result<(), ConfigError> {
        let mut hostnames = HashSet::new();

        for site in &config.sites {
            // Check for duplicate hostnames
            let normalized = site.hostname.to_lowercase();
            if !hostnames.insert(normalized.clone()) {
                return Err(ConfigError::DuplicateHostname {
                    hostname: site.hostname.clone(),
                });
            }

            // Validate upstreams
            if site.upstreams.is_empty() {
                return Err(ConfigError::ValidationError(format!(
                    "site '{}' has no upstreams configured; add at least one upstream with host and port",
                    site.hostname
                )));
            }

            // Validate TLS configuration
            if let Some(tls) = &site.tls {
                Self::validate_tls(tls)?;
            }

            // Validate WAF configuration
            if let Some(waf) = &site.waf {
                // Warn if WAF is explicitly disabled (SYNAPSE-SEC-011)
                if !waf.enabled {
                    warn!(
                        site = %site.hostname,
                        "WAF protection DISABLED for site - backend may be exposed to attacks"
                    );
                }
                // Validate threshold (must be 1-100, 0 effectively disables protection)
                if let Some(threshold) = waf.threshold {
                    if threshold == 0 {
                        return Err(ConfigError::ValidationError(format!(
                            "site '{}' has WAF threshold of 0, which effectively disables protection. \
                             Use waf.enabled: false to disable the WAF, or set threshold between 1-100",
                            site.hostname
                        )));
                    }
                    if threshold > 100 {
                        return Err(ConfigError::ValidationError(format!(
                            "site '{}' has invalid WAF threshold {} (must be 1-100); \
                             use waf.enabled: false to disable or set a valid threshold",
                            site.hostname, threshold
                        )));
                    }
                }
            }

            // Validate rate limit
            if let Some(rl) = &site.rate_limit {
                if rl.rps == 0 && rl.enabled {
                    warn!(
                        "Site '{}' has rate limiting enabled with 0 RPS; set rps > 0 or disable rate limiting",
                        site.hostname
                    );
                }
                // P1-RUST-002: Bounds checking for RPS
                if rl.rps > 1_000_000 {
                    return Err(ConfigError::ValidationError(format!(
                        "site '{}' has extreme RPS limit {} (max 1,000,000)",
                        site.hostname, rl.rps
                    )));
                }
            }

            // Validate shadow mirroring config
            if let Some(shadow) = &site.shadow_mirror {
                if let Err(e) = shadow.validate() {
                    return Err(ConfigError::ValidationError(format!(
                        "site '{}' has invalid shadow_mirror config: {}. Fix shadow_mirror settings or remove the block",
                        site.hostname,
                        e
                    )));
                }
            }
        }

        // P1-RUST-002: Global bounds checking
        if config.server.workers > 1024 {
            return Err(ConfigError::ValidationError(format!(
                "extreme worker count {} (max 1024)",
                config.server.workers
            )));
        }

        if config.server.shutdown_timeout_secs > 3600 {
            return Err(ConfigError::ValidationError(format!(
                "extreme shutdown timeout {}s (max 3600)",
                config.server.shutdown_timeout_secs
            )));
        }

        if config.server.waf_regex_timeout_ms > 500 {
            return Err(ConfigError::ValidationError(format!(
                "extreme WAF regex timeout {}ms (max 500)",
                config.server.waf_regex_timeout_ms
            )));
        }

        // Warn if global WAF is disabled (SYNAPSE-SEC-011)
        if !config.server.waf_enabled {
            warn!(
                "Global WAF protection DISABLED - all sites may be exposed to attacks unless individually configured"
            );
        }

        // Validate global WAF threshold (must be 1-100, 0 effectively disables protection)
        if config.server.waf_threshold == 0 {
            return Err(ConfigError::ValidationError(
                "global WAF threshold of 0 effectively disables protection. \
                 Use waf_enabled: false to disable globally, or set waf_threshold between 1-100"
                    .to_string(),
            ));
        }
        if config.server.waf_threshold > 100 {
            return Err(ConfigError::ValidationError(format!(
                "global WAF threshold {} is invalid (must be 1-100); set waf_threshold between 1-100",
                config.server.waf_threshold
            )));
        }

        Ok(())
    }

    /// Validates TLS configuration paths.
    fn validate_tls(tls: &TlsConfig) -> Result<(), ConfigError> {
        // Check for path traversal (including URL-encoded variants)
        if contains_path_traversal(&tls.cert_path) {
            return Err(ConfigError::PathTraversal {
                path: tls.cert_path.clone(),
            });
        }
        if contains_path_traversal(&tls.key_path) {
            return Err(ConfigError::PathTraversal {
                path: tls.key_path.clone(),
            });
        }

        // Check cert exists
        if !Path::new(&tls.cert_path).exists() {
            return Err(ConfigError::CertNotFound {
                path: tls.cert_path.clone(),
            });
        }

        // Check key exists
        if !Path::new(&tls.key_path).exists() {
            return Err(ConfigError::KeyNotFound {
                path: tls.key_path.clone(),
            });
        }

        // Validate TLS version
        match tls.min_version.as_str() {
            "1.2" | "1.3" => {}
            _ => {
                return Err(ConfigError::InvalidTlsVersion {
                    version: tls.min_version.clone(),
                });
            }
        }

        debug!(
            "Validated TLS config: cert={}, key=[REDACTED]",
            tls.cert_path
        );
        Ok(())
    }

    /// Converts YAML site configs to internal SiteConfig format.
    pub fn to_site_configs(config: &ConfigFile) -> Vec<SiteConfig> {
        config
            .sites
            .iter()
            .map(|site| SiteConfig {
                hostname: site.hostname.clone(),
                upstreams: site
                    .upstreams
                    .iter()
                    .map(|u| format!("{}:{}", u.host, u.port))
                    .collect(),
                tls_enabled: site.tls.is_some(),
                tls_cert: site.tls.as_ref().map(|t| t.cert_path.clone()),
                tls_key: site.tls.as_ref().map(|t| t.key_path.clone()),
                waf_threshold: site.waf.as_ref().and_then(|w| w.threshold),
                waf_enabled: site.waf.as_ref().map(|w| w.enabled).unwrap_or(true),
                access_control: site.access_control.clone(),
                headers: site.headers.as_ref().map(|headers| headers.compile()),
                shadow_mirror: site.shadow_mirror.clone(),
            })
            .collect()
    }
}

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

    fn create_temp_config(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file
    }

    #[test]
    fn test_load_minimal_config() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        assert_eq!(config.sites.len(), 1);
        assert_eq!(config.sites[0].hostname, "example.com");
    }

    #[test]
    fn test_load_full_config() {
        let yaml = r#"
server:
  http_addr: "0.0.0.0:8080"
  https_addr: "0.0.0.0:8443"
  workers: 4
  waf_threshold: 80
  log_level: debug

rate_limit:
  rps: 5000
  enabled: true

sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
        weight: 2
    waf:
      enabled: true
      threshold: 60
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();

        assert_eq!(config.server.http_addr, "0.0.0.0:8080");
        assert_eq!(config.server.workers, 4);
        assert_eq!(config.rate_limit.rps, 5000);
        assert_eq!(config.sites[0].waf.as_ref().unwrap().threshold, Some(60));
    }

    #[test]
    fn test_duplicate_hostname() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8081
"#;
        let file = create_temp_config(yaml);
        let result = ConfigLoader::load(file.path());
        assert!(matches!(result, Err(ConfigError::DuplicateHostname { .. })));
    }

    #[test]
    fn test_no_upstreams() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams: []
"#;
        let file = create_temp_config(yaml);
        let result = ConfigLoader::load(file.path());
        assert!(matches!(result, Err(ConfigError::ValidationError(_))));
    }

    #[test]
    fn test_invalid_waf_threshold() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
    waf:
      threshold: 150
"#;
        let file = create_temp_config(yaml);
        let result = ConfigLoader::load(file.path());
        assert!(matches!(result, Err(ConfigError::ValidationError(_))));
    }

    #[test]
    fn test_file_not_found() {
        let result = ConfigLoader::load("/nonexistent/config.yaml");
        assert!(matches!(result, Err(ConfigError::NotFound { .. })));
    }

    #[test]
    fn test_default_values() {
        let config = GlobalConfig::default();
        assert_eq!(config.http_addr, "0.0.0.0:80");
        assert_eq!(config.https_addr, "0.0.0.0:443");
        assert_eq!(config.waf_threshold, 70);
        assert!(config.waf_enabled);
        assert_eq!(config.waf_regex_timeout_ms, 100); // Default 100ms
    }

    #[test]
    fn test_debug_redacts_admin_api_key() {
        let mut config = GlobalConfig::default();
        config.admin_api_key = Some("super-secret-key-12345".to_string());

        let debug_output = format!("{:?}", config);

        // Must NOT contain the actual secret
        assert!(!debug_output.contains("super-secret-key-12345"));
        // Must contain the redaction marker
        assert!(debug_output.contains("[REDACTED]"));
        // Non-secret fields should still be visible
        assert!(debug_output.contains("0.0.0.0:80"));
    }

    #[test]
    fn test_debug_shows_none_when_no_key() {
        let config = GlobalConfig::default();
        let debug_output = format!("{:?}", config);

        // When no key is set, should show None
        assert!(debug_output.contains("None"));
        assert!(!debug_output.contains("[REDACTED]"));
    }

    #[test]
    fn test_waf_regex_timeout_config() {
        let yaml = r#"
server:
  waf_regex_timeout_ms: 200
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        assert_eq!(config.server.waf_regex_timeout_ms, 200);
    }

    #[test]
    fn test_waf_regex_timeout_default() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        // Should use default of 100ms when not specified
        assert_eq!(config.server.waf_regex_timeout_ms, 100);
    }

    #[test]
    fn test_to_site_configs() {
        let yaml = r#"
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
    waf:
      enabled: true
      threshold: 80
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        let sites = ConfigLoader::to_site_configs(&config);

        assert_eq!(sites.len(), 1);
        assert_eq!(sites[0].hostname, "example.com");
        assert_eq!(sites[0].waf_threshold, Some(80));
        assert!(sites[0].waf_enabled);
    }

    #[test]
    fn test_yaml_with_unknown_fields_passes() {
        // serde_yaml default behavior: unknown fields are silently ignored
        // unless deny_unknown_fields is set. Our config structs do not use it,
        // so unknown fields should be accepted without error.
        let yaml = r#"
server:
  http_addr: "0.0.0.0:9090"
  unknown_field: "should be ignored"
  another_mystery: 42
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
    extra_site_field: true
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        assert_eq!(config.server.http_addr, "0.0.0.0:9090");
        assert_eq!(config.sites.len(), 1);
        assert_eq!(config.sites[0].hostname, "example.com");
    }

    #[test]
    fn test_yaml_with_unknown_top_level_field_passes() {
        // Unknown top-level keys should also be silently ignored
        let yaml = r#"
some_future_feature:
  enabled: true
sites:
  - hostname: example.com
    upstreams:
      - host: 127.0.0.1
        port: 8080
"#;
        let file = create_temp_config(yaml);
        let config = ConfigLoader::load(file.path()).unwrap();
        assert_eq!(config.sites.len(), 1);
    }

    #[test]
    fn test_path_traversal_detection() {
        use super::contains_path_traversal;

        // Literal parent directory references
        assert!(contains_path_traversal(".."));
        assert!(contains_path_traversal("../etc/passwd"));
        assert!(contains_path_traversal("/path/../secret"));
        assert!(contains_path_traversal("path/to/../../root"));

        // URL-encoded variants
        assert!(contains_path_traversal("%2e%2e"));
        assert!(contains_path_traversal("%2E%2E"));
        assert!(contains_path_traversal("%2e."));
        assert!(contains_path_traversal(".%2e"));

        // Double-URL-encoded
        assert!(contains_path_traversal("%252e%252e"));
        assert!(contains_path_traversal("path/%252e%252e/file"));

        // Null byte injection
        assert!(contains_path_traversal("\x00"));
        assert!(contains_path_traversal("path\x00/file"));
        assert!(contains_path_traversal("%00"));
        assert!(contains_path_traversal("path/%00/file"));

        // Clean paths
        assert!(!contains_path_traversal("/path/to/file"));
        assert!(!contains_path_traversal("certs/server.pem"));
        assert!(!contains_path_traversal("/etc/nginx/ssl/cert.pem"));
        assert!(!contains_path_traversal("./relative/path")); // Single dot is OK
    }
}