domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! Config construction: merge typed TOML [`FileConfig`] with CLI-derived config.
//!
//! Precedence: CLI > env (via clap before this merge) > config file > defaults.
//! The CLI layer loads [`FileConfig`] and passes it here so config building and
//! validation stay in the config module.

use std::fmt;
use std::path::PathBuf;

use serde::de::{self, Deserializer, Visitor};
use serde::Deserialize;

use super::types::{Config, FailOn, LogFormat, LogLevel};

/// TOML overlay keys matching [`FileConfig`] fields 1:1.
///
/// [`crate::cli`] compile-time checks that every key is listed in
/// `SCAN_CONFIG_ARG_IDS` so a new file field cannot silently ignore CLI/env
/// overlay detection. Keep this list in lockstep with the struct below.
pub(crate) const FILE_CONFIG_OVERLAY_KEYS: &[&str] = &[
    "file",
    "log_level",
    "log_format",
    "db_path",
    "max_concurrency",
    "timeout_seconds",
    "user_agent",
    "rate_limit_rps",
    "fingerprints",
    "geoip",
    "status_port",
    "enable_whois",
    "cache_dir",
    "scan_external_scripts",
    "fail_on",
    "fail_on_pct_threshold",
    "log_file",
    "drain_timeout_secs",
];

/// TOML overlay for scan settings.
///
/// All fields are `Option` so absent keys leave [`Config`] defaults in place.
/// Deserialized from TOML via the `config` crate. Env (`DOMAIN_STATUS_*`) is
/// applied through clap, not this struct.
/// Invalid enum/bool values fail deserialization (no silent skip).
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
pub struct FileConfig {
    /// URL list path (library / non-CLI embeds; CLI uses the positional arg).
    pub file: Option<PathBuf>,
    /// Baseline log level.
    #[serde(default, deserialize_with = "deserialize_option_log_level")]
    pub log_level: Option<LogLevel>,
    /// Scan log file format.
    #[serde(default, deserialize_with = "deserialize_option_log_format")]
    pub log_format: Option<LogFormat>,
    /// `SQLite` database path.
    pub db_path: Option<PathBuf>,
    /// Maximum concurrent requests.
    pub max_concurrency: Option<usize>,
    /// Per-request HTTP timeout in seconds.
    pub timeout_seconds: Option<u64>,
    /// HTTP User-Agent.
    pub user_agent: Option<String>,
    /// URL admission tokens per second (`0` disables). Not per-HTTP-request RPS.
    pub rate_limit_rps: Option<u32>,
    /// Fingerprints URL or local path.
    pub fingerprints: Option<String>,
    /// `GeoIP` database path or download URL.
    pub geoip: Option<String>,
    /// Optional status HTTP server port.
    pub status_port: Option<u16>,
    /// Enable WHOIS/RDAP lookups.
    #[serde(default, deserialize_with = "deserialize_option_bool")]
    pub enable_whois: Option<bool>,
    /// Shared cache root.
    pub cache_dir: Option<PathBuf>,
    /// Fetch first-party external scripts for analysis.
    #[serde(default, deserialize_with = "deserialize_option_bool")]
    pub scan_external_scripts: Option<bool>,
    /// Exit-code failure policy.
    #[serde(default, deserialize_with = "deserialize_option_fail_on")]
    pub fail_on: Option<FailOn>,
    /// Failure % threshold when `fail_on` is `pct>`.
    pub fail_on_pct_threshold: Option<u8>,
    /// Scan log file path.
    pub log_file: Option<PathBuf>,
    /// Drain timeout after the input queue is empty (seconds).
    pub drain_timeout_secs: Option<u64>,
}

/// Parsers for string values from config file / env (case-insensitive).
fn parse_log_level(s: &str) -> Option<LogLevel> {
    match s.to_lowercase().as_str() {
        "error" => Some(LogLevel::Error),
        "warn" => Some(LogLevel::Warn),
        "info" => Some(LogLevel::Info),
        "debug" => Some(LogLevel::Debug),
        "trace" => Some(LogLevel::Trace),
        _ => None,
    }
}

fn parse_log_format(s: &str) -> Option<LogFormat> {
    match s.to_lowercase().as_str() {
        "plain" => Some(LogFormat::Plain),
        "json" => Some(LogFormat::Json),
        _ => None,
    }
}

