crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 配置服务模块
//!
//! 提供统一的配置访问接口,封装环境变量读取。
//! 支持通过 DI 注入,便于测试时模拟不同配置。

use async_trait::async_trait;
use std::time::Duration;

/// 配置服务 trait
///
/// 统一管理所有环境变量配置,支持测试时注入 mock 实现。
#[async_trait]
pub trait ConfigServiceTrait: Send + Sync {
    /// 获取代理 URL
    fn get_proxy_url(&self) -> Option<String>;

    /// 获取远程调试 URL(Chrome)
    fn get_remote_debugging_url(&self) -> Option<String>;

    /// 是否处于测试模式(禁用浏览器复用)
    fn is_test_mode(&self) -> bool;

    /// 获取默认 HTTP 超时时间
    fn get_default_timeout(&self) -> Duration;

    /// 获取浏览器连接超时时间
    fn get_browser_timeout(&self) -> Duration;

    /// 获取浏览器启动超时时间
    fn get_browser_launch_timeout(&self) -> Duration;

    /// 获取应用环境(development/staging/production)
    fn get_app_environment(&self) -> String;

    /// 是否处于生产环境
    fn is_production(&self) -> bool;

    /// 是否处于开发环境
    fn is_development(&self) -> bool;

    /// 获取 Webhook Secret
    fn get_webhook_secret(&self) -> String;

    /// 获取健康检查 URL
    fn get_health_check_url(&self) -> Option<String>;

    /// 是否禁用 SSRF 保护
    fn is_ssrf_protection_disabled(&self) -> bool;

    /// 是否启用网络测试
    fn is_network_tests_enabled(&self) -> bool;

    /// 是否启用调试 HTML 保存
    fn is_debug_save_html_enabled(&self) -> bool;

    /// 获取 FlareSolverr URL
    fn get_flaresolverr_url(&self) -> Option<String>;
}

/// 浏览器配置 trait
///
/// 专门用于浏览器相关的配置。
pub trait BrowserConfigTrait: Send + Sync {
    /// 获取代理 URL
    fn get_proxy_url(&self) -> Option<String>;

    /// 获取远程调试 URL
    fn get_remote_debugging_url(&self) -> Option<String>;

    /// 是否测试模式
    fn is_test_mode(&self) -> bool;
}

/// 浏览器配置组件
///
/// 通过 DI 注入的浏览器配置实现。
pub struct BrowserConfigComponent {
    /// 代理 URL(优先使用环境变量)
    proxy_url: Option<String>,
    /// 远程调试 URL
    remote_debugging_url: Option<String>,
    /// 测试模式标志
    test_mode: bool,
}

impl BrowserConfigComponent {
    pub fn new() -> Self {
        Self {
            proxy_url: std::env::var("CRAWLRS_PROXY_URL")
                .ok()
                .filter(|url| !url.is_empty()),
            remote_debugging_url: std::env::var("CHROMIUM_REMOTE_DEBUGGING_URL")
                .ok()
                .filter(|url| !url.is_empty()),
            test_mode: std::env::var("CRAWLRS_TEST_NO_BROWSER_REUSE").is_ok(),
        }
    }
}

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

impl BrowserConfigTrait for BrowserConfigComponent {
    fn get_proxy_url(&self) -> Option<String> {
        self.proxy_url.clone()
    }

    fn get_remote_debugging_url(&self) -> Option<String> {
        self.remote_debugging_url.clone()
    }

    fn is_test_mode(&self) -> bool {
        self.test_mode
    }
}

