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
//! Configuration types and library config struct.
//!
//! Shared enums (`FailOn`, `LogLevel`, `LogFormat`) live in `domain_status_cli`
//! (single source for clap `ValueEnum` / completions) and are re-exported here.

use std::path::PathBuf;

use reqwest::Client;

use crate::config::constants::DEFAULT_USER_AGENT;

// Single source of truth: CLI crate (clap ValueEnum + help text).
pub use domain_status_cli::{FailOn, LogFormat, LogLevel};

/// Convert [`LogLevel`] to [`log::LevelFilter`].
///
/// Kept as a free function (not `From`) because both types are foreign to this crate
/// after re-exporting `LogLevel` from `domain_status_cli`.
#[must_use]
pub fn log_level_filter(level: &LogLevel) -> log::LevelFilter {
    match level {
        LogLevel::Error => log::LevelFilter::Error,
        LogLevel::Warn => log::LevelFilter::Warn,
        LogLevel::Info => log::LevelFilter::Info,
        LogLevel::Debug => log::LevelFilter::Debug,
        LogLevel::Trace => log::LevelFilter::Trace,
    }
}

/// Optional dependency overrides for tests or custom environments.
///
/// When set on [`Config`], these values are used instead of creating new
/// instances during scan resource initialization. This allows tests to inject
/// mock HTTP clients, resolvers, or other dependencies without starting real
/// servers or touching global state.
///
/// # Example (tests)
///
/// ```ignore
/// let config = Config {
///     dependency_overrides: Some(ScanDependencyOverrides {
///         http_client: Some(my_mock_client),
///     }),
///     ..Default::default()
/// };
/// let report = run_scan(config).await?;
/// ```
#[derive(Clone, Debug, Default)]
pub struct ScanDependencyOverrides {
    /// If set, this client is used instead of creating one from config (e.g. a mock in tests).
    pub http_client: Option<Client>,
}

/// Configuration validation error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigValidationError {
    /// The field that failed validation
    pub field: String,
    /// Description of the validation failure
    pub message: String,
}

impl std::fmt::Display for ConfigValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Invalid config '{}': {}", self.field, self.message)
    }
}

impl std::error::Error for ConfigValidationError {}

/// Library configuration for [`crate::run_scan`].
///
/// Construct programmatically; shared enums are re-exported from `domain_status_cli`.
///
/// # Examples
///
/// ```no_run
/// use domain_status::Config;
/// use std::path::PathBuf;
///
/// let config = Config {
///     file: PathBuf::from("urls.txt"),
///     max_concurrency: 50,
///     rate_limit_rps: 20,
///     ..Default::default()
/// };
/// ```
#[derive(Clone)]
pub struct Config {
    /// File to read URLs from
    pub file: PathBuf,

    /// Log level
    pub log_level: LogLevel,

    /// When set (e.g. from CLI `-v` / `-vv`), overrides `log_level` for the actual filter. Used by CLI verbosity flag.
    #[doc(hidden)]
    pub log_level_filter_override: Option<log::LevelFilter>,

    /// Log format
    pub log_format: LogFormat,

    /// Database path (`SQLite` file)
    pub db_path: PathBuf,

    /// Maximum concurrent requests
    pub max_concurrency: usize,

    /// Per-request HTTP timeout in seconds (default: 10).
    ///
    /// This is the timeout for each individual HTTP request. The overall
    /// per-URL processing timeout (`URL_PROCESSING_TIMEOUT`, 35s) is separate
    /// and encompasses all stages (DNS, TLS, HTTP, enrichment).
    pub timeout_seconds: u64,

    /// HTTP User-Agent header value
    pub user_agent: String,

    /// URL admission tokens per second (`0` disables). Redirects, favicon, scripts,
    /// TLS, and WHOIS share that token. If you see 429s, lower this and re-run.
    pub rate_limit_rps: u32,

    /// Fingerprints source URL or local path
    pub fingerprints: Option<String>,

