ivoryvalley 0.3.0

A transparent deduplication proxy for Mastodon and the Fediverse
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
//! Configuration module for IvoryValley proxy
//!
//! Configuration is loaded with the following priority (highest first):
//! 1. Command line arguments
//! 2. Environment variables (prefixed with IV_)
//! 3. Configuration file (config.toml or config.yaml)
//! 4. Default values
//!
//! Note: The IV_ prefix is used instead of IVORYVALLEY_ to avoid collision
//! with Kubernetes service discovery environment variables. When a service
//! named "ivoryvalley" is deployed, Kubernetes injects variables like
//! IVORYVALLEY_PORT=tcp://10.43.62.146:80 which would conflict.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use clap::Parser;
use config::{ConfigError, File};
use serde::Deserialize;

/// Default upstream URL
const DEFAULT_UPSTREAM_URL: &str = "https://mastodon.social";
/// Default host to bind to
const DEFAULT_HOST: &str = "0.0.0.0";
/// Default port
const DEFAULT_PORT: u16 = 8080;
/// Default database path
const DEFAULT_DATABASE_PATH: &str = "ivoryvalley.db";
/// Default maximum body size (50MB - allows video uploads)
const DEFAULT_MAX_BODY_SIZE: usize = 50 * 1024 * 1024;
/// Default HTTP connect timeout in seconds
const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
/// Default HTTP request timeout in seconds
const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;
/// Default recording path (None = disabled)
const DEFAULT_RECORD_TRAFFIC_PATH: Option<&str> = None;
/// Default cleanup interval in seconds (1 hour)
const DEFAULT_CLEANUP_INTERVAL_SECS: u64 = 3600;
/// Default cleanup max age in seconds (7 days)
const DEFAULT_CLEANUP_MAX_AGE_SECS: u64 = 7 * 24 * 3600;

/// Command line arguments
#[derive(Parser, Debug)]
#[command(name = "ivoryvalley")]
#[command(about = "A Mastodon proxy server for filtering content")]
pub struct CliArgs {
    /// Upstream Mastodon server URL
    #[arg(long, env = "IV_UPSTREAM_URL")]
    pub upstream_url: Option<String>,

    /// Host to bind the proxy server to
    #[arg(long, env = "IV_HOST")]
    pub host: Option<String>,

    /// Port to bind the proxy server to
    #[arg(short, long, env = "IV_PORT")]
    pub port: Option<u16>,

    /// Path to the SQLite database file
    #[arg(long, env = "IV_DATABASE_PATH")]
    pub database_path: Option<PathBuf>,

    /// Maximum request body size in bytes (default: 50MB)
    #[arg(long, env = "IV_MAX_BODY_SIZE")]
    pub max_body_size: Option<usize>,

    /// HTTP client connect timeout in seconds
    #[arg(long, env = "IV_CONNECT_TIMEOUT_SECS")]
    pub connect_timeout_secs: Option<u64>,

    /// HTTP client request timeout in seconds
    #[arg(long, env = "IV_REQUEST_TIMEOUT_SECS")]
    pub request_timeout_secs: Option<u64>,

    /// Path to record traffic (JSONL file). If set, all request/response pairs are recorded.
    #[arg(long, env = "IV_RECORD_TRAFFIC_PATH")]
    pub record_traffic_path: Option<PathBuf>,

    /// Interval between cleanup runs in seconds (default: 3600 = 1 hour)
    #[arg(long, env = "IV_CLEANUP_INTERVAL_SECS")]
    pub cleanup_interval_secs: Option<u64>,

    /// Maximum age of stored URIs in seconds (default: 604800 = 7 days)
    #[arg(long, env = "IV_CLEANUP_MAX_AGE_SECS")]
    pub cleanup_max_age_secs: Option<u64>,

    /// Path to configuration file
    #[arg(short, long, env = "IV_CONFIG")]
    pub config: Option<PathBuf>,
}