/// 配置服务组件
///
/// 从 Settings 中读取配置,支持环境变量覆盖。
pub struct ConfigServiceComponent {
    /// 代理 URL
    proxy_url: Option<String>,
    /// 远程调试 URL
    remote_debugging_url: Option<String>,
    /// 测试模式标志
    test_mode: bool,
    /// 默认超时(秒)
    default_timeout: u64,
    /// 浏览器超时(秒)
    browser_timeout: u64,
    /// 浏览器启动超时(秒)
    browser_launch_timeout: u64,
    /// 应用环境
    app_environment: String,
    /// Webhook Secret
    webhook_secret: String,
    /// 健康检查 URL
    health_check_url: Option<String>,
    /// 是否禁用 SSRF 保护
    ssrf_protection_disabled: bool,
    /// 是否启用网络测试
    network_tests_enabled: bool,
    /// 是否启用调试 HTML 保存
    debug_save_html_enabled: bool,
    /// FlareSolverr URL
    flaresolverr_url: Option<String>,
}

/// 解析 webhook 签名密钥(CWE-798 / CWE-326:禁止硬编码弱默认)。
///
/// - `WEBHOOK_SECRET` 已设置且非空 → 直接使用;
/// - 未设置且为生产环境 → 返回空串并 `error!`;真正的启动拦截由
///   `bootstrap::config::config_validator` 基于 `settings.webhook.secret`
///   的 fail-fast 校验完成,服务不会带着空密钥上线;
/// - 未设置且为非生产环境 → 生成 32 字节随机十六进制密钥并 `warn!`
///   (进程内临时密钥,重启后失效,仅用于本地开发)。
fn resolve_webhook_secret(app_environment: &str) -> String {
    if let Some(secret) = std::env::var("WEBHOOK_SECRET")
        .ok()
        .filter(|s| !s.is_empty())
    {
        return secret;
    }
    let env_lower = app_environment.to_lowercase();
    if env_lower == "production" || env_lower == "prod" {
        log::error!(
            "WEBHOOK_SECRET is not set in production: startup will be rejected by \
             webhook secret validation (hardcoded weak default has been removed)"
        );
        String::new()
    } else {
        let bytes: [u8; 32] = rand::random();
        log::warn!(
            "WEBHOOK_SECRET is not set: generated an ephemeral random webhook secret \
             for this process only; signatures cannot be verified across restarts"
        );
        hex::encode(bytes)
    }
}

impl ConfigServiceComponent {
    /// 从 Settings 创建配置服务
    pub fn from_settings(
        proxy_enabled: bool,
        proxy_url: &str,
        default_timeout: u64,
        browser_timeout: u64,
    ) -> Self {
        // 环境变量优先于配置文件
        let proxy_url = std::env::var("CRAWLRS_PROXY_URL")
            .ok()
            .filter(|url| !url.is_empty())
            .or_else(|| {
                if proxy_enabled {
                    Some(proxy_url.to_string())
                } else {
                    None
                }
            });
        let app_environment = std::env::var("CRAWLRS_ENV")
            .or_else(|_| std::env::var("APP_ENVIRONMENT"))
            .unwrap_or_else(|_| "development".to_string());

        Self {
            proxy_url,
            remote_debugging_url: std::env::var("CHROMIUM_REMOTE_DEBUGGING_URL")
                .ok()
                .filter(|url| !url.is_empty()),
            test_mode: std::env::var("CRAWLRS_TEST_NO_BROWSER_REUSE").is_ok(),
            default_timeout,
            browser_timeout,
            browser_launch_timeout: 30,
            app_environment: app_environment.clone(),
            webhook_secret: resolve_webhook_secret(&app_environment),
            health_check_url: std::env::var("CRAWLRS_HEALTH_CHECK_URL").ok(),
            ssrf_protection_disabled: std::env::var("CRAWLRS_DISABLE_SSRF_PROTECTION").is_ok(),
            network_tests_enabled: std::env::var("CRAWLRS_ENABLE_NETWORK_TESTS").is_ok(),
            debug_save_html_enabled: std::env::var("DEBUG_SAVE_HTML").is_ok(),
            flaresolverr_url: std::env::var("CRAWLRS_FLARESOLVERR_URL")
                .ok()
                .filter(|url| !url.is_empty()),
        }
    }
}

impl ConfigServiceTrait for ConfigServiceComponent {
    fn get_proxy_url(&self) -> Option<String> {
        self.proxy_url.clone()
    }

