style: switch rustfmt to hard tabs; document tests-separate rule in TODO

- rustfmt.toml: hard_tabs = true.
- TODO §0.7: tests live in tests/, no #[cfg(test)] modules in code files.
This commit is contained in:
Loki 2026-11-15 22:34:29 +01:00
parent d8393e0f39
commit a90f0da226
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
96 changed files with 6542 additions and 6537 deletions

View file

@ -20,200 +20,200 @@ const BAN_REASON_ATTACK: &str = "attack_detector";
/// События: новое соединение (`on_accept`), завершение обработки соединения
/// (`on_connection_end`), эскалация детектора атак (`ban_offenders`).
pub struct TrafficHook {
reputation: Arc<IpReputation>,
blacklist: Arc<Blacklist>,
autoban: DetectAutobanConfig,
ban_ttl_secs: u64,
conn_window: AtomicU64,
reputation: Arc<IpReputation>,
blacklist: Arc<Blacklist>,
autoban: DetectAutobanConfig,
ban_ttl_secs: u64,
conn_window: AtomicU64,
}
impl TrafficHook {
pub fn new(
reputation: Arc<IpReputation>,
blacklist: Arc<Blacklist>,
autoban: DetectAutobanConfig,
ban_ttl_secs: u64,
) -> Self {
Self {
reputation,
blacklist,
autoban,
ban_ttl_secs,
conn_window: AtomicU64::new(0),
}
}
pub fn new(
reputation: Arc<IpReputation>,
blacklist: Arc<Blacklist>,
autoban: DetectAutobanConfig,
ban_ttl_secs: u64,
) -> Self {
Self {
reputation,
blacklist,
autoban,
ban_ttl_secs,
conn_window: AtomicU64::new(0),
}
}
/// Новое соединение принято accept-loop'ом. Только счётчик окна cps.
pub fn on_accept(&self) {
self.conn_window.fetch_add(1, Ordering::Relaxed);
}
/// Новое соединение принято accept-loop'ом. Только счётчик окна cps.
pub fn on_accept(&self) {
self.conn_window.fetch_add(1, Ordering::Relaxed);
}
/// Соединение обработано. Если источник попал под rate-limit (репутация
/// упала до порога) — авто-бан с TTL из конфига.
pub fn on_connection_end(&self, ip: IpAddr) {
if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
return;
}
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
}
/// Соединение обработано. Если источник попал под rate-limit (репутация
/// упала до порога) — авто-бан с TTL из конфига.
pub fn on_connection_end(&self, ip: IpAddr) {
if !self.autoban.enabled || self.blacklist.is_blocked(ip) {
return;
}
self.autoban_if_toxic(ip, BAN_REASON_LOW_REPUTATION);
}
/// Эскалация детектора атак: бан всех источников ниже порога репутации.
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик.
pub fn ban_offenders(&self) -> usize {
if !self.autoban.enabled {
return 0;
}
let offenders = self.reputation.offenders_below(self.autoban.reputation_threshold);
let mut banned = 0;
for ip in offenders {
if self.blacklist.is_blocked(ip) {
continue;
}
self.ban(ip, BAN_REASON_ATTACK);
banned += 1;
}
banned
}
/// Эскалация детектора атак: бан всех источников ниже порога репутации.
/// Вызывается один раз на переход в `UnderAttack`, не на каждый тик.
pub fn ban_offenders(&self) -> usize {
if !self.autoban.enabled {
return 0;
}
let offenders = self.reputation.offenders_below(self.autoban.reputation_threshold);
let mut banned = 0;
for ip in offenders {
if self.blacklist.is_blocked(ip) {
continue;
}
self.ban(ip, BAN_REASON_ATTACK);
banned += 1;
}
banned
}
/// Забирает накопленное окно новых соединений за секунду (cps).
pub fn take_cps(&self) -> u64 {
self.conn_window.swap(0, Ordering::Relaxed)
}
/// Забирает накопленное окно новых соединений за секунду (cps).
pub fn take_cps(&self) -> u64 {
self.conn_window.swap(0, Ordering::Relaxed)
}
fn autoban_if_toxic(&self, ip: IpAddr, reason: &str) {
if self.reputation.score(ip) > self.autoban.reputation_threshold {
return;
}
self.ban(ip, reason);
}
fn autoban_if_toxic(&self, ip: IpAddr, reason: &str) {
if self.reputation.score(ip) > self.autoban.reputation_threshold {
return;
}
self.ban(ip, reason);
}
fn ban(&self, ip: IpAddr, reason: &str) {
self.blacklist.add(ip, Duration::from_secs(self.ban_ttl_secs), reason);
metrics::AUTO_BANS_TOTAL.with_label_values(&[reason]).inc();
tracing::warn!(%ip, reason, ttl_secs = self.ban_ttl_secs, "auto-ban issued by traffic intelligence");
}
fn ban(&self, ip: IpAddr, reason: &str) {
self.blacklist.add(ip, Duration::from_secs(self.ban_ttl_secs), reason);
metrics::AUTO_BANS_TOTAL.with_label_values(&[reason]).inc();
tracing::warn!(%ip, reason, ttl_secs = self.ban_ttl_secs, "auto-ban issued by traffic intelligence");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
use super::*;
use std::net::{IpAddr, Ipv4Addr};
fn ip(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
}
fn ip(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
}
fn hook(rep: &Arc<IpReputation>, bl: &Arc<Blacklist>) -> TrafficHook {
TrafficHook::new(
Arc::clone(rep),
Arc::clone(bl),
DetectAutobanConfig {
enabled: true,
reputation_threshold: -50,
},
60,
)
}
fn hook(rep: &Arc<IpReputation>, bl: &Arc<Blacklist>) -> TrafficHook {
TrafficHook::new(
Arc::clone(rep),
Arc::clone(bl),
DetectAutobanConfig {
enabled: true,
reputation_threshold: -50,
},
60,
)
}
#[test]
fn test_cps_window_counts_and_resets() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
hook.on_accept();
hook.on_accept();
hook.on_accept();
assert_eq!(hook.take_cps(), 3);
assert_eq!(hook.take_cps(), 0);
}
#[test]
fn test_cps_window_counts_and_resets() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
hook.on_accept();
hook.on_accept();
hook.on_accept();
assert_eq!(hook.take_cps(), 3);
assert_eq!(hook.take_cps(), 0);
}
#[test]
fn test_reputation_fall_triggers_autoban() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let target = ip([10, 1, 0, 1]);
for _ in 0..6 {
rep.record_bad(target);
}
assert_eq!(rep.score(target), -60);
assert!(!bl.is_blocked(target));
hook.on_connection_end(target);
assert!(bl.is_blocked(target));
}
#[test]
fn test_reputation_fall_triggers_autoban() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let target = ip([10, 1, 0, 1]);
for _ in 0..6 {
rep.record_bad(target);
}
assert_eq!(rep.score(target), -60);
assert!(!bl.is_blocked(target));
hook.on_connection_end(target);
assert!(bl.is_blocked(target));
}
#[test]
fn test_no_autoban_above_threshold() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let target = ip([10, 1, 0, 2]);
for _ in 0..4 {
rep.record_bad(target);
}
assert_eq!(rep.score(target), -40);
hook.on_connection_end(target);
assert!(!bl.is_blocked(target));
}
#[test]
fn test_no_autoban_above_threshold() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let target = ip([10, 1, 0, 2]);
for _ in 0..4 {
rep.record_bad(target);
}
assert_eq!(rep.score(target), -40);
hook.on_connection_end(target);
assert!(!bl.is_blocked(target));
}
#[test]
fn test_disabled_autoban_never_bans() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = TrafficHook::new(
Arc::clone(&rep),
Arc::clone(&bl),
DetectAutobanConfig {
enabled: false,
reputation_threshold: -50,
},
60,
);
let target = ip([10, 1, 0, 3]);
for _ in 0..20 {
rep.record_bad(target);
}
hook.on_connection_end(target);
assert!(hook.ban_offenders() == 0);
assert!(!bl.is_blocked(target));
}
#[test]
fn test_disabled_autoban_never_bans() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = TrafficHook::new(
Arc::clone(&rep),
Arc::clone(&bl),
DetectAutobanConfig {
enabled: false,
reputation_threshold: -50,
},
60,
);
let target = ip([10, 1, 0, 3]);
for _ in 0..20 {
rep.record_bad(target);
}
hook.on_connection_end(target);
assert!(hook.ban_offenders() == 0);
assert!(!bl.is_blocked(target));
}
#[test]
fn test_ban_offenders_bans_only_below_threshold() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let bad = ip([10, 2, 0, 1]);
let ok = ip([10, 2, 0, 2]);
for _ in 0..8 {
rep.record_bad(bad);
}
rep.record_good(ok);
assert_eq!(hook.ban_offenders(), 1);
assert!(bl.is_blocked(bad));
assert!(!bl.is_blocked(ok));
assert_eq!(hook.ban_offenders(), 0);
}
#[test]
fn test_ban_offenders_bans_only_below_threshold() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = hook(&rep, &bl);
let bad = ip([10, 2, 0, 1]);
let ok = ip([10, 2, 0, 2]);
for _ in 0..8 {
rep.record_bad(bad);
}
rep.record_good(ok);
assert_eq!(hook.ban_offenders(), 1);
assert!(bl.is_blocked(bad));
assert!(!bl.is_blocked(ok));
assert_eq!(hook.ban_offenders(), 0);
}
#[test]
fn test_autoban_ttl_expires() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = TrafficHook::new(
Arc::clone(&rep),
Arc::clone(&bl),
DetectAutobanConfig {
enabled: true,
reputation_threshold: -50,
},
// Короткий TTL как мок времени: бан жив, потом истекает.
0,
);
let target = ip([10, 3, 0, 1]);
for _ in 0..20 {
rep.record_bad(target);
}
hook.on_connection_end(target);
assert!(!bl.is_blocked(target), "zero TTL must not produce an active ban");
}
#[test]
fn test_autoban_ttl_expires() {
let rep = Arc::new(IpReputation::new());
let bl = Arc::new(Blacklist::new());
let hook = TrafficHook::new(
Arc::clone(&rep),
Arc::clone(&bl),
DetectAutobanConfig {
enabled: true,
reputation_threshold: -50,
},
// Короткий TTL как мок времени: бан жив, потом истекает.
0,
);
let target = ip([10, 3, 0, 1]);
for _ in 0..20 {
rep.record_bad(target);
}
hook.on_connection_end(target);
assert!(!bl.is_blocked(target), "zero TTL must not produce an active ban");
}
}

