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
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Unified HTTP Client Module
//!
//! Provides HTTP client factory functions for creating consistently configured clients.
//! All clients include SSRF protection through redirect validation.
//!
//! ## Features
//!
//! - Connection pooling for performance
//! - SSRF-safe redirect policy
//! - Configurable timeouts
//! - Custom user agent support

mod redirect_dns;
use redirect_dns::redirect_dns_check_blocks;

use reqwest::Client;
use std::sync::Arc;
use std::time::Duration;

/// Default HTTP client configuration
const DEFAULT_TIMEOUT: u64 = 30;
const DEFAULT_POOL_MAX_IDLE_PER_HOST: usize = 10;
const DEFAULT_POOL_IDLE_TIMEOUT: u64 = 90;
/// Default User-Agent for HTTP requests.
///
/// Uses a real desktop browser UA string so that anti-bot services (e.g.
/// Baidu search) do not return JS-redirect error pages instead of content.
/// A `crawlrs/*` UA is intentionally avoided because major search engines
/// reject requests identifying as bots.
pub(crate) const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const DEFAULT_MAX_REDIRECTS: u8 = 10;

/// TCP 连接建立阶段超时上限。
///
/// 注意覆盖范围:reqwest/hyper 的 connect_timeout 只包住 TCP `socket.connect()`
/// (多地址按地址数均分预算);DNS 解析在其前、TLS 握手在其后,均不在覆盖内,
/// 仍由总超时兜底。
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// 从请求总超时推导连接超时:`min(总超时, 上限)`。
///
/// 只设总超时时,TCP 不可达(丢包黑洞)会耗满总超时才失败。连接超时独立
/// 封顶后连接失败快速暴露,剩余预算留给上层重试;取 `min` 保证连接超时
/// 永不长于总超时。
pub(crate) fn connect_timeout_for(total_timeout: Duration) -> Duration {
    total_timeout.min(DEFAULT_CONNECT_TIMEOUT)
}

/// Create an HTTP client with custom timeout.
///
/// This client has SSRF-safe redirect policy enabled.
///
/// # Arguments
///
/// * `timeout_secs` - Request timeout in seconds
///
/// # Returns
///
/// A configured `reqwest::Client`
pub fn create_http_client_with_timeout(timeout_secs: u64) -> Client {
    create_client(timeout_secs, DEFAULT_MAX_REDIRECTS)
}

/// Create an HTTP client with default configuration.
///
/// This client has SSRF-safe redirect policy enabled.
///
/// # Returns
///
/// An `Arc<Client>` with default settings
pub fn create_http_client() -> Arc<Client> {
    Arc::new(create_client(DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTS))
}

/// Create an HTTP client with custom redirect limit.
///
/// # Arguments
///
/// * `timeout_secs` - Request timeout in seconds
/// * `max_redirects` - Maximum number of redirects to follow
///
/// # Returns
///
/// A configured `reqwest::Client`
pub fn create_http_client_with_redirects(timeout_secs: u64, max_redirects: u8) -> Client {
    create_client(timeout_secs, max_redirects)
}

/// Create an HTTP client that does not follow redirects.
///
/// Use this when you need to handle redirects manually with SSRF validation.
///
/// # Returns
///
/// A `reqwest::Client` that does not follow redirects
pub fn create_http_client_no_redirects() -> Client {
    Client::builder()
        .user_agent(DEFAULT_USER_AGENT)
        .timeout(Duration::from_secs(DEFAULT_TIMEOUT))
        .connect_timeout(connect_timeout_for(Duration::from_secs(DEFAULT_TIMEOUT)))
        .pool_max_idle_per_host(DEFAULT_POOL_MAX_IDLE_PER_HOST)
        .pool_idle_timeout(Duration::from_secs(DEFAULT_POOL_IDLE_TIMEOUT))
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .unwrap_or_else(|e| {
            log::error!("Failed to build HTTP client (no-redirect): {}", e);
            panic!("HTTP client build failed: {}", e);
        })
}

