Skip to main content

wordval_utils/
web.rs

1//! Web 解析工具:URL 解析、IP 提取、User-Agent 解析等
2
3use std::net::SocketAddr;
4
5/// 检查是否为私有 IP(IPv4/IPv6)
6///
7/// IPv4 私有地址包括:私有地址(10/8, 172.16/12, 192.168/16)、环回地址(127/8)、
8/// 链路本地地址(169.254/16)、未指定地址(0.0.0.0)、组播地址(224/4)
9///
10/// IPv6 私有地址包括:环回地址(::1)、未指定地址(::)、链路本地单播(fe80::/10)、
11/// 唯一本地地址(fc00::/7)、组播地址(ff::/8)
12///
13/// # 参数
14/// - `ip`: IP 地址字符串
15///
16/// # 返回
17/// 若为私有 IP 返回 true,否则返回 false
18pub fn is_private_ip(ip: &str) -> bool {
19    if let Ok(addr) = ip.parse::<std::net::IpAddr>() {
20        match addr {
21            std::net::IpAddr::V4(ipv4) => {
22                ipv4.is_private()
23                    || ipv4.is_loopback()
24                    || ipv4.is_link_local()
25                    || ipv4.is_unspecified()
26                    || ipv4.is_multicast()
27            }
28            std::net::IpAddr::V6(ipv6) => {
29                let seg0 = ipv6.segments()[0];
30                ipv6.is_loopback()
31                    || ipv6.is_unspecified()
32                    // fe80::/10 链路本地(MSRV 1.75 无 is_unicast_link_local,手写段判断)
33                    || (seg0 & 0xffc0) == 0xfe80
34                    // fc00::/7 唯一本地
35                    || (seg0 & 0xfe00) == 0xfc00
36                    || ipv6.is_multicast()
37            }
38        }
39    } else {
40        false
41    }
42}
43
44/// 安全默认:从直连对端地址提取客户端 IP。
45///
46/// **不信任任何代理头**(X-Forwarded-For / CF-Connecting-IP 等)。
47///
48/// 若服务前置可信反代/负载均衡,请改用 [`extract_client_ip_trusted`]
49/// 并在配置中声明 `trusted_proxies`,仅在直连对端为可信网段时才读取头部。
50pub fn extract_client_ip(_headers: &http::HeaderMap, connect_info: &SocketAddr) -> String {
51    connect_info.ip().to_string()
52}
53
54/// 可信代理网段集合(支持精确 IP 或 CIDR,如 `10.0.0.0/8`)
55pub struct TrustedProxies {
56    nets: Vec<(std::net::IpAddr, u32)>,
57}
58
59impl TrustedProxies {
60    /// 从配置字符串列表解析可信代理(支持 `ip` 或 `ip/bits` CIDR)。
61    /// 无法解析的项会被静默忽略。
62    pub fn new(specs: &[String]) -> Self {
63        let mut nets = Vec::with_capacity(specs.len());
64        for s in specs {
65            let trimmed = s.trim();
66            if trimmed.is_empty() {
67                continue;
68            }
69            let (ip_str, bits) = match trimmed.split_once('/') {
70                Some((ip_s, pre_s)) => {
71                    match (
72                        ip_s.trim().parse::<std::net::IpAddr>(),
73                        pre_s.trim().parse::<u32>(),
74                    ) {
75                        (Ok(ip), Ok(b)) => (ip, b),
76                        _ => continue,
77                    }
78                }
79                None => match trimmed.parse::<std::net::IpAddr>() {
80                    Ok(ip) => (ip, if ip.is_ipv4() { 32 } else { 128 }),
81                    _ => continue,
82                },
83            };
84            nets.push((ip_str, bits));
85        }
86        TrustedProxies { nets }
87    }
88
89    /// 是否为空(未配置任何可信代理)
90    pub fn is_empty(&self) -> bool {
91        self.nets.is_empty()
92    }
93
94    /// 判断给定 IP 是否落在某个可信网段内
95    pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
96        self.nets
97            .iter()
98            .any(|(net, bits)| ip_in_net(ip, net, *bits))
99    }
100}
101
102/// 判断 `ip` 是否落在以 `net` 为网络地址、`bits` 为前缀长度的网络内
103fn ip_in_net(ip: &std::net::IpAddr, net: &std::net::IpAddr, bits: u32) -> bool {
104    match (ip, net) {
105        (std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
106            let bits = bits.min(32);
107            if bits == 0 {
108                return true;
109            }
110            let mask = if bits >= 32 {
111                u32::MAX
112            } else {
113                !(u32::MAX >> bits)
114            };
115            (u32::from(*a) & mask) == (u32::from(*b) & mask)
116        }
117        (std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
118            let bits = bits.min(128);
119            if bits == 0 {
120                return true;
121            }
122            let ma = a.segments();
123            let mb = b.segments();
124            let mut done = 0u32;
125            for i in 0..8 {
126                if done >= bits {
127                    return true;
128                }
129                let remain = bits - done;
130                let m: u16 = if remain >= 16 {
131                    0xFFFF
132                } else {
133                    !(0xFFFFu16 >> remain)
134                };
135                if (ma[i] & m) != (mb[i] & m) {
136                    return false;
137                }
138                done += 16;
139            }
140            true
141        }
142        _ => false,
143    }
144}
145
146/// 从请求头提取客户端真实 IP(仅在直连对端为可信代理时读取头部)。
147///
148/// 算法:
149/// 1. 若直连对端 IP 不在可信网段内,直接返回直连 IP(不读取任何头部)。
150/// 2. 若直连对端可信,则优先取 `CF-Connecting-IP`;否则解析 `X-Forwarded-For`
151///    从右向左遍历,跳过可信网段与私有/环回/未指定地址,取第一个真实公网 IP。
152pub fn extract_client_ip_trusted(
153    headers: &http::HeaderMap,
154    connect_info: &SocketAddr,
155    trusted: &TrustedProxies,
156) -> String {
157    let peer = connect_info.ip();
158    if !trusted.contains(&peer) {
159        return peer.to_string();
160    }
161
162    // 直连对端是可信代理,从头部取真实 IP
163    if let Some(v) = headers
164        .get("CF-Connecting-IP")
165        .and_then(|h| h.to_str().ok())
166    {
167        if let Ok(ip) = v.trim().parse::<std::net::IpAddr>() {
168            if !trusted.contains(&ip) {
169                return ip.to_string();
170            }
171        }
172    }
173
174    if let Some(v) = headers.get("X-Forwarded-For").and_then(|h| h.to_str().ok()) {
175        let ips: Vec<std::net::IpAddr> = v
176            .split(',')
177            .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
178            .collect();
179        for ip in ips.iter().rev() {
180            if trusted.contains(ip) || is_internal_ip(ip) {
181                continue;
182            }
183            return ip.to_string();
184        }
185    }
186
187    peer.to_string()
188}
189
190/// 判断 IP 是否为内部/不可路由地址(私有、环回、未指定、IPv6 唯一本地)
191fn is_internal_ip(ip: &std::net::IpAddr) -> bool {
192    match ip {
193        std::net::IpAddr::V4(a) => a.is_private() || a.is_loopback() || a.is_unspecified(),
194        std::net::IpAddr::V6(a) => {
195            // fc00::/7 唯一本地(MSRV 1.75 无 is_unique_local,手写段判断)
196            a.is_loopback() || a.is_unspecified() || (a.segments()[0] & 0xfe00) == 0xfc00
197        }
198    }
199}
200
201/// Web 解析工具
202///
203/// 提供 URL 解析、真实 IP 获取、私网 IP 判断、查询字符串构造等功能。
204pub struct WebExt;
205
206impl WebExt {
207    /// 拆分 URL:返回 `(host[:port], 路径部分)`。路径部分含开头 `/`,无路径时为 None。
208    /// 仅支持带 `scheme://` 的绝对 URL(与原 url crate 行为一致:相对 URL 返回 None)。
209    fn split_authority(url_str: &str) -> Option<(&str, Option<&str>)> {
210        let rest = url_str.split_once("://")?.1;
211        let (authority, path_part) = match rest.find(['/', '?', '#']) {
212            Some(i) => (&rest[..i], Some(&rest[i..])),
213            None => (rest, None),
214        };
215        // authority 中跳过 userinfo(`user:pass@`),取最后一个 `@` 之后
216        let host_port = authority
217            .rsplit_once('@')
218            .map(|(_, h)| h)
219            .unwrap_or(authority);
220        Some((host_port, path_part))
221    }
222
223    /// 解析 URL 获取域名(自研实现,替代 url crate)
224    ///
225    /// 支持 userinfo、IPv6 括号形式;端口会被剥离,IPv6 返回无括号形式。
226    pub fn domain(url_str: &str) -> Option<String> {
227        let (host_port, _) = Self::split_authority(url_str)?;
228        if host_port.is_empty() {
229            return None;
230        }
231        if let Some(ipv6) = host_port.strip_prefix('[') {
232            return ipv6.find(']').map(|end| ipv6[..end].to_string());
233        }
234        host_port.split(':').next().map(|h| h.to_string())
235    }
236
237    /// 解析 URL 获取路径(含开头的 `/`,不含 query/fragment;自研实现,替代 url crate)
238    pub fn path(url_str: &str) -> Option<String> {
239        let (_, path_part) = Self::split_authority(url_str)?;
240        match path_part {
241            None => Some("/".to_string()),
242            Some(p) => {
243                if p.starts_with('?') || p.starts_with('#') {
244                    return Some("/".to_string());
245                }
246                let end = p.find(['?', '#']).unwrap_or(p.len());
247                Some(p[..end].to_string())
248            }
249        }
250    }
251
252    /// 从请求头获取真实 IP(X-Forwarded-For 或 X-Real-IP)。
253    ///
254    /// # 安全警告
255    ///
256    /// 本方法**无条件信任** `X-Forwarded-For` / `X-Real-IP` 头,任何客户端都能
257    /// 伪造这些头来伪装来源 IP。**切勿**用于限流、鉴权、审计等安全敏感场景。
258    /// 仅当服务确定运行在可信反向代理之后、且该代理会覆盖这些头时才可使用。
259    ///
260    /// 安全场景请改用 [`extract_client_ip_trusted`],它会校验直连对端是否为
261    /// 可信代理网段后再读取头部。
262    pub fn real_ip(headers: &[(String, String)], remote_addr: &str) -> String {
263        for (key, val) in headers {
264            if key.eq_ignore_ascii_case("x-forwarded-for") {
265                // 取最左侧(最接近原始客户端)的有效 IP
266                if let Some(ip) = val
267                    .split(',')
268                    .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
269                    .next()
270                {
271                    return ip.to_string();
272                }
273            }
274            if key.eq_ignore_ascii_case("x-real-ip") {
275                if let Ok(ip) = val.trim().parse::<std::net::IpAddr>() {
276                    return ip.to_string();
277                }
278            }
279        }
280        // 兜底:优先按 `IP:port` / `[IPv6]:port` 解析,其次按裸 IP,最后才做字符串截断
281        let trimmed = remote_addr.trim();
282        if let Ok(sa) = trimmed.parse::<SocketAddr>() {
283            return sa.ip().to_string();
284        }
285        if let Ok(ip) = trimmed.parse::<std::net::IpAddr>() {
286            return ip.to_string();
287        }
288        trimmed.split(':').next().unwrap_or(trimmed).to_string()
289    }
290    /// 检查是否为私有 IP(委托给公共函数 `is_private_ip`)
291    pub fn is_private_ip(ip: &str) -> bool {
292        is_private_ip(ip)
293    }
294    /// 构建 URL 查询字符串
295    pub fn build_query(params: &[(&str, &str)]) -> String {
296        if params.is_empty() {
297            return String::new();
298        }
299        let parts: Vec<String> = params
300            .iter()
301            .map(|(k, v)| format!("{}={}", Self::percent_encode(k), Self::percent_encode(v)))
302            .collect();
303        format!("?{}", parts.join("&"))
304    }
305
306    /// URL 路径段/查询参数编码:仅保留字母数字与 `-` `.` `_` `~`,其余字节转 `%XX`(大写)。
307    ///
308    /// 对应 RFC 3986 unreserved 字符集,与 SigV4 canonical URI/query 编码要求一致。
309    /// 逐字节直接拼装,不为每个转义字节分配临时字符串。
310    ///
311    /// # 示例
312    ///
313    /// ```
314    /// use wordval_utils::WebExt;
315    ///
316    /// assert_eq!(WebExt::percent_encode("a-b_c.d~"), "a-b_c.d~");
317    /// assert_eq!(WebExt::percent_encode("a b"), "a%20b");
318    /// assert_eq!(WebExt::percent_encode("/"), "%2F");
319    /// assert_eq!(WebExt::percent_encode("中文"), "%E4%B8%AD%E6%96%87");
320    /// ```
321    pub fn percent_encode(seg: &str) -> String {
322        const HEX: &[u8; 16] = b"0123456789ABCDEF";
323        // 容量按最大膨胀(每字节 -> %XX,3 倍)预留,避免二次分配
324        let mut out = String::with_capacity(seg.len() * 3);
325        for &byte in seg.as_bytes() {
326            if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
327                out.push(byte as char);
328            } else {
329                out.push('%');
330                out.push(HEX[(byte >> 4) as usize] as char);
331                out.push(HEX[(byte & 0x0f) as usize] as char);
332            }
333        }
334        out
335    }
336
337    /// 按扩展名推断 MIME 类型(返回静态字符串,零分配;需要所有权时自行 `to_string()`)
338    ///
339    /// # 示例
340    ///
341    /// ```
342    /// use wordval_utils::WebExt;
343    ///
344    /// assert_eq!(WebExt::mime_guess("a.PNG"), "image/png");
345    /// assert_eq!(WebExt::mime_guess("noext"), "application/octet-stream");
346    /// ```
347    pub fn mime_guess(filename: &str) -> &'static str {
348        let ext = std::path::Path::new(filename)
349            .extension()
350            .and_then(|e| e.to_str())
351            .unwrap_or("bin");
352
353        match ext.to_ascii_lowercase().as_str() {
354            "jpg" | "jpeg" => "image/jpeg",
355            "png" => "image/png",
356            "gif" => "image/gif",
357            "webp" => "image/webp",
358            "svg" => "image/svg+xml",
359            "pdf" => "application/pdf",
360            "json" => "application/json",
361            "html" | "htm" => "text/html",
362            "css" => "text/css",
363            "js" => "application/javascript",
364            "txt" => "text/plain",
365            "csv" => "text/csv",
366            "zip" => "application/zip",
367            "mp4" => "video/mp4",
368            "mp3" => "audio/mpeg",
369            "doc" => "application/msword",
370            "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
371            "xls" => "application/vnd.ms-excel",
372            "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
373            _ => "application/octet-stream",
374        }
375    }
376
377    /// URL 解码(`%E4%BD%A0` → `"你"`)
378    ///
379    /// 支持 `%XX` 十六进制编码和 `+` 作为空格。
380    /// 非法编码(如 `%ZZ` 或不完整的 `%X`)会原样保留。
381    pub fn url_decode(s: &str) -> String {
382        urldecode(s)
383    }
384
385    /// 解析 Content-Type 头,提取 MIME 类型
386    ///
387    /// # 示例
388    ///
389    /// ```
390    /// use wordval_utils::WebExt;
391    ///
392    /// assert_eq!(
393    ///     WebExt::content_type_mime("application/json; charset=utf-8"),
394    ///     Some("application/json".to_string())
395    /// );
396    /// assert_eq!(
397    ///     WebExt::content_type_mime("text/html"),
398    ///     Some("text/html".to_string())
399    /// );
400    /// ```
401    pub fn content_type_mime(content_type: &str) -> Option<String> {
402        content_type
403            .split(';')
404            .next()
405            .map(|s| s.trim().to_lowercase())
406            .filter(|s| !s.is_empty())
407    }
408}
409
410fn urldecode(s: &str) -> String {
411    fn hex_val(c: u8) -> Option<u8> {
412        match c {
413            b'0'..=b'9' => Some(c - b'0'),
414            b'a'..=b'f' => Some(c - b'a' + 10),
415            b'A'..=b'F' => Some(c - b'A' + 10),
416            _ => None,
417        }
418    }
419    let bytes = s.as_bytes();
420    let mut out = Vec::with_capacity(bytes.len());
421    let mut i = 0;
422    while i < bytes.len() {
423        match bytes[i] {
424            b'%' => match (bytes.get(i + 1), bytes.get(i + 2)) {
425                (Some(&h), Some(&l)) => match (hex_val(h), hex_val(l)) {
426                    (Some(h), Some(l)) => {
427                        out.push((h << 4) | l);
428                        i += 3;
429                    }
430                    // 非法十六进制,`%` 原样保留
431                    _ => {
432                        out.push(b'%');
433                        i += 1;
434                    }
435                },
436                // 不完整,`%` 原样保留
437                _ => {
438                    out.push(b'%');
439                    i += 1;
440                }
441            },
442            b'+' => {
443                // URL 编码中 + 表示空格
444                out.push(b' ');
445                i += 1;
446            }
447            b => {
448                out.push(b);
449                i += 1;
450            }
451        }
452    }
453    // 尝试转换为 UTF-8,失败则原样返回
454    String::from_utf8(out).unwrap_or_else(|_| s.to_string())
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn test_url_decode_basic() {
463        assert_eq!(WebExt::url_decode("hello%20world"), "hello world");
464        assert_eq!(WebExt::url_decode("hello+world"), "hello world");
465    }
466
467    #[test]
468    fn test_url_decode_utf8() {
469        // "%E4%BD%A0%E5%A5%BD" = "你好"
470        assert_eq!(WebExt::url_decode("%E4%BD%A0%E5%A5%BD"), "你好");
471    }
472
473    #[test]
474    fn test_url_decode_invalid() {
475        // 非法十六进制,原样保留
476        assert_eq!(WebExt::url_decode("%ZZ"), "%ZZ");
477        // 不完整
478        assert_eq!(WebExt::url_decode("%E"), "%E");
479    }
480
481    #[test]
482    fn test_url_decode_no_encoding() {
483        assert_eq!(WebExt::url_decode("hello"), "hello");
484    }
485
486    #[test]
487    fn test_percent_encode_keeps_unreserved() {
488        assert_eq!(WebExt::percent_encode("a-b_c.d~"), "a-b_c.d~");
489        assert_eq!(WebExt::percent_encode("a b"), "a%20b");
490        assert_eq!(WebExt::percent_encode("/"), "%2F");
491        assert_eq!(WebExt::percent_encode("中文"), "%E4%B8%AD%E6%96%87");
492    }
493
494    #[test]
495    fn test_mime_guess_extensions() {
496        assert_eq!(WebExt::mime_guess("a.PNG"), "image/png");
497        assert_eq!(WebExt::mime_guess("a.jpeg"), "image/jpeg");
498        assert_eq!(WebExt::mime_guess("noext"), "application/octet-stream");
499    }
500
501    #[test]
502    fn test_content_type_mime_json() {
503        assert_eq!(
504            WebExt::content_type_mime("application/json; charset=utf-8"),
505            Some("application/json".to_string())
506        );
507    }
508
509    #[test]
510    fn test_content_type_mime_html() {
511        assert_eq!(
512            WebExt::content_type_mime("text/html"),
513            Some("text/html".to_string())
514        );
515    }
516
517    #[test]
518    fn test_content_type_mime_with_params() {
519        assert_eq!(
520            WebExt::content_type_mime("multipart/form-data; boundary=something"),
521            Some("multipart/form-data".to_string())
522        );
523    }
524
525    #[test]
526    fn test_content_type_mime_empty() {
527        assert_eq!(WebExt::content_type_mime(""), None);
528    }
529
530    #[test]
531    fn test_content_type_mime_case_insensitive() {
532        assert_eq!(
533            WebExt::content_type_mime("Application/JSON"),
534            Some("application/json".to_string())
535        );
536    }
537}
538
539#[cfg(test)]
540mod extra_web_tests {
541    use super::*;
542    use std::net::{IpAddr, SocketAddr};
543
544    fn ip(s: &str) -> IpAddr {
545        s.parse().unwrap()
546    }
547
548    #[test]
549    fn is_private_ip_all_families() {
550        assert!(is_private_ip("10.1.2.3")); // 10/8
551        assert!(is_private_ip("172.16.0.1")); // 172.16/12
552        assert!(is_private_ip("192.168.0.1"));
553        assert!(is_private_ip("127.0.0.1")); // 环回
554        assert!(is_private_ip("169.254.1.1")); // 链路本地
555        assert!(is_private_ip("0.0.0.0")); // 未指定
556        assert!(is_private_ip("224.0.0.1")); // 组播
557        assert!(!is_private_ip("8.8.8.8"));
558        assert!(is_private_ip("::1")); // v6 环回
559        assert!(is_private_ip("::")); // v6 未指定
560        assert!(is_private_ip("fe80::1")); // v6 链路本地
561        assert!(is_private_ip("fc00::1")); // v6 唯一本地
562        assert!(is_private_ip("fd12::34")); // v6 唯一本地
563        assert!(is_private_ip("ff02::1")); // v6 组播
564        assert!(!is_private_ip("2606:4700::1")); // 公网 v6
565        assert!(!is_private_ip("not-an-ip")); // 解析失败 → false
566    }
567
568    #[test]
569    fn extract_client_ip_never_reads_headers() {
570        let mut headers = http::HeaderMap::new();
571        headers.insert("x-forwarded-for", "8.8.8.8".parse().unwrap());
572        let peer: SocketAddr = "127.0.0.1:1234".parse().unwrap();
573        assert_eq!(extract_client_ip(&headers, &peer), "127.0.0.1");
574    }
575
576    #[test]
577    fn trusted_proxies_parse_contains() {
578        let t = TrustedProxies::new(&[
579            "10.0.0.0/8".into(),
580            "192.168.1.10".into(), // 精确 IP → /32
581            "fc00::/7".into(),
582            "garbage".into(), // 非法项静默忽略
583            "".into(), // 空白忽略
584            "10.0.0.0/abc".into(), // 非法前缀忽略
585        ]);
586        assert!(!t.is_empty());
587        assert!(t.contains(&ip("10.1.2.3")));
588        assert!(t.contains(&ip("192.168.1.10")));
589        assert!(!t.contains(&ip("192.168.1.11"))); // /32 精确匹配
590        assert!(t.contains(&ip("fd00::1"))); // v6 唯一本地段
591        // IPv4 网段不匹配 IPv6(跨家族 → false):单独用只含 v4 的集合
592        let v4only = TrustedProxies::new(&["172.16.0.0/12".into()]);
593        assert!(!v4only.contains(&ip("::1")));
594        // /0 全匹配(单独集合,不干扰精确匹配断言)
595        let any = TrustedProxies::new(&["0.0.0.0/0".into()]);
596        assert!(any.contains(&ip("8.8.8.8")));
597        // 空集合
598        assert!(TrustedProxies::new(&[]).is_empty());
599    }
600
601    #[test]
602    fn ip_in_net_edge_prefixes() {
603        // 前缀超过地址家族上限 → 被 clamp
604        let t = TrustedProxies::new(&["10.0.0.0/99".into()]); // clamp 到 32
605        assert!(t.contains(&ip("10.0.0.0")));
606        assert!(!t.contains(&ip("10.0.0.1"))); // /32 精确
607        let t6 = TrustedProxies::new(&["fe80::/10".into()]);
608        assert!(t6.contains(&ip("fe80::1")));
609        assert!(t6.contains(&ip("febf::1"))); // /10 覆盖 fe80..febf
610        assert!(!t6.contains(&ip("fec0::1"))); // 前 10 位不同 → 不匹配
611    }
612
613    fn hm(pairs: &[(&str, &str)]) -> http::HeaderMap {
614        let mut h = http::HeaderMap::new();
615        for (k, v) in pairs {
616            h.insert(k.parse::<http::header::HeaderName>().unwrap(), v.parse().unwrap());
617        }
618        h
619    }
620
621    #[test]
622    fn extract_client_ip_trusted_paths() {
623        let trusted = TrustedProxies::new(&["127.0.0.1".into(), "10.0.0.0/8".into()]);
624        let peer_trusted: SocketAddr = "127.0.0.1:443".parse().unwrap();
625        let peer_untrusted: SocketAddr = "8.8.8.8:443".parse().unwrap();
626
627        // 直连不可信:完全忽略头部
628        let headers = hm(&[("x-forwarded-for", "1.2.3.4")]);
629        assert_eq!(
630            extract_client_ip_trusted(&headers, &peer_untrusted, &trusted),
631            "8.8.8.8"
632        );
633
634        // CF-Connecting-IP 优先
635        let headers = hm(&[("cf-connecting-ip", "203.0.113.9"), ("x-forwarded-for", "1.1.1.1")]);
636        assert_eq!(
637            extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
638            "203.0.113.9"
639        );
640
641        // CF 头是可信 IP 本身 → 继续看 XFF,从右向左取第一个公网 IP
642        let headers = hm(&[("cf-connecting-ip", "127.0.0.1"), ("x-forwarded-for", "198.51.100.7, 10.0.0.9")]);
643        assert_eq!(
644            extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
645            "198.51.100.7"
646        );
647
648        // XFF 全为内部/可信 → 回退直连 IP
649        let headers = hm(&[("x-forwarded-for", "127.0.0.1, 10.1.1.1, 192.168.5.5")]);
650        assert_eq!(
651            extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
652            "127.0.0.1"
653        );
654
655        // 非法 XFF 内容 → 回退
656        let headers = hm(&[("x-forwarded-for", "not, an, ip")]);
657        assert_eq!(
658            extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
659            "127.0.0.1"
660        );
661
662        // 无头 → 直连
663        assert_eq!(
664            extract_client_ip_trusted(&http::HeaderMap::new(), &peer_trusted, &trusted),
665            "127.0.0.1"
666        );
667    }
668
669    #[test]
670    fn webext_domain_and_path() {
671        assert_eq!(
672            WebExt::domain("http://user:pass@ex.com:8080/a/b?c=1#frag"),
673            Some("ex.com".into())
674        );
675        assert_eq!(WebExt::domain("https://ex.com"), Some("ex.com".into()));
676        assert_eq!(WebExt::domain("http://[::1]:80/x"), Some("::1".into()));
677        assert_eq!(WebExt::domain("[unclosed"), None); // 无 scheme
678        assert_eq!(WebExt::domain("http://"), None); // 空 authority
679        assert_eq!(WebExt::domain("http://[::1"), None); // 括号未闭合
680
681        assert_eq!(WebExt::path("http://ex.com/a/b?c=1"), Some("/a/b".into()));
682        assert_eq!(WebExt::path("http://ex.com"), Some("/".into()));
683        assert_eq!(WebExt::path("http://ex.com?q=1"), Some("/".into()));
684        assert_eq!(WebExt::path("http://ex.com#f"), Some("/".into()));
685        assert_eq!(WebExt::path("http://ex.com/a#f"), Some("/a".into()));
686        assert_eq!(WebExt::path("relative/path"), None); // 无 scheme
687    }
688
689    #[test]
690    fn webext_real_ip_resolution() {
691        let h = |pairs: Vec<(String, String)>| pairs;
692        // XFF 取最左侧有效 IP
693        assert_eq!(
694            WebExt::real_ip(
695                &h(vec![("X-Forwarded-For".into(), "1.2.3.4, 5.6.7.8".into())]),
696                "9.9.9.9:443"
697            ),
698            "1.2.3.4"
699        );
700        // X-Real-IP
701        assert_eq!(
702            WebExt::real_ip(&h(vec![("x-real-ip".into(), "42.42.42.42".into())]), "peer"),
703            "42.42.42.42"
704        );
705        // 非法头值 → 回退 remote_addr 各形态
706        assert_eq!(
707            WebExt::real_ip(&h(vec![("x-forwarded-for".into(), "garbage".into())]), "9.9.9.9:443"),
708            "9.9.9.9"
709        );
710        assert_eq!(WebExt::real_ip(&h(vec![]), "1.1.1.1"), "1.1.1.1"); // 裸 IP
711        assert_eq!(WebExt::real_ip(&h(vec![]), "[::1]:8080"), "::1"); // v6 socket addr
712        assert_eq!(WebExt::real_ip(&h(vec![]), "abc:123"), "abc"); // 非 IP → 截断
713        assert_eq!(WebExt::real_ip(&h(vec![]), ""), "");
714        assert!(WebExt::is_private_ip("10.0.0.1"));
715    }
716
717    #[test]
718    fn build_query_percent_encodes() {
719        assert_eq!(WebExt::build_query(&[]), "");
720        assert_eq!(
721            WebExt::build_query(&[("a b", "中/文"), ("k", "v1")]),
722            "?a%20b=%E4%B8%AD%2F%E6%96%87&k=v1"
723        );
724    }
725
726    #[test]
727    fn urldecode_invalid_utf8_falls_back() {
728        // %FF%FE 不是合法 UTF-8 → 原样返回
729        assert_eq!(WebExt::url_decode("%FF%FE"), "%FF%FE");
730        // 尾部单独 %
731        assert_eq!(WebExt::url_decode("a%"), "a%");
732    }
733}