View file

@ -2,109 +2,109 @@ use crate::traffic::profiler::TrafficProfiler;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttackStatus {
Normal,
Suspicious,
UnderAttack,
Normal,
Suspicious,
UnderAttack,
}
pub struct AttackDetector {
pps_profiler: TrafficProfiler,
cps_profiler: TrafficProfiler,
consecutive_anomalies: u32,
pps_profiler: TrafficProfiler,
cps_profiler: TrafficProfiler,
consecutive_anomalies: u32,
}
impl Default for AttackDetector {
fn default() -> Self {
Self::new()
}
fn default() -> Self {
Self::new()
}
}
impl AttackDetector {
pub fn new() -> Self {
Self {
pps_profiler: TrafficProfiler::new(),
cps_profiler: TrafficProfiler::new(),
consecutive_anomalies: 0,
}
}
pub fn new() -> Self {
Self {
pps_profiler: TrafficProfiler::new(),
cps_profiler: TrafficProfiler::new(),
consecutive_anomalies: 0,
}
}
/// Анализирует окно метрик (пакеты/с и новые соединения/с) относительно
/// накопленных профилей. Аномалией считается всплеск любой из метрик.
pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus {
self.pps_profiler.record(pps);
self.cps_profiler.record(cps);
let score = self
.pps_profiler
.anomaly_score(pps)
.max(self.cps_profiler.anomaly_score(cps));
/// Анализирует окно метрик (пакеты/с и новые соединения/с) относительно
/// накопленных профилей. Аномалией считается всплеск любой из метрик.
pub fn analyze(&mut self, pps: f64, cps: f64) -> AttackStatus {
self.pps_profiler.record(pps);
self.cps_profiler.record(cps);
let score = self
.pps_profiler
.anomaly_score(pps)
.max(self.cps_profiler.anomaly_score(cps));
if score > 3.0 {
self.consecutive_anomalies += 1;
} else {
self.consecutive_anomalies = 0;
}
if score > 3.0 {
self.consecutive_anomalies += 1;
} else {
self.consecutive_anomalies = 0;
}
if self.consecutive_anomalies >= 3 {
AttackStatus::UnderAttack
} else if score > 2.0 {
AttackStatus::Suspicious
} else {
AttackStatus::Normal
}
}
if self.consecutive_anomalies >= 3 {
AttackStatus::UnderAttack
} else if score > 2.0 {
AttackStatus::Suspicious
} else {
AttackStatus::Normal
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[test]
fn test_attack_status_normal() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(100.0, 10.0);
}
assert_eq!(d.analyze(100.0, 10.0), AttackStatus::Normal);
}
#[test]
fn test_attack_status_normal() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(100.0, 10.0);
}
assert_eq!(d.analyze(100.0, 10.0), AttackStatus::Normal);
}
#[test]
fn test_attack_status_suspicious_pps_spike() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
assert_eq!(d.analyze(5.0, 1.0), AttackStatus::Suspicious);
}
#[test]
fn test_attack_status_suspicious_pps_spike() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
assert_eq!(d.analyze(5.0, 1.0), AttackStatus::Suspicious);
}
#[test]
fn test_attack_status_suspicious_cps_spike() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
assert_eq!(d.analyze(1.0, 5.0), AttackStatus::Suspicious);
}
#[test]
fn test_attack_status_suspicious_cps_spike() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
assert_eq!(d.analyze(1.0, 5.0), AttackStatus::Suspicious);
}
#[test]
fn test_attack_status_under_attack() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
d.analyze(10_000.0, 100.0);
d.analyze(10_000.0, 100.0);
assert_eq!(d.analyze(10_000.0, 100.0), AttackStatus::UnderAttack);
}
#[test]
fn test_attack_status_under_attack() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
d.analyze(10_000.0, 100.0);
d.analyze(10_000.0, 100.0);
assert_eq!(d.analyze(10_000.0, 100.0), AttackStatus::UnderAttack);
}
#[test]
fn test_consecutive_resets_on_normal() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
d.analyze(100.0, 10.0);
d.analyze(100.0, 10.0);
d.analyze(1.0, 1.0);
assert_eq!(d.analyze(1.0, 1.0), AttackStatus::Normal);
}
#[test]
fn test_consecutive_resets_on_normal() {
let mut d = AttackDetector::new();
for _ in 0..10 {
d.analyze(1.0, 1.0);
}
d.analyze(100.0, 10.0);
d.analyze(100.0, 10.0);
d.analyze(1.0, 1.0);
assert_eq!(d.analyze(1.0, 1.0), AttackStatus::Normal);
}
}