    fn get_remote_debugging_url(&self) -> Option<String> {
        self.remote_debugging_url.clone()
    }

    fn is_test_mode(&self) -> bool {
        self.test_mode
    }

    fn get_default_timeout(&self) -> Duration {
        Duration::from_secs(self.default_timeout)
    }

    fn get_browser_timeout(&self) -> Duration {
        Duration::from_secs(self.browser_timeout)
    }

    fn get_browser_launch_timeout(&self) -> Duration {
        Duration::from_secs(self.browser_launch_timeout)
    }

    fn get_app_environment(&self) -> String {
        self.app_environment.clone()
    }

    fn is_production(&self) -> bool {
        self.app_environment == "production"
    }

    fn is_development(&self) -> bool {
        self.app_environment == "development"
    }

    fn get_webhook_secret(&self) -> String {
        self.webhook_secret.clone()
    }

    fn get_health_check_url(&self) -> Option<String> {
        self.health_check_url.clone()
    }

    fn is_ssrf_protection_disabled(&self) -> bool {
        self.ssrf_protection_disabled
    }

    fn is_network_tests_enabled(&self) -> bool {
        self.network_tests_enabled
    }

    fn is_debug_save_html_enabled(&self) -> bool {
        self.debug_save_html_enabled
    }

    fn get_flaresolverr_url(&self) -> Option<String> {
        self.flaresolverr_url.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::test_support::ENV_MUTEX;

    #[test]
    fn test_config_service_proxy_url_from_env() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        // 设置环境变量
        std::env::set_var("CRAWLRS_PROXY_URL", "http://test.proxy:8080");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(
            config.get_proxy_url(),
            Some("http://test.proxy:8080".to_string())
        );

        // 清理
        std::env::remove_var("CRAWLRS_PROXY_URL");
    }

    #[test]
    fn test_config_service_proxy_from_settings() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_PROXY_URL");