/// File-based configuration (for TOML/YAML)
#[derive(Debug, Deserialize, Default)]
#[serde(default)]
struct FileConfig {
    upstream_url: Option<String>,
    host: Option<String>,
    port: Option<u16>,
    database_path: Option<PathBuf>,
    max_body_size: Option<usize>,
    connect_timeout_secs: Option<u64>,
    request_timeout_secs: Option<u64>,
    record_traffic_path: Option<PathBuf>,
    cleanup_interval_secs: Option<u64>,
    cleanup_max_age_secs: Option<u64>,
}

/// Configuration for the IvoryValley proxy server
#[derive(Debug, Clone)]
pub struct Config {
    /// Upstream Mastodon server URL (e.g., "https://mastodon.social")
    pub upstream_url: String,

    /// Host to bind the proxy server to
    pub host: String,

    /// Port to bind the proxy server to
    pub port: u16,

    /// Path to the SQLite database file
    pub database_path: PathBuf,

    /// Maximum request body size in bytes (prevents DoS via memory exhaustion)
    pub max_body_size: usize,

    /// HTTP client connect timeout in seconds
    pub connect_timeout_secs: u64,

    /// HTTP client request timeout in seconds
    pub request_timeout_secs: u64,

    /// Path to record traffic (JSONL file). If Some, all traffic is recorded.
    pub record_traffic_path: Option<PathBuf>,

    /// Interval between cleanup runs in seconds
    pub cleanup_interval_secs: u64,

    /// Maximum age of stored URIs in seconds (older entries are removed during cleanup)
    pub cleanup_max_age_secs: u64,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            upstream_url: DEFAULT_UPSTREAM_URL.to_string(),
            host: DEFAULT_HOST.to_string(),
            port: DEFAULT_PORT,
            database_path: PathBuf::from(DEFAULT_DATABASE_PATH),
            max_body_size: DEFAULT_MAX_BODY_SIZE,
            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
            request_timeout_secs: DEFAULT_REQUEST_TIMEOUT_SECS,
            record_traffic_path: DEFAULT_RECORD_TRAFFIC_PATH.map(PathBuf::from),
            cleanup_interval_secs: DEFAULT_CLEANUP_INTERVAL_SECS,
            cleanup_max_age_secs: DEFAULT_CLEANUP_MAX_AGE_SECS,
        }
    }
}

impl Config {
    /// Create a new configuration with explicit values (uses default max_body_size and timeouts)
    #[allow(dead_code)] // Used in tests via library crate
    pub fn new(upstream_url: &str, host: &str, port: u16, database_path: PathBuf) -> Self {
        Self {
            upstream_url: upstream_url.to_string(),
            host: host.to_string(),
            port,
            database_path,
            max_body_size: DEFAULT_MAX_BODY_SIZE,
            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
            request_timeout_secs: DEFAULT_REQUEST_TIMEOUT_SECS,
            record_traffic_path: None,
            cleanup_interval_secs: DEFAULT_CLEANUP_INTERVAL_SECS,
            cleanup_max_age_secs: DEFAULT_CLEANUP_MAX_AGE_SECS,
        }
    }

    /// Create a new configuration with a custom max body size (for testing)
    #[allow(dead_code)] // Used in tests via library crate
    pub fn with_max_body_size(
        upstream_url: &str,
        host: &str,
        port: u16,
        database_path: PathBuf,
        max_body_size: usize,
    ) -> Self {
        Self {
            upstream_url: upstream_url.to_string(),
            host: host.to_string(),
            port,
            database_path,
            max_body_size,
            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
            request_timeout_secs: DEFAULT_REQUEST_TIMEOUT_SECS,
            record_traffic_path: None,
            cleanup_interval_secs: DEFAULT_CLEANUP_INTERVAL_SECS,
            cleanup_max_age_secs: DEFAULT_CLEANUP_MAX_AGE_SECS,
        }
    }

    /// Load configuration from all sources (CLI > env > file > defaults)
    pub fn load() -> Result<Self, ConfigError> {
        Self::load_from_args(CliArgs::parse())
    }