View file

@ -1,57 +1,57 @@
use std::time::Instant;
pub struct Ewma {
value: f64,
last: Instant,
alpha: f64,
value: f64,
last: Instant,
alpha: f64,
}
impl Ewma {
pub fn new(alpha: f64) -> Self {
Self {
value: 0.0,
last: Instant::now(),
alpha,
}
}
pub fn new(alpha: f64) -> Self {
Self {
value: 0.0,
last: Instant::now(),
alpha,
}
}
pub fn update(&mut self, sample: f64) {
let now = Instant::now();
let elapsed = now.duration_since(self.last).as_secs_f64();
let steps = elapsed.max(1.0);
let weight = (1.0 - self.alpha).powf(steps);
self.value = self.value * weight + sample * (1.0 - weight);
self.last = now;
}
pub fn update(&mut self, sample: f64) {
let now = Instant::now();
let elapsed = now.duration_since(self.last).as_secs_f64();
let steps = elapsed.max(1.0);
let weight = (1.0 - self.alpha).powf(steps);
self.value = self.value * weight + sample * (1.0 - weight);
self.last = now;
}
pub fn value(&self) -> f64 {
self.value
}
pub fn value(&self) -> f64 {
self.value
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[test]
fn test_ewma_initial() {
let ewma = Ewma::new(0.125);
assert_eq!(ewma.value(), 0.0);
}
#[test]
fn test_ewma_initial() {
let ewma = Ewma::new(0.125);
assert_eq!(ewma.value(), 0.0);
}
#[test]
fn test_ewma_update() {
let mut ewma = Ewma::new(1.0);
ewma.update(100.0);
assert!((ewma.value() - 100.0).abs() < 1.0);
}
#[test]
fn test_ewma_update() {
let mut ewma = Ewma::new(1.0);
ewma.update(100.0);
assert!((ewma.value() - 100.0).abs() < 1.0);
}
#[test]
fn test_ewma_convergence() {
let mut ewma = Ewma::new(0.5);
for _ in 0..10 {
ewma.update(50.0);
}
assert!((ewma.value() - 50.0).abs() < 1.0);
}
#[test]
fn test_ewma_convergence() {
let mut ewma = Ewma::new(0.5);
for _ in 0..10 {
ewma.update(50.0);
}
assert!((ewma.value() - 50.0).abs() < 1.0);
}
}

View file

@ -3,136 +3,136 @@ use std::net::IpAddr;
use std::sync::Arc;
pub struct IpReputation {
scores: Arc<DashMap<IpAddr, i32>>,
scores: Arc<DashMap<IpAddr, i32>>,
}
impl Default for IpReputation {
fn default() -> Self {
Self::new()
}
fn default() -> Self {
Self::new()
}
}
impl IpReputation {
pub fn new() -> Self {
Self {
scores: Arc::new(DashMap::new()),
}
}
pub fn new() -> Self {
Self {
scores: Arc::new(DashMap::new()),
}
}
pub fn record_good(&self, ip: IpAddr) {
let mut entry = self.scores.entry(ip).or_insert(0);
*entry = (*entry + 1).min(100);
}
pub fn record_good(&self, ip: IpAddr) {
let mut entry = self.scores.entry(ip).or_insert(0);
*entry = (*entry + 1).min(100);
}
pub fn record_bad(&self, ip: IpAddr) {
let mut entry = self.scores.entry(ip).or_insert(0);
*entry = (*entry - 10).max(-100);
}
pub fn record_bad(&self, ip: IpAddr) {
let mut entry = self.scores.entry(ip).or_insert(0);
*entry = (*entry - 10).max(-100);
}
pub fn score(&self, ip: IpAddr) -> i32 {
self.scores.get(&ip).map(|v| *v).unwrap_or(0)
}
pub fn score(&self, ip: IpAddr) -> i32 {
self.scores.get(&ip).map(|v| *v).unwrap_or(0)
}
/// Возвращает источники со скором не выше `threshold` (нарушители).
pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
self.scores
.iter()
.filter(|entry| *entry.value() <= threshold)
.map(|entry| *entry.key())
.collect()
}
/// Возвращает источники со скором не выше `threshold` (нарушители).
pub fn offenders_below(&self, threshold: i32) -> Vec<IpAddr> {
self.scores
.iter()
.filter(|entry| *entry.value() <= threshold)
.map(|entry| *entry.key())
.collect()
}
pub fn is_trusted(&self, ip: IpAddr) -> bool {
self.score(ip) > 50
}
pub fn is_trusted(&self, ip: IpAddr) -> bool {
self.score(ip) > 50
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use super::*;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
fn v4(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
}
fn v4(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
}
#[test]
fn test_reputation_initial_score() {
let rep = IpReputation::new();
assert_eq!(rep.score(v4([192, 168, 1, 1])), 0);
}
#[test]
fn test_reputation_initial_score() {
let rep = IpReputation::new();
assert_eq!(rep.score(v4([192, 168, 1, 1])), 0);
}
#[test]
fn test_reputation_good() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 1]);
rep.record_good(ip);
assert_eq!(rep.score(ip), 1);
}
#[test]
fn test_reputation_good() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 1]);
rep.record_good(ip);
assert_eq!(rep.score(ip), 1);
}
#[test]
fn test_reputation_bad() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 2]);
rep.record_bad(ip);
assert_eq!(rep.score(ip), -10);
}
#[test]
fn test_reputation_bad() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 2]);
rep.record_bad(ip);
assert_eq!(rep.score(ip), -10);
}
#[test]
fn test_reputation_cap_positive() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 3]);
for _ in 0..200 {
rep.record_good(ip);
}
assert_eq!(rep.score(ip), 100);
}
#[test]
fn test_reputation_cap_positive() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 3]);
for _ in 0..200 {
rep.record_good(ip);
}
assert_eq!(rep.score(ip), 100);
}
#[test]
fn test_reputation_cap_negative() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 4]);
for _ in 0..20 {
rep.record_bad(ip);
}
assert_eq!(rep.score(ip), -100);
}
#[test]
fn test_reputation_cap_negative() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 4]);
for _ in 0..20 {
rep.record_bad(ip);
}
assert_eq!(rep.score(ip), -100);
}
#[test]
fn test_is_trusted() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 5]);
assert!(!rep.is_trusted(ip));
for _ in 0..51 {
rep.record_good(ip);
}
assert!(rep.is_trusted(ip));
}
#[test]
fn test_is_trusted() {
let rep = IpReputation::new();
let ip = v4([10, 0, 0, 5]);
assert!(!rep.is_trusted(ip));
for _ in 0..51 {
rep.record_good(ip);
}
assert!(rep.is_trusted(ip));
}
#[test]
fn test_reputation_v6() {
let rep = IpReputation::new();
let ip = IpAddr::V6(Ipv6Addr::LOCALHOST);
rep.record_bad(ip);
assert_eq!(rep.score(ip), -10);
}
#[test]
fn test_reputation_v6() {
let rep = IpReputation::new();
let ip = IpAddr::V6(Ipv6Addr::LOCALHOST);
rep.record_bad(ip);
assert_eq!(rep.score(ip), -10);
}
#[test]
fn test_offenders_below_threshold() {
let rep = IpReputation::new();
let bad = v4([10, 0, 0, 1]);
let good = v4([10, 0, 0, 2]);
for _ in 0..6 {
rep.record_bad(bad);
}
rep.record_good(good);
let offenders = rep.offenders_below(-50);
assert_eq!(offenders, vec![bad]);
}
#[test]
fn test_offenders_below_threshold() {
let rep = IpReputation::new();
let bad = v4([10, 0, 0, 1]);
let good = v4([10, 0, 0, 2]);
for _ in 0..6 {
rep.record_bad(bad);
}
rep.record_good(good);
let offenders = rep.offenders_below(-50);
assert_eq!(offenders, vec![bad]);
}
#[test]
fn test_offenders_empty_when_none_below() {
let rep = IpReputation::new();
assert!(rep.offenders_below(-50).is_empty());
}
#[test]
fn test_offenders_empty_when_none_below() {
let rep = IpReputation::new();
assert!(rep.offenders_below(-50).is_empty());
}
}

