Skip to main content

guard_core_engine/
user_agent.rs

1//! The blocked user-agent pattern filter.
2//!
3//! This is the Rust family's port of the reference engine's user-agent
4//! matching (`guard_core/core/checks/helpers.py::check_user_agent_allowed`
5//! and `guard_core/_utils/access_control.py::is_user_agent_allowed`, backed
6//! by `guard_core/_utils/detection_scan.py::_user_agent_matches_blocked_pattern`).
7//! One call, [`UserAgentFilter::is_blocked`], answers whether a
8//! `User-Agent` header value matches any configured blocked pattern:
9//!
10//! ```text
11//! subject = user_agent truncated to the first 512 code points
12//! blocked = any pattern matches the subject (search semantics,
13//!           case-insensitive, multiline)
14//! ```
15//!
16//! The config constructor mirrors the reference's
17//! `_validate_blocked_user_agents_value`: every entry is a regular
18//! expression, and a pattern the ReDoS validator flags is a config error
19//! (the reference raises `ValueError` at config construction). This port
20//! also fails closed on an entry the regex engine cannot compile - the
21//! reference would instead raise at request time and trip the pipeline's
22//! fail-secure 500, so the failure moves earlier without changing what a
23//! valid config does.
24//!
25//! Matching semantics mirror the reference compiler exactly: the Python
26//! side compiles with `re.IGNORECASE | re.MULTILINE` and scans with
27//! `finditer` (search semantics, not fullmatch), and the 512-code-point
28//! truncation is `_MAX_USER_AGENT_MATCH_LENGTH`. Patterns are evaluated in
29//! configured order and the first match wins.
30//!
31//! # Example
32//!
33//! ```
34//! use guard_core_engine::user_agent::UserAgentFilter;
35//!
36//! let filter = UserAgentFilter::new(["sqlmap", r"^\S*\(compatible; Googlebot\)"])
37//!     .expect("valid patterns");
38//!
39//! // Search semantics: a substring match is enough, case-insensitively.
40//! assert!(filter.is_blocked("Mozilla/5.0 (sqlmap/1.8)"));
41//! assert!(filter.is_blocked("SQLMAP"));
42//! assert!(!filter.is_blocked("Mozilla/5.0 (X11; Linux x86_64)"));
43//!
44//! // A missing User-Agent header reads as the empty string, which only a
45//! // pattern targeting emptiness can block.
46//! assert!(!filter.is_blocked(""));
47//!
48//! // The default (no patterns) never blocks.
49//! assert!(!UserAgentFilter::default().is_blocked("sqlmap"));
50//! ```
51
52use std::fmt;
53
54use regex::Regex;
55
56use crate::compiler;
57
58/// The match subject cap: a `User-Agent` header value is truncated to its
59/// first 512 code points before pattern evaluation
60/// (`_MAX_USER_AGENT_MATCH_LENGTH` in the reference).
61pub const MAX_USER_AGENT_MATCH_LENGTH: usize = 512;
62
63/// An invalid `blocked_user_agents` entry: the config error
64/// [`UserAgentFilter::new`] fails closed with.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct UserAgentConfigError {
67    /// The rejected pattern.
68    pub entry: String,
69    /// Why it was rejected (the ReDoS validator's reason, or the compile
70    /// error).
71    pub reason: String,
72}
73
74impl fmt::Display for UserAgentConfigError {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(
77            f,
78            "invalid blocked_user_agents pattern '{}': {}",
79            self.entry, self.reason
80        )
81    }
82}
83
84impl std::error::Error for UserAgentConfigError {}
85
86/// The compiled blocked user-agent patterns.
87///
88/// Build it once at startup with [`UserAgentFilter::new`] (which fails
89/// closed on an unsafe or uncompilable pattern) and evaluate header values
90/// with [`UserAgentFilter::is_blocked`]. The default value holds no
91/// patterns and never blocks. Cheap to clone; clones share the compiled
92/// regexes.
93#[derive(Debug, Clone, Default)]
94pub struct UserAgentFilter {
95    patterns: Vec<Regex>,
96}
97
98impl UserAgentFilter {
99    /// Compile and validate the blocked patterns, failing closed on the
100    /// first rejected entry.
101    ///
102    /// Every entry is validated with the engine's ReDoS validator (the
103    /// reference's `validate_pattern_safety`, max content length 512) and
104    /// compiled case-insensitive + multiline, the reference compiler's
105    /// flags.
106    ///
107    /// # Errors
108    ///
109    /// [`UserAgentConfigError`] naming the first entry that is flagged
110    /// ReDoS-unsafe or that the regex engine cannot compile.
111    pub fn new<I, S>(patterns: I) -> Result<Self, UserAgentConfigError>
112    where
113        I: IntoIterator<Item = S>,
114        S: AsRef<str>,
115    {
116        let mut compiled = Vec::new();
117        for pattern in patterns {
118            let pattern = pattern.as_ref();
119            let verdict = crate::redos::validate_pattern_safety(
120                pattern,
121                &crate::redos::SafetyMode::CostVerdict {
122                    // The reference validates UA rules against the max
123                    // user-agent match length (512).
124                    max_content_length: Some(MAX_USER_AGENT_MATCH_LENGTH),
125                },
126            );
127            let (is_safe, reason) = (verdict.safe, verdict.reason.to_string());
128            if !is_safe {
129                return Err(UserAgentConfigError {
130                    entry: pattern.to_owned(),
131                    reason: format!("rejected by ReDoS validator ({reason})"),
132                });
133            }
134            let regex = compiler::compile(pattern).map_err(|error| UserAgentConfigError {
135                entry: pattern.to_owned(),
136                reason: format!("expected a compilable regular expression ({error})"),
137            })?;
138            compiled.push(regex);
139        }
140        Ok(Self { patterns: compiled })
141    }
142
143    /// Whether the `User-Agent` value matches any blocked pattern.
144    ///
145    /// The subject is the value truncated to its first
146    /// [`MAX_USER_AGENT_MATCH_LENGTH`] code points (the reference's
147    /// `_MAX_USER_AGENT_MATCH_LENGTH` slice); matching is search semantics
148    /// under the reference's case-insensitive + multiline flags. A missing
149    /// header reads as the empty string.
150    #[must_use]
151    pub fn is_blocked(&self, user_agent: &str) -> bool {
152        let subject: String = user_agent
153            .chars()
154            .take(MAX_USER_AGENT_MATCH_LENGTH)
155            .collect();
156        self.patterns.iter().any(|regex| regex.is_match(&subject))
157    }
158
159    /// How many patterns the filter holds.
160    #[must_use]
161    pub const fn len(&self) -> usize {
162        self.patterns.len()
163    }
164
165    /// Whether the filter holds no patterns (it never blocks).
166    #[must_use]
167    pub const fn is_empty(&self) -> bool {
168        self.patterns.is_empty()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn default_filter_is_empty_and_never_blocks() {
178        let filter = UserAgentFilter::default();
179        assert!(filter.is_empty());
180        assert_eq!(filter.len(), 0);
181        for agent in ["sqlmap", "", "Mozilla/5.0"] {
182            assert!(
183                !filter.is_blocked(agent),
184                "{agent} must pass an empty filter"
185            );
186        }
187    }
188
189    #[test]
190    fn matches_are_search_semantics_case_insensitive() {
191        let filter = UserAgentFilter::new(["sqlmap", "havij"]).expect("valid patterns");
192        assert_eq!(filter.len(), 2);
193        assert!(filter.is_blocked("sqlmap"));
194        assert!(filter.is_blocked("Mozilla/5.0 (SQLMAP/1.8)"));
195        assert!(filter.is_blocked("user agent: HaViJ probe"));
196        assert!(
197            filter.is_blocked("innocent-looking sqlmapbot client"),
198            "search semantics: any substring occurrence is enough"
199        );
200        assert!(!filter.is_blocked("Mozilla/5.0 (X11; Linux x86_64)"));
201    }
202
203    #[test]
204    fn patterns_are_multiline_and_anchored_patterns_behave_like_python() {
205        // ^ with MULTILINE anchors per line, like the reference compiler's
206        // re.IGNORECASE | re.MULTILINE.
207        let filter = UserAgentFilter::new(["^bot/"]).expect("valid pattern");
208        assert!(filter.is_blocked("bot/1.0"));
209        assert!(!filter.is_blocked("see bot/1.0"));
210    }
211
212    #[test]
213    fn subject_is_truncated_to_512_code_points() {
214        let filter = UserAgentFilter::new(["tail-marker"]).expect("valid pattern");
215        let mut agent = "a".repeat(600);
216        agent.push_str(" tail-marker");
217        assert!(
218            !filter.is_blocked(&agent),
219            "a match living past the 512-code-point cap must not block"
220        );
221        let mut inside = "x".repeat(500);
222        inside.push_str(" tail-marker");
223        assert!(
224            filter.is_blocked(&inside),
225            "a match inside the cap must block"
226        );
227        // Code points, not bytes: the cap lands past a multi-byte prefix.
228        let mut multibyte = "\u{00e9}".repeat(500);
229        multibyte.push_str("tail-marker");
230        assert!(filter.is_blocked(&multibyte));
231    }
232
233    #[test]
234    fn missing_header_reads_as_the_empty_string() {
235        let filter = UserAgentFilter::new(["^$"]).expect("valid pattern");
236        assert!(filter.is_blocked(""), "an empty value matches ^$");
237        assert!(!filter.is_blocked("Mozilla/5.0"));
238    }
239
240    #[test]
241    fn new_fails_closed_on_an_uncompilable_pattern() {
242        // The full safety chain validates every entry first, so an
243        // uncompilable pattern is rejected there (the validator subsumes
244        // the compile check).
245        let error = UserAgentFilter::new(["(unclosed"]).unwrap_err();
246        assert_eq!(error.entry, "(unclosed");
247        assert!(
248            error.reason.starts_with("rejected by ReDoS validator ("),
249            "unexpected reason: {}",
250            error.reason
251        );
252        assert!(
253            error
254                .to_string()
255                .starts_with("invalid blocked_user_agents pattern '(unclosed':"),
256            "unexpected display: {error}"
257        );
258    }
259
260    #[test]
261    fn new_fails_closed_on_a_redos_unsafe_pattern() {
262        // Nested quantifiers are the canonical catastrophic-backtracking
263        // shape the reference validator rejects.
264        let error = UserAgentFilter::new(["(a+)+b"]).unwrap_err();
265        assert_eq!(error.entry, "(a+)+b");
266        assert!(
267            error.reason.contains("rejected by ReDoS validator"),
268            "unexpected reason: {}",
269            error.reason
270        );
271        assert!(
272            error
273                .to_string()
274                .starts_with("invalid blocked_user_agents pattern '(a+)+b':")
275        );
276    }
277
278    #[test]
279    fn first_rejected_entry_wins_and_valid_prefixes_are_not_retained() {
280        let error = UserAgentFilter::new(["sqlmap", "(bad", "worse]"]).unwrap_err();
281        assert_eq!(error.entry, "(bad");
282    }
283
284    #[test]
285    fn clone_shares_nothing_observable() {
286        let filter = UserAgentFilter::new(["sqlmap"]).expect("valid pattern");
287        let clone = filter.clone();
288        assert!(clone.is_blocked("SQLMAP"));
289        assert_eq!(clone.len(), filter.len());
290    }
291
292    #[test]
293    fn a_chain_safe_pattern_the_engine_cannot_compile_is_rejected() {
294        // Lookarounds pass the Python-syntax safety chain but the concrete
295        // engine compiler rejects them, so the config constructor fails.
296        let error = UserAgentFilter::new(["(?=x)a"]).expect_err("rejected");
297        assert_eq!(error.entry, "(?=x)a");
298        assert!(
299            error
300                .reason
301                .starts_with("expected a compilable regular expression"),
302            "{}",
303            error.reason
304        );
305    }
306}