    /// Load configuration from provided CLI args (for testing)
    pub fn load_from_args(args: CliArgs) -> Result<Self, ConfigError> {
        // Start with defaults
        let mut config = Config::default();

        // Load from config file if specified or if default exists
        let file_config = Self::load_file_config(&args.config)?;

        // Apply file config (file overrides defaults)
        if let Some(url) = file_config.upstream_url {
            config.upstream_url = url;
        }
        if let Some(h) = file_config.host {
            config.host = h;
        }
        if let Some(p) = file_config.port {
            config.port = p;
        }
        if let Some(db) = file_config.database_path {
            config.database_path = db;
        }
        if let Some(size) = file_config.max_body_size {
            config.max_body_size = size;
        }
        if let Some(ct) = file_config.connect_timeout_secs {
            config.connect_timeout_secs = ct;
        }
        if let Some(rt) = file_config.request_timeout_secs {
            config.request_timeout_secs = rt;
        }
        if let Some(path) = file_config.record_traffic_path {
            config.record_traffic_path = Some(path);
        }
        if let Some(interval) = file_config.cleanup_interval_secs {
            config.cleanup_interval_secs = interval;
        }
        if let Some(max_age) = file_config.cleanup_max_age_secs {
            config.cleanup_max_age_secs = max_age;
        }

        // Apply CLI args (CLI overrides everything)
        if let Some(url) = args.upstream_url {
            config.upstream_url = url;
        }
        if let Some(h) = args.host {
            config.host = h;
        }
        if let Some(p) = args.port {
            config.port = p;
        }
        if let Some(db) = args.database_path {
            config.database_path = db;
        }
        if let Some(size) = args.max_body_size {
            config.max_body_size = size;
        }
        if let Some(ct) = args.connect_timeout_secs {
            config.connect_timeout_secs = ct;
        }
        if let Some(rt) = args.request_timeout_secs {
            config.request_timeout_secs = rt;
        }
        if let Some(path) = args.record_traffic_path {
            config.record_traffic_path = Some(path);
        }
        if let Some(interval) = args.cleanup_interval_secs {
            config.cleanup_interval_secs = interval;
        }
        if let Some(max_age) = args.cleanup_max_age_secs {
            config.cleanup_max_age_secs = max_age;
        }

        Ok(config)
    }

    /// Load configuration from file
    ///
    /// Note: Environment variables are handled by clap's `env` attribute on CliArgs,
    /// not by the config crate. This ensures CLI args (including env vars) always
    /// take precedence over file config.
    fn load_file_config(config_path: &Option<PathBuf>) -> Result<FileConfig, ConfigError> {
        let mut builder = config::Config::builder();

        // Add config file if specified
        if let Some(path) = config_path {
            builder = builder.add_source(File::from(path.as_path()));
        } else {
            // Try default config files (optional)
            builder = builder
                .add_source(File::with_name("config").required(false))
                .add_source(File::with_name("ivoryvalley").required(false));
        }

        let settings = builder.build()?;
        settings.try_deserialize()
    }