/// Create an HTTP client with SSRF-safe redirect policy.
///
/// The redirect policy validates each redirect URL before following it.
fn create_client(timeout_secs: u64, max_redirects: u8) -> Client {
    let redirect_policy = create_ssrf_safe_redirect_policy(max_redirects);

    Client::builder()
        .user_agent(DEFAULT_USER_AGENT)
        .timeout(Duration::from_secs(timeout_secs))
        .connect_timeout(connect_timeout_for(Duration::from_secs(timeout_secs)))
        .pool_max_idle_per_host(DEFAULT_POOL_MAX_IDLE_PER_HOST)
        .pool_idle_timeout(Duration::from_secs(DEFAULT_POOL_IDLE_TIMEOUT))
        .redirect(redirect_policy)
        .build()
        .unwrap_or_else(|e| {
            log::error!("Failed to build SSRF-safe HTTP client: {}", e);
            panic!("SSRF-safe HTTP client build failed: {}", e);
        })
}

/// Create a reqwest redirect policy with SSRF protection.
///
/// This policy validates each redirect URL before following it,
/// blocking redirects to internal/private addresses.
///
/// # Arguments
///
/// * `max_redirects` - Maximum number of redirects to follow
///
/// # Returns
///
/// A `reqwest::redirect::Policy` that validates redirect URLs
pub fn create_ssrf_safe_redirect_policy(max_redirects: u8) -> reqwest::redirect::Policy {
    // SSRF 禁用开关(仅开发/测试):降级为普通重定向跟随
    if crate::infrastructure::security::ssrf::ssrf_protection_disabled() {
        return reqwest::redirect::Policy::limited(max_redirects as usize);
    }

    use crate::infrastructure::security::ssrf::is_internal_url;

    reqwest::redirect::Policy::custom(move |attempt| {
        if attempt.previous().len() >= max_redirects as usize {
            log::warn!(
                "Redirect limit ({}) exceeded, stopping redirect chain",
                max_redirects
            );
            return attempt.stop();
        }

        let redirect_url = attempt.url();

        // 1) 只允许 http/https
        if redirect_url.scheme() != "http" && redirect_url.scheme() != "https" {
            log::warn!(
                "SSRF protection: Blocking redirect with non-HTTP scheme: {}",
                redirect_url.scheme()
            );
            return attempt.stop();
        }

        // 2) 静态检查:IP 字面量私网地址 / 内部 hostname(localhost、元数据端点等)
        if is_internal_url(redirect_url.as_str()) {
            log::warn!(
                "SSRF protection: Blocking redirect to internal URL: {}",
                redirect_url
            );
            return attempt.stop();
        }

        // 3) DNS 级检查:解析出的全部 IP 必须是公网地址(详见
        // [`redirect_dns_check_blocks`]),任一失败按 fail-closed 阻断
        if redirect_dns_check_blocks(redirect_url) {
            return attempt.stop();
        }

        log::debug!(
            "Following redirect {} -> {}",
            attempt
                .previous()
                .last()
                .map(|u| u.to_string())
                .unwrap_or_else(|| "unknown".to_string()),
            redirect_url
        );

        // Follow the redirect
        attempt.follow()
    })
}

/// 响应体读取错误:大小超限或网络流错误。
///
/// 由 [`read_body_limited`] 返回,调用方按各自错误体系映射
/// (引擎 → `EngineError`,搜索 → `SearchError`,agent_lib → `AgentLibError`)。
#[derive(Debug)]
pub enum BodyReadError {
    /// 响应体超过 `max_bytes` 上限(content_length 预检或流式累积触发)。
    LimitExceeded {
        /// 配置的上限字节数
        max_bytes: usize,
    },
    /// 读取响应体流时发生网络错误。
    Network(reqwest::Error),
}