View file

@ -9,83 +9,83 @@ pub const PREFIX_FAMILY_V6: u8 = 6;
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixKey {
pub family: u8,
pub pad: [u8; 7],
pub addr: [u8; 16],
pub family: u8,
pub pad: [u8; 7],
pub addr: [u8; 16],
}
impl PrefixKey {
/// Строит ключ префикса для адреса (v4 → /24 в первых 4 байтах, v6 → /64).
#[must_use]
pub fn new(ip: IpAddr) -> Self {
let mut key = Self::default();
match ip {
IpAddr::V4(v4) => {
key.family = PREFIX_FAMILY_V4;
key.addr[..4].copy_from_slice(&masked_v4(v4).octets());
},
IpAddr::V6(v6) => {
key.family = PREFIX_FAMILY_V6;
key.addr.copy_from_slice(&masked_v6_segments(v6));
},
}
key
}
/// Строит ключ префикса для адреса (v4 → /24 в первых 4 байтах, v6 → /64).
#[must_use]
pub fn new(ip: IpAddr) -> Self {
let mut key = Self::default();
match ip {
IpAddr::V4(v4) => {
key.family = PREFIX_FAMILY_V4;
key.addr[..4].copy_from_slice(&masked_v4(v4).octets());
},
IpAddr::V6(v6) => {
key.family = PREFIX_FAMILY_V6;
key.addr.copy_from_slice(&masked_v6_segments(v6));
},
}
key
}
/// Префикс как IP-адрес (маскированный).
#[must_use]
pub fn to_prefix(self) -> Option<IpAddr> {
match self.family {
PREFIX_FAMILY_V4 => Some(IpAddr::V4(Ipv4Addr::new(
self.addr[0],
self.addr[1],
self.addr[2],
self.addr[3],
))),
PREFIX_FAMILY_V6 => Some(IpAddr::V6(Ipv6Addr::from(self.addr))),
_ => None,
}
}
/// Префикс как IP-адрес (маскированный).
#[must_use]
pub fn to_prefix(self) -> Option<IpAddr> {
match self.family {
PREFIX_FAMILY_V4 => Some(IpAddr::V4(Ipv4Addr::new(
self.addr[0],
self.addr[1],
self.addr[2],
self.addr[3],
))),
PREFIX_FAMILY_V6 => Some(IpAddr::V6(Ipv6Addr::from(self.addr))),
_ => None,
}
}
#[must_use]
pub fn from_bytes(bytes: [u8; 24]) -> Self {
Self {
family: bytes[0],
pad: bytes[1..8].try_into().expect("7 pad bytes"),
addr: bytes[8..24].try_into().expect("16 addr bytes"),
}
}
#[must_use]
pub fn from_bytes(bytes: [u8; 24]) -> Self {
Self {
family: bytes[0],
pad: bytes[1..8].try_into().expect("7 pad bytes"),
addr: bytes[8..24].try_into().expect("16 addr bytes"),
}
}
#[must_use]
pub fn to_bytes(self) -> [u8; 24] {
let mut out = [0u8; 24];
out[0] = self.family;
out[1..8].copy_from_slice(&self.pad);
out[8..24].copy_from_slice(&self.addr);
out
}
#[must_use]
pub fn to_bytes(self) -> [u8; 24] {
let mut out = [0u8; 24];
out[0] = self.family;
out[1..8].copy_from_slice(&self.pad);
out[8..24].copy_from_slice(&self.addr);
out
}
}
/// Возвращает префикс адреса: IPv4 и IPv4-mapped → /24, IPv6 → /64.
#[must_use]
pub fn prefix_of(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)),
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
// ::ffff:a.b.c.d живёт в том же /24-пространстве, что и a.b.c.d.
Some(v4) => IpAddr::V4(masked_v4(v4)),
None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))),
},
}
match ip {
IpAddr::V4(v4) => IpAddr::V4(masked_v4(v4)),
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
// ::ffff:a.b.c.d живёт в том же /24-пространстве, что и a.b.c.d.
Some(v4) => IpAddr::V4(masked_v4(v4)),
None => IpAddr::V6(Ipv6Addr::from(masked_v6_segments(v6))),
},
}
}
fn masked_v4(ip: Ipv4Addr) -> Ipv4Addr {
let o = ip.octets();
Ipv4Addr::new(o[0], o[1], o[2], 0)
let o = ip.octets();
Ipv4Addr::new(o[0], o[1], o[2], 0)
}
fn masked_v6_segments(ip: Ipv6Addr) -> [u8; 16] {
let mut segs = ip.octets();
segs[8..].fill(0);
segs
let mut segs = ip.octets();
segs[8..].fill(0);
segs
}