    /// Get the socket address for binding
    pub fn bind_addr(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

/// Shared application state containing configuration
#[derive(Clone)]
pub struct AppState {
    pub config: Arc<Config>,
    pub http_client: reqwest::Client,
    pub seen_uri_store: Arc<crate::db::SeenUriStore>,
    pub traffic_recorder: Option<Arc<crate::recording::TrafficRecorder>>,
}

impl AppState {
    /// Create a new application state from configuration and seen URI store.
    ///
    /// The `SeenUriStore` is wrapped in an `Arc` so it can be shared with other
    /// components (e.g., WebSocket handlers) that also need deduplication.
    pub fn new(config: Config, seen_store: Arc<crate::db::SeenUriStore>) -> Self {
        let http_client = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .connect_timeout(Duration::from_secs(config.connect_timeout_secs))
            .timeout(Duration::from_secs(config.request_timeout_secs))
            .build()
            .expect("Failed to create HTTP client");

        // Initialize traffic recorder if configured
        let traffic_recorder = config.record_traffic_path.as_ref().and_then(|path| {
            match crate::recording::TrafficRecorder::new(path.clone()) {
                Ok(recorder) => {
                    tracing::info!("Traffic recording enabled: {}", path.display());
                    Some(Arc::new(recorder))
                }
                Err(e) => {
                    tracing::error!("Failed to initialize traffic recorder: {}", e);
                    None
                }
            }
        });

        Self {
            config: Arc::new(config),
            http_client,
            seen_uri_store: seen_store,
            traffic_recorder,
        }
    }
}

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

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(config.upstream_url, "https://mastodon.social");
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
        assert_eq!(config.database_path, PathBuf::from("ivoryvalley.db"));
        assert_eq!(config.max_body_size, 50 * 1024 * 1024);
        assert_eq!(config.connect_timeout_secs, 10);
        assert_eq!(config.request_timeout_secs, 30);
        assert_eq!(config.cleanup_interval_secs, 3600);
        assert_eq!(config.cleanup_max_age_secs, 7 * 24 * 3600);
    }

