wisegate 0.11.0

A high-performance, secure reverse proxy with rate limiting and IP filtering
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
//! Configuration management for WiseGate.
//!
//! This module handles loading and caching configuration from environment variables.
//! All configurations are computed once at first access and cached for the lifetime
//! of the application using `std::sync::LazyLock`.
//!
//! # Caching
//!
//! Configuration values are read from environment variables only once, at startup.
//! This provides:
//! - Consistent configuration throughout the application lifetime
//! - No runtime overhead from repeated environment lookups
//! - Thread-safe access without locking
//!
//! # Example
//!
//! ```
//! use wisegate::config;
//!
//! // Get cached configuration
//! let rate_config = config::get_rate_limit_config();
//! println!("Max requests: {}", rate_config.max_requests);
//!
//! let proxy_config = config::get_proxy_config();
//! println!("Timeout: {:?}", proxy_config.timeout);
//! ```

use std::env;
use std::str::FromStr;
use std::time::Duration;

use std::sync::LazyLock;
use tracing::warn;

use crate::env_vars;
use wisegate_core::{
    AuthenticationProvider, ConnectionProvider, Credential, Credentials, FilteringProvider,
    ProxyConfig, ProxyProvider, RateLimitCleanupConfig, RateLimitConfig, RateLimitingProvider,
    defaults,
};

// ============================================================================
// Cached Configuration (computed once at first access)
// ============================================================================

static RATE_LIMIT_CONFIG: LazyLock<RateLimitConfig> = LazyLock::new(compute_rate_limit_config);
static RATE_LIMIT_CLEANUP_CONFIG: LazyLock<RateLimitCleanupConfig> =
    LazyLock::new(compute_rate_limit_cleanup_config);
static PROXY_CONFIG: LazyLock<ProxyConfig> = LazyLock::new(compute_proxy_config);
static BLOCKED_IPS: LazyLock<Vec<String>> = LazyLock::new(compute_blocked_ips);
static BLOCKED_PATTERNS: LazyLock<Vec<String>> = LazyLock::new(compute_blocked_patterns);
static BLOCKED_METHODS: LazyLock<Vec<String>> = LazyLock::new(compute_blocked_methods);
static ALLOWED_PROXY_IPS: LazyLock<Option<Vec<String>>> =
    LazyLock::new(|| compute_allowed_proxy_ips_internal(|key| std::env::var(key)));
static MAX_CONNECTIONS: LazyLock<usize> = LazyLock::new(compute_max_connections);
static AUTH_CREDENTIALS: LazyLock<Credentials> = LazyLock::new(compute_auth_credentials);
static AUTH_REALM: LazyLock<String> = LazyLock::new(compute_auth_realm);
static BEARER_TOKEN: LazyLock<Option<String>> = LazyLock::new(compute_bearer_token);

/// Whitelisted environment variable names for proxy IPs.
///
/// This prevents arbitrary environment variable disclosure via `TRUSTED_PROXY_IPS_VAR`.
const ALLOWED_PROXY_VAR_NAMES: &[&str] = &[
    "TRUSTED_PROXY_IPS",
    "REVERSE_PROXY_IPS",
    "PROXY_ALLOWLIST",
    "ALLOWED_PROXY_IPS",
    "PROXY_IPS",
];

// ============================================================================
// Internal Helpers
// ============================================================================

/// Parses an environment variable with fallback to a default value.
///
/// Logs a warning if the value exists but cannot be parsed.
fn parse_env_var_or_default<T>(var_name: &str, default: T) -> T
where
    T: FromStr + Copy,
{
    match env::var(var_name) {
        Ok(value) => match value.parse() {
            Ok(parsed) => parsed,
            Err(_) => {
                warn!(var = var_name, value = %value, "Invalid env var value, using default");
                default
            }
        },
        Err(_) => default,
    }
}