    /// `GeoIP` database path or download URL
    pub geoip: Option<String>,

    /// HTTP status server port (optional, disabled by default)
    pub status_port: Option<u16>,

    /// Enable WHOIS/RDAP lookup for domain registration information
    pub enable_whois: bool,

    /// Shared cache root for fingerprints / `GeoIP` / WHOIS / User-Agent.
    ///
    /// When `None`, resolves via `DOMAIN_STATUS_CACHE_DIR` or the platform cache
    /// directory (`dirs::cache_dir`) plus `domain_status/` (Linux `~/.cache/…`,
    /// macOS `~/Library/Caches/…`, Windows `%LOCALAPPDATA%\…`). The `SQLite` DB
    /// and log file are separate outputs (`db_path` / `log_file`).
    pub cache_dir: Option<PathBuf>,

    /// Fetch first-party `<script src>` bodies for secret detection and static
    /// `scripts` technology patterns. Off by default. When enabled, fetches are
    /// SSRF-validated, size/timeout capped, and limited to 10 scripts per page.
    pub scan_external_scripts: bool,

    /// Exit code policy for handling failures
    pub fail_on: FailOn,

    /// Failure percentage threshold (used with `fail_on: FailOn::PctGreaterThan`)
    ///
    /// A number between 0 and 100. If failure percentage exceeds this value,
    /// exit with code 2. Only used when `fail_on` is `PctGreaterThan`.
    pub fail_on_pct_threshold: u8,

    /// Log file path for detailed logging (always used in CLI)
    pub log_file: Option<PathBuf>,

    /// Progress callback for external progress tracking.
    ///
    /// Called with (completed, failed, skipped, total) after each URL is processed.
    /// This allows external code (like CLI) to update progress bars.
    ///
    /// **Important**: The callback is invoked synchronously from async tasks.
    /// Keep callback execution fast (microseconds) to avoid blocking URL processing.
    /// For slow operations, spawn a separate task inside the callback.
    ///
    /// **Thread Safety**: The callback may be invoked concurrently from multiple
    /// tokio tasks. If the callback maintains state, use `Arc<Mutex<_>>` or atomic
    /// operations. The `completed` and `failed` counters are already `Arc<AtomicUsize>`,
    /// so they can be safely read from multiple threads.
    #[doc(hidden)]
    #[allow(clippy::type_complexity)]
    // Type alias would obscure the callback signature at its only usage site
    pub progress_callback: Option<std::sync::Arc<dyn Fn(usize, usize, usize, usize) + Send + Sync>>,

    /// Optional dependency overrides for tests (inject mock HTTP client, etc.).
    ///
    /// When set, scan resource initialization uses these instead of creating new
    /// instances. Production callers should leave this `None`.
    #[doc(hidden)]
    pub dependency_overrides: Option<ScanDependencyOverrides>,

    /// If true, skip SSRF validation for initial URLs (localhost/private IPs allowed).
    ///
    /// **For integration tests only.** Set to `true` when scanning mock servers bound to
    /// 127.0.0.1 or ::1. Must not be set in production.
    #[doc(hidden)]
    pub allow_localhost_for_tests: bool,

    /// Maximum time (seconds) to wait for in-flight tasks to drain after the input
    /// queue is exhausted (or after a Ctrl-C). Tasks that haven't completed within
    /// this window are aborted. Each abandoned URL is recorded as a `url_failures`
    /// row with `error_type = ProcessUrlTimeout` so users can see which URLs were
    /// lost.
    ///
    /// Default: 10 seconds. Lower this in tests to deterministically force the
    /// drain-timeout path; raise it for production scans with very slow upstream
    /// services (e.g. WHOIS-heavy workloads on small batches).
    pub drain_timeout_secs: u64,