    #[test]
    fn test_config_new() {
        let config = Config::new(
            "https://example.com",
            "127.0.0.1",
            3000,
            PathBuf::from("/data/test.db"),
        );
        assert_eq!(config.upstream_url, "https://example.com");
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 3000);
        assert_eq!(config.database_path, PathBuf::from("/data/test.db"));
    }

    #[test]
    fn test_bind_addr() {
        let config = Config::new(
            "https://mastodon.social",
            "127.0.0.1",
            3000,
            PathBuf::from("test.db"),
        );
        assert_eq!(config.bind_addr(), "127.0.0.1:3000");
    }

    #[test]
    fn test_load_defaults_when_no_config() {
        // Use an empty temp config file to isolate from env vars
        // (without a config file, the config crate would load env vars)
        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        writeln!(file, "# empty config").unwrap();

        let args = CliArgs {
            upstream_url: None,
            host: None,
            port: None,
            database_path: None,
            max_body_size: None,
            connect_timeout_secs: None,
            request_timeout_secs: None,
            record_traffic_path: None,
            cleanup_interval_secs: None,
            cleanup_max_age_secs: None,
            config: Some(file.path().to_path_buf()),
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://mastodon.social");
        assert_eq!(config.host, "0.0.0.0");
        assert_eq!(config.port, 8080);
        assert_eq!(config.database_path, PathBuf::from("ivoryvalley.db"));
        assert_eq!(config.max_body_size, 50 * 1024 * 1024);
        assert_eq!(config.connect_timeout_secs, 10);
        assert_eq!(config.request_timeout_secs, 30);
        assert_eq!(config.record_traffic_path, None);
        assert_eq!(config.cleanup_interval_secs, 3600);
        assert_eq!(config.cleanup_max_age_secs, 7 * 24 * 3600);
    }

    #[test]
    fn test_load_from_cli_args() {
        let args = CliArgs {
            upstream_url: Some("https://cli.example.com".to_string()),
            host: Some("192.168.1.1".to_string()),
            port: Some(9000),
            database_path: Some(PathBuf::from("/cli/path.db")),
            max_body_size: Some(100 * 1024 * 1024),
            connect_timeout_secs: Some(5),
            request_timeout_secs: Some(60),
            record_traffic_path: Some(PathBuf::from("/tmp/traffic.jsonl")),
            cleanup_interval_secs: Some(1800),
            cleanup_max_age_secs: Some(86400),
            config: None,
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://cli.example.com");
        assert_eq!(config.host, "192.168.1.1");
        assert_eq!(config.port, 9000);
        assert_eq!(config.database_path, PathBuf::from("/cli/path.db"));
        assert_eq!(config.max_body_size, 100 * 1024 * 1024);
        assert_eq!(config.connect_timeout_secs, 5);
        assert_eq!(config.request_timeout_secs, 60);
        assert_eq!(
            config.record_traffic_path,
            Some(PathBuf::from("/tmp/traffic.jsonl"))
        );
        assert_eq!(config.cleanup_interval_secs, 1800);
        assert_eq!(config.cleanup_max_age_secs, 86400);
    }

    #[test]
    fn test_load_from_toml_file() {
        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        writeln!(
            file,
            r#"
upstream_url = "https://toml.example.com"
host = "10.0.0.1"
port = 7000
database_path = "/toml/db.sqlite"
connect_timeout_secs = 15
request_timeout_secs = 45
"#
        )
        .unwrap();

        let args = CliArgs {
            upstream_url: None,
            host: None,
            port: None,
            database_path: None,
            max_body_size: None,
            connect_timeout_secs: None,
            request_timeout_secs: None,
            record_traffic_path: None,
            cleanup_interval_secs: None,
            cleanup_max_age_secs: None,
            config: Some(file.path().to_path_buf()),
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://toml.example.com");
        assert_eq!(config.host, "10.0.0.1");
        assert_eq!(config.port, 7000);
        assert_eq!(config.database_path, PathBuf::from("/toml/db.sqlite"));
        assert_eq!(config.connect_timeout_secs, 15);
        assert_eq!(config.request_timeout_secs, 45);
    }

    #[test]
    fn test_load_from_yaml_file() {
        let mut file = NamedTempFile::with_suffix(".yaml").unwrap();
        writeln!(
            file,
            r#"
upstream_url: "https://yaml.example.com"
host: "10.0.0.2"
port: 6000
database_path: "/yaml/db.sqlite"
connect_timeout_secs: 20
request_timeout_secs: 120
"#
        )
        .unwrap();

        let args = CliArgs {
            upstream_url: None,
            host: None,
            port: None,
            database_path: None,
            max_body_size: None,
            connect_timeout_secs: None,
            request_timeout_secs: None,
            record_traffic_path: None,
            cleanup_interval_secs: None,
            cleanup_max_age_secs: None,
            config: Some(file.path().to_path_buf()),
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://yaml.example.com");
        assert_eq!(config.host, "10.0.0.2");
        assert_eq!(config.port, 6000);
        assert_eq!(config.database_path, PathBuf::from("/yaml/db.sqlite"));
        assert_eq!(config.connect_timeout_secs, 20);
        assert_eq!(config.request_timeout_secs, 120);
    }

    #[test]
    fn test_cli_overrides_file() {
        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        writeln!(
            file,
            r#"
upstream_url = "https://file.example.com"
host = "10.0.0.1"
port = 7000
database_path = "/file/db.sqlite"
connect_timeout_secs = 15
request_timeout_secs = 45
"#
        )
        .unwrap();

        let args = CliArgs {
            upstream_url: Some("https://cli.example.com".to_string()),
            host: None, // Use file value
            port: Some(9999),
            database_path: None, // Use file value
            max_body_size: None,
            connect_timeout_secs: Some(5), // Override file value
            request_timeout_secs: None,    // Use file value
            record_traffic_path: None,
            cleanup_interval_secs: None,
            cleanup_max_age_secs: None,
            config: Some(file.path().to_path_buf()),
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://cli.example.com"); // CLI
        assert_eq!(config.host, "10.0.0.1"); // File
        assert_eq!(config.port, 9999); // CLI
        assert_eq!(config.database_path, PathBuf::from("/file/db.sqlite")); // File
        assert_eq!(config.connect_timeout_secs, 5); // CLI override
        assert_eq!(config.request_timeout_secs, 45); // File
    }

    #[test]
    fn test_partial_file_config_uses_defaults() {
        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        writeln!(
            file,
            r#"
upstream_url = "https://partial.example.com"
"#
        )
        .unwrap();

        let args = CliArgs {
            upstream_url: None,
            host: None,
            port: None,
            database_path: None,
            max_body_size: None,
            connect_timeout_secs: None,
            request_timeout_secs: None,
            record_traffic_path: None,
            cleanup_interval_secs: None,
            cleanup_max_age_secs: None,
            config: Some(file.path().to_path_buf()),
        };
        let config = Config::load_from_args(args).unwrap();
        assert_eq!(config.upstream_url, "https://partial.example.com"); // From file
        assert_eq!(config.host, "0.0.0.0"); // Default
        assert_eq!(config.port, 8080); // Default
        assert_eq!(config.database_path, PathBuf::from("ivoryvalley.db")); // Default
        assert_eq!(config.max_body_size, 50 * 1024 * 1024); // Default 50MB
        assert_eq!(config.connect_timeout_secs, 10); // Default
        assert_eq!(config.request_timeout_secs, 30); // Default
        assert_eq!(config.record_traffic_path, None); // Default
        assert_eq!(config.cleanup_interval_secs, 3600); // Default
        assert_eq!(config.cleanup_max_age_secs, 7 * 24 * 3600); // Default
    }

    // Mutex to serialize env var tests (env vars are process-global)
    use std::sync::Mutex;
    static ENV_VAR_TEST_MUTEX: Mutex<()> = Mutex::new(());

    /// Helper struct to ensure env var cleanup on drop (even if test panics)
    /// Also holds the mutex guard to serialize access to env vars.
    struct EnvVarGuard<'a> {
        vars: Vec<&'static str>,
        _lock: std::sync::MutexGuard<'a, ()>,
    }

    impl<'a> EnvVarGuard<'a> {
        fn new(vars: &[(&'static str, &str)]) -> Self {
            // Acquire lock before modifying env vars
            let lock = ENV_VAR_TEST_MUTEX.lock().unwrap();
            for (key, value) in vars {
                std::env::set_var(key, value);
            }
            Self {
                vars: vars.iter().map(|(k, _)| *k).collect(),
                _lock: lock,
            }
        }
    }

    impl Drop for EnvVarGuard<'_> {
        fn drop(&mut self) {
            for var in &self.vars {
                std::env::remove_var(var);
            }
            // Lock is automatically released when _lock is dropped
        }
    }

    #[test]
    fn test_env_var_prefix_uses_iv() {
        // This test verifies that environment variables use the IV_ prefix
        // to avoid collision with Kubernetes service discovery variables
        // (which would use IVORYVALLEY_ for a service named "ivoryvalley")

        // Set env vars with IV_ prefix (cleanup guaranteed by guard)
        let _guard = EnvVarGuard::new(&[
            ("IV_HOST", "192.168.99.1"),
            ("IV_PORT", "9999"),
            ("IV_UPSTREAM_URL", "https://env.example.com"),
        ]);

        // Use clap's try_parse_from to simulate CLI parsing with env vars
        // (passing empty args so env vars are used as fallback)
        let args = CliArgs::try_parse_from(["ivoryvalley"]).unwrap();

        assert_eq!(args.host, Some("192.168.99.1".to_string()));
        assert_eq!(args.port, Some(9999));
        assert_eq!(
            args.upstream_url,
            Some("https://env.example.com".to_string())
        );
    }

    #[test]
    fn test_kubernetes_style_env_vars_ignored() {
        // This test verifies that Kubernetes-style env vars don't interfere
        // with configuration loading (simulating IVORYVALLEY_PORT=tcp://...)
        //
        // Before the fix, having a Kubernetes service named "ivoryvalley" would
        // inject IVORYVALLEY_PORT=tcp://... which would collide with the config
        // env vars and cause a parse error.

        // Set Kubernetes-style env vars (cleanup guaranteed by guard)
        let _guard = EnvVarGuard::new(&[
            ("IVORYVALLEY_PORT", "tcp://10.43.62.146:80"),
            ("IVORYVALLEY_PORT_80_TCP", "tcp://10.43.62.146:80"),
        ]);

        // Use clap's try_parse_from to simulate CLI parsing
        // This should succeed without errors, ignoring the IVORYVALLEY_* vars
        let args = CliArgs::try_parse_from(["ivoryvalley"]).unwrap();

        // Port should be None (using default), not causing a parse error
        assert_eq!(args.port, None);
    }
}