/// Parses a comma-separated string into a Vec of trimmed strings.
///
/// Filters out empty entries after trimming.
///
/// # Arguments
///
/// * `input` - The comma-separated string to parse
///
/// # Returns
///
/// A Vec of non-empty, trimmed strings
fn parse_comma_separated(input: &str) -> Vec<String> {
    input
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Parses a comma-separated string with uppercase normalization.
///
/// Used for HTTP methods and other case-insensitive values.
///
/// # Arguments
///
/// * `input` - The comma-separated string to parse
///
/// # Returns
///
/// A Vec of non-empty, trimmed, uppercase strings
fn parse_comma_separated_uppercase(input: &str) -> Vec<String> {
    input
        .split(',')
        .map(|s| s.trim().to_uppercase())
        .filter(|s| !s.is_empty())
        .collect()
}

// ============================================================================
// Public Configuration Getters
// ============================================================================

/// Returns the cached rate limiting configuration.
///
/// Configuration is read from environment variables on first access:
/// - `RATE_LIMIT_REQUESTS`: Max requests per window (default: 100)
/// - `RATE_LIMIT_WINDOW_SECS`: Window duration in seconds (default: 60)
///
/// # Example
///
/// ```
/// use wisegate::config::get_rate_limit_config;
///
/// let config = get_rate_limit_config();
/// println!("Allowing {} requests per {:?}", config.max_requests, config.window_duration);
/// ```
pub fn get_rate_limit_config() -> &'static RateLimitConfig {
    &RATE_LIMIT_CONFIG
}

/// Compute rate limiting configuration from environment variables
/// Invalid values fall back to defaults and log warnings
fn compute_rate_limit_config() -> RateLimitConfig {
    let max_requests =
        parse_env_var_or_default(env_vars::RATE_LIMIT_REQUESTS, defaults::RATE_LIMIT_REQUESTS);

    let window_secs = parse_env_var_or_default(
        env_vars::RATE_LIMIT_WINDOW_SECS,
        defaults::RATE_LIMIT_WINDOW_SECS,
    );

    let config = RateLimitConfig {
        max_requests,
        window_duration: Duration::from_secs(window_secs),
    };

    // Validate configuration
    if !config.is_valid() {
        warn!("Invalid rate limit configuration, using defaults");
        return RateLimitConfig {
            max_requests: defaults::RATE_LIMIT_REQUESTS,
            window_duration: Duration::from_secs(defaults::RATE_LIMIT_WINDOW_SECS),
        };
    }

    config
}

/// Returns the cached rate limiter cleanup configuration.
///
/// Controls automatic cleanup of expired entries to prevent memory exhaustion.
///
/// Configuration is read from environment variables on first access:
/// - `RATE_LIMIT_CLEANUP_THRESHOLD`: Entry count before cleanup (default: 10000, 0 = disabled)
/// - `RATE_LIMIT_CLEANUP_INTERVAL_SECS`: Minimum interval between cleanups (default: 60)
///
/// # Example
///
/// ```
/// use wisegate::config::get_rate_limit_cleanup_config;
///
/// let config = get_rate_limit_cleanup_config();
/// if config.is_enabled() {
///     println!("Cleanup triggers at {} entries", config.threshold);
/// }
/// ```
pub fn get_rate_limit_cleanup_config() -> &'static RateLimitCleanupConfig {
    &RATE_LIMIT_CLEANUP_CONFIG
}

/// Computes rate limiter cleanup configuration from environment variables.
fn compute_rate_limit_cleanup_config() -> RateLimitCleanupConfig {
    let threshold = parse_env_var_or_default(
        env_vars::RATE_LIMIT_CLEANUP_THRESHOLD,
        defaults::RATE_LIMIT_CLEANUP_THRESHOLD,
    );

    let interval_secs = parse_env_var_or_default(
        env_vars::RATE_LIMIT_CLEANUP_INTERVAL_SECS,
        defaults::RATE_LIMIT_CLEANUP_INTERVAL_SECS,
    );

    RateLimitCleanupConfig {
        threshold,
        interval: Duration::from_secs(interval_secs),
    }
}

/// Returns the cached proxy configuration.
///
/// Controls upstream request behavior including timeouts and size limits.
///
/// Configuration is read from environment variables on first access:
/// - `PROXY_TIMEOUT_SECS`: Upstream request timeout (default: 30)
/// - `MAX_BODY_SIZE_MB`: Maximum request body size (default: 100, 0 = unlimited)
///
/// # Example
///
/// ```
/// use wisegate::config::get_proxy_config;
///
/// let config = get_proxy_config();
/// println!("Timeout: {:?}, Max body: {}", config.timeout, config.max_body_size_mb());
/// ```
pub fn get_proxy_config() -> &'static ProxyConfig {
    &PROXY_CONFIG
}

