rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
use http::HeaderMap;

use super::patterns::{self, Kind, PatternRemover};

/// 检测请求是否来自机器人; `allow_legitimate` 为 `true` 时放行合法搜索引擎爬虫
pub fn is_bot(headers: &HeaderMap, allow_legitimate: bool) -> bool {
    is_bot_user_agent(&patterns::user_agent(headers), allow_legitimate)
}

/// 检测 User-Agent 字符串是否为机器人; 空 User-Agent 视为机器人。
/// `allow_legitimate` 为 `true` 时先匹配合法爬虫白名单, 命中即放行
pub fn is_bot_user_agent(user_agent: &str, allow_legitimate: bool) -> bool {
    if user_agent.is_empty() {
        return true;
    }
    let ua = user_agent.to_lowercase();
    let p = patterns::read();

    if allow_legitimate && p.legitimate.iter().any(|pat| ua.contains(pat.as_str())) {
        return false;
    }
    p.bot.iter().any(|pat| ua.contains(pat.as_str()))
}

/// 添加自定义机器人特征 (转小写); 返回的句柄可移除该特征
pub fn add_custom_bot_pattern(pattern: &str) -> PatternRemover {
    patterns::add(Kind::Bot, pattern)
}

/// 添加自定义合法爬虫特征 (转小写); 返回的句柄可移除该特征
pub fn add_legitimate_bot(pattern: &str) -> PatternRemover {
    patterns::add(Kind::Legitimate, pattern)
}

/// 当前机器人特征列表 (副本)
pub fn bot_patterns() -> Vec<String> {
    patterns::snapshot(Kind::Bot)
}

/// 当前合法爬虫特征列表 (副本)
pub fn legitimate_patterns() -> Vec<String> {
    patterns::snapshot(Kind::Legitimate)
}

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

    #[test]
    fn detects_bots() {
        let cases = [
            ("", false, true),
            ("python-requests/2.31.0", false, true),
            ("curl/8.4.0", false, true),
            ("Wget/1.21", false, true),
            ("Go-http-client/1.1", false, true),
            ("sqlmap/1.7", false, true),
            ("Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/120.0", false, true),
            (
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
                false,
                true,
            ),
            (
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
                true,
                false,
            ),
            ("Mozilla/5.0 (compatible; Baiduspider/2.0)", true, false),
            ("TelegramBot (like TwitterBot)", true, false),
            ("SomeRandomCrawler/1.0", true, true),
            (
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36",
                false,
                false,
            ),
        ];
        for (ua, allow, want) in cases {
            assert_eq!(is_bot_user_agent(ua, allow), want, "{ua:?} allow={allow}");
        }
    }

    #[test]
    fn reads_header() {
        let mut h = HeaderMap::new();
        assert!(is_bot(&h, true));
        h.insert("user-agent", "curl/8".parse().unwrap());
        assert!(is_bot(&h, true));
    }

    #[test]
    fn custom_patterns() {
        let ua = "MyInternalMonitorXYZ/1.0";
        assert!(!is_bot_user_agent(ua, false));
        let remover = add_custom_bot_pattern("InternalMonitorXYZ");
        assert!(bot_patterns().contains(&"internalmonitorxyz".to_owned()));
        assert!(is_bot_user_agent(ua, false));
        remover.remove();
        assert!(!is_bot_user_agent(ua, false));

        let legit_ua = "PartnerFetchBotQRS/2.0";
        assert!(is_bot_user_agent(legit_ua, true));
        let remover = add_legitimate_bot("partnerfetchbotqrs");
        assert!(legitimate_patterns().contains(&"partnerfetchbotqrs".to_owned()));
        assert!(!is_bot_user_agent(legit_ua, true));
        assert!(is_bot_user_agent(legit_ua, false));
        remover.remove();
        assert!(is_bot_user_agent(legit_ua, true));
    }

    #[test]
    fn concurrent_add_and_detect() {
        let handles: Vec<_> = (0..8)
            .map(|i| {
                std::thread::spawn(move || {
                    for j in 0..200 {
                        let r = add_custom_bot_pattern(&format!("concurrency-{i}-{j}"));
                        let _ = is_bot_user_agent("Mozilla/5.0 Chrome/130.0", true);
                        r.remove();
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        assert!(!bot_patterns().iter().any(|p| p.starts_with("concurrency-")));
    }
}