fn parse_fail_on(s: &str) -> Option<FailOn> {
    match s.to_lowercase().as_str() {
        "never" => Some(FailOn::Never),
        "any-failure" | "any_failure" | "anyfailure" => Some(FailOn::AnyFailure),
        "pct>" => Some(FailOn::PctGreaterThan),
        _ => None,
    }
}

fn parse_bool(s: &str) -> Option<bool> {
    match s.trim().to_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Some(true),
        "false" | "0" | "no" | "off" => Some(false),
        _ => None,
    }
}

fn deserialize_option_bool<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
where
    D: Deserializer<'de>,
{
    struct OptBoolVisitor;

    impl<'de> Visitor<'de> for OptBoolVisitor {
        type Value = Option<bool>;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("a boolean or bool-like string (true/false, 1/0, yes/no, on/off)")
        }

        fn visit_bool<E: de::Error>(self, v: bool) -> Result<Self::Value, E> {
            Ok(Some(v))
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            parse_bool(v)
                .map(Some)
                .ok_or_else(|| E::custom(format!("invalid boolean value: {v:?}")))
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }

        fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
            match v {
                0 => Ok(Some(false)),
                1 => Ok(Some(true)),
                _ => Err(E::custom(format!("invalid boolean integer: {v}"))),
            }
        }

        fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
            match v {
                0 => Ok(Some(false)),
                1 => Ok(Some(true)),
                _ => Err(E::custom(format!("invalid boolean integer: {v}"))),
            }
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_some<D2: Deserializer<'de>>(
            self,
            deserializer: D2,
        ) -> Result<Self::Value, D2::Error> {
            deserializer.deserialize_any(OptBoolVisitor)
        }
    }

    deserializer.deserialize_any(OptBoolVisitor)
}

fn deserialize_option_fail_on<'de, D>(deserializer: D) -> Result<Option<FailOn>, D::Error>
where
    D: Deserializer<'de>,
{
    struct OptFailOnVisitor;

    impl<'de> Visitor<'de> for OptFailOnVisitor {
        type Value = Option<FailOn>;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("fail_on: never | any-failure | any_failure | pct>")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            parse_fail_on(v)
                .map(Some)
                .ok_or_else(|| E::custom(format!("invalid fail_on value: {v:?}")))
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_some<D2: Deserializer<'de>>(
            self,
            deserializer: D2,
        ) -> Result<Self::Value, D2::Error> {
            deserializer.deserialize_any(OptFailOnVisitor)
        }
    }

    deserializer.deserialize_any(OptFailOnVisitor)
}

fn deserialize_option_log_level<'de, D>(deserializer: D) -> Result<Option<LogLevel>, D::Error>
where
    D: Deserializer<'de>,
{
    struct OptLogLevelVisitor;

    impl<'de> Visitor<'de> for OptLogLevelVisitor {
        type Value = Option<LogLevel>;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("log_level: error | warn | info | debug | trace")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            parse_log_level(v)
                .map(Some)
                .ok_or_else(|| E::custom(format!("invalid log_level value: {v:?}")))
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_some<D2: Deserializer<'de>>(
            self,
            deserializer: D2,
        ) -> Result<Self::Value, D2::Error> {
            deserializer.deserialize_any(OptLogLevelVisitor)
        }
    }

    deserializer.deserialize_any(OptLogLevelVisitor)
}

fn deserialize_option_log_format<'de, D>(deserializer: D) -> Result<Option<LogFormat>, D::Error>
where
    D: Deserializer<'de>,
{
    struct OptLogFormatVisitor;

    impl<'de> Visitor<'de> for OptLogFormatVisitor {
        type Value = Option<LogFormat>;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("log_format: plain | json")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            parse_log_format(v)
                .map(Some)
                .ok_or_else(|| E::custom(format!("invalid log_format value: {v:?}")))
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }

        fn visit_some<D2: Deserializer<'de>>(
            self,
            deserializer: D2,
        ) -> Result<Self::Value, D2::Error> {
            deserializer.deserialize_any(OptLogFormatVisitor)
        }
    }

    deserializer.deserialize_any(OptLogFormatVisitor)
}