        let config =
            ConfigServiceComponent::from_settings(true, "http://settings.proxy:8080", 30, 30);
        assert_eq!(
            config.get_proxy_url(),
            Some("http://settings.proxy:8080".to_string())
        );
    }

    #[test]
    fn test_config_service_test_mode() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_TEST_NO_BROWSER_REUSE", "1");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(config.is_test_mode());

        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");
    }

    #[test]
    fn test_browser_config_component() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "localhost:9222");
        std::env::set_var("CRAWLRS_PROXY_URL", "http://localhost:1080");

        let config = BrowserConfigComponent::new();
        assert_eq!(
            config.get_remote_debugging_url(),
            Some("localhost:9222".to_string())
        );
        assert_eq!(
            config.get_proxy_url(),
            Some("http://localhost:1080".to_string())
        );

        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
        std::env::remove_var("CRAWLRS_PROXY_URL");
    }

    #[test]
    fn test_browser_config_component_default_impl() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_PROXY_URL");
        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");

        let config = BrowserConfigComponent::default();
        assert_eq!(config.get_proxy_url(), None);
        assert_eq!(config.get_remote_debugging_url(), None);
        assert!(!config.is_test_mode());
    }

    #[test]
    fn test_browser_config_component_empty_env_vars_filtered() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_PROXY_URL", "");
        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "");

        let config = BrowserConfigComponent::new();
        assert_eq!(config.get_proxy_url(), None);
        assert_eq!(config.get_remote_debugging_url(), None);

        std::env::remove_var("CRAWLRS_PROXY_URL");
        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
    }

    #[test]
    fn test_browser_config_component_test_mode() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_TEST_NO_BROWSER_REUSE", "1");

        let config = BrowserConfigComponent::new();
        assert!(config.is_test_mode());

        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");
    }

    #[test]
    fn test_config_service_proxy_disabled_no_env() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_PROXY_URL");

        let config =
            ConfigServiceComponent::from_settings(false, "http://ignored.proxy:8080", 30, 30);
        assert_eq!(config.get_proxy_url(), None);
    }

    #[test]
    fn test_config_service_default_timeout_values() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_PROXY_URL");

        let config = ConfigServiceComponent::from_settings(false, "", 45, 60);
        assert_eq!(config.get_default_timeout(), Duration::from_secs(45));
        assert_eq!(config.get_browser_timeout(), Duration::from_secs(60));
        assert_eq!(config.get_browser_launch_timeout(), Duration::from_secs(30));
    }

    #[test]
    fn test_config_service_app_environment_default() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "development");
        assert!(config.is_development());
        assert!(!config.is_production());
    }

    #[test]
    fn test_config_service_app_environment_from_crawlrs_env() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_ENV", "production");
        std::env::remove_var("APP_ENVIRONMENT");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "production");
        assert!(config.is_production());
        assert!(!config.is_development());

        std::env::remove_var("CRAWLRS_ENV");
    }

    #[test]
    fn test_config_service_app_environment_from_app_env_fallback() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::set_var("APP_ENVIRONMENT", "staging");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "staging");
        assert!(!config.is_development());
        assert!(!config.is_production());

        std::env::remove_var("APP_ENVIRONMENT");
    }

    #[test]
    fn test_config_service_webhook_secret_random_in_dev() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("WEBHOOK_SECRET");
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        let secret = config.get_webhook_secret();
        // 弱默认已移除:非生产环境自动生成 64 位十六进制随机密钥,且两次生成不同
        assert_eq!(secret.len(), 64);
        assert!(secret.chars().all(|c| c.is_ascii_hexdigit()));
        assert_ne!(secret, "default-webhook-secret");
        let config2 = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_ne!(config2.get_webhook_secret(), secret);
    }

    #[test]
    fn test_config_service_webhook_secret_empty_in_production() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("WEBHOOK_SECRET");
        std::env::set_var("CRAWLRS_ENV", "production");

        // 生产环境未设置:组件返回空串(真正的启动拦截在 config_validator 的
        // fail-fast 校验),绝不回退硬编码默认值
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_webhook_secret(), "");

        std::env::remove_var("CRAWLRS_ENV");
    }

    #[test]
    fn test_config_service_webhook_secret_from_env() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("WEBHOOK_SECRET", "my-secret-key");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_webhook_secret(), "my-secret-key");

        std::env::remove_var("WEBHOOK_SECRET");
    }

    #[test]
    fn test_config_service_health_check_url() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_HEALTH_CHECK_URL");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_health_check_url(), None);

        std::env::set_var("CRAWLRS_HEALTH_CHECK_URL", "http://health:8080/check");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(
            config.get_health_check_url(),
            Some("http://health:8080/check".to_string())
        );

        std::env::remove_var("CRAWLRS_HEALTH_CHECK_URL");
    }

    #[test]
    fn test_config_service_ssrf_protection_disabled() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_DISABLE_SSRF_PROTECTION");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(!config.is_ssrf_protection_disabled());

        std::env::set_var("CRAWLRS_DISABLE_SSRF_PROTECTION", "1");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(config.is_ssrf_protection_disabled());

        std::env::remove_var("CRAWLRS_DISABLE_SSRF_PROTECTION");
    }

    #[test]
    fn test_config_service_network_tests_enabled() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENABLE_NETWORK_TESTS");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(!config.is_network_tests_enabled());

        std::env::set_var("CRAWLRS_ENABLE_NETWORK_TESTS", "1");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(config.is_network_tests_enabled());

        std::env::remove_var("CRAWLRS_ENABLE_NETWORK_TESTS");
    }

    #[test]
    fn test_config_service_debug_save_html_enabled() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("DEBUG_SAVE_HTML");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(!config.is_debug_save_html_enabled());

        std::env::set_var("DEBUG_SAVE_HTML", "1");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(config.is_debug_save_html_enabled());

        std::env::remove_var("DEBUG_SAVE_HTML");
    }

    #[test]
    fn test_config_service_flaresolverr_url() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_FLARESOLVERR_URL");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_flaresolverr_url(), None);

        std::env::set_var("CRAWLRS_FLARESOLVERR_URL", "");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_flaresolverr_url(), None);

        std::env::set_var("CRAWLRS_FLARESOLVERR_URL", "http://flaresolverr:8191");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(
            config.get_flaresolverr_url(),
            Some("http://flaresolverr:8191".to_string())
        );

        std::env::remove_var("CRAWLRS_FLARESOLVERR_URL");
    }

    #[test]
    fn test_config_service_remote_debugging_url() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_remote_debugging_url(), None);

        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "localhost:9222");
        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(
            config.get_remote_debugging_url(),
            Some("localhost:9222".to_string())
        );

        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
    }

    #[test]
    fn test_config_service_proxy_url_env_overrides_settings() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_PROXY_URL", "http://env.proxy:9090");

        let config =
            ConfigServiceComponent::from_settings(true, "http://settings.proxy:8080", 30, 30);
        assert_eq!(
            config.get_proxy_url(),
            Some("http://env.proxy:9090".to_string())
        );

        std::env::remove_var("CRAWLRS_PROXY_URL");
    }

    #[test]
    fn test_config_service_empty_proxy_url_filtered_as_none() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_PROXY_URL", "");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_proxy_url(), None);

        std::env::remove_var("CRAWLRS_PROXY_URL");
    }

    #[test]
    fn test_config_service_empty_remote_debugging_url_filtered_as_none() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_remote_debugging_url(), None);

        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
    }

    #[test]
    fn test_config_service_empty_flaresolverr_url_filtered_as_none() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_FLARESOLVERR_URL", "");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_flaresolverr_url(), None);

        std::env::remove_var("CRAWLRS_FLARESOLVERR_URL");
    }

    #[test]
    fn test_config_service_crawlrs_env_takes_priority_over_app_environment() {
        // 当 CRAWLRS_ENV 和 APP_ENVIRONMENT 都设置时,CRAWLRS_ENV 应优先
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_ENV", "production");
        std::env::set_var("APP_ENVIRONMENT", "staging");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(
            config.get_app_environment(),
            "production",
            "CRAWLRS_ENV 应优先于 APP_ENVIRONMENT"
        );
        assert!(config.is_production());
        assert!(!config.is_development());

        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("APP_ENVIRONMENT");
    }

    #[test]
    fn test_config_service_staging_environment_neither_prod_nor_dev() {
        // staging 环境既不是 production 也不是 development
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_ENV", "staging");
        std::env::remove_var("APP_ENVIRONMENT");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "staging");
        assert!(!config.is_production());
        assert!(!config.is_development());

        std::env::remove_var("CRAWLRS_ENV");
    }

    #[test]
    fn test_config_service_development_environment_from_app_environment() {
        // APP_ENVIRONMENT=development 应触发 is_development()
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::set_var("APP_ENVIRONMENT", "development");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "development");
        assert!(config.is_development());
        assert!(!config.is_production());

        std::env::remove_var("APP_ENVIRONMENT");
    }

    #[test]
    fn test_config_service_production_environment_from_app_environment() {
        // APP_ENVIRONMENT=production 应触发 is_production()
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_ENV");
        std::env::set_var("APP_ENVIRONMENT", "production");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert_eq!(config.get_app_environment(), "production");
        assert!(config.is_production());
        assert!(!config.is_development());

        std::env::remove_var("APP_ENVIRONMENT");
    }

    #[test]
    fn test_config_service_all_optional_features_enabled() {
        // 综合测试:所有可选功能同时启用
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_DISABLE_SSRF_PROTECTION", "1");
        std::env::set_var("CRAWLRS_ENABLE_NETWORK_TESTS", "1");
        std::env::set_var("DEBUG_SAVE_HTML", "1");
        std::env::set_var("CRAWLRS_TEST_NO_BROWSER_REUSE", "1");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(config.is_ssrf_protection_disabled());
        assert!(config.is_network_tests_enabled());
        assert!(config.is_debug_save_html_enabled());
        assert!(config.is_test_mode());

        std::env::remove_var("CRAWLRS_DISABLE_SSRF_PROTECTION");
        std::env::remove_var("CRAWLRS_ENABLE_NETWORK_TESTS");
        std::env::remove_var("DEBUG_SAVE_HTML");
        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");
    }

    #[test]
    fn test_config_service_all_optional_features_disabled() {
        // 综合测试:所有可选功能同时禁用
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("CRAWLRS_DISABLE_SSRF_PROTECTION");
        std::env::remove_var("CRAWLRS_ENABLE_NETWORK_TESTS");
        std::env::remove_var("DEBUG_SAVE_HTML");
        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");

        let config = ConfigServiceComponent::from_settings(false, "", 30, 30);
        assert!(!config.is_ssrf_protection_disabled());
        assert!(!config.is_network_tests_enabled());
        assert!(!config.is_debug_save_html_enabled());
        assert!(!config.is_test_mode());
    }

    #[test]
    fn test_config_service_comprehensive_env_configuration() {
        // 综合测试:同时设置多个环境变量,验证所有 getter 返回正确值
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_PROXY_URL", "http://comprehensive.proxy:9090");
        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "localhost:9222");
        std::env::set_var("CRAWLRS_ENV", "production");
        std::env::set_var("WEBHOOK_SECRET", "comprehensive-secret");
        std::env::set_var("CRAWLRS_HEALTH_CHECK_URL", "http://health:8080/check");
        std::env::set_var("CRAWLRS_FLARESOLVERR_URL", "http://flaresolverr:8191");

        let config = ConfigServiceComponent::from_settings(false, "", 45, 60);

        assert_eq!(
            config.get_proxy_url(),
            Some("http://comprehensive.proxy:9090".to_string())
        );
        assert_eq!(
            config.get_remote_debugging_url(),
            Some("localhost:9222".to_string())
        );
        assert_eq!(config.get_app_environment(), "production");
        assert!(config.is_production());
        assert_eq!(config.get_webhook_secret(), "comprehensive-secret");
        assert_eq!(
            config.get_health_check_url(),
            Some("http://health:8080/check".to_string())
        );
        assert_eq!(
            config.get_flaresolverr_url(),
            Some("http://flaresolverr:8191".to_string())
        );
        assert_eq!(config.get_default_timeout(), Duration::from_secs(45));
        assert_eq!(config.get_browser_timeout(), Duration::from_secs(60));
        assert_eq!(config.get_browser_launch_timeout(), Duration::from_secs(30));

        std::env::remove_var("CRAWLRS_PROXY_URL");
        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
        std::env::remove_var("CRAWLRS_ENV");
        std::env::remove_var("WEBHOOK_SECRET");
        std::env::remove_var("CRAWLRS_HEALTH_CHECK_URL");
        std::env::remove_var("CRAWLRS_FLARESOLVERR_URL");
    }

    #[test]
    fn test_browser_config_component_with_test_mode_and_proxy() {
        // 综合测试:BrowserConfigComponent 同时设置 test_mode 和 proxy
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("CRAWLRS_TEST_NO_BROWSER_REUSE", "1");
        std::env::set_var("CRAWLRS_PROXY_URL", "http://browser.proxy:1080");
        std::env::set_var("CHROMIUM_REMOTE_DEBUGGING_URL", "localhost:9222");

        let config = BrowserConfigComponent::new();
        assert!(config.is_test_mode());
        assert_eq!(
            config.get_proxy_url(),
            Some("http://browser.proxy:1080".to_string())
        );
        assert_eq!(
            config.get_remote_debugging_url(),
            Some("localhost:9222".to_string())
        );

        std::env::remove_var("CRAWLRS_TEST_NO_BROWSER_REUSE");
        std::env::remove_var("CRAWLRS_PROXY_URL");
        std::env::remove_var("CHROMIUM_REMOTE_DEBUGGING_URL");
    }
}