From 15f3fcb895c5be1e525da7f4093c8a00959e6b95 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Mon, 16 Nov 2026 13:11:31 +0100 Subject: [PATCH] refactor(subnet): split verdict enforcement out of the monitor monitor.rs reached 257 lines after the trusted-network suppression (limit is 250). BanPolicy, enforce_tracker_verdicts, ban_xdp_verdicts and prefix_len move to src/engine/subnet/enforce.rs; the monitor keeps the task, source selection and verdict logging, re-exporting enforce_tracker_verdicts so existing paths stay valid. Also documents the new tests/edge_e2e.rs scenarios in docs/testing.md. --- docs/testing.md | 8 +++ src/engine/subnet/enforce.rs | 108 +++++++++++++++++++++++++++++++++++ src/engine/subnet/mod.rs | 1 + src/engine/subnet/monitor.rs | 105 ++-------------------------------- 4 files changed, 122 insertions(+), 100 deletions(-) create mode 100644 src/engine/subnet/enforce.rs diff --git a/docs/testing.md b/docs/testing.md index 2a7582f..5c3b685 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -31,6 +31,14 @@ cargo clippy --all-targets --all-features -- -D warnings cargo deny check ``` +E2E-сценарии живут в `tests/edge_e2e.rs`: реальный TCP-клиент через продакшн-accept-loop и +pipeline до upstream на loopback (обычный HTTP, PoW с решённым и неверным nonce, rate-limit, +blacklist). Root и внешняя сеть не нужны, каждый тест укладывается в 5 с: + +```bash +cargo test --all-features --test edge_e2e +``` + XDP: smoke-check компиляции BPF-программы: ```bash diff --git a/src/engine/subnet/enforce.rs b/src/engine/subnet/enforce.rs new file mode 100644 index 0000000..70632ef --- /dev/null +++ b/src/engine/subnet/enforce.rs @@ -0,0 +1,108 @@ +//! Verdict enforcement: turning subnet `Block` verdicts into bans. +//! +//! Kept apart from [`super::monitor`] so the monitor task and the ban policy +//! stay within the module-size budget. + +use crate::filter::blacklist::Blacklist; +use crate::traffic::prefix::{PrefixVerdict, SubnetVerdict}; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; + +/// Verdict enforcement settings shared by every snapshot tick. +pub(super) struct BanPolicy { + pub(super) blacklist: Arc, + pub(super) ttl: Duration, + pub(super) trusted: bool, + /// Trusted PROXY-protocol networks; a prefix ban overlapping one of them is + /// suppressed, because it would punish the proxy and every client behind it. + pub(super) trusted_networks: Vec, +} + +/// Applies userspace `Block` verdicts to the shared blacklist. +/// +/// Returns the number of banned prefixes. When `trusted` is false the observed +/// addresses belong to an unverified ingress path, so the verdict is only logged +/// at warn level and no ban is installed. +/// +/// The ban is inserted as a CIDR range, so every address inside the detected +/// `/24` or `/64` is blocked, not just its network address. +pub fn enforce_tracker_verdicts( + verdicts: &[PrefixVerdict], + blacklist: &Blacklist, + ttl: Duration, + trusted: bool, + trusted_networks: &[crate::config::TrustedProxyCidr], +) -> usize { + let mut banned = 0; + for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { + if !trusted { + tracing::warn!( + prefix = %pv.prefix, + "subnet block verdict on an untrusted peer path; not adding to the blacklist" + ); + continue; + } + if overlaps_trusted(pv.prefix, trusted_networks) { + tracing::warn!( + prefix = %pv.prefix, + "subnet ban suppressed: the prefix contains a trusted proxy network" + ); + continue; + } + blacklist.add_cidr(pv.prefix, prefix_len(pv.prefix), ttl, "subnet_attack"); + banned += 1; + tracing::warn!( + prefix = %pv.prefix, + ttl_secs = ttl.as_secs(), + "subnet blocked in the userspace blacklist" + ); + } + banned +} + +/// Installs XDP prefix bans for `Block` verdicts. +#[cfg(feature = "xdp")] +pub(super) fn ban_xdp_verdicts( + xdp: &crate::traffic::prefix::XdpPrefixStats, + verdicts: &[PrefixVerdict], + ttl: Duration, + trusted_networks: &[crate::config::TrustedProxyCidr], +) { + for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { + if overlaps_trusted(pv.prefix, trusted_networks) { + tracing::warn!( + prefix = %pv.prefix, + "subnet kernel ban suppressed: the prefix contains a trusted proxy network" + ); + continue; + } + let result = { + let guard = xdp.filter_lock(); + guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), ttl.as_secs()) + }; + match result { + Ok(()) => tracing::warn!( + prefix = %pv.prefix, + ttl_secs = ttl.as_secs(), + "subnet blocked in XDP" + ), + Err(e) => tracing::warn!("subnet block failed for {}: {e}", pv.prefix), + } + } +} + +/// Returns whether a ban of `prefix/prefix_len` would cover a trusted proxy. +fn overlaps_trusted(prefix: IpAddr, trusted_networks: &[crate::config::TrustedProxyCidr]) -> bool { + trusted_networks + .iter() + .any(|net| net.overlaps_prefix(prefix, prefix_len(prefix))) +} + +/// Prefix length matching the detection granularity (v4 /24, v6 /64). +pub(super) fn prefix_len(prefix: IpAddr) -> u8 { + match prefix { + IpAddr::V4(_) => 24, + IpAddr::V6(_) => 64, + } +} diff --git a/src/engine/subnet/mod.rs b/src/engine/subnet/mod.rs index ef35227..c760ca4 100644 --- a/src/engine/subnet/mod.rs +++ b/src/engine/subnet/mod.rs @@ -1,3 +1,4 @@ //! Subnet-level detector: userspace prefix aggregator and verdict monitor. +mod enforce; pub mod monitor; pub mod tracker; diff --git a/src/engine/subnet/monitor.rs b/src/engine/subnet/monitor.rs index 3a55e58..c954d61 100644 --- a/src/engine/subnet/monitor.rs +++ b/src/engine/subnet/monitor.rs @@ -4,6 +4,9 @@ //! (feature `xdp` with a loaded filter) or the userspace aggregator //! [`SubnetTracker`]. +use super::enforce::BanPolicy; +#[cfg(feature = "xdp")] +use super::enforce::ban_xdp_verdicts; use crate::config::DetectPrefixConfig; use crate::engine::subnet_tracker::{SubnetTracker, TrackerSource}; use crate::filter::blacklist::Blacklist; @@ -17,6 +20,8 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::watch; +pub use super::enforce::enforce_tracker_verdicts; + enum Source { #[cfg(feature = "xdp")] Xdp(XdpPrefixStats), @@ -33,22 +38,6 @@ impl Source { } } -/// Verdict enforcement settings shared by every snapshot tick. -struct BanPolicy { - blacklist: Arc, - ttl: Duration, - trusted: bool, - /// Trusted PROXY-protocol networks; a prefix ban overlapping one of them is - /// suppressed, because it would punish the proxy and every client behind it. - trusted_networks: Vec, -} - -/// Spawns the background subnet monitor when `[detect.prefix] enabled`. -/// -/// Source priority: the XDP map when a filter is loaded, otherwise the userspace -/// aggregator. Without either source the monitor stays disabled and logs a -/// warning. -/// /// Everything the monitor task needs besides the detection config. pub struct MonitorSetup { /// Ban lifetime, from `[ban].ban_duration_secs`. @@ -162,90 +151,6 @@ fn apply_verdicts(verdicts: &[PrefixVerdict], source: &Source, policy: &BanPolic } } -/// Applies userspace `Block` verdicts to the shared blacklist. -/// -/// Returns the number of banned prefixes. When `trusted` is false the observed -/// addresses belong to an unverified ingress path, so the verdict is only logged -/// at warn level and no ban is installed. -/// -/// The ban is inserted as a CIDR range, so every address inside the detected -/// `/24` or `/64` is blocked, not just its network address. -pub fn enforce_tracker_verdicts( - verdicts: &[PrefixVerdict], - blacklist: &Blacklist, - ttl: Duration, - trusted: bool, - trusted_networks: &[crate::config::TrustedProxyCidr], -) -> usize { - let mut banned = 0; - for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { - if !trusted { - tracing::warn!( - prefix = %pv.prefix, - "subnet block verdict on an untrusted peer path; not adding to the blacklist" - ); - continue; - } - if trusted_networks - .iter() - .any(|net| net.overlaps_prefix(pv.prefix, prefix_len(pv.prefix))) - { - tracing::warn!( - prefix = %pv.prefix, - "subnet ban suppressed: the prefix contains a trusted proxy network" - ); - continue; - } - blacklist.add_cidr(pv.prefix, prefix_len(pv.prefix), ttl, "subnet_attack"); - banned += 1; - tracing::warn!( - prefix = %pv.prefix, - ttl_secs = ttl.as_secs(), - "subnet blocked in the userspace blacklist" - ); - } - banned -} - -#[cfg(feature = "xdp")] -fn ban_xdp_verdicts( - xdp: &XdpPrefixStats, - verdicts: &[PrefixVerdict], - ttl: Duration, - trusted_networks: &[crate::config::TrustedProxyCidr], -) { - for pv in verdicts.iter().filter(|pv| pv.verdict == SubnetVerdict::Block) { - let len = prefix_len(pv.prefix); - if trusted_networks.iter().any(|net| net.overlaps_prefix(pv.prefix, len)) { - tracing::warn!( - prefix = %pv.prefix, - "subnet kernel ban suppressed: the prefix contains a trusted proxy network" - ); - continue; - } - let result = { - let guard = xdp.filter_lock(); - guard.ban_cidr(pv.prefix, prefix_len(pv.prefix), ttl.as_secs()) - }; - match result { - Ok(()) => tracing::warn!( - prefix = %pv.prefix, - ttl_secs = ttl.as_secs(), - "subnet blocked in XDP" - ), - Err(e) => tracing::warn!("subnet block failed for {}: {e}", pv.prefix), - } - } -} - -/// Prefix length matching the detection granularity (v4 /24, v6 /64). -fn prefix_len(prefix: IpAddr) -> u8 { - match prefix { - IpAddr::V4(_) => 24, - IpAddr::V6(_) => 64, - } -} - #[must_use] fn verdict_name(verdict: SubnetVerdict) -> &'static str { match verdict {