/// Applies a typed TOML overlay onto `Config` (only `Some` fields).
pub fn apply_file_config(config: &mut Config, file: &FileConfig) {
    if let Some(ref path) = file.file {
        config.file.clone_from(path);
    }
    if let Some(ref path) = file.db_path {
        config.db_path.clone_from(path);
    }
    if let Some(ref path) = file.log_file {
        config.log_file = Some(path.clone());
    }
    if let Some(ref lvl) = file.log_level {
        config.log_level = lvl.clone();
    }
    if let Some(fmt) = file.log_format {
        config.log_format = fmt;
    }
    if let Some(n) = file.max_concurrency {
        config.max_concurrency = n;
    }
    if let Some(n) = file.timeout_seconds {
        config.timeout_seconds = n;
    }
    if let Some(n) = file.drain_timeout_secs {
        config.drain_timeout_secs = n;
    }
    if let Some(ref ua) = file.user_agent {
        config.user_agent.clone_from(ua);
    }
    if let Some(n) = file.rate_limit_rps {
        config.rate_limit_rps = n;
    }
    if let Some(ref fp) = file.fingerprints {
        config.fingerprints = Some(fp.clone());
    }
    if let Some(ref geo) = file.geoip {
        config.geoip = Some(geo.clone());
    }
    if let Some(n) = file.status_port {
        config.status_port = Some(n);
    }
    if let Some(b) = file.enable_whois {
        config.enable_whois = b;
    }
    if let Some(ref path) = file.cache_dir {
        config.cache_dir = Some(path.clone());
    }
    if let Some(b) = file.scan_external_scripts {
        config.scan_external_scripts = b;
    }
    if let Some(ref f) = file.fail_on {
        config.fail_on = f.clone();
    }
    if let Some(n) = file.fail_on_pct_threshold {
        config.fail_on_pct_threshold = n;
    }
}

