feat(xdp): auto-ban from ringbuf events; fix feature gating, exit path, pow flake
- xdp: real 24-byte xdp_event parsing (fixes LE byte-swap of src IP), opt-in [xdp] auto_ban (RATE_LIMIT always, CONN_DROP at fails>=threshold; EVENT_BAN/POLICY_DROP excluded by design), rampart_xdp_autobans_total; wired in app before load(); 10 tests in tests/xdp_events.rs - build: --no-default-features compiles — redis paths cfg-gated behind store-redis, manager fail-fasts without it; CI gates the config now - app: RunExit enum replaces process::exit in lib; single exit site in main - tests: seed PoW roundtrip token (was ~1/16 flaky; 50 pre-fix fails -> 0) - docs: TODO statuses refreshed (round 2)
This commit is contained in:
parent
bf6d34c882
commit
f85ea6c380
23 changed files with 714 additions and 50 deletions
|
|
@ -2,5 +2,7 @@
|
|||
|
||||
pub mod runtime;
|
||||
pub mod services;
|
||||
mod shutdown;
|
||||
|
||||
pub use runtime::run;
|
||||
pub use shutdown::RunExit;
|
||||
|
|
|
|||
|
|
@ -17,10 +17,12 @@ use std::sync::Arc;
|
|||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
use super::services::{build_registry, build_whitelist, start_subnet_tracker, start_xdp};
|
||||
use super::shutdown::{RunExit, spawn_shutdown_drain};
|
||||
|
||||
fn attack_status_value(status: AttackStatus) -> i64 {
|
||||
match status {
|
||||
|
|
@ -32,9 +34,11 @@ fn attack_status_value(status: AttackStatus) -> i64 {
|
|||
|
||||
/// Точка входа edge-демона (`rampart`): то, что делал `main` бинаря.
|
||||
///
|
||||
/// Возвращает [`RunExit`] — выбор кода и самого завершения делает бинарь.
|
||||
///
|
||||
/// # Errors
|
||||
/// Ошибки старта: нечитаемый конфиг, пустой реестр протоколов, сбой listener.
|
||||
pub async fn run() -> anyhow::Result<()> {
|
||||
pub async fn run() -> anyhow::Result<RunExit> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
.init();
|
||||
|
|
@ -70,20 +74,9 @@ pub async fn run() -> anyhow::Result<()> {
|
|||
let allowed_1s = Arc::new(AtomicU64::new(0));
|
||||
|
||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
||||
let (drain_tx, drain_rx) = oneshot::channel();
|
||||
|
||||
let sig_tx = shutdown_tx.clone();
|
||||
// shutdown-таймер обязан завершить процесс; в исходном коде вызов жил
|
||||
// внутри `fn main` и был освобождён от clippy::exit. Чистый перенос в
|
||||
// lib сохранил бы поведение, поэтому узкий allow — минимальная цена.
|
||||
#[allow(clippy::exit)]
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
tracing::info!("shutdown signal received, draining connections...");
|
||||
let _ = sig_tx.send(true);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
tracing::info!("shutdown timeout reached, exiting");
|
||||
std::process::exit(0);
|
||||
});
|
||||
spawn_shutdown_drain(shutdown_tx.clone(), drain_tx);
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
if let Some(redis_url) = &config.store.redis_url
|
||||
|
|
@ -121,7 +114,7 @@ pub async fn run() -> anyhow::Result<()> {
|
|||
_ => None,
|
||||
};
|
||||
|
||||
let xdp_filter = start_xdp(&config, &shutdown_rx)?;
|
||||
let xdp_filter = start_xdp(&config, &shutdown_rx, &blacklist)?;
|
||||
let subnet_tracker = start_subnet_tracker(&config);
|
||||
monitor::spawn(
|
||||
&config.detect.prefix,
|
||||
|
|
@ -197,7 +190,15 @@ pub async fn run() -> anyhow::Result<()> {
|
|||
registry,
|
||||
subnet_tracker,
|
||||
));
|
||||
listener::run(config, gateway, hook, shutdown_rx).await
|
||||
tokio::select! {
|
||||
result = listener::run(config, gateway, hook, shutdown_rx) => {
|
||||
result?;
|
||||
Ok(RunExit::Ok)
|
||||
}
|
||||
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс
|
||||
// немедленно, как это делал прежний `process::exit(0)`.
|
||||
_ = drain_rx => Ok(RunExit::DrainTimeout),
|
||||
}
|
||||
}
|
||||
|
||||
async fn push_attack_event(writer: &Option<Arc<tokio::sync::Mutex<ClickHouseWriter>>>, pps: f64) {
|
||||
|
|
@ -216,14 +217,3 @@ async fn push_attack_event(writer: &Option<Arc<tokio::sync::Mutex<ClickHouseWrit
|
|||
tracing::debug!("clickhouse push error: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_signal() {
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("failed to install SIGTERM handler");
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
use crate::config::Config;
|
||||
use crate::engine::subnet::tracker::SubnetTracker;
|
||||
use crate::filter::blacklist::Blacklist;
|
||||
use crate::protocol::ProtocolRegistry;
|
||||
use crate::xdp::XdpFilter;
|
||||
#[cfg(feature = "xdp")]
|
||||
|
|
@ -10,7 +11,6 @@ use std::collections::HashSet;
|
|||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Собирает реестр протоколов из скомпилированных реализаций.
|
||||
|
|
@ -44,7 +44,10 @@ fn register_http(registry: &mut ProtocolRegistry, config: &Config) {
|
|||
pub(crate) fn start_xdp(
|
||||
config: &Arc<Config>,
|
||||
shutdown_rx: &watch::Receiver<bool>,
|
||||
blacklist: &Arc<Blacklist>,
|
||||
) -> anyhow::Result<Option<Arc<Mutex<XdpFilter>>>> {
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::xdp::XdpMetrics;
|
||||
|
||||
if !config.xdp.enabled {
|
||||
|
|
@ -57,6 +60,10 @@ pub(crate) fn start_xdp(
|
|||
let mut guard = shared.lock().expect("xdp lock poisoned");
|
||||
let globals = XdpGlobals::from_config(&config.xdp)?;
|
||||
guard.set_globals(globals);
|
||||
// Порядок load-bearing: `load()` захватывает blacklist и политику
|
||||
// авто-бана в ringbuf-колбэк (XdpFilter::load -> build_ringbuf),
|
||||
// поэтому set_autoban обязан отработать ДО load(), а не после.
|
||||
guard.set_autoban(blacklist.clone(), &config.xdp);
|
||||
guard.load()?;
|
||||
}
|
||||
let xdp_metrics = XdpMetrics::register()?;
|
||||
|
|
@ -87,6 +94,7 @@ pub(crate) fn start_xdp(
|
|||
pub(crate) fn start_xdp(
|
||||
_config: &Arc<Config>,
|
||||
_shutdown_rx: &watch::Receiver<bool>,
|
||||
_blacklist: &Arc<Blacklist>,
|
||||
) -> anyhow::Result<Option<Arc<Mutex<XdpFilter>>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
|
@ -107,7 +115,23 @@ pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>
|
|||
}
|
||||
}
|
||||
|
||||
/// Store-фичи проверяются на старте edge-демона: конфиг, запрашивающий redis,
|
||||
/// в бинаре без `store-redis` должен упасть сразу, а не молча потерять
|
||||
/// blacklist-sync (sync-задача в runtime.rs живёт под тем же cfg).
|
||||
/// Точка вызова — `build_whitelist`: ближайший `?`-хук, принимающий конфиг
|
||||
/// до бинда listener'а (сам runtime.rs вне правок этой задачи).
|
||||
fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) {
|
||||
anyhow::bail!("[store].redis_url requires a redis-backed store: built without store-redis feature");
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
let _ = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>> {
|
||||
ensure_store_features(config)?;
|
||||
let mut set = HashSet::with_capacity(config.whitelist.len());
|
||||
for entry in &config.whitelist {
|
||||
let ip: IpAddr = entry
|
||||
|
|
@ -117,3 +141,51 @@ pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpA
|
|||
}
|
||||
Ok(Arc::new(set))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config_with_redis() -> Config {
|
||||
Config {
|
||||
store: crate::config::StoreConfig {
|
||||
redis_url: Some("redis://127.0.0.1:6379/0".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn redis_config_without_feature_fails_fast() {
|
||||
let err = ensure_store_features(&config_with_redis()).expect_err("must fail without store-redis");
|
||||
assert!(err.to_string().contains("built without store-redis feature"));
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn empty_store_config_passes_without_feature() {
|
||||
assert!(ensure_store_features(&Config::default()).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
#[test]
|
||||
fn guard_is_noop_with_feature() {
|
||||
assert!(ensure_store_features(&config_with_redis()).is_ok());
|
||||
}
|
||||
|
||||
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>`
|
||||
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]`
|
||||
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()`
|
||||
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова.
|
||||
#[test]
|
||||
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
|
||||
let (_tx, rx) = watch::channel(false);
|
||||
let blacklist = Arc::new(Blacklist::new());
|
||||
let started = start_xdp(&Arc::new(Config::default()), &rx, &blacklist)
|
||||
.expect("xdp disabled: no kernel work and no error");
|
||||
assert!(started.is_none());
|
||||
assert!(blacklist.is_empty());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
67
src/app/shutdown.rs
Normal file
67
src/app/shutdown.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! Shutdown-drain машина edge-демона: сигнал, drain-таймер и код завершения.
|
||||
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Результат завершения демона. Код выхода вычисляется здесь, но сам
|
||||
/// `process::exit` вызывается только в точке входа бинаря (`src/bin/rampart.rs`),
|
||||
/// поэтому библиотечный код остаётся свободным от lint `exit`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunExit {
|
||||
/// Listener отработал штатно: drain уложился в таймаут.
|
||||
Ok,
|
||||
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно
|
||||
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера).
|
||||
DrainTimeout,
|
||||
}
|
||||
|
||||
impl RunExit {
|
||||
/// Код завершения процесса для данного результата.
|
||||
#[must_use]
|
||||
pub const fn code(self) -> i32 {
|
||||
match self {
|
||||
Self::Ok => 0,
|
||||
Self::DrainTimeout => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ставит фоновую shutdown-задачу.
|
||||
///
|
||||
/// shutdown-таймер обязан завершить процесс: сам `process::exit` вынесен в
|
||||
/// бинарь, а здесь мы лишь уведомляем `run` об истечении drain-таймаута через
|
||||
/// oneshot-канал. Логи и тайминг (5s после сигнала) сохранены без изменений.
|
||||
pub(crate) fn spawn_shutdown_drain(shutdown_tx: watch::Sender<bool>, drain_tx: oneshot::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
tracing::info!("shutdown signal received, draining connections...");
|
||||
let _ = shutdown_tx.send(true);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
tracing::info!("shutdown timeout reached, exiting");
|
||||
let _ = drain_tx.send(());
|
||||
});
|
||||
}
|
||||
|
||||
async fn wait_for_signal() {
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("failed to install SIGTERM handler");
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::RunExit;
|
||||
|
||||
#[test]
|
||||
fn run_exit_codes_match_previous_process_exit() {
|
||||
// Штатный путь и прежний drain-timeout (`process::exit(0)`) завершались с кодом 0.
|
||||
assert_eq!(RunExit::Ok.code(), 0);
|
||||
assert_eq!(RunExit::DrainTimeout.code(), 0);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue