bluebox 0.1.4

A fast DNS interceptor and cache for local networks
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
//! Configuration loading and validation.

use std::collections::HashSet;
use std::net::{Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::error::{ConfigError, Result, ValidationError};

/// Supported blocklist file formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BlocklistFormat {
    /// One domain per line.
    #[default]
    Domains,
    /// Standard hosts file format (e.g., `0.0.0.0 example.com`).
    Hosts,
    /// `AdBlock` filter syntax (future support).
    Adblock,
}

/// Source type for a blocklist.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum BlocklistSourceType {
    /// Load blocklist from a local file.
    File {
        /// Path to the blocklist file.
        path: PathBuf,
    },
    /// Fetch blocklist from a remote URL.
    Remote {
        /// URL to fetch the blocklist from.
        url: String,
    },
}

/// Configuration for a blocklist source.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BlocklistSourceConfig {
    /// Unique name for this blocklist source.
    pub name: String,
    /// Whether this source is enabled.
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    /// Source location (file or remote URL).
    pub source: BlocklistSourceType,
    /// Format of the blocklist file.
    #[serde(default)]
    pub format: BlocklistFormat,
    /// Refresh interval in hours (only applicable for remote sources).
    pub refresh_interval_hours: Option<u64>,
}

const fn default_enabled() -> bool {
    true
}

/// Main configuration for the Bluebox DNS server.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Network interface to listen on. If None, auto-detect.
    pub interface: Option<String>,

    /// Upstream DNS resolver address (e.g., "1.1.1.1:53").
    #[serde(deserialize_with = "deserialize_socket_addr")]
    pub upstream_resolver: SocketAddr,

    /// Cache TTL in seconds.
    #[serde(default = "default_cache_ttl")]
    pub cache_ttl_seconds: u64,

    /// Legacy inline blocklist (backwards compatible).
    /// Supports exact matches ("example.com") and wildcards ("*.example.com").
    #[serde(default)]
    pub blocklist: Vec<String>,

    /// External blocklist sources.
    #[serde(default)]
    pub blocklist_sources: Vec<BlocklistSourceConfig>,

    /// Cache directory for remote blocklists.
    /// Defaults to platform-specific cache directory.
    pub blocklist_cache_dir: Option<PathBuf>,

    /// Size of the packet buffer pool.
    #[serde(default = "default_buffer_pool_size")]
    pub buffer_pool_size: usize,

    /// Channel capacity for packet queue.
    #[serde(default = "default_channel_capacity")]
    pub channel_capacity: usize,

    /// ARP spoofing configuration for transparent DNS interception.
    #[serde(default)]
    pub arp_spoof: ArpSpoofSettings,

    /// Metrics configuration for Prometheus exporter.
    #[serde(default)]
    pub metrics: MetricsConfig,
}

/// ARP spoofing settings for transparent DNS interception.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ArpSpoofSettings {
    /// Enable ARP spoofing for transparent interception.
    /// When enabled, the server will impersonate the gateway to intercept DNS queries.
    #[serde(default)]
    pub enabled: bool,

    /// Gateway IP address to impersonate. If None, auto-detect.
    pub gateway_ip: Option<Ipv4Addr>,

    /// Interval in seconds between ARP spoof packets.
    #[serde(default = "default_spoof_interval")]
    pub spoof_interval_secs: u64,

    /// Whether to restore ARP tables when shutting down.
    #[serde(default = "default_restore_on_shutdown")]
    pub restore_on_shutdown: bool,

    /// Forward non-DNS traffic to the real gateway.
    #[serde(default = "default_forward_traffic")]
    pub forward_traffic: bool,
}

impl Default for ArpSpoofSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            gateway_ip: None,
            spoof_interval_secs: default_spoof_interval(),
            restore_on_shutdown: default_restore_on_shutdown(),
            forward_traffic: default_forward_traffic(),
        }
    }
}

/// Metrics configuration for Prometheus exporter.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MetricsConfig {
    /// Enable metrics collection and Prometheus endpoint.
    #[serde(default)]
    pub enabled: bool,
    /// Prometheus HTTP listener address.
    #[serde(default = "default_metrics_listen")]
    pub listen: SocketAddr,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            listen: default_metrics_listen(),
        }
    }
}

const fn default_cache_ttl() -> u64 {
    300
}