    /// Allow a scan to start on the vendored / partial fingerprint catalog.
    /// Default scans abort when the Enthec + `HTTPArchive` merge is incomplete.
    pub allow_degraded_fingerprints: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            file: PathBuf::from("urls.txt"),
            log_level: LogLevel::Info,
            log_level_filter_override: None,
            log_format: LogFormat::Plain,
            db_path: PathBuf::from("./domain_status.db"),
            max_concurrency: 30,
            timeout_seconds: 10,
            user_agent: DEFAULT_USER_AGENT.to_string(),
            rate_limit_rps: 15,
            fingerprints: None,
            geoip: None,
            status_port: None,
            enable_whois: true,
            cache_dir: None,
            scan_external_scripts: false,
            fail_on: FailOn::Never,
            fail_on_pct_threshold: 10,
            log_file: None,
            progress_callback: None,
            dependency_overrides: None,
            allow_localhost_for_tests: false,
            drain_timeout_secs: 10,
            allow_degraded_fingerprints: false,
        }
    }
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("file", &self.file)
            .field("log_level", &self.log_level)
            .field("log_level_filter_override", &self.log_level_filter_override)
            .field("log_format", &self.log_format)
            .field("db_path", &self.db_path)
            .field("max_concurrency", &self.max_concurrency)
            .field("timeout_seconds", &self.timeout_seconds)
            .field("user_agent", &self.user_agent)
            .field("rate_limit_rps", &self.rate_limit_rps)
            .field("fingerprints", &self.fingerprints)
            .field("geoip", &self.geoip)
            .field("status_port", &self.status_port)
            .field("enable_whois", &self.enable_whois)
            .field("cache_dir", &self.cache_dir)
            .field("scan_external_scripts", &self.scan_external_scripts)
            .field("fail_on", &self.fail_on)
            .field("fail_on_pct_threshold", &self.fail_on_pct_threshold)
            .field("log_file", &self.log_file)
            .field(
                "progress_callback",
                &self.progress_callback.as_ref().map(|_| "<callback>"),
            )
            .field(
                "dependency_overrides",
                &self.dependency_overrides.as_ref().map(|_| "<overrides>"),
            )
            .field("allow_localhost_for_tests", &self.allow_localhost_for_tests)
            .field("drain_timeout_secs", &self.drain_timeout_secs)
            .field(
                "allow_degraded_fingerprints",
                &self.allow_degraded_fingerprints,
            )
            .finish()
    }
}

impl Config {
    /// Maximum allowed concurrency to prevent resource exhaustion.
    pub const MAX_CONCURRENCY: usize = 500;

    /// Maximum allowed URL-admission rate (tokens per second).
    pub const MAX_RATE_LIMIT_RPS: u32 = 100;