impl std::fmt::Display for BodyReadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BodyReadError::LimitExceeded { max_bytes } => {
                write!(f, "response body exceeds {} byte limit", max_bytes)
            }
            BodyReadError::Network(e) => write!(f, "failed to read response body: {}", e),
        }
    }
}

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

/// 从字节流累积读取,累计字节数一旦超过 `max_bytes` 立即中断。
///
/// 抽为泛型以便用合成流单测累积分支(无需真实分块 HTTP 服务器)。
/// `bytes_stream()` 等非 Unpin 流由调用方 `Box::pin` 后传入。
async fn accumulate_limited<S, B>(mut stream: S, max_bytes: usize) -> Result<Vec<u8>, BodyReadError>
where
    S: futures::Stream<Item = Result<B, reqwest::Error>> + Unpin,
    B: AsRef<[u8]>,
{
    use futures::StreamExt;
    let mut buf: Vec<u8> = Vec::new();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk.map_err(BodyReadError::Network)?;
        let chunk = chunk.as_ref();
        if buf.len() + chunk.len() > max_bytes {
            return Err(BodyReadError::LimitExceeded { max_bytes });
        }
        buf.extend_from_slice(chunk);
    }
    Ok(buf)
}

/// 读取响应体,受 `max_bytes` 上限约束(防止超大响应导致 OOM)。
///
/// 两步防护
/// 1. **content_length 预检**:若响应声明的 `Content-Length` 已超限,读取前直接拒绝,
///    不消耗带宽/内存。
/// 2. **bytes_stream 累积**:逐块读取并累加,一旦累计字节数将超过上限立即中断
///    (覆盖 chunked 传输无 Content-Length 或声明值不实的情况)。
///
/// 编码:优先按 `Content-Type` 的 `charset` 参数解码(encoding_rs),缺省或无法
/// 识别时回退 UTF-8 lossy(与 reqwest `.text` 行为一致)。
pub async fn read_body_limited(
    resp: reqwest::Response,
    max_bytes: usize,
) -> Result<String, BodyReadError> {
    // 在消费 body 前提取 charset(bytes_stream 会消耗 response)。
    // 遍历所有 `;` 分段查找 charset=,兼容 charset 不在第二段的 Content-Type。
    let charset = resp
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .and_then(|ct| {
            ct.split(';')
                .map(|part| part.trim())
                .find_map(|part| part.strip_prefix("charset="))
        })
        .map(|s| s.trim().trim_matches('"').to_string());

    // 1. content_length 预检
    if let Some(len) = resp.content_length() {
        if len as usize > max_bytes {
            return Err(BodyReadError::LimitExceeded { max_bytes });
        }
    }

    // 2. bytes_stream 累积 + 上限中断
    let bytes = accumulate_limited(Box::pin(resp.bytes_stream()), max_bytes).await?;

    // 编码解码
    let decoded = match charset.as_deref() {
        Some(label) => {
            let encoding =
                encoding_rs::Encoding::for_label(label.as_bytes()).unwrap_or(encoding_rs::UTF_8);
            let (text, _, _) = encoding.decode(&bytes);
            text.into_owned()
        }
        None => String::from_utf8_lossy(&bytes).into_owned(),
    };

    Ok(decoded)
}

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

    #[test]
    fn test_create_http_client_with_timeout() {
        let client = create_http_client_with_timeout(60);
        let _ = client.clone();
    }

    #[test]
    fn test_create_default_http_client() {
        let client = create_http_client();
        let _ = client.clone();
    }

    #[test]
    fn test_create_http_client_no_redirects() {
        let client = create_http_client_no_redirects();
        let _ = client.clone();
    }

    #[test]
    fn test_create_http_client_with_redirects() {
        let client = create_http_client_with_redirects(30, 5);
        let _ = client.clone();
    }

    #[test]
    fn test_default_constants_values() {
        // Verify the default configuration constants are the expected values.
        assert_eq!(DEFAULT_TIMEOUT, 30);
        assert_eq!(DEFAULT_POOL_MAX_IDLE_PER_HOST, 10);
        assert_eq!(DEFAULT_POOL_IDLE_TIMEOUT, 90);
        assert_eq!(DEFAULT_MAX_REDIRECTS, 10);
        assert!(!DEFAULT_USER_AGENT.is_empty());
    }

    #[test]
    fn connect_timeout_capped_at_upper_bound() {
        // 总超时高于上限时,连接超时封顶(不可达目标 10s 内失败,而非耗满总超时)。
        assert_eq!(
            connect_timeout_for(Duration::from_secs(30)),
            Duration::from_secs(10)
        );
        assert_eq!(
            connect_timeout_for(Duration::from_secs(60)),
            Duration::from_secs(10)
        );
    }

    #[test]
    fn connect_timeout_never_exceeds_total() {
        // 总超时低于上限时连接超时跟随总超时,绝不长于它。
        assert_eq!(
            connect_timeout_for(Duration::from_secs(5)),
            Duration::from_secs(5)
        );
        assert_eq!(connect_timeout_for(Duration::ZERO), Duration::ZERO);
    }

    #[test]
    fn test_create_http_client_with_zero_timeout() {
        // A zero timeout is a valid edge case; the client must still build.
        let client = create_http_client_with_timeout(0);
        let _ = client.clone();
    }

    #[test]
    fn test_create_http_client_with_large_timeout() {
        let client = create_http_client_with_timeout(86400);
        let _ = client.clone();
    }

    #[test]
    fn test_create_http_client_with_zero_redirects() {
        // max_redirects=0 should still produce a working client.
        let client = create_http_client_with_redirects(30, 0);
        let _ = client.clone();
    }

    #[test]
    fn test_create_http_client_with_max_redirects() {
        let client = create_http_client_with_redirects(30, u8::MAX);
        let _ = client.clone();
    }

    #[test]
    fn test_create_ssrf_safe_redirect_policy_returns_policy() {
        // The policy factory must return a usable Policy for various limits.
        let _policy = create_ssrf_safe_redirect_policy(5);
        let _policy_zero = create_ssrf_safe_redirect_policy(0);
        let _policy_max = create_ssrf_safe_redirect_policy(u8::MAX);
    }

    #[test]
    fn test_default_http_client_is_arc_wrapped() {
        // create_http_client returns an Arc<Client>; verify it can be shared.
        let client = create_http_client();
        let client2 = client.clone();
        // Both Arcs should point to the same underlying Client.
        assert!(std::sync::Arc::ptr_eq(&client, &client2));
    }

    #[test]
    fn test_no_redirect_client_follows_no_redirects() {
        // The no-redirect client must report that it won't follow redirects.
        // We verify this indirectly by ensuring the client builds with the
        // none redirect policy without panicking.
        let _client = create_http_client_no_redirects();
    }

    // SSRF-safe redirect policy behavior tests (wiremock)

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_internal_url() {
        // A redirect to an internal URL (127.0.0.1) must be blocked by the
        // SSRF-safe redirect policy. The client should return the 302
        // response instead of following the redirect.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://127.0.0.1:1/destination"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        // The redirect target is 127.0.0.1 which is_internal_url returns true,
        // so the policy calls attempt.stop and returns the 302 response.
        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to internal URL should be blocked (302 returned, not followed)"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_zero_max_redirects() {
        // With max_redirects=0, the policy must stop immediately on the first
        // redirect regardless of the target URL.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://127.0.0.1:1/destination"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 0);
        let url = format!("{}/redirect", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "with max_redirects=0, redirect should not be followed"
        );
    }

    #[tokio::test]
    async fn test_client_with_ssrf_policy_successful_non_redirect_request() {
        // A normal 200 response (no redirect) should pass through the client
        // without being affected by the SSRF redirect policy.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/normal"))
            .respond_with(ResponseTemplate::new(200).set_body_string("ok"))
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/normal", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(response.status().as_u16(), 200);
        let body = response.text().await.expect("body should be readable");
        assert_eq!(body, "ok");
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_localhost() {
        // A redirect to "localhost" hostname should also be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-localhost"))
            .respond_with(
                ResponseTemplate::new(301)
                    .insert_header("Location", "http://localhost:1/destination"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-localhost", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            301,
            "redirect to localhost should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_private_ip() {
        // A redirect to a private IP range (10.x.x.x) should be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-private"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://10.0.0.1:8080/internal"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-private", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to private IP (10.0.0.1) should be blocked"
        );
    }

    // Supplementary tests: edge cases and parameter coverage

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_172_16() {
        // Another private IP range (172.16.0.0/12) should also be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-172"))
            .respond_with(
                ResponseTemplate::new(301).insert_header("Location", "http://172.16.0.1:80/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-172", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            301,
            "redirect to 172.16.0.0/12 should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_192_168() {
        // The 192.168.0.0/16 private range should also be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-192"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("Location", "http://192.168.1.1:80/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-192", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to 192.168.0.0/16 should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_ipv6_loopback() {
        // IPv6 loopback [::1] should also be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-ipv6"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("Location", "http://[::1]:80/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-ipv6", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to [::1] should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_169_254() {
        // Link-local address 169.254.0.0/16 should be blocked (cloud metadata).
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-link-local"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://169.254.169.254/latest/meta-data/"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-link-local", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to 169.254.169.254 should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_redirect_to_0_0_0_0() {
        // 0.0.0.0 should be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-zero"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("Location", "http://0.0.0.0:80/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-zero", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to 0.0.0.0 should be blocked"
        );
    }

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_blocks_non_http_scheme() {
        // A redirect to a non-HTTP scheme (file) should be blocked.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-file"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("Location", "file:///etc/passwd"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-file", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to file:// scheme should be blocked"
        );
    }

    #[tokio::test]
    async fn test_no_redirect_client_returns_redirect_response() {
        // The no-redirect client should return the redirect response as-is,
        // without following it.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("Location", "http://127.0.0.1:1/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_no_redirects();
        let url = format!("{}/redirect", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        // The no-redirect client should NOT follow the redirect.
        assert_eq!(
            response.status().as_u16(),
            302,
            "no-redirect client should return 302 without following"
        );
    }

    #[tokio::test]
    async fn test_client_with_ssrf_policy_handles_post_request() {
        // Verify the SSRF-safe client handles POST requests without redirect issues.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/submit"))
            .respond_with(ResponseTemplate::new(200).set_body_string("accepted"))
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/submit", mock_server.uri());
        let response = client
            .post(&url)
            .body("data")
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(response.status().as_u16(), 200);
        assert_eq!(response.text().await.unwrap(), "accepted");
    }

    #[tokio::test]
    async fn test_client_with_ssrf_policy_follows_safe_redirect_to_mock_server() {
        // NOTE: This test requires network access. The SSRF-safe policy allows
        // redirects to non-internal URLs. We use the mock server's own address
        // as the redirect target, but 127.0.0.1 is internal, so the redirect
        // is blocked. This test documents that behavior: even a redirect to
        // the mock server (127.0.0.1) is blocked by SSRF protection.
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        // Set up a destination endpoint on the mock server.
        Mock::given(method("GET"))
            .and(path("/destination"))
            .respond_with(ResponseTemplate::new(200).set_body_string("reached"))
            .mount(&mock_server)
            .await;

        // Redirect to the mock server's own /destination endpoint.
        Mock::given(method("GET"))
            .and(path("/redirect-to-dest"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", format!("{}/destination", mock_server.uri())),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-to-dest", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        // The redirect target is 127.0.0.1 (mock server), which is_internal_url
        // returns true, so the redirect is blocked and the 302 is returned.
        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to 127.0.0.1 (mock server) should be blocked by SSRF policy"
        );
    }

    #[test]
    fn test_default_user_agent_is_chrome_like() {
        // Verify the default User-Agent contains Chrome identifiers.
        assert!(DEFAULT_USER_AGENT.contains("Chrome"));
        assert!(DEFAULT_USER_AGENT.contains("Mozilla"));
    }

    #[test]
    fn test_create_ssrf_safe_redirect_policy_with_different_limits() {
        // Verify policies can be created for a range of redirect limits.
        for limit in [1u8, 2, 5, 10, 20, 50, 100, 200] {
            let _policy = create_ssrf_safe_redirect_policy(limit);
        }
    }

    #[test]
    fn test_http_client_functions_return_usable_clients() {
        // Smoke test: all factory functions must return usable clients.
        let c1 = create_http_client_with_timeout(10);
        let c2 = create_http_client();
        let c3 = create_http_client_no_redirects();
        let c4 = create_http_client_with_redirects(10, 5);
        // Verify they can be cloned without panic.
        let _ = c1.clone();
        let _ = c2.clone();
        let _ = c3.clone();
        let _ = c4.clone();
    }

    // Test logger for covering log::warn!/log::debug! in redirect policy

    use crate::test_utils::ensure_debug_logger;

    // log::warn! coverage tests for SSRF redirect policy

    #[tokio::test]
    async fn test_ssrf_block_logs_warning_with_logger_initialized() {
        // With logger initialized, the log::warn! for SSRF block should execute.
        ensure_debug_logger();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-logged"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://127.0.0.1:1/destination"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-logged", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            302,
            "redirect to internal URL should be blocked (302 returned)"
        );
    }

    #[tokio::test]
    async fn test_redirect_limit_exceeded_logs_warning_with_logger() {
        // With max_redirects=0 and logger initialized, the log::warn! for
        // redirect limit exceeded should execute.
        ensure_debug_logger();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-limit-logged"))
            .respond_with(
                ResponseTemplate::new(301).insert_header("Location", "http://127.0.0.1:1/dest"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 0);
        let url = format!("{}/redirect-limit-logged", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(
            response.status().as_u16(),
            301,
            "with max_redirects=0, redirect should not be followed"
        );
    }

    #[tokio::test]
    async fn test_ssrf_block_localhost_logs_warning_with_logger() {
        // With logger initialized, blocking redirect to localhost logs warning.
        ensure_debug_logger();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-localhost-logged"))
            .respond_with(
                ResponseTemplate::new(301)
                    .insert_header("Location", "http://localhost:1/destination"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-localhost-logged", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(response.status().as_u16(), 301);
    }

    #[tokio::test]
    async fn test_ssrf_block_private_ip_logs_warning_with_logger() {
        // With logger initialized, blocking redirect to private IP logs warning.
        ensure_debug_logger();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-private-logged"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://10.0.0.1:8080/internal"),
            )
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let url = format!("{}/redirect-private-logged", mock_server.uri());
        let response = client
            .get(&url)
            .send()
            .await
            .expect("request should succeed");

        assert_eq!(response.status().as_u16(), 302);
    }

    // redirect follow 分支覆盖测试

    #[tokio::test]
    async fn test_ssrf_safe_redirect_policy_follows_external_redirect() {
        // 当 redirect 目标是外部 URL(is_internal_url 返回 false)时,
        // policy 应执行 log::debug!(行 141-149)和 attempt.follow(行 152)。
        // 使用 TEST-NET-1 (192.0.2.1, RFC 5737) 端口 1,确保不可达,
        // 触发 attempt.follow 后连接失败返回错误。
        ensure_debug_logger();
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/redirect-external-follow"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("Location", "http://192.0.2.1:1/destination"),
            )
            .mount(&mock_server)
            .await;

        // 使用短超时(2 秒),避免测试等待过久
        let client = create_http_client_with_redirects(2, 10);
        let url = format!("{}/redirect-external-follow", mock_server.uri());
        let result = client.get(&url).send().await;

        // redirect 目标不可达,send 应返回错误(覆盖 attempt.follow 分支)
        assert!(
            result.is_err(),
            "redirect to unreachable external URL should fail after attempt.follow()"
        );
    }

    // read_body_limited 上限测试

    #[tokio::test]
    async fn test_read_body_limited_within_limit() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/small"))
            .respond_with(ResponseTemplate::new(200).set_body_string("hello world"))
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let resp = client
            .get(format!("{}/small", mock_server.uri()))
            .send()
            .await
            .expect("request should succeed");

        let body = read_body_limited(resp, 1024).await.expect("within limit");
        assert_eq!(body, "hello world");
    }

    #[tokio::test]
    async fn test_read_body_limited_rejects_oversized_content_length() {
        // content_length 预检:声明长度超限 → 读取前拒绝
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        let big = "x".repeat(2048);
        Mock::given(method("GET"))
            .and(path("/big"))
            .respond_with(ResponseTemplate::new(200).set_body_raw(big.as_str(), "text/plain"))
            .mount(&mock_server)
            .await;

        let client = create_http_client_with_redirects(5, 10);
        let resp = client
            .get(format!("{}/big", mock_server.uri()))
            .send()
            .await
            .expect("request should succeed");

        // 上限 1024 < 2048 声明长度 → LimitExceeded
        let err = read_body_limited(resp, 1024)
            .await
            .expect_err("should reject oversized content_length before reading");
        assert!(
            matches!(err, BodyReadError::LimitExceeded { max_bytes: 1024 }),
            "expected LimitExceeded, got {:?}",
            err
        );
    }

    #[tokio::test]
    async fn test_accumulate_limited_within_limit() {
        // 合成分块流:累计未超限 → 完整拼接
        let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
            Ok(bytes::Bytes::from_static(b"hello ")),
            Ok(bytes::Bytes::from_static(b"world")),
        ];
        let out = accumulate_limited(futures::stream::iter(chunks), 1024)
            .await
            .expect("within limit");
        assert_eq!(out, b"hello world");
    }

    #[tokio::test]
    async fn test_accumulate_limited_exact_boundary_is_allowed() {
        // 边界契约:body 恰好等于 max_bytes 时放行(守卫语义为 `> max_bytes` 才拒绝,
        // 即"至多 max_bytes")。锁定该语义,防止将来误改为 `>=` 造成回归。
        let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
            Ok(bytes::Bytes::from_static(b"aaaa")),
            Ok(bytes::Bytes::from_static(b"bbbb")),
        ];
        let out = accumulate_limited(futures::stream::iter(chunks), 8)
            .await
            .expect("body of exactly max_bytes must be allowed");
        assert_eq!(out, b"aaaabbbb");
    }

    #[tokio::test]
    async fn test_accumulate_limited_exceeds_returns_error() {
        // 分块累积:总字节数超过上限时立即中断返回 LimitExceeded(而非 OOM)。
        // 覆盖 chunked 传输无 content_length 预检、仅靠累积守卫的场景。
        let chunks: Vec<Result<bytes::Bytes, reqwest::Error>> = vec![
            Ok(bytes::Bytes::from_static(b"aaaa")),
            Ok(bytes::Bytes::from_static(b"bbbb")),
            Ok(bytes::Bytes::from_static(b"cccc")),
        ];
        let err = accumulate_limited(futures::stream::iter(chunks), 8)
            .await
            .expect_err("should exceed limit on third chunk");
        assert!(
            matches!(err, BodyReadError::LimitExceeded { max_bytes: 8 }),
            "expected LimitExceeded, got {:?}",
            err
        );
    }
}