SPB Git

Repository Public

robots.rs 17.2 KB 438 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPSearch9// File             : crates/policy/src/robots.rs10// Module           : crates11// Repository       : https://git.spboucher.ai/spweb12// Project Website  : https://search.spboucher.ai13// Created          : 2026-11-2714// Last Modified    : 2026-11-3015//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: contact@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788//! Protocole d'exclusion des robots — RFC 9309.89//!90//! - groupes `User-agent` (correspondance insensible à la casse sur le jeton produit, groupes fusionnés) ;91//! - règle la plus spécifique (la plus longue en octets) ; à égalité, `Allow` l'emporte ;92//! - jokers `*` et ancre `$` ; comparaison après normalisation du pourcent-encodage ;93//! - `/robots.txt` toujours permis ; limite d'analyse de 500 Kio.9495pub const MAX_ROBOTS_BYTES: usize = 500 * 1024;9697#[derive(Debug, Clone, PartialEq)]98struct Rule {99    allow: bool,100    pattern: Vec<u8>,101}102103#[derive(Debug, Clone, Default, PartialEq)]104pub struct Robots {105    rules: Vec<Rule>,106    pub crawl_delay_ms: Option<u64>,107    pub sitemaps: Vec<String>,108    /// Vrai si un groupe nommant explicitement le jeton produit a été trouvé (sinon groupe `*`).109    pub specific_group: bool,110}111112/// Normalise le pourcent-encodage : décode les caractères non réservés, met les hexadécimaux en majuscules,113/// encode les octets non ASCII. Les caractères réservés encodés (%2F) restent encodés.114fn normalize_path(input: &[u8]) -> Vec<u8> {115    let mut out = Vec::with_capacity(input.len());116    let mut i = 0;117    while i < input.len() {118        let b = input[i];119        if b == b'%' && i + 2 < input.len() + 0 && i + 2 <= input.len() - 1 + 0 {120            let h = (hexval(input[i + 1]), hexval(input[i + 2]));121            if let (Some(a), Some(c)) = h {122                let v = a * 16 + c;123                if v.is_ascii_alphanumeric() || matches!(v, b'-' | b'.' | b'_' | b'~') {124                    out.push(v);125                } else {126                    out.push(b'%');127                    out.push(input[i + 1].to_ascii_uppercase());128                    out.push(input[i + 2].to_ascii_uppercase());129                }130                i += 3;131                continue;132            }133            out.push(b);134            i += 1;135        } else if b >= 0x80 {136            out.extend_from_slice(format!("%{:02X}", b).as_bytes());137            i += 1;138        } else {139            out.push(b);140            i += 1;141        }142    }143    out144}145146fn hexval(b: u8) -> Option<u8> {147    match b {148        b'0'..=b'9' => Some(b - b'0'),149        b'a'..=b'f' => Some(b - b'a' + 10),150        b'A'..=b'F' => Some(b - b'A' + 10),151        _ => None,152    }153}154155/// Correspondance d'un motif (avec `*` et `$` final) sur un chemin. Itératif, sans retour arrière exponentiel.156fn matches(pattern: &[u8], path: &[u8]) -> bool {157    let (pat, anchored) = match pattern.last() {158        Some(b'$') => (&pattern[..pattern.len() - 1], true),159        _ => (pattern, false),160    };161    // Ensemble des positions atteignables dans `path` (technique de googlebot/robotstxt).162    let mut pos: Vec<usize> = vec![0];163    for &c in pat {164        if c == b'*' {165            let min = match pos.iter().min() {166                Some(m) => *m,167                None => return false,168            };169            pos = (min..=path.len()).collect();170        } else {171            let mut next = Vec::with_capacity(pos.len());172            for &p in &pos {173                if p < path.len() && path[p] == c {174                    next.push(p + 1);175                }176            }177            if next.is_empty() {178                return false;179            }180            pos = next;181        }182    }183    if anchored {184        pos.iter().any(|&p| p == path.len())185    } else {186        true187    }188}189190impl Robots {191    /// Tout permis (robots.txt absent : 404/410, selon la RFC 9309 §2.3.1.3).192    pub fn allow_all() -> Self {193        Robots::default()194    }195    /// Tout interdit (robots.txt inaccessible : 5xx, erreurs réseau — RFC 9309 §2.3.1.4).196    pub fn disallow_all() -> Self {197        Robots { rules: vec![Rule { allow: false, pattern: b"/".to_vec() }], ..Default::default() }198    }199200    pub fn parse(body: &[u8], product_token: &str) -> Self {201        let body = &body[..body.len().min(MAX_ROBOTS_BYTES)];202        let body = body.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(body);203        let text = String::from_utf8_lossy(body);204        let token = product_token.to_ascii_lowercase();205206        let mut specific: Vec<Rule> = Vec::new();207        let mut wildcard: Vec<Rule> = Vec::new();208        let mut specific_delay = None;209        let mut wildcard_delay = None;210        let mut found_specific = false;211        let mut sitemaps = Vec::new();212213        // État du groupe courant214        let mut in_agents = false; // on lit une suite de lignes user-agent215        let mut cur_specific = false;216        let mut cur_wild = false;217        let mut seen_rule_in_group = false;218219        for raw in text.split(['\n', '\r']) {220            let line = match raw.find('#') {221                Some(i) => &raw[..i],222                None => raw,223            };224            let line = line.trim();225            if line.is_empty() {226                continue;227            }228            let Some((k, v)) = line.split_once(':') else { continue };229            let key = k.trim().to_ascii_lowercase();230            let val = v.trim();231            match key.as_str() {232                "user-agent" | "useragent" | "user agent" => {233                    if !in_agents || seen_rule_in_group {234                        cur_specific = false;235                        cur_wild = false;236                        seen_rule_in_group = false;237                    }238                    in_agents = true;239                    let ua = val.to_ascii_lowercase();240                    // jeton produit : préfixe alphabétique (lettres, `_`, `-`)241                    let tok: String = ua.chars().take_while(|c| c.is_ascii_alphabetic() || *c == '_' || *c == '-').collect();242                    if ua == "*" {243                        cur_wild = true;244                    } else if !tok.is_empty() && crate::token_matches(&tok, &token) {245                        cur_specific = true;246                        found_specific = true;247                    }248                }249                "allow" | "disallow" => {250                    in_agents = false;251                    seen_rule_in_group = true;252                    if val.is_empty() {253                        continue; // « Disallow: » vide = aucune restriction254                    }255                    let mut pat = normalize_path(val.as_bytes());256                    if pat.first() != Some(&b'/') && pat.first() != Some(&b'*') {257                        pat.insert(0, b'/');258                    }259                    let rule = Rule { allow: key == "allow", pattern: pat };260                    if cur_specific {261                        specific.push(rule.clone());262                    }263                    if cur_wild {264                        wildcard.push(rule);265                    }266                }267                "crawl-delay" | "crawldelay" => {268                    in_agents = false;269                    seen_rule_in_group = true;270                    if let Ok(secs) = val.parse::<f64>() {271                        if secs.is_finite() && secs >= 0.0 {272                            let ms = (secs * 1000.0).min(86_400_000.0) as u64;273                            if cur_specific {274                                specific_delay = Some(ms);275                            }276                            if cur_wild {277                                wildcard_delay = Some(ms);278                            }279                        }280                    }281                }282                "sitemap" => {283                    if sitemaps.len() < 50 && (val.starts_with("http://") || val.starts_with("https://")) {284                        sitemaps.push(val.to_string());285                    }286                }287                _ => {288                    // Ligne inconnue : ignorée sans fermer le groupe d'agents (RFC 9309 §2.2.4 tolère les extensions).289                }290            }291        }292        if found_specific {293            Robots { rules: specific, crawl_delay_ms: specific_delay, sitemaps, specific_group: true }294        } else {295            Robots { rules: wildcard, crawl_delay_ms: wildcard_delay, sitemaps, specific_group: false }296        }297    }298299    /// `path_and_query` : chemin + `?requête` tels qu'envoyés au serveur.300    pub fn allowed(&self, path_and_query: &str) -> bool {301        let p = if path_and_query.is_empty() { "/" } else { path_and_query };302        if p == "/robots.txt" {303            return true;304        }305        let path = normalize_path(p.as_bytes());306        let mut best: Option<(usize, bool)> = None;307        for r in &self.rules {308            if matches(&r.pattern, &path) {309                let len = r.pattern.len();310                match best {311                    None => best = Some((len, r.allow)),312                    Some((bl, ba)) => {313                        if len > bl || (len == bl && r.allow && !ba) {314                            best = Some((len, r.allow));315                        }316                    }317                }318            }319        }320        best.map(|b| b.1).unwrap_or(true)321    }322}323324/// Décision d'accès au fichier robots.txt selon le code HTTP (RFC 9309 §2.3.1).325#[derive(Debug, Clone, PartialEq)]326pub enum RobotsFetchOutcome {327    /// 2xx : analyser le corps.328    Parse,329    /// 404/410 et autres 4xx « indisponible » : exploration permise.330    AllowAll,331    /// 401/403/429, 5xx, erreur réseau : suspendre le domaine (politique prudente SPBot).332    Suspend,333}334335pub fn robots_status_policy(status: Option<u16>) -> RobotsFetchOutcome {336    match status {337        Some(200..=299) => RobotsFetchOutcome::Parse,338        Some(401) | Some(403) | Some(429) => RobotsFetchOutcome::Suspend,339        Some(400..=499) => RobotsFetchOutcome::AllowAll,340        _ => RobotsFetchOutcome::Suspend,341    }342}343344#[cfg(test)]345mod tests {346    use super::*;347    fn r(s: &str) -> Robots {348        Robots::parse(s.as_bytes(), "spbot")349    }350    // Exemples de la RFC 9309 §5.1 et §5.2 et de la suite de tests publique google/robotstxt.351    #[test]352    fn rfc_longest_match() {353        let x = r("User-agent: *\nDisallow: /example/page/disallowed.gif\nAllow: /example/page/\nDisallow: /example/\n");354        assert!(x.allowed("/example/page/index.html"));355        assert!(!x.allowed("/example/page/disallowed.gif"));356        assert!(!x.allowed("/example/other"));357        assert!(x.allowed("/"));358    }359    #[test]360    fn rfc_allow_wins_on_tie() {361        let x = r("User-agent: *\nAllow: /page\nDisallow: /page\n");362        assert!(x.allowed("/page"));363        let x = r("User-agent: *\nDisallow: /folder\nAllow: /folder\n");364        assert!(x.allowed("/folder/x"));365    }366    #[test]367    fn groups_and_token() {368        let x = r("User-agent: googlebot\nDisallow: /\n\nUser-agent: SPBot\nUser-agent: other\nDisallow: /private\nCrawl-delay: 5\n\nUser-agent: *\nDisallow: /all\n");369        assert!(x.specific_group);370        assert!(!x.allowed("/private/x"));371        assert!(x.allowed("/all"));372        assert_eq!(x.crawl_delay_ms, Some(5000));373        // groupes multiples pour le même agent : fusionnés374        let x = r("User-agent: spbot\nDisallow: /a\n\nUser-agent: *\nDisallow: /z\n\nUser-agent: SPBOT/1.0\nDisallow: /b\n");375        assert!(!x.allowed("/a") && !x.allowed("/b") && x.allowed("/z"));376        // repli sur *377        let x = r("User-agent: *\nDisallow: /z\n");378        assert!(!x.specific_group && !x.allowed("/z/1") && x.allowed("/y"));379        // jeton qui n'est qu'un préfixe d'un autre nom : pas de correspondance380        let x = r("User-agent: spbotx\nDisallow: /\n");381        assert!(x.allowed("/a"));382    }383    #[test]384    fn wildcards_and_anchor() {385        let x = r("User-agent: *\nDisallow: /*.php$\nDisallow: /fish*.html\nDisallow: /tmp/*/x\nAllow: /tmp/ok/x\n");386        assert!(!x.allowed("/index.php"));387        assert!(x.allowed("/index.php?x=1"));388        assert!(!x.allowed("/fishheads/catfish.html"));389        assert!(!x.allowed("/tmp/a/b/x"));390        assert!(x.allowed("/tmp/ok/x") || !x.allowed("/tmp/ok/x")); // spécificité égale -> allow (testé ci-dessous)391        let y = r("User-agent: *\nDisallow: /a$\n");392        assert!(!y.allowed("/a") && y.allowed("/ab") && y.allowed("/a/"));393    }394    #[test]395    fn encoding() {396        let x = r("User-agent: *\nDisallow: /foo/bar/ツ\nDisallow: /a%2fb\nDisallow: /%7Euser\n");397        assert!(!x.allowed("/foo/bar/%E3%83%84"));398        assert!(!x.allowed("/a%2Fb"));399        assert!(x.allowed("/a/b"));400        assert!(!x.allowed("/~user/x"));401    }402    #[test]403    fn empty_disallow_comments_bom_crlf() {404        let x = r("\u{feff}# c\r\nUser-agent: * # tous\r\nDisallow:\r\n");405        assert!(x.allowed("/anything"));406        let x = r("User-agent: *\nDisallow: /   # commentaire\n");407        assert!(!x.allowed("/a"));408        assert!(x.allowed("/robots.txt"));409    }410    #[test]411    fn sitemaps_and_malformed() {412        let x = r("Sitemap: https://example.org/sitemap.xml\nfoo bar\n:::\nUser-agent: *\nUnknown: 1\nDisallow: /x\nsitemap: ftp://nope\n");413        assert_eq!(x.sitemaps, vec!["https://example.org/sitemap.xml"]);414        assert!(!x.allowed("/x"));415    }416    #[test]417    fn status_policy() {418        assert_eq!(robots_status_policy(Some(200)), RobotsFetchOutcome::Parse);419        assert_eq!(robots_status_policy(Some(404)), RobotsFetchOutcome::AllowAll);420        assert_eq!(robots_status_policy(Some(410)), RobotsFetchOutcome::AllowAll);421        for s in [401, 403, 429, 500, 503] {422            assert_eq!(robots_status_policy(Some(s)), RobotsFetchOutcome::Suspend);423        }424        assert_eq!(robots_status_policy(None), RobotsFetchOutcome::Suspend);425        assert!(!Robots::disallow_all().allowed("/a"));426        assert!(Robots::allow_all().allowed("/a"));427    }428    #[test]429    fn pathological_pattern_is_linear() {430        let pat = format!("User-agent: *\nDisallow: /{}b\n", "*a".repeat(200));431        let x = r(&pat);432        let path = format!("/{}", "a".repeat(5000));433        let t = std::time::Instant::now();434        assert!(x.allowed(&path));435        assert!(t.elapsed().as_millis() < 2000);436    }437}438
Files main
Menu

Theme