View file

@ -6,33 +6,33 @@ use std::net::IpAddr;
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixStatsVal {
pub syn_count: u64,
pub pkt_count: u64,
pub last_seen_ns: u64,
pub syn_count: u64,
pub pkt_count: u64,
pub last_seen_ns: u64,
}
impl PrefixStatsVal {
/// Разбирает сырые 24 байта значения карты.
#[must_use]
pub fn from_bytes(bytes: [u8; 24]) -> Self {
let read_u64 =
|range: std::ops::Range<usize>| u64::from_le_bytes(bytes[range].try_into().expect("8-byte field"));
Self {
syn_count: read_u64(0..8),
pkt_count: read_u64(8..16),
last_seen_ns: read_u64(16..24),
}
}
/// Разбирает сырые 24 байта значения карты.
#[must_use]
pub fn from_bytes(bytes: [u8; 24]) -> Self {
let read_u64 =
|range: std::ops::Range<usize>| u64::from_le_bytes(bytes[range].try_into().expect("8-byte field"));
Self {
syn_count: read_u64(0..8),
pkt_count: read_u64(8..16),
last_seen_ns: read_u64(16..24),
}
}
/// Сериализует значение в сырые 24 байта карты.
#[must_use]
pub fn to_bytes(self) -> [u8; 24] {
let mut out = [0u8; 24];
out[0..8].copy_from_slice(&self.syn_count.to_le_bytes());
out[8..16].copy_from_slice(&self.pkt_count.to_le_bytes());
out[16..24].copy_from_slice(&self.last_seen_ns.to_le_bytes());
out
}
/// Сериализует значение в сырые 24 байта карты.
#[must_use]
pub fn to_bytes(self) -> [u8; 24] {
let mut out = [0u8; 24];
out[0..8].copy_from_slice(&self.syn_count.to_le_bytes());
out[8..16].copy_from_slice(&self.pkt_count.to_le_bytes());
out[16..24].copy_from_slice(&self.last_seen_ns.to_le_bytes());
out
}
}
/// Агрегат по одному префиксу за окно детекции.
@ -41,36 +41,36 @@ impl PrefixStatsVal {
/// (XDP-путь); spoof-gate в этом случае Block не подтверждает.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefixSnapshot {
pub syn_count: u64,
pub pkt_count: u64,
pub last_seen_ns: u64,
pub unique_sources: u64,
pub syn_count: u64,
pub pkt_count: u64,
pub last_seen_ns: u64,
pub unique_sources: u64,
}
/// Источник агрегатов по префиксам. Позволяет тестам работать без ядра.
pub trait PrefixStatsSource {
/// Снимок агрегатов за текущее окно.
///
/// # Errors
/// Ошибка чтения источника (карта не загружена, BPF-сбой и т.п.).
fn snapshot(&self) -> impl Future<Output = Result<Vec<(IpAddr, PrefixSnapshot)>>> + Send;
/// Снимок агрегатов за текущее окно.
///
/// # Errors
/// Ошибка чтения источника (карта не загружена, BPF-сбой и т.п.).
fn snapshot(&self) -> impl Future<Output = Result<Vec<(IpAddr, PrefixSnapshot)>>> + Send;
}
/// Эскалация вердиктов subnet-level детектора.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubnetVerdict {
Monitor,
StrictLimit,
Challenge,
Block,
Monitor,
StrictLimit,
Challenge,
Block,
}
/// Вердикт по одному префиксу.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrefixVerdict {
pub prefix: IpAddr,
pub verdict: SubnetVerdict,
pub snapshot: PrefixSnapshot,
pub prefix: IpAddr,
pub verdict: SubnetVerdict,
pub snapshot: PrefixSnapshot,
}
/// Детектор распределённых атак по префиксам.
@ -81,59 +81,59 @@ pub struct PrefixVerdict {
/// уникальных IP — защита от ложного бана CGNAT/спуфинга).
#[derive(Debug, Clone)]
pub struct SubnetDetector {
syn_threshold: u64,
min_unique_sources: u64,
syn_threshold: u64,
min_unique_sources: u64,
}
impl SubnetDetector {
#[must_use]
pub fn new(syn_threshold: u64, min_unique_sources: u64) -> Self {
Self {
syn_threshold: syn_threshold.max(1),
min_unique_sources,
}
}
#[must_use]
pub fn new(syn_threshold: u64, min_unique_sources: u64) -> Self {
Self {
syn_threshold: syn_threshold.max(1),
min_unique_sources,
}
}
#[must_use]
pub fn from_config(config: &crate::config::DetectPrefixConfig) -> Self {
Self::new(config.syn_threshold, config.min_unique_sources)
}
#[must_use]
pub fn from_config(config: &crate::config::DetectPrefixConfig) -> Self {
Self::new(config.syn_threshold, config.min_unique_sources)
}
/// Оценивает снимок и возвращает вердикты по активным префиксам.
#[must_use]
pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> {
snapshots
.iter()
.filter(|(_, snap)| snap.syn_count > 0)
.map(|(prefix, snap)| PrefixVerdict {
prefix: *prefix,
verdict: self.verdict_for(snap),
snapshot: *snap,
})
.collect()
}
/// Оценивает снимок и возвращает вердикты по активным префиксам.
#[must_use]
pub fn evaluate(&self, snapshots: &[(IpAddr, PrefixSnapshot)]) -> Vec<PrefixVerdict> {
snapshots
.iter()
.filter(|(_, snap)| snap.syn_count > 0)
.map(|(prefix, snap)| PrefixVerdict {
prefix: *prefix,
verdict: self.verdict_for(snap),
snapshot: *snap,
})
.collect()
}
#[must_use]
fn verdict_for(&self, snap: &PrefixSnapshot) -> SubnetVerdict {
let t = self.syn_threshold;
if snap.syn_count < t {
return SubnetVerdict::Monitor;
}
if snap.syn_count < t.saturating_mul(2) {
return SubnetVerdict::StrictLimit;
}
let extreme = snap.syn_count >= t.saturating_mul(4);
if extreme && self.spoof_gate_passed(snap) {
return SubnetVerdict::Block;
}
SubnetVerdict::Challenge
}
#[must_use]
fn verdict_for(&self, snap: &PrefixSnapshot) -> SubnetVerdict {
let t = self.syn_threshold;
if snap.syn_count < t {
return SubnetVerdict::Monitor;
}
if snap.syn_count < t.saturating_mul(2) {
return SubnetVerdict::StrictLimit;
}
let extreme = snap.syn_count >= t.saturating_mul(4);
if extreme && self.spoof_gate_passed(snap) {
return SubnetVerdict::Block;
}
SubnetVerdict::Challenge
}
#[must_use]
fn spoof_gate_passed(&self, snap: &PrefixSnapshot) -> bool {
// gate отключён (min_unique_sources == 0) либо подтверждено разнообразие.
self.min_unique_sources == 0 || snap.unique_sources >= self.min_unique_sources
}
#[must_use]
fn spoof_gate_passed(&self, snap: &PrefixSnapshot) -> bool {
// gate отключён (min_unique_sources == 0) либо подтверждено разнообразие.
self.min_unique_sources == 0 || snap.unique_sources >= self.min_unique_sources
}
}
/// Реализация [`PrefixStatsSource`] поверх XDP-фильтра (feature `xdp`).
@ -141,59 +141,59 @@ impl SubnetDetector {
/// поэтому spoof-gate на этом пути Block не подтверждает.
#[cfg(feature = "xdp")]
pub struct XdpPrefixStats {
filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>,
filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>,
}
#[cfg(feature = "xdp")]
impl XdpPrefixStats {
#[must_use]
pub fn new(filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>) -> Self {
Self { filter }
}
#[must_use]
pub fn new(filter: std::sync::Arc<std::sync::Mutex<crate::xdp::XdpFilter>>) -> Self {
Self { filter }
}
/// Блокирует мьютекс фильтра (для kernel-enforcement вердиктов).
///
/// # Panics
/// Если мьютекс отравлен (паника в другом потоке во время удержания).
pub fn filter_lock(&self) -> std::sync::MutexGuard<'_, crate::xdp::XdpFilter> {
self.filter.lock().expect("xdp lock poisoned")
}
/// Блокирует мьютекс фильтра (для kernel-enforcement вердиктов).
///
/// # Panics
/// Если мьютекс отравлен (паника в другом потоке во время удержания).
pub fn filter_lock(&self) -> std::sync::MutexGuard<'_, crate::xdp::XdpFilter> {
self.filter.lock().expect("xdp lock poisoned")
}
}
#[cfg(feature = "xdp")]
impl PrefixStatsSource for XdpPrefixStats {
async fn snapshot(&self) -> Result<Vec<(IpAddr, PrefixSnapshot)>> {
let raw = self.filter_lock().read_prefix_stats()?;
Ok(raw
.into_iter()
.filter_map(|(key, val)| {
let prefix = key.to_prefix()?;
Some((
prefix,
PrefixSnapshot {
syn_count: val.syn_count,
pkt_count: val.pkt_count,
last_seen_ns: val.last_seen_ns,
unique_sources: 0,
},
))
})
.collect())
}
async fn snapshot(&self) -> Result<Vec<(IpAddr, PrefixSnapshot)>> {
let raw = self.filter_lock().read_prefix_stats()?;
Ok(raw
.into_iter()
.filter_map(|(key, val)| {
let prefix = key.to_prefix()?;
Some((
prefix,
PrefixSnapshot {
syn_count: val.syn_count,
pkt_count: val.pkt_count,
last_seen_ns: val.last_seen_ns,
unique_sources: 0,
},
))
})
.collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[test]
fn stats_val_roundtrip() {
let val = PrefixStatsVal {
syn_count: 42,
pkt_count: 100,
last_seen_ns: 1_234_567_890,
};
assert_eq!(PrefixStatsVal::from_bytes(val.to_bytes()), val);
assert_eq!(size_of::<PrefixStatsVal>(), 24);
}
#[test]
fn stats_val_roundtrip() {
let val = PrefixStatsVal {
syn_count: 42,
pkt_count: 100,
last_seen_ns: 1_234_567_890,
};
assert_eq!(PrefixStatsVal::from_bytes(val.to_bytes()), val);
assert_eq!(size_of::<PrefixStatsVal>(), 24);
}
}

View file

@ -7,53 +7,53 @@ use crate::traffic::detector::AttackStatus;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertLevel {
Info,
Warning,
Critical,
Info,
Warning,
Critical,
}
impl fmt::Display for AlertLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlertLevel::Info => write!(f, "INFO"),
AlertLevel::Warning => write!(f, "WARNING"),
AlertLevel::Critical => write!(f, "CRITICAL"),
}
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlertLevel::Info => write!(f, "INFO"),
AlertLevel::Warning => write!(f, "WARNING"),
AlertLevel::Critical => write!(f, "CRITICAL"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Alert {
pub level: AlertLevel,
pub message: String,
pub ip: Option<Ipv4Addr>,
pub pps: f64,
pub timestamp: Instant,
pub level: AlertLevel,
pub message: String,
pub ip: Option<Ipv4Addr>,
pub pps: f64,
pub timestamp: Instant,
}
impl Alert {
pub fn new(level: AlertLevel, message: String, ip: Option<Ipv4Addr>, pps: f64) -> Self {
Self {
level,
message,
ip,
pps,
timestamp: Instant::now(),
}
}
pub fn new(level: AlertLevel, message: String, ip: Option<Ipv4Addr>, pps: f64) -> Self {
Self {
level,
message,
ip,
pps,
timestamp: Instant::now(),
}
}
}
impl fmt::Display for Alert {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.ip {
Some(ip) => write!(
f,
"[{}] {} | IP: {} | PPS: {:.2}",
self.level, self.message, ip, self.pps
),
None => write!(f, "[{}] {} | PPS: {:.2}", self.level, self.message, self.pps),
}
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.ip {
Some(ip) => write!(
f,
"[{}] {} | IP: {} | PPS: {:.2}",
self.level, self.message, ip, self.pps
),
None => write!(f, "[{}] {} | PPS: {:.2}", self.level, self.message, self.pps),
}
}
}
/// Дедуплицирующий диспетчер алертов: алерт выдаётся только на переходе
@ -61,109 +61,109 @@ impl fmt::Display for Alert {
/// тике. Логика — poll-and-persist (LNVPS issue #331).
#[derive(Default)]
pub struct AlertDispatcher {
previous: Mutex<Option<AttackStatus>>,
previous: Mutex<Option<AttackStatus>>,
}
impl AlertDispatcher {
pub fn new() -> Self {
Self::default()
}
pub fn new() -> Self {
Self::default()
}
/// Возвращает `Some(Alert)` только при переходе через границу атаки:
/// вход в `UnderAttack` («attack started») или выход из него
/// («attack ended»). Первое наблюдение алерта не порождает.
pub fn on_status(&self, status: AttackStatus) -> Option<Alert> {
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
if *previous == Some(status) {
return None;
}
let was_under_attack = *previous == Some(AttackStatus::UnderAttack);
*previous = Some(status);
match (was_under_attack, status) {
(false, AttackStatus::UnderAttack) => {
Some(Alert::new(AlertLevel::Critical, "attack started".into(), None, 0.0))
},
(true, _) => Some(Alert::new(AlertLevel::Info, "attack ended".into(), None, 0.0)),
_ => None,
}
}
/// Возвращает `Some(Alert)` только при переходе через границу атаки:
/// вход в `UnderAttack` («attack started») или выход из него
/// («attack ended»). Первое наблюдение алерта не порождает.
pub fn on_status(&self, status: AttackStatus) -> Option<Alert> {
let mut previous = self.previous.lock().expect("alert dispatcher lock poisoned");
if *previous == Some(status) {
return None;
}
let was_under_attack = *previous == Some(AttackStatus::UnderAttack);
*previous = Some(status);
match (was_under_attack, status) {
(false, AttackStatus::UnderAttack) => {
Some(Alert::new(AlertLevel::Critical, "attack started".into(), None, 0.0))
},
(true, _) => Some(Alert::new(AlertLevel::Info, "attack ended".into(), None, 0.0)),
_ => None,
}
}
}
/// Отправляет алерт на webhook (fire-and-forget, с таймаутом).
///
/// Вызывать следует из фоновых задач: сетевой ввод-вывод недопустим в hot path.
pub async fn send_webhook(url: String, alert: Alert) {
let payload = serde_json::json!({
"level": alert.level.to_string(),
"message": alert.message,
"pps": alert.pps,
});
let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build();
let client = match client {
Ok(c) => c,
Err(e) => {
tracing::warn!("webhook client build failed: {e}");
return;
},
};
if let Err(e) = client.post(url).json(&payload).send().await {
tracing::warn!("webhook delivery failed: {e}");
}
let payload = serde_json::json!({
"level": alert.level.to_string(),
"message": alert.message,
"pps": alert.pps,
});
let client = reqwest::Client::builder().timeout(Duration::from_secs(5)).build();
let client = match client {
Ok(c) => c,
Err(e) => {
tracing::warn!("webhook client build failed: {e}");
return;
},
};
if let Err(e) = client.post(url).json(&payload).send().await {
tracing::warn!("webhook delivery failed: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[test]
fn test_alert_display_with_ip() {
let alert = Alert::new(
AlertLevel::Critical,
"possible attack".into(),
Some(Ipv4Addr::new(192, 168, 1, 1)),
100500.0,
);
let s = alert.to_string();
assert!(s.contains("CRITICAL"));
assert!(s.contains("192.168.1.1"));
}
#[test]
fn test_alert_display_with_ip() {
let alert = Alert::new(
AlertLevel::Critical,
"possible attack".into(),
Some(Ipv4Addr::new(192, 168, 1, 1)),
100500.0,
);
let s = alert.to_string();
assert!(s.contains("CRITICAL"));
assert!(s.contains("192.168.1.1"));
}
#[test]
fn test_alert_display_without_ip() {
let alert = Alert::new(AlertLevel::Info, "traffic spike".into(), None, 5000.0);
let s = alert.to_string();
assert!(s.contains("INFO"));
assert!(s.contains("traffic spike"));
}
#[test]
fn test_alert_display_without_ip() {
let alert = Alert::new(AlertLevel::Info, "traffic spike".into(), None, 5000.0);
let s = alert.to_string();
assert!(s.contains("INFO"));
assert!(s.contains("traffic spike"));
}
#[test]
fn test_dispatcher_two_transitions_two_alerts() {
let dispatcher = AlertDispatcher::new();
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert_eq!(dispatcher.on_status(AttackStatus::Suspicious), None);
let started = dispatcher.on_status(AttackStatus::UnderAttack);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
let ended = dispatcher.on_status(AttackStatus::Normal);
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert!(started.is_some());
assert!(ended.is_some());
assert!(
started.expect("started alert").message.contains("attack started")
&& ended.expect("ended alert").message.contains("attack ended")
);
}
#[test]
fn test_dispatcher_two_transitions_two_alerts() {
let dispatcher = AlertDispatcher::new();
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert_eq!(dispatcher.on_status(AttackStatus::Suspicious), None);
let started = dispatcher.on_status(AttackStatus::UnderAttack);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
assert_eq!(dispatcher.on_status(AttackStatus::UnderAttack), None);
let ended = dispatcher.on_status(AttackStatus::Normal);
assert_eq!(dispatcher.on_status(AttackStatus::Normal), None);
assert!(started.is_some());
assert!(ended.is_some());
assert!(
started.expect("started alert").message.contains("attack started")
&& ended.expect("ended alert").message.contains("attack ended")
);
}
#[test]
fn test_dispatcher_suspicious_does_not_flap_alerts() {
let dispatcher = AlertDispatcher::new();
for status in [
AttackStatus::Normal,
AttackStatus::Suspicious,
AttackStatus::Normal,
AttackStatus::Suspicious,
] {
assert_eq!(dispatcher.on_status(status), None);
}
}
#[test]
fn test_dispatcher_suspicious_does_not_flap_alerts() {
let dispatcher = AlertDispatcher::new();
for status in [
AttackStatus::Normal,
AttackStatus::Suspicious,
AttackStatus::Normal,
AttackStatus::Suspicious,
] {
assert_eq!(dispatcher.on_status(status), None);
}
}
}

View file

@ -2,84 +2,84 @@ use crate::traffic::ewma::Ewma;
use std::time::Instant;
pub struct TrafficProfiler {
slots: [Ewma; 168],
current_slot: usize,
epoch: Instant,
slots: [Ewma; 168],
current_slot: usize,
epoch: Instant,
}
impl Default for TrafficProfiler {
fn default() -> Self {
Self::new()
}
fn default() -> Self {
Self::new()
}
}
impl TrafficProfiler {
pub fn new() -> Self {
Self {
slots: std::array::from_fn(|_| Ewma::new(0.125)),
current_slot: 0,
epoch: Instant::now(),
}
}
pub fn new() -> Self {
Self {
slots: std::array::from_fn(|_| Ewma::new(0.125)),
current_slot: 0,
epoch: Instant::now(),
}
}
fn slot_index(&self) -> usize {
(self.epoch.elapsed().as_secs() / 3600) as usize % 168
}
fn slot_index(&self) -> usize {
(self.epoch.elapsed().as_secs() / 3600) as usize % 168
}
pub fn record(&mut self, pps: f64) {
self.current_slot = self.slot_index();
self.slots[self.current_slot].update(pps);
}
pub fn record(&mut self, pps: f64) {
self.current_slot = self.slot_index();
self.slots[self.current_slot].update(pps);
}
pub fn baseline(&self) -> f64 {
self.slots[self.slot_index()].value()
}
pub fn baseline(&self) -> f64 {
self.slots[self.slot_index()].value()
}
pub fn anomaly_score(&self, pps: f64) -> f64 {
let base = self.baseline();
if base <= 0.0 {
return 0.0;
}
(pps / base).min(10.0)
}
pub fn anomaly_score(&self, pps: f64) -> f64 {
let base = self.baseline();
if base <= 0.0 {
return 0.0;
}
(pps / base).min(10.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::*;
#[test]
fn test_profiler_record_and_baseline() {
let mut p = TrafficProfiler::new();
p.record(1000.0);
p.record(1100.0);
let base = p.baseline();
assert!(base > 0.0);
}
#[test]
fn test_profiler_record_and_baseline() {
let mut p = TrafficProfiler::new();
p.record(1000.0);
p.record(1100.0);
let base = p.baseline();
assert!(base > 0.0);
}
#[test]
fn test_anomaly_score_normal() {
let mut p = TrafficProfiler::new();
for _ in 0..10 {
p.record(100.0);
}
let score = p.anomaly_score(100.0);
assert!(score < 2.0);
}
#[test]
fn test_anomaly_score_normal() {
let mut p = TrafficProfiler::new();
for _ in 0..10 {
p.record(100.0);
}
let score = p.anomaly_score(100.0);
assert!(score < 2.0);
}
#[test]
fn test_anomaly_score_capped() {
let mut p = TrafficProfiler::new();
for _ in 0..10 {
p.record(1.0);
}
let score = p.anomaly_score(1_000_000.0);
assert!((score - 10.0).abs() < 0.001);
}
#[test]
fn test_anomaly_score_capped() {
let mut p = TrafficProfiler::new();
for _ in 0..10 {
p.record(1.0);
}
let score = p.anomaly_score(1_000_000.0);
assert!((score - 10.0).abs() < 0.001);
}
#[test]
fn test_anomaly_score_zero_baseline() {
let p = TrafficProfiler::new();
assert_eq!(p.anomaly_score(100.0), 0.0);
}
#[test]
fn test_anomaly_score_zero_baseline() {
let p = TrafficProfiler::new();
assert_eq!(p.anomaly_score(100.0), 0.0);
}
}