/// Builds `Config` with precedence: CLI > env (clap) > config file > defaults.
///
/// When `cli_explicit` is `Some(keys)`, only config fields whose name is in `keys` are
/// overwritten with `cli_config`; others keep file values. When `None`, every field
/// is overwritten (backward compatible). Use `Some` so file values are preserved
/// for options the user did not set on the CLI or via env.
///
/// Call this from the CLI layer after loading [`FileConfig`] and converting
/// the scan command to `Config` via `config_from_scan_command(scan_cmd)`.
#[must_use]
pub fn merge_file_and_cli(
    file: Option<&FileConfig>,
    cli_config: Config,
    cli_explicit: Option<&[&str]>,
) -> Config {
    let overwrite = |key: &str| -> bool { cli_explicit.is_none_or(|keys| keys.contains(&key)) };

    let mut config = Config::default();
    if let Some(file) = file {
        apply_file_config(&mut config, file);
    }

    if overwrite("file") {
        config.file = cli_config.file;
    }
    if overwrite("log_level") {
        config.log_level = cli_config.log_level;
    }
    if overwrite("log_level_filter_override") {
        config.log_level_filter_override = cli_config.log_level_filter_override;
    }
    if overwrite("log_format") {
        config.log_format = cli_config.log_format;
    }
    if overwrite("db_path") {
        config.db_path = cli_config.db_path;
    }
    if overwrite("max_concurrency") {
        config.max_concurrency = cli_config.max_concurrency;
    }
    if overwrite("timeout_seconds") {
        config.timeout_seconds = cli_config.timeout_seconds;
    }
    if overwrite("user_agent") {
        config.user_agent = cli_config.user_agent;
    }
    if overwrite("rate_limit_rps") {
        config.rate_limit_rps = cli_config.rate_limit_rps;
    }
    if overwrite("fingerprints") {
        config.fingerprints = cli_config.fingerprints;
    }
    if overwrite("geoip") {
        config.geoip = cli_config.geoip;
    }
    if overwrite("status_port") {
        config.status_port = cli_config.status_port;
    }
    if overwrite("enable_whois") {
        config.enable_whois = cli_config.enable_whois;
    }
    // `--no-whois` wins over TOML enable_whois=true when set on the CLI.
    if overwrite("no_whois") {
        config.enable_whois = false;
    }
    if overwrite("cache_dir") {
        config.cache_dir = cli_config.cache_dir;
    }
    if overwrite("scan_external_scripts") {
        config.scan_external_scripts = cli_config.scan_external_scripts;
    }
    if overwrite("fail_on") {
        config.fail_on = cli_config.fail_on;
    }
    if overwrite("fail_on_pct_threshold") {
        config.fail_on_pct_threshold = cli_config.fail_on_pct_threshold;
    }
    if overwrite("log_file") {
        config.log_file = cli_config.log_file;
    }
    if overwrite("drain_timeout_secs") {
        config.drain_timeout_secs = cli_config.drain_timeout_secs;
    }

    config.progress_callback = None;
    config.dependency_overrides = None;
    config.allow_localhost_for_tests = false; // Never enable from file/CLI; tests set in code only
    config
}

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

    fn file_config_from_json(value: serde_json::Value) -> Result<FileConfig, serde_json::Error> {
        serde_json::from_value(value)
    }

    #[test]
    fn test_merge_preserves_file_when_cli_not_explicit() {
        let file = FileConfig {
            file: Some(PathBuf::from("/path/to/urls.txt")),
            log_level: Some(LogLevel::Debug),
            max_concurrency: Some(100),
            ..Default::default()
        };

        let cli_config = Config {
            file: PathBuf::from("/cli/urls.txt"),
            log_level: LogLevel::Info,
            max_concurrency: 30,
            ..Default::default()
        };

        // Explicit empty: user set nothing, so file values are preserved
        let merged = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&[]));
        assert!(
            matches!(merged.log_level, LogLevel::Debug),
            "file log_level preserved when not explicit"
        );
        assert_eq!(
            merged.max_concurrency, 100,
            "file max_concurrency preserved when not explicit"
        );

        // Only log_level explicitly set: only it is overwritten
        let merged2 = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&["log_level"]));
        assert!(
            matches!(merged2.log_level, LogLevel::Info),
            "cli log_level overwrites when explicit"
        );
        assert_eq!(
            merged2.max_concurrency, 100,
            "file max_concurrency still preserved"
        );

        // None: backward compat, all overwritten
        let merged3 = merge_file_and_cli(Some(&file), cli_config, None);
        assert!(matches!(merged3.log_level, LogLevel::Info));
        assert_eq!(merged3.max_concurrency, 30);
    }

    #[test]
    fn test_merge_applies_explicit_drain_timeout_secs() {
        let file = FileConfig {
            drain_timeout_secs: Some(45),
            ..Default::default()
        };

        let cli_config = Config {
            drain_timeout_secs: 90,
            ..Default::default()
        };

        // Not explicit: file value wins
        let merged = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&[]));
        assert_eq!(merged.drain_timeout_secs, 45);

        // Explicit CLI flag wins
        let merged2 = merge_file_and_cli(Some(&file), cli_config, Some(&["drain_timeout_secs"]));
        assert_eq!(merged2.drain_timeout_secs, 90);
    }

    #[test]
    fn test_merge_fail_on_invalid_rejected_valid_applied_cli_overrides() {
        // Invalid fail_on fails deserialization (no silent skip)
        let err = file_config_from_json(json!({"fail_on": "boom"})).unwrap_err();
        let err_s = err.to_string();
        assert!(
            err_s.contains("fail_on"),
            "invalid fail_on must name the field, got: {err_s}"
        );

        // Valid file value applied when CLI not explicit
        let valid = FileConfig {
            fail_on: Some(FailOn::PctGreaterThan),
            ..Default::default()
        };
        let merged_valid = merge_file_and_cli(
            Some(&valid),
            Config {
                fail_on: FailOn::Never,
                ..Default::default()
            },
            Some(&[]),
        );
        assert!(
            matches!(merged_valid.fail_on, FailOn::PctGreaterThan),
            "valid file fail_on=pct> must apply"
        );

        // Explicit CLI any_failure overrides file pct>
        let merged_cli = merge_file_and_cli(
            Some(&valid),
            Config {
                fail_on: FailOn::AnyFailure,
                ..Default::default()
            },
            Some(&["fail_on"]),
        );
        assert!(
            matches!(merged_cli.fail_on, FailOn::AnyFailure),
            "explicit CLI fail_on must override file"
        );

        // Invalid bool for enable_whois fails deserialization (TOML names the key)
        let bool_err = file_config_from_toml(r#"enable_whois = "maybe""#).unwrap_err();
        let bool_s = bool_err.to_string();
        assert!(
            bool_s.contains("enable_whois"),
            "invalid enable_whois must name the field, got: {bool_s}"
        );

        // CLI-style any-failure must parse from env/TOML
        let any_failure = file_config_from_json(json!({"fail_on": "any-failure"})).unwrap();
        let merged_any = merge_file_and_cli(
            Some(&any_failure),
            Config {
                fail_on: FailOn::Never,
                ..Default::default()
            },
            Some(&[]),
        );
        assert!(
            matches!(merged_any.fail_on, FailOn::AnyFailure),
            "fail_on=any-failure must apply from file"
        );
    }

    /// Kills: invalid `enable_whois` deserializing as `Ok(Some(false))` or an
    /// `Err` that does not name the field.
    #[test]
    fn test_invalid_bool_deserialize_fails_instead_of_forcing_false() {
        let err = file_config_from_toml(r#"enable_whois = "maybe""#).unwrap_err();
        let err_s = err.to_string();
        assert!(
            err_s.contains("enable_whois"),
            "invalid enable_whois must name the field, got: {err_s}"
        );
        assert!(parse_bool("maybe").is_none());
        assert!(parse_bool(" nah ").is_none());
    }

    /// Adversarial: `--no-whois` on the CLI must beat `enable_whois=true` from the config
    /// file, even though `no_whois` and `enable_whois` are different keys under the hood.
    #[test]
    fn test_no_whois_cli_flag_overrides_toml_enable_whois_true() {
        let file = FileConfig {
            enable_whois: Some(true),
            ..Default::default()
        };

        // `--no-whois` set: explicit key list includes "no_whois" (not "enable_whois").
        let merged = merge_file_and_cli(
            Some(&file),
            Config {
                enable_whois: true, // irrelevant: overwrite("enable_whois") is false here
                ..Default::default()
            },
            Some(&["no_whois"]),
        );
        assert!(
            !merged.enable_whois,
            "--no-whois must force enable_whois=false even though the TOML file says true"
        );
    }

    /// Without `--no-whois`, file `enable_whois=true` must still apply normally.
    #[test]
    fn test_enable_whois_true_from_file_applies_without_no_whois_flag() {
        let file = FileConfig {
            enable_whois: Some(true),
            ..Default::default()
        };

        let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
        assert!(
            merged.enable_whois,
            "file enable_whois=true must apply when --no-whois was not set"
        );
    }

    /// Adversarial: `scan_external_scripts` must parse permissive truthy string forms
    /// ("yes", "true", "1") from the config file / env map, not just canonical "true".
    #[test]
    fn test_scan_external_scripts_parses_permissive_truthy_strings() {
        for truthy in ["yes", "true", "1", "on", "YES", "True"] {
            let file = file_config_from_json(json!({"scan_external_scripts": truthy})).unwrap();

            let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
            assert!(
                merged.scan_external_scripts,
                "scan_external_scripts={truthy:?} must parse to true"
            );
        }

        for falsy in ["no", "false", "0", "off"] {
            let file = file_config_from_json(json!({"scan_external_scripts": falsy})).unwrap();

            let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
            assert!(
                !merged.scan_external_scripts,
                "scan_external_scripts={falsy:?} must parse to false"
            );
        }
    }

    #[test]
    fn test_fail_on_aliases_deserialize() {
        for alias in ["any-failure", "any_failure", "anyfailure", "ANY-FAILURE"] {
            let fc = file_config_from_json(json!({"fail_on": alias})).unwrap();
            assert_eq!(fc.fail_on, Some(FailOn::AnyFailure), "alias={alias}");
        }
        let pct = file_config_from_json(json!({"fail_on": "pct>"})).unwrap();
        assert_eq!(pct.fail_on, Some(FailOn::PctGreaterThan));
    }

    #[test]
    fn test_file_config_deserializes_via_config_crate_toml() {
        let settings = config::Config::builder()
            .add_source(config::File::from_str(
                r#"
                max_concurrency = 42
                enable_whois = true
                fail_on = "any-failure"
                scan_external_scripts = "yes"
                log_level = "debug"
                "#,
                config::FileFormat::Toml,
            ))
            .build()
            .expect("build");
        let fc: FileConfig = settings.try_deserialize().expect("deserialize FileConfig");
        assert_eq!(fc.max_concurrency, Some(42));
        assert_eq!(fc.enable_whois, Some(true));
        assert_eq!(fc.fail_on, Some(FailOn::AnyFailure));
        assert_eq!(fc.scan_external_scripts, Some(true));
        assert_eq!(fc.log_level, Some(LogLevel::Debug));
    }

    #[test]
    fn file_config_overlay_keys_are_unique() {
        let mut seen = std::collections::HashSet::new();
        for key in FILE_CONFIG_OVERLAY_KEYS {
            assert!(seen.insert(*key), "duplicate overlay key {key}");
        }
    }

    /// Sentinel TOML line for one overlay key. Adding a `FILE_CONFIG_OVERLAY_KEYS`
    /// entry without a sentinel (or without a Config assertion below) fails this
    /// test — not a magic `len() == N`.
    fn overlay_key_sentinel_toml(key: &str) -> String {
        let line = match key {
            "file" => r#"file = "/sentinel/urls.txt""#,
            "log_level" => r#"log_level = "debug""#,
            "log_format" => r#"log_format = "json""#,
            "db_path" => r#"db_path = "/sentinel/scan.db""#,
            "max_concurrency" => "max_concurrency = 77",
            "timeout_seconds" => "timeout_seconds = 42",
            "user_agent" => r#"user_agent = "SentinelAgent/1.0""#,
            "rate_limit_rps" => "rate_limit_rps = 3",
            "fingerprints" => r#"fingerprints = "/sentinel/fp.json""#,
            "geoip" => r#"geoip = "/sentinel/geo.mmdb""#,
            "status_port" => "status_port = 9999",
            "enable_whois" => "enable_whois = false",
            "cache_dir" => r#"cache_dir = "/sentinel/cache""#,
            "scan_external_scripts" => "scan_external_scripts = true",
            "fail_on" => r#"fail_on = "any-failure""#,
            "fail_on_pct_threshold" => "fail_on_pct_threshold = 25",
            "log_file" => r#"log_file = "/sentinel/scan.log""#,
            "drain_timeout_secs" => "drain_timeout_secs = 99",
            other => panic!(
                "overlay key {other} has no sentinel TOML; add a line here and assert Config"
            ),
        };
        line.to_string()
    }

    fn assert_overlay_sentinel_on_config(config: &Config, key: &str) {
        match key {
            "file" => assert_eq!(config.file, PathBuf::from("/sentinel/urls.txt")),
            "log_level" => assert_eq!(config.log_level, LogLevel::Debug),
            "log_format" => assert_eq!(config.log_format, LogFormat::Json),
            "db_path" => assert_eq!(config.db_path, PathBuf::from("/sentinel/scan.db")),
            "max_concurrency" => assert_eq!(config.max_concurrency, 77),
            "timeout_seconds" => assert_eq!(config.timeout_seconds, 42),
            "user_agent" => assert_eq!(config.user_agent, "SentinelAgent/1.0"),
            "rate_limit_rps" => assert_eq!(config.rate_limit_rps, 3),
            "fingerprints" => {
                assert_eq!(config.fingerprints.as_deref(), Some("/sentinel/fp.json"));
            }
            "geoip" => assert_eq!(config.geoip.as_deref(), Some("/sentinel/geo.mmdb")),
            "status_port" => assert_eq!(config.status_port, Some(9999)),
            "enable_whois" => assert!(!config.enable_whois),
            "cache_dir" => {
                assert_eq!(
                    config.cache_dir.as_deref(),
                    Some(PathBuf::from("/sentinel/cache").as_path())
                );
            }
            "scan_external_scripts" => assert!(config.scan_external_scripts),
            "fail_on" => assert_eq!(config.fail_on, FailOn::AnyFailure),
            "fail_on_pct_threshold" => assert_eq!(config.fail_on_pct_threshold, 25),
            "log_file" => {
                assert_eq!(
                    config.log_file.as_deref(),
                    Some(PathBuf::from("/sentinel/scan.log").as_path())
                );
            }
            "drain_timeout_secs" => assert_eq!(config.drain_timeout_secs, 99),
            other => panic!("overlay key {other} has no Config assertion"),
        }
    }

    #[test]
    fn file_config_overlay_toml_sentinels_land_on_config() {
        let toml = FILE_CONFIG_OVERLAY_KEYS
            .iter()
            .map(|key| overlay_key_sentinel_toml(key))
            .collect::<Vec<_>>()
            .join("\n");
        let settings = config::Config::builder()
            .add_source(config::File::from_str(&toml, config::FileFormat::Toml))
            .build()
            .expect("build overlay sentinel TOML");
        let fc: FileConfig = settings
            .try_deserialize()
            .expect("deserialize FileConfig from overlay sentinels");
        let mut config = Config::default();
        apply_file_config(&mut config, &fc);
        for key in FILE_CONFIG_OVERLAY_KEYS {
            assert_overlay_sentinel_on_config(&config, key);
        }
    }

    fn file_config_from_toml(toml: &str) -> Result<FileConfig, config::ConfigError> {
        let settings = config::Config::builder()
            .add_source(config::File::from_str(toml, config::FileFormat::Toml))
            .build()?;
        settings.try_deserialize()
    }

    /// Kills: deleting any `parse_log_level` arm (`error`/`warn`/`info`/`debug`/
    /// `trace`) or accepting an unknown token.
    #[rstest::rstest]
    #[case("error", Some(LogLevel::Error))]
    #[case("warn", Some(LogLevel::Warn))]
    #[case("info", Some(LogLevel::Info))]
    #[case("debug", Some(LogLevel::Debug))]
    #[case("trace", Some(LogLevel::Trace))]
    #[case("ERROR", Some(LogLevel::Error))]
    #[case("unknown", None)]
    #[case("", None)]
    fn test_parse_log_level_exact(#[case] raw: &str, #[case] expected: Option<LogLevel>) {
        assert_eq!(parse_log_level(raw), expected);
    }

    /// Kills: deleting the `plain` (or `json`) arm of `parse_log_format`.
    #[rstest::rstest]
    #[case("plain", Some(LogFormat::Plain))]
    #[case("json", Some(LogFormat::Json))]
    #[case("PLAIN", Some(LogFormat::Plain))]
    #[case("yaml", None)]
    #[case("", None)]
    fn test_parse_log_format_exact(#[case] raw: &str, #[case] expected: Option<LogFormat>) {
        assert_eq!(parse_log_format(raw), expected);
    }

    /// Kills: deleting the `never` arm of `parse_fail_on`, or dropping any
    /// any-failure spelling / `pct>`.
    #[rstest::rstest]
    #[case("never", Some(FailOn::Never))]
    #[case("any-failure", Some(FailOn::AnyFailure))]
    #[case("any_failure", Some(FailOn::AnyFailure))]
    #[case("anyfailure", Some(FailOn::AnyFailure))]
    #[case("pct>", Some(FailOn::PctGreaterThan))]
    #[case("NEVER", Some(FailOn::Never))]
    #[case("always", None)]
    #[case("", None)]
    fn test_parse_fail_on_exact(#[case] raw: &str, #[case] expected: Option<FailOn>) {
        assert_eq!(parse_fail_on(raw), expected);
    }

    /// Kills: `visit_u64`/`visit_i64` dropping `1`/`0`, or string/bool
    /// synonyms for `enable_whois` failing to deserialize from TOML.
    #[rstest::rstest]
    #[case("enable_whois = 1", true)]
    #[case("enable_whois = 0", false)]
    #[case(r#"enable_whois = "yes""#, true)]
    #[case(r#"enable_whois = "no""#, false)]
    #[case("enable_whois = true", true)]
    #[case("enable_whois = false", false)]
    fn test_enable_whois_toml_synonyms(#[case] toml: &str, #[case] expected: bool) {
        let fc = file_config_from_toml(toml).expect("valid enable_whois TOML");
        assert_eq!(fc.enable_whois, Some(expected), "toml={toml}");
    }

    /// Kills: `visit_u64` mapping `1` → `false` (JSON numbers take this path;
    /// TOML integers typically take `visit_i64`).
    #[test]
    fn test_enable_whois_json_integer_synonyms() {
        let one = file_config_from_json(json!({"enable_whois": 1})).expect("1");
        assert_eq!(one.enable_whois, Some(true));
        let zero = file_config_from_json(json!({"enable_whois": 0})).expect("0");
        assert_eq!(zero.enable_whois, Some(false));
    }

    /// Kills: unknown `fail_on` / `log_level` / `log_format` silently defaulting
    /// instead of `Err` that names the field.
    #[rstest::rstest]
    #[case(r#"fail_on = "boom""#, "fail_on")]
    #[case(r#"log_level = "silent""#, "log_level")]
    #[case(r#"log_format = "yaml""#, "log_format")]
    #[case(r#"enable_whois = "maybe""#, "enable_whois")]
    fn test_unknown_config_value_err_names_field(#[case] toml: &str, #[case] field: &str) {
        let err = file_config_from_toml(toml).expect_err("unknown value must fail");
        let err_s = err.to_string();
        assert!(
            err_s.contains(field),
            "reject must name {field}, got: {err_s}"
        );
    }
}