Skip to main content

Module user_agent

Module user_agent 

Source
Expand description

The blocked user-agent pattern filter.

This is the Rust family’s port of the reference engine’s user-agent matching (guard_core/core/checks/helpers.py::check_user_agent_allowed and guard_core/_utils/access_control.py::is_user_agent_allowed, backed by guard_core/_utils/detection_scan.py::_user_agent_matches_blocked_pattern). One call, UserAgentFilter::is_blocked, answers whether a User-Agent header value matches any configured blocked pattern:

subject = user_agent truncated to the first 512 code points
blocked = any pattern matches the subject (search semantics,
          case-insensitive, multiline)

The config constructor mirrors the reference’s _validate_blocked_user_agents_value: every entry is a regular expression, and a pattern the ReDoS validator flags is a config error (the reference raises ValueError at config construction). This port also fails closed on an entry the regex engine cannot compile - the reference would instead raise at request time and trip the pipeline’s fail-secure 500, so the failure moves earlier without changing what a valid config does.

Matching semantics mirror the reference compiler exactly: the Python side compiles with re.IGNORECASE | re.MULTILINE and scans with finditer (search semantics, not fullmatch), and the 512-code-point truncation is _MAX_USER_AGENT_MATCH_LENGTH. Patterns are evaluated in configured order and the first match wins.

§Example

use guard_core_engine::user_agent::UserAgentFilter;

let filter = UserAgentFilter::new(["sqlmap", r"^\S*\(compatible; Googlebot\)"])
    .expect("valid patterns");

// Search semantics: a substring match is enough, case-insensitively.
assert!(filter.is_blocked("Mozilla/5.0 (sqlmap/1.8)"));
assert!(filter.is_blocked("SQLMAP"));
assert!(!filter.is_blocked("Mozilla/5.0 (X11; Linux x86_64)"));

// A missing User-Agent header reads as the empty string, which only a
// pattern targeting emptiness can block.
assert!(!filter.is_blocked(""));

// The default (no patterns) never blocks.
assert!(!UserAgentFilter::default().is_blocked("sqlmap"));

Structs§

UserAgentConfigError
An invalid blocked_user_agents entry: the config error UserAgentFilter::new fails closed with.
UserAgentFilter
The compiled blocked user-agent patterns.

Constants§

MAX_USER_AGENT_MATCH_LENGTH
The match subject cap: a User-Agent header value is truncated to its first 512 code points before pattern evaluation (_MAX_USER_AGENT_MATCH_LENGTH in the reference).