/// Computes proxy configuration from environment variables.
fn compute_proxy_config() -> ProxyConfig {
    let timeout_secs =
        parse_env_var_or_default(env_vars::PROXY_TIMEOUT_SECS, defaults::PROXY_TIMEOUT_SECS);

    let max_body_mb =
        parse_env_var_or_default(env_vars::MAX_BODY_SIZE_MB, defaults::MAX_BODY_SIZE_MB);

    let config = ProxyConfig {
        timeout: Duration::from_secs(timeout_secs),
        max_body_size: ProxyConfig::mb_to_bytes(max_body_mb),
    };

    // Validate configuration
    if !config.is_valid() {
        warn!("Invalid proxy configuration, using defaults");
        return ProxyConfig {
            timeout: Duration::from_secs(defaults::PROXY_TIMEOUT_SECS),
            max_body_size: ProxyConfig::mb_to_bytes(defaults::MAX_BODY_SIZE_MB),
        };
    }

    config
}

/// Returns the cached maximum number of concurrent connections.
///
/// Limits simultaneous connections to prevent resource exhaustion under attack.
/// When the limit is reached, new connections are rejected immediately.
///
/// Configuration is read from `MAX_CONNECTIONS` environment variable on first access.
///
/// # Returns
///
/// - `0`: Unlimited connections (not recommended for production)
/// - `> 0`: Maximum number of concurrent connections
///
/// **Default**: `10000`
///
/// # Example
///
/// ```
/// use wisegate::config::get_max_connections;
///
/// let max_conn = get_max_connections();
/// if max_conn > 0 {
///     println!("Limiting to {} concurrent connections", max_conn);
/// } else {
///     println!("Unlimited connections (not recommended)");
/// }
/// ```
pub fn get_max_connections() -> usize {
    *MAX_CONNECTIONS
}

/// Computes maximum connections from environment variable.
fn compute_max_connections() -> usize {
    parse_env_var_or_default(env_vars::MAX_CONNECTIONS, defaults::MAX_CONNECTIONS)
}

/// Returns the cached list of allowed proxy IPs, if configured.
///
/// When `Some`, WiseGate operates in strict mode, validating that requests
/// come from trusted proxies. When `None`, permissive mode is used.
///
/// Configuration is read from environment variables on first access:
/// - `CC_REVERSE_PROXY_IPS`: Primary variable for trusted proxy IPs
/// - `TRUSTED_PROXY_IPS_VAR`: Alternative variable name (must be whitelisted)
///
/// # Returns
///
/// - `Some(&Vec<String>)`: List of trusted proxy IPs (strict mode)
/// - `None`: No proxy validation (permissive mode)
///
/// # Example
///
/// ```
/// use wisegate::config::get_allowed_proxy_ips;
///
/// match get_allowed_proxy_ips() {
///     Some(ips) => println!("Strict mode with {} trusted proxies", ips.len()),
///     None => println!("Permissive mode"),
/// }
/// ```
pub fn get_allowed_proxy_ips() -> Option<&'static Vec<String>> {
    ALLOWED_PROXY_IPS.as_ref()
}

/// Computes allowed proxy IPs from environment variables.
fn compute_allowed_proxy_ips_internal<F>(env_var: F) -> Option<Vec<String>>
where
    F: Fn(&str) -> Result<String, std::env::VarError>,
{
    // Try primary variable first
    if let Ok(ips) = env_var(env_vars::ALLOWED_PROXY_IPS)
        && !ips.trim().is_empty()
    {
        return Some(parse_comma_separated(&ips));
    }

    // Try user-defined alternative variable if set (only from whitelist)
    if let Ok(alt_var_name) = env_var(env_vars::TRUSTED_PROXY_IPS_VAR) {
        // Security: only allow reading from whitelisted variable names
        // This prevents arbitrary environment variable disclosure
        if ALLOWED_PROXY_VAR_NAMES.contains(&alt_var_name.as_str())
            && let Ok(ips) = env_var(&alt_var_name)
            && !ips.trim().is_empty()
        {
            return Some(parse_comma_separated(&ips));
        } else if !ALLOWED_PROXY_VAR_NAMES.contains(&alt_var_name.as_str()) {
            warn!(
                var = %alt_var_name,
                allowed = ?ALLOWED_PROXY_VAR_NAMES,
                "Invalid TRUSTED_PROXY_IPS_VAR value"
            );
        }
    }

    None
}