const fn default_buffer_pool_size() -> usize {
    64
}

const fn default_channel_capacity() -> usize {
    1000
}

const fn default_spoof_interval() -> u64 {
    2
}

const fn default_restore_on_shutdown() -> bool {
    true
}

const fn default_forward_traffic() -> bool {
    true
}

fn default_metrics_listen() -> SocketAddr {
    SocketAddr::from(([0, 0, 0, 0], 9090))
}

fn deserialize_socket_addr<'de, D>(deserializer: D) -> std::result::Result<SocketAddr, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    s.parse().map_err(serde::de::Error::custom)
}

impl Config {
    /// Load configuration from a TOML file.
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path).map_err(ConfigError::ReadFile)?;
        Self::parse(&content)
    }

    /// Parse configuration from a TOML string.
    pub fn parse(content: &str) -> Result<Self> {
        let config: Self = toml::from_str(content).map_err(ConfigError::Parse)?;
        config.validate()?;
        Ok(config)
    }

    /// Get the blocklist cache directory.
    ///
    /// Returns the configured directory or falls back to the platform-specific
    /// default cache directory.
    #[must_use]
    pub fn blocklist_cache_dir(&self) -> PathBuf {
        self.blocklist_cache_dir
            .clone()
            .unwrap_or_else(crate::blocklist::remote::default_cache_dir)
    }

    /// Validate the configuration.
    fn validate(&self) -> Result<()> {
        if self.cache_ttl_seconds == 0 {
            return Err(ConfigError::from(ValidationError::ZeroCacheTtl).into());
        }

        if self.buffer_pool_size == 0 {
            return Err(ConfigError::from(ValidationError::ZeroBufferPoolSize).into());
        }

        if self.channel_capacity == 0 {
            return Err(ConfigError::from(ValidationError::ZeroChannelCapacity).into());
        }

        if self.arp_spoof.spoof_interval_secs == 0 {
            return Err(ConfigError::from(ValidationError::ZeroSpoofInterval).into());
        }

        // Validate blocklist patterns
        for pattern in &self.blocklist {
            if pattern.is_empty() {
                return Err(ConfigError::from(ValidationError::EmptyBlocklistPattern).into());
            }
            if pattern.starts_with("*.") && pattern.len() <= 2 {
                return Err(ConfigError::from(ValidationError::InvalidWildcardPattern {
                    pattern: pattern.clone(),
                })
                .into());
            }
        }

        // Validate blocklist sources
        self.validate_blocklist_sources()?;

        Ok(())
    }

    /// Validate blocklist source configurations.
    fn validate_blocklist_sources(&self) -> Result<()> {
        let mut seen_names = HashSet::new();

        for source in &self.blocklist_sources {
            // Validate name is not empty
            if source.name.is_empty() {
                return Err(ConfigError::from(ValidationError::EmptyBlocklistSourceName).into());
            }

            // Validate name is unique
            if !seen_names.insert(&source.name) {
                return Err(
                    ConfigError::from(ValidationError::DuplicateBlocklistSourceName {
                        name: source.name.clone(),
                    })
                    .into(),
                );
            }

            // Validate source-specific constraints
            match &source.source {
                BlocklistSourceType::File { path } => {
                    // Validate path is not empty
                    if path.as_os_str().is_empty() {
                        return Err(
                            ConfigError::from(ValidationError::EmptyBlocklistSourcePath {
                                name: source.name.clone(),
                            })
                            .into(),
                        );
                    }

                    // Warn if refresh_interval is set for file sources (it's ignored)
                    if source.refresh_interval_hours.is_some() {
                        tracing::warn!(
                            name = ?source.name,
                            "refresh_interval_hours is ignored for file sources"
                        );
                    }
                }
                BlocklistSourceType::Remote { url } => {
                    // Validate URL is not empty
                    if url.is_empty() {
                        return Err(ConfigError::from(ValidationError::EmptyBlocklistSourceUrl {
                            name: source.name.clone(),
                        })
                        .into());
                    }

                    // Validate URL format (basic check for http/https scheme)
                    if !url.starts_with("http://") && !url.starts_with("https://") {
                        return Err(ConfigError::from(
                            ValidationError::InvalidBlocklistSourceUrl {
                                name: source.name.clone(),
                                url: url.clone(),
                            },
                        )
                        .into());
                    }
                }
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn should_parse_valid_config() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            cache_ttl_seconds = 600
            blocklist = ["example.com", "*.ads.com"]
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.upstream_resolver.to_string(), "1.1.1.1:53");
        assert_eq!(config.cache_ttl_seconds, 600);
        assert_eq!(config.blocklist.len(), 2);
        assert!(config.interface.is_none());
    }

    #[test]
    fn should_parse_config_with_interface() {
        let toml = r#"
            interface = "eth0"
            upstream_resolver = "8.8.8.8:53"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.interface.as_deref(), Some("eth0"));
    }

    #[test]
    fn should_use_default_values_when_not_specified() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.cache_ttl_seconds, 300);
        assert_eq!(config.buffer_pool_size, 64);
        assert_eq!(config.channel_capacity, 1000);
        assert!(config.blocklist.is_empty());
        assert!(!config.arp_spoof.enabled);
    }

    #[test]
    fn should_parse_arp_spoof_config() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [arp_spoof]
            enabled = true
            gateway_ip = "192.168.1.1"
            spoof_interval_secs = 5
            restore_on_shutdown = true
            forward_traffic = true
        "#;

        let config = Config::parse(toml).unwrap();
        assert!(config.arp_spoof.enabled);
        assert_eq!(
            config.arp_spoof.gateway_ip,
            Some(Ipv4Addr::new(192, 168, 1, 1))
        );
        assert_eq!(config.arp_spoof.spoof_interval_secs, 5);
        assert!(config.arp_spoof.restore_on_shutdown);
        assert!(config.arp_spoof.forward_traffic);
    }

    #[test]
    fn should_use_arp_spoof_defaults_when_not_specified() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [arp_spoof]
            enabled = true
        "#;

        let config = Config::parse(toml).unwrap();
        assert!(config.arp_spoof.enabled);
        assert!(config.arp_spoof.gateway_ip.is_none());
        assert_eq!(config.arp_spoof.spoof_interval_secs, 2);
        assert!(config.arp_spoof.restore_on_shutdown);
        assert!(config.arp_spoof.forward_traffic);
    }

    #[test]
    fn should_reject_invalid_resolver_address() {
        let toml = r#"
            upstream_resolver = "not-an-address"
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_zero_cache_ttl() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            cache_ttl_seconds = 0
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_empty_blocklist_pattern() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            blocklist = ["example.com", ""]
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_unknown_field() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            unknown_field = "value"
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_zero_spoof_interval() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [arp_spoof]
            enabled = true
            spoof_interval_secs = 0
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_parse_blocklist_source_file() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "local-custom"
            enabled = true
            source = { type = "file", path = "/etc/bluebox/custom-blocklist.txt" }
            format = "domains"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist_sources.len(), 1);

        let source = &config.blocklist_sources[0];
        assert_eq!(source.name, "local-custom");
        assert!(source.enabled);
        assert_eq!(source.format, BlocklistFormat::Domains);
        assert!(source.refresh_interval_hours.is_none());

        match &source.source {
            BlocklistSourceType::File { path } => {
                assert_eq!(path.to_str().unwrap(), "/etc/bluebox/custom-blocklist.txt");
            }
            BlocklistSourceType::Remote { .. } => panic!("expected file source"),
        }
    }

    #[test]
    fn should_parse_blocklist_source_remote() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "steven-black-hosts"
            enabled = true
            source = { type = "remote", url = "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts" }
            format = "hosts"
            refresh_interval_hours = 24
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist_sources.len(), 1);

        let source = &config.blocklist_sources[0];
        assert_eq!(source.name, "steven-black-hosts");
        assert!(source.enabled);
        assert_eq!(source.format, BlocklistFormat::Hosts);
        assert_eq!(source.refresh_interval_hours, Some(24));

        match &source.source {
            BlocklistSourceType::Remote { url } => {
                assert_eq!(
                    url,
                    "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"
                );
            }
            BlocklistSourceType::File { .. } => panic!("expected remote source"),
        }
    }

    #[test]
    fn should_use_blocklist_source_defaults() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "test"
            source = { type = "file", path = "/path/to/file.txt" }
        "#;

        let config = Config::parse(toml).unwrap();
        let source = &config.blocklist_sources[0];

        // Default enabled is true
        assert!(source.enabled);
        // Default format is domains
        assert_eq!(source.format, BlocklistFormat::Domains);
    }

    #[test]
    fn should_parse_disabled_blocklist_source() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "disabled-source"
            enabled = false
            source = { type = "remote", url = "https://example.com/blocklist.txt" }
        "#;

        let config = Config::parse(toml).unwrap();
        assert!(!config.blocklist_sources[0].enabled);
    }

    #[test]
    fn should_parse_blocklist_source_adblock_format() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "adguard"
            source = { type = "remote", url = "https://example.com/filter.txt" }
            format = "adblock"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist_sources[0].format, BlocklistFormat::Adblock);
    }

    #[test]
    fn should_parse_multiple_blocklist_sources() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "source-1"
            source = { type = "file", path = "/path/1.txt" }

            [[blocklist_sources]]
            name = "source-2"
            source = { type = "remote", url = "https://example.com/list.txt" }
            format = "hosts"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist_sources.len(), 2);
        assert_eq!(config.blocklist_sources[0].name, "source-1");
        assert_eq!(config.blocklist_sources[1].name, "source-2");
    }

    #[test]
    fn should_parse_blocklist_sources_with_legacy_blocklist() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            blocklist = ["custom-domain.com"]

            [[blocklist_sources]]
            name = "remote-list"
            source = { type = "remote", url = "https://example.com/list.txt" }
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist.len(), 1);
        assert_eq!(config.blocklist[0], "custom-domain.com");
        assert_eq!(config.blocklist_sources.len(), 1);
    }

    #[test]
    fn should_reject_duplicate_blocklist_source_name() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "same-name"
            source = { type = "file", path = "/path/1.txt" }

            [[blocklist_sources]]
            name = "same-name"
            source = { type = "file", path = "/path/2.txt" }
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_empty_blocklist_source_name() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = ""
            source = { type = "file", path = "/path/file.txt" }
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_empty_blocklist_source_path() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "test"
            source = { type = "file", path = "" }
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_empty_blocklist_source_url() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "test"
            source = { type = "remote", url = "" }
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_invalid_blocklist_source_url() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "test"
            source = { type = "remote", url = "ftp://example.com/list.txt" }
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_unknown_blocklist_source_field() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "test"
            source = { type = "file", path = "/path/file.txt" }
            unknown_field = "value"
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_zero_buffer_pool_size() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            buffer_pool_size = 0
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_zero_channel_capacity() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            channel_capacity = 0
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_reject_invalid_wildcard_pattern() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            blocklist = ["*."]
        "#;

        assert!(Config::parse(toml).is_err());
    }

    #[test]
    fn should_allow_file_source_with_refresh_interval() {
        // This should parse successfully but emit a warning
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"

            [[blocklist_sources]]
            name = "local-custom"
            source = { type = "file", path = "/etc/bluebox/custom-blocklist.txt" }
            refresh_interval_hours = 24
        "#;

        // Should succeed despite refresh_interval being set for a file source
        let config = Config::parse(toml).unwrap();
        assert_eq!(config.blocklist_sources[0].refresh_interval_hours, Some(24));
    }

    #[test]
    fn should_return_error_when_loading_nonexistent_file() {
        let result = Config::load("/nonexistent/path/to/config.toml");
        assert!(result.is_err());
    }

    #[test]
    fn should_parse_blocklist_cache_dir() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
            blocklist_cache_dir = "/var/cache/bluebox/blocklists"
        "#;

        let config = Config::parse(toml).unwrap();
        assert_eq!(
            config.blocklist_cache_dir,
            Some(PathBuf::from("/var/cache/bluebox/blocklists"))
        );
        assert_eq!(
            config.blocklist_cache_dir(),
            PathBuf::from("/var/cache/bluebox/blocklists")
        );
    }

    #[test]
    fn should_use_default_blocklist_cache_dir_when_not_specified() {
        let toml = r#"
            upstream_resolver = "1.1.1.1:53"
        "#;

        let config = Config::parse(toml).unwrap();
        assert!(config.blocklist_cache_dir.is_none());
        // The method should return the platform-specific default
        let cache_dir = config.blocklist_cache_dir();
        assert!(cache_dir.ends_with("bluebox/blocklists") || cache_dir.ends_with("blocklists"));
    }
}