    /// Validates the configuration and returns any validation errors.
    ///
    /// # Returns
    ///
    /// `Ok(())` if configuration is valid, or `Err(ConfigValidationError)` with
    /// details about the first validation failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain_status::Config;
    ///
    /// let mut config = Config::default();
    /// assert!(config.validate().is_ok());
    ///
    /// config.max_concurrency = 0;
    /// assert!(config.validate().is_err());
    /// ```
    ///
    /// # Errors
    /// Returns `Err` when a validation rule is violated (e.g. `max_concurrency` out of range).
    pub fn validate(&self) -> Result<(), ConfigValidationError> {
        // Validate max_concurrency
        if self.max_concurrency == 0 {
            return Err(ConfigValidationError {
                field: "max_concurrency".to_string(),
                message: "must be greater than 0".to_string(),
            });
        }
        if self.max_concurrency > Self::MAX_CONCURRENCY {
            return Err(ConfigValidationError {
                field: "max_concurrency".to_string(),
                message: format!(
                    "must be <= {} to prevent resource exhaustion",
                    Self::MAX_CONCURRENCY
                ),
            });
        }

        // Validate rate_limit_rps (0 means disabled, which is valid)
        if self.rate_limit_rps > Self::MAX_RATE_LIMIT_RPS {
            return Err(ConfigValidationError {
                field: "rate_limit_rps".to_string(),
                message: format!(
                    "must be <= {} to prevent overwhelming targets",
                    Self::MAX_RATE_LIMIT_RPS
                ),
            });
        }

        // Validate timeout_seconds
        if self.timeout_seconds == 0 {
            return Err(ConfigValidationError {
                field: "timeout_seconds".to_string(),
                message: "must be greater than 0".to_string(),
            });
        }

        // Validate fail_on_pct_threshold
        if self.fail_on_pct_threshold > 100 {
            return Err(ConfigValidationError {
                field: "fail_on_pct_threshold".to_string(),
                message: "must be between 0 and 100".to_string(),
            });
        }

        // Validate user_agent is not empty
        if self.user_agent.trim().is_empty() {
            return Err(ConfigValidationError {
                field: "user_agent".to_string(),
                message: "cannot be empty".to_string(),
            });
        }

        Ok(())
    }
}

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

    #[test]
    fn test_log_level_conversion() {
        // Test all LogLevel variants convert correctly to log::LevelFilter
        assert_eq!(
            crate::config::log_level_filter(&LogLevel::Error),
            log::LevelFilter::Error
        );
        assert_eq!(
            crate::config::log_level_filter(&LogLevel::Warn),
            log::LevelFilter::Warn
        );
        assert_eq!(
            crate::config::log_level_filter(&LogLevel::Info),
            log::LevelFilter::Info
        );
        assert_eq!(
            crate::config::log_level_filter(&LogLevel::Debug),
            log::LevelFilter::Debug
        );
        assert_eq!(
            crate::config::log_level_filter(&LogLevel::Trace),
            log::LevelFilter::Trace
        );
    }

    #[test]
    fn test_log_level_ordering() {
        // Verify that log levels are ordered correctly (Error < Warn < Info < Debug < Trace)
        let error = crate::config::log_level_filter(&LogLevel::Error);
        let warn = crate::config::log_level_filter(&LogLevel::Warn);
        let info = crate::config::log_level_filter(&LogLevel::Info);
        let debug = crate::config::log_level_filter(&LogLevel::Debug);
        let trace = crate::config::log_level_filter(&LogLevel::Trace);

        // Each level should be more restrictive than the next
        assert!(error < warn);
        assert!(warn < info);
        assert!(info < debug);
        assert!(debug < trace);
    }

    #[test]
    fn test_config_default_values() {
        // Test that Config::default() provides sensible defaults
        // This is critical - incorrect defaults could break production usage
        let config = Config::default();

        // Verify critical defaults
        assert_eq!(config.max_concurrency, 30);
        assert_eq!(config.timeout_seconds, 10);
        assert_eq!(config.rate_limit_rps, 15);
        assert_eq!(config.fail_on, FailOn::Never);
        assert_eq!(config.fail_on_pct_threshold, 10);
        assert!(config.enable_whois);
        assert!(config.fingerprints.is_none());
        assert!(config.geoip.is_none());
        assert!(config.status_port.is_none());
    }

    #[test]
    fn test_config_default_paths() {
        // Test that default paths are correct
        let config = Config::default();
        assert_eq!(config.file, PathBuf::from("urls.txt"));
        assert_eq!(config.db_path, PathBuf::from("./domain_status.db"));
    }

    #[test]
    fn test_config_default_user_agent() {
        // Test that default user agent is set correctly
        // The default mimics a real browser to avoid bot detection
        let config = Config::default();
        assert!(!config.user_agent.is_empty());
        assert!(config.user_agent.contains("Mozilla"));
    }

    #[test]
    fn test_fail_on_variants() {
        // Test that all FailOn variants are distinct
        assert_ne!(FailOn::Never, FailOn::AnyFailure);
        assert_ne!(FailOn::AnyFailure, FailOn::PctGreaterThan);
        assert_ne!(FailOn::PctGreaterThan, FailOn::Never);
    }

    // Config validation tests

    #[test]
    fn test_config_validate_default_is_valid() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validate_max_concurrency_zero() {
        let config = Config {
            max_concurrency: 0,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "max_concurrency");
        assert!(err.message.contains("greater than 0"));
    }

    #[test]
    fn test_config_validate_max_concurrency_too_high() {
        let config = Config {
            max_concurrency: Config::MAX_CONCURRENCY + 1,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "max_concurrency");
        assert!(err.message.contains("resource exhaustion"));
    }

    #[test]
    fn test_config_validate_max_concurrency_at_limit() {
        let config = Config {
            max_concurrency: Config::MAX_CONCURRENCY,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validate_rate_limit_zero_is_valid() {
        // 0 means "disabled" which is valid for tests and special use cases
        let config = Config {
            rate_limit_rps: 0,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validate_rate_limit_too_high() {
        let config = Config {
            rate_limit_rps: Config::MAX_RATE_LIMIT_RPS + 1,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "rate_limit_rps");
        assert!(err.message.contains("overwhelming"));
    }

    #[test]
    fn test_config_validate_rate_limit_at_limit() {
        let config = Config {
            rate_limit_rps: Config::MAX_RATE_LIMIT_RPS,
            ..Default::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_validate_timeout_zero() {
        let config = Config {
            timeout_seconds: 0,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "timeout_seconds");
        assert!(err.message.contains("greater than 0"));
    }

    #[test]
    fn test_config_validate_fail_on_pct_threshold_over_100() {
        let config = Config {
            fail_on_pct_threshold: 101,
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "fail_on_pct_threshold");
        assert!(err.message.contains("between 0 and 100"));
    }

    #[test]
    fn test_config_validate_fail_on_pct_threshold_boundary() {
        // 0 and 100 should be valid
        let config_zero = Config {
            fail_on_pct_threshold: 0,
            ..Default::default()
        };
        assert!(config_zero.validate().is_ok());

        let config_hundred = Config {
            fail_on_pct_threshold: 100,
            ..Default::default()
        };
        assert!(config_hundred.validate().is_ok());
    }

    #[test]
    fn test_config_validate_empty_user_agent() {
        let config = Config {
            user_agent: "".to_string(),
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "user_agent");
        assert!(err.message.contains("empty"));
    }

    #[test]
    fn test_config_validate_whitespace_user_agent() {
        let config = Config {
            user_agent: "   ".to_string(),
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        assert_eq!(err.field, "user_agent");
    }

    #[test]
    fn test_config_validation_error_display() {
        let err = ConfigValidationError {
            field: "test_field".to_string(),
            message: "test message".to_string(),
        };
        let display = format!("{}", err);
        assert!(display.contains("test_field"));
        assert!(display.contains("test message"));
    }

    /// Kills: `ConfigValidationError` Display dropping the field name or
    /// message (e.g. formatting only one of the two).
    #[test]
    fn test_config_validation_error_error_trait() {
        let err = ConfigValidationError {
            field: "test_field".to_string(),
            message: "test message".to_string(),
        };
        let error_ref: &dyn std::error::Error = &err;
        assert_eq!(
            error_ref.to_string(),
            "Invalid config 'test_field': test message"
        );
    }

    /// Kills: `Config` Debug rendering an unset `progress_callback` as
    /// `"<callback>"` instead of `None`.
    #[test]
    fn test_config_debug_formatting() {
        let config = Config {
            max_concurrency: 50,
            rate_limit_rps: 25,
            enable_whois: true,
            cache_dir: None,
            status_port: Some(8080),
            ..Default::default()
        };
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("Config"));
        assert!(debug_str.contains("max_concurrency"));
        assert!(debug_str.contains("50"));
        assert!(
            debug_str.contains("progress_callback: None"),
            "unset callback must debug as None, got: {debug_str}"
        );
        assert!(
            !debug_str.contains("<callback>"),
            "unset callback must not render as <callback>, got: {debug_str}"
        );
    }

    /// Kills: `Config` Debug exposing a function pointer (`0x…`) instead of
    /// `"<callback>"` when `progress_callback` is set.
    #[test]
    fn test_config_debug_with_callback() {
        use std::sync::Arc;
        let callback =
            Arc::new(|_completed: usize, _failed: usize, _skipped: usize, _total: usize| {});
        let config = Config {
            progress_callback: Some(callback),
            ..Default::default()
        };
        let debug_str = format!("{:?}", config);
        assert!(
            debug_str.contains("<callback>"),
            "set callback must render as <callback>, got: {debug_str}"
        );
        assert!(
            !debug_str.contains("0x"),
            "set callback must not expose a function pointer, got: {debug_str}"
        );
    }

    #[test]
    fn test_config_validate_all_fields_valid() {
        // Test validation with all fields at valid boundary values
        let config = Config {
            max_concurrency: Config::MAX_CONCURRENCY,
            rate_limit_rps: Config::MAX_RATE_LIMIT_RPS,
            timeout_seconds: 1,
            fail_on_pct_threshold: 100,
            user_agent: "Valid User Agent".to_string(),
            ..Default::default()
        };
        assert!(
            config.validate().is_ok(),
            "All valid boundary values should pass"
        );
    }

    #[test]
    fn test_config_validate_multiple_errors_first_one_returned() {
        // Test that validation returns the first error encountered
        // This is important - validation order matters for error messages
        let config = Config {
            max_concurrency: 0,         // First validation check
            timeout_seconds: 0,         // Would be second, but first error is returned
            user_agent: "".to_string(), // Would be third, but first error is returned
            ..Default::default()
        };
        let err = config.validate().unwrap_err();
        // Should return max_concurrency error (first check)
        assert_eq!(err.field, "max_concurrency");
    }

    // Property-based tests using proptest
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn test_config_validation_concurrency(n in 1u32..=500) {
            let config = Config {
                max_concurrency: n as usize,
                ..Default::default()
            };
            prop_assert!(config.validate().is_ok(),
                "Concurrency 1-500 should be valid");
        }

        #[test]
        fn test_config_validation_concurrency_invalid(n in 501u32..1000) {
            let config = Config {
                max_concurrency: n as usize,
                ..Default::default()
            };
            prop_assert!(config.validate().is_err(),
                "Concurrency > 500 should be invalid");
        }

        #[test]
        fn test_config_validation_rate_limit(n in 0u32..=100) {
            let config = Config {
                rate_limit_rps: n,
                ..Default::default()
            };
            prop_assert!(config.validate().is_ok(),
                "Rate limit 0-100 should be valid");
        }

        #[test]
        fn test_config_validation_rate_limit_invalid(n in 101u32..1000) {
            let config = Config {
                rate_limit_rps: n,
                ..Default::default()
            };
            prop_assert!(config.validate().is_err(),
                "Rate limit > 100 should be invalid");
        }

        #[test]
        fn test_config_validation_fail_on_pct(pct in 0u8..=100) {
            let config = Config {
                fail_on_pct_threshold: pct,
                ..Default::default()
            };
            prop_assert!(config.validate().is_ok(),
                "Fail on pct 0-100 should be valid");
        }

        #[test]
        fn test_config_validation_fail_on_pct_invalid(pct in 101u8..=255) {
            let config = Config {
                fail_on_pct_threshold: pct,
                ..Default::default()
            };
            prop_assert!(config.validate().is_err(),
                "Fail on pct > 100 should be invalid");
        }

        #[test]
        fn test_config_validation_timeout(timeout in 1u64..3600) {
            let config = Config {
                timeout_seconds: timeout,
                ..Default::default()
            };
            prop_assert!(config.validate().is_ok(),
                "Timeout >= 1 should be valid");
        }

        #[test]
        fn test_config_validation_user_agent_nonempty(agent in "[a-zA-Z0-9]+( [a-zA-Z0-9]+){0,10}") {
            let config = Config {
                user_agent: agent.clone(),
                ..Default::default()
            };
            // Ensure the agent is not just whitespace after trimming
            if !agent.trim().is_empty() {
                prop_assert!(config.validate().is_ok(),
                    "Non-empty user agent should be valid");
            }
        }
    }
}