/// Returns the cached list of blocked IP addresses.
///
/// Requests from these IPs will receive a 403 Forbidden response.
///
/// Configuration is read from `BLOCKED_IPS` environment variable on first access.
///
/// # Example
///
/// ```
/// use wisegate::config::get_blocked_ips;
///
/// let blocked = get_blocked_ips();
/// println!("{} IPs are blocked", blocked.len());
/// ```
pub fn get_blocked_ips() -> &'static Vec<String> {
    &BLOCKED_IPS
}

/// Computes blocked IPs from environment variable.
fn compute_blocked_ips() -> Vec<String> {
    env::var(env_vars::BLOCKED_IPS)
        .map(|s| parse_comma_separated(&s))
        .unwrap_or_default()
}

/// Returns the cached list of blocked URL patterns.
///
/// Requests with URLs containing these patterns will receive a 404 Not Found response.
/// Patterns are matched as substrings and also checked after URL decoding.
///
/// Configuration is read from `BLOCKED_PATTERNS` environment variable on first access.
///
/// # Example
///
/// ```
/// use wisegate::config::get_blocked_patterns;
///
/// let patterns = get_blocked_patterns();
/// for pattern in patterns.iter() {
///     println!("Blocking URLs containing: {}", pattern);
/// }
/// ```
pub fn get_blocked_patterns() -> &'static Vec<String> {
    &BLOCKED_PATTERNS
}

/// Computes blocked URL patterns from environment variable.
/// Patterns are pre-normalized to lowercase for case-insensitive matching.
fn compute_blocked_patterns() -> Vec<String> {
    env::var(env_vars::BLOCKED_PATTERNS)
        .map(|s| {
            s.split(',')
                .map(|p| p.trim().to_lowercase())
                .filter(|p| !p.is_empty())
                .collect()
        })
        .unwrap_or_default()
}

/// Returns the cached list of blocked HTTP methods.
///
/// Requests using these methods will receive a 405 Method Not Allowed response.
/// Method names are normalized to uppercase.
///
/// Configuration is read from `BLOCKED_METHODS` environment variable on first access.
///
/// # Example
///
/// ```
/// use wisegate::config::get_blocked_methods;
///
/// let methods = get_blocked_methods();
/// if methods.contains(&"DELETE".to_string()) {
///     println!("DELETE requests are blocked");
/// }
/// ```
pub fn get_blocked_methods() -> &'static Vec<String> {
    &BLOCKED_METHODS
}

/// Computes blocked HTTP methods from environment variable.
fn compute_blocked_methods() -> Vec<String> {
    env::var(env_vars::BLOCKED_METHODS)
        .map(|s| parse_comma_separated_uppercase(&s))
        .unwrap_or_default()
}

/// Returns the cached authentication credentials.
///
/// Credentials are loaded from environment variables:
/// - `CC_HTTP_BASIC_AUTH`: Primary credentials
/// - `CC_HTTP_BASIC_AUTH_1`, `CC_HTTP_BASIC_AUTH_2`, etc.: Additional credentials
///
/// Format: `username:password` or `username:$2y$...` (hashed)
///
/// # Returns
///
/// A reference to the cached credentials store.
///
/// # Example
///
/// ```
/// use wisegate::config::get_auth_credentials;
///
/// let creds = get_auth_credentials();
/// if !creds.is_empty() {
///     println!("Basic auth enabled with {} user(s)", creds.len());
/// }
/// ```
pub fn get_auth_credentials() -> &'static Credentials {
    &AUTH_CREDENTIALS
}

/// Computes authentication credentials from environment variables.
fn compute_auth_credentials() -> Credentials {
    let mut entries = Vec::new();

    // Check CC_HTTP_BASIC_AUTH first
    if let Ok(value) = env::var(env_vars::CC_HTTP_BASIC_AUTH) {
        if let Some(cred) = Credential::parse(&value) {
            entries.push(cred);
        } else {
            warn!(
                var = env_vars::CC_HTTP_BASIC_AUTH,
                "Invalid credential format (expected username:password)"
            );
        }
    }

    // Check CC_HTTP_BASIC_AUTH_1, CC_HTTP_BASIC_AUTH_2, etc.
    let mut index = 1;
    let mut consecutive_missing = 0;
    loop {
        let var_name = format!("{}{}", env_vars::CC_HTTP_BASIC_AUTH_N, index);
        match env::var(&var_name) {
            Ok(value) => {
                if consecutive_missing > 0 {
                    warn!(
                        gap_at = index - consecutive_missing,
                        found_at = index,
                        "Gap in numbered credentials, some may have been skipped"
                    );
                }
                consecutive_missing = 0;
                if let Some(cred) = Credential::parse(&value) {
                    entries.push(cred);
                } else {
                    warn!(var = %var_name, "Invalid credential format (expected username:password)");
                }
                index += 1;
            }
            Err(_) => {
                consecutive_missing += 1;
                // Stop after 3 consecutive missing to handle gaps
                if consecutive_missing >= 3 {
                    break;
                }
                index += 1;
            }
        }
    }

    Credentials::from_entries(entries)
}

/// Returns the cached authentication realm.
///
/// The realm is displayed in the browser's authentication dialog.
///
/// Configuration is read from `CC_HTTP_BASIC_AUTH_REALM` environment variable.
///
/// **Default**: `"WiseGate"`
///
/// # Example
///
/// ```
/// use wisegate::config::get_auth_realm;
///
/// let realm = get_auth_realm();
/// println!("Auth realm: {}", realm);
/// ```
pub fn get_auth_realm() -> &'static str {
    &AUTH_REALM
}

/// Computes authentication realm from environment variable.
fn compute_auth_realm() -> String {
    env::var(env_vars::CC_HTTP_BASIC_AUTH_REALM)
        .unwrap_or_else(|_| defaults::AUTH_REALM.to_string())
}

/// Returns the cached bearer token for API authentication.
///
/// The bearer token enables RFC 6750 Bearer Token authentication.
/// Requests can authenticate by providing the token in the Authorization header:
/// `Authorization: Bearer <token>`
///
/// Configuration is read from `CC_BEARER_TOKEN` environment variable.
///
/// # Returns
///
/// - `Some(&str)`: The configured bearer token
/// - `None`: Bearer token authentication is disabled
///
/// # Example
///
/// ```
/// use wisegate::config::get_bearer_token;
///
/// if let Some(token) = get_bearer_token() {
///     println!("Bearer token authentication enabled");
/// }
/// ```
pub fn get_bearer_token() -> Option<&'static str> {
    BEARER_TOKEN.as_deref()
}

/// Computes bearer token from environment variable.
fn compute_bearer_token() -> Option<String> {
    env::var(env_vars::CC_BEARER_TOKEN)
        .ok()
        .filter(|s| !s.trim().is_empty())
}

// ============================================================================
// EnvVarConfig - ConfigProvider implementation using environment variables
// ============================================================================

/// Configuration provider that reads from environment variables.
///
/// This is the default configuration provider for WiseGate CLI.
/// All values are cached at creation time using the global lazy statics.
///
/// Implements all composable configuration traits:
/// - [`RateLimitingProvider`] for rate limiting settings
/// - [`ProxyProvider`] for proxy behavior
/// - [`FilteringProvider`] for request filtering
/// - [`ConnectionProvider`] for connection limits
///
/// # Example
///
/// ```
/// use wisegate::config::EnvVarConfig;
/// use wisegate_core::RateLimitingProvider;
///
/// let config = EnvVarConfig::new();
/// println!("Max requests: {}", config.rate_limit_config().max_requests);
/// ```
#[derive(Clone, Debug)]
pub struct EnvVarConfig {
    // We use references to the global lazy statics for zero-copy access
    _private: (),
}

impl EnvVarConfig {
    /// Creates a new configuration provider from environment variables.
    ///
    /// This triggers lazy initialization of all configuration values
    /// if they haven't been accessed yet.
    pub fn new() -> Self {
        Self { _private: () }
    }
}

impl Default for EnvVarConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl RateLimitingProvider for EnvVarConfig {
    fn rate_limit_config(&self) -> &RateLimitConfig {
        get_rate_limit_config()
    }

    fn rate_limit_cleanup_config(&self) -> &RateLimitCleanupConfig {
        get_rate_limit_cleanup_config()
    }
}

impl ProxyProvider for EnvVarConfig {
    fn proxy_config(&self) -> &ProxyConfig {
        get_proxy_config()
    }

    fn allowed_proxy_ips(&self) -> Option<&[String]> {
        get_allowed_proxy_ips().map(|v| v.as_slice())
    }
}

impl FilteringProvider for EnvVarConfig {
    fn blocked_ips(&self) -> &[String] {
        get_blocked_ips()
    }

    fn blocked_methods(&self) -> &[String] {
        get_blocked_methods()
    }

    fn blocked_patterns(&self) -> &[String] {
        get_blocked_patterns()
    }
}

impl ConnectionProvider for EnvVarConfig {
    fn max_connections(&self) -> usize {
        get_max_connections()
    }
}

impl AuthenticationProvider for EnvVarConfig {
    fn auth_credentials(&self) -> &Credentials {
        get_auth_credentials()
    }

    fn auth_realm(&self) -> &str {
        get_auth_realm()
    }

    fn bearer_token(&self) -> Option<&str> {
        get_bearer_token()
    }
}

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

    // Helper function to create a mock environment function for testing
    fn create_mock_env(
        vars: HashMap<&str, &str>,
    ) -> impl Fn(&str) -> Result<String, std::env::VarError> {
        move |key: &str| {
            vars.get(key)
                .map(|v| v.to_string())
                .ok_or(std::env::VarError::NotPresent)
        }
    }

    #[test]
    fn test_get_allowed_proxy_ips_with_cc_reverse_proxy_ips() {
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::ALLOWED_PROXY_IPS, "192.168.1.1,10.0.0.1");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_some());
        let ips = result.unwrap();
        assert_eq!(ips.len(), 2);
        assert_eq!(ips[0], "192.168.1.1");
        assert_eq!(ips[1], "10.0.0.1");
    }

    #[test]
    fn test_get_allowed_proxy_ips_with_alternative_var() {
        let mut env_vars = HashMap::new();
        // Use a whitelisted variable name
        env_vars.insert(env_vars::TRUSTED_PROXY_IPS_VAR, "TRUSTED_PROXY_IPS");
        env_vars.insert("TRUSTED_PROXY_IPS", "172.16.0.1,203.0.113.1");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_some());
        let ips = result.unwrap();
        assert_eq!(ips.len(), 2);
        assert_eq!(ips[0], "172.16.0.1");
        assert_eq!(ips[1], "203.0.113.1");
    }

    #[test]
    fn test_get_allowed_proxy_ips_cc_takes_priority() {
        // Both variables set - CC_REVERSE_PROXY_IPS should take priority
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::ALLOWED_PROXY_IPS, "192.168.1.1");
        env_vars.insert(env_vars::TRUSTED_PROXY_IPS_VAR, "MY_CUSTOM_PROXY_IPS");
        env_vars.insert("MY_CUSTOM_PROXY_IPS", "172.16.0.1");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_some());
        let ips = result.unwrap();
        assert_eq!(ips.len(), 1);
        assert_eq!(ips[0], "192.168.1.1"); // Should use CC_REVERSE_PROXY_IPS value
    }

    #[test]
    fn test_get_allowed_proxy_ips_fallback_to_alternative() {
        // Don't set CC_REVERSE_PROXY_IPS, only alternative (using whitelisted name)
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::TRUSTED_PROXY_IPS_VAR, "PROXY_ALLOWLIST");
        env_vars.insert("PROXY_ALLOWLIST", "10.1.1.1,10.1.1.2,10.1.1.3");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_some());
        let ips = result.unwrap();
        assert_eq!(ips.len(), 3);
        assert_eq!(ips[0], "10.1.1.1");
        assert_eq!(ips[1], "10.1.1.2");
        assert_eq!(ips[2], "10.1.1.3");
    }

    #[test]
    fn test_get_allowed_proxy_ips_rejects_non_whitelisted_var() {
        // Try to use a non-whitelisted variable name - should be rejected
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::TRUSTED_PROXY_IPS_VAR, "DATABASE_URL");
        env_vars.insert("DATABASE_URL", "10.1.1.1,10.1.1.2");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        // Should return None because DATABASE_URL is not in the whitelist
        assert!(result.is_none());
    }

    #[test]
    fn test_get_allowed_proxy_ips_none_when_no_vars() {
        // No relevant env vars set
        let env_vars = HashMap::new();
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_none());
    }

    #[test]
    fn test_get_allowed_proxy_ips_handles_whitespace() {
        // Test with whitespace around IPs
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::ALLOWED_PROXY_IPS, " 192.168.1.1 , 10.0.0.1 ");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_some());
        let ips = result.unwrap();
        assert_eq!(ips.len(), 2);
        assert_eq!(ips[0], "192.168.1.1");
        assert_eq!(ips[1], "10.0.0.1");
    }

    #[test]
    fn test_get_allowed_proxy_ips_ignores_empty_alternative_var() {
        // Set alternative var but with empty value
        let mut env_vars = HashMap::new();
        env_vars.insert(env_vars::TRUSTED_PROXY_IPS_VAR, "EMPTY_PROXY_VAR");
        env_vars.insert("EMPTY_PROXY_VAR", "");
        let env_fn = create_mock_env(env_vars);

        let result = compute_allowed_proxy_ips_internal(env_fn);

        assert!(result.is_none());
    }

    // ===========================================
    // parse_comma_separated tests
    // ===========================================

    #[test]
    fn test_parse_comma_separated_basic() {
        let result = parse_comma_separated("a,b,c");
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_comma_separated_with_whitespace() {
        let result = parse_comma_separated(" a , b , c ");
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_comma_separated_empty_string() {
        let result = parse_comma_separated("");
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_comma_separated_single_item() {
        let result = parse_comma_separated("single");
        assert_eq!(result, vec!["single"]);
    }

    #[test]
    fn test_parse_comma_separated_filters_empty_entries() {
        let result = parse_comma_separated("a,,b,,,c");
        assert_eq!(result, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_comma_separated_only_commas() {
        let result = parse_comma_separated(",,,");
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_comma_separated_whitespace_only() {
        let result = parse_comma_separated("  ,  ,  ");
        assert!(result.is_empty());
    }

    // ===========================================
    // parse_comma_separated_uppercase tests
    // ===========================================

    #[test]
    fn test_parse_comma_separated_uppercase_basic() {
        let result = parse_comma_separated_uppercase("get,post,put");
        assert_eq!(result, vec!["GET", "POST", "PUT"]);
    }

    #[test]
    fn test_parse_comma_separated_uppercase_mixed_case() {
        let result = parse_comma_separated_uppercase("Get,POST,pUt");
        assert_eq!(result, vec!["GET", "POST", "PUT"]);
    }

    #[test]
    fn test_parse_comma_separated_uppercase_with_whitespace() {
        let result = parse_comma_separated_uppercase(" get , post , put ");
        assert_eq!(result, vec!["GET", "POST", "PUT"]);
    }

    #[test]
    fn test_parse_comma_separated_uppercase_empty() {
        let result = parse_comma_separated_uppercase("");
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_comma_separated_uppercase_filters_empty() {
        let result = parse_comma_separated_uppercase("get,,post");
        assert_eq!(result, vec!["GET", "POST"]);
    }

    // ===========================================
    // EnvVarConfig trait implementation tests
    // ===========================================

    #[test]
    fn test_env_var_config_default_values() {
        let config = EnvVarConfig::new();

        // Rate limiting defaults
        let rate_config = config.rate_limit_config();
        assert!(rate_config.is_valid());
        assert_eq!(rate_config.max_requests, defaults::RATE_LIMIT_REQUESTS);
        assert_eq!(
            rate_config.window_duration,
            Duration::from_secs(defaults::RATE_LIMIT_WINDOW_SECS)
        );

        // Proxy defaults
        assert!(config.proxy_config().is_valid());

        // Cleanup defaults
        assert!(config.rate_limit_cleanup_config().is_enabled());

        // Connection defaults
        assert_eq!(config.max_connections(), defaults::MAX_CONNECTIONS);

        // Blocked lists should be empty by default
        assert!(config.blocked_ips().is_empty());
        assert!(config.blocked_methods().is_empty());
        assert!(config.blocked_patterns().is_empty());
    }
}