fix(core): close auth bypass, hangs and memory leaks found by review

Security:
- An empty API_PASSWORD passed validation (only the literal "changeme" was
  rejected) and verify_password("", "") returned true, so a login with an
  empty password minted an admin token. Require >= 16 characters and >= 32
  non-whitespace bytes for JWT_SECRET; verify rejects an empty stored secret.
- syn_challenge_enabled required a real challenge_secret_hex: the public
  placeholder from config.h is now rejected in every spelling.
- docker-compose: Redis/ClickHouse/Grafana are loopback-only and every
  password uses ${VAR:?} instead of a default. An exposed Redis was a way to
  lift bans and publish unbans to the whole fleet with one redis-cli.
- Empty CORS_ORIGIN no longer means "allow any origin".
- ban_cidr / userspace blacklist validate and mask prefixes; CIDR bans are
  stored as ranges, so a /24 or /64 ban actually covers the subnet (before,
  only the network address was blocked).

Availability:
- ClickHouse client has connect/request timeouts and no mutex held across
  await: a hung analytics backend can no longer freeze the ban path. Events
  go through a bounded buffer with a drop counter.
- Redis uses a ConnectionManager with per-command timeouts; pubsub and
  reconcile reset the backoff after success; publish cannot block shutdown.
- Ban durations from pubsub are clamped and use checked_add; the sync task
  survives panics instead of silently dying.
- Blacklist TOCTOU (remove_if) and replace_redis no longer empties the table
  during a Redis reconnect.
- RateLimiter and reputation have hard caps with incremental eviction instead
  of an unbounded DashMap and a stop-the-world retain.
- The attack detector scores before updating its baseline and needs several
  quiet windows to leave UnderAttack, so a sustained flood keeps banning new
  offenders instead of ending after one tick.
- accept() backs off on EMFILE/ENFILE, shutdown Err is treated as shutdown,
  a global semaphore bounds in-flight connections, rate limiting runs before
  PoW, whitelisted IPs are never banned, and connect/handshake/relay have
  timeouts with an idle budget.
- PoW uses the configured difficulty as a floor, the clamp is enforced, and
  nonce framing survives split segments and coalesced handshake bytes.
- Subnet tracker memory is capped (prefixes and per-prefix sources) and the
  monitor bans with the configured TTL.

CI and docs:
- CI runs the test suite with --no-default-features --features protocol-http;
  make ebpf fails on errors; the secrets gate catches weak compose defaults.
- doctor skips protected endpoints without a token and exits non-zero on
  failure; a drain timeout returns exit code 1.
- TODO §2b records the review findings, what is fixed and what is deferred;
  configuration/testing docs describe the new XDP and secret semantics.
This commit is contained in:
Loki 2026-11-16 12:06:23 +01:00
parent 14dcaccdbf
commit c1a076a4a3
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
57 changed files with 4193 additions and 1171 deletions

15
tests/app_shutdown.rs Normal file
View file

@ -0,0 +1,15 @@
//! Edge daemon exit codes: a forced drain timeout must not look like success.
use rampart::app::RunExit;
#[test]
fn clean_shutdown_exits_zero() {
assert_eq!(RunExit::Ok.code(), 0);
}
#[test]
fn forced_drain_timeout_exits_nonzero() {
// Connections were cut before finishing: supervisors and scripts must see a
// failure, not a clean exit.
assert_eq!(RunExit::DrainTimeout.code(), 1);
}

View file

@ -0,0 +1,81 @@
//! Integration tests for the ClickHouse sink: buffering, bounded flush and
//! retry on failure.
use std::time::{Duration, Instant};
use rampart::store::clickhouse::{ClickHouseEvent, ClickHouseWriter, MAX_BUFFER_EVENTS};
fn event(seq: usize) -> ClickHouseEvent {
ClickHouseEvent {
timestamp: chrono::Utc::now(),
event_type: "test".to_string(),
ip: format!("192.0.2.{}", seq % 250),
data_float: 0.0,
data_int: 0,
data_string: String::new(),
}
}
#[tokio::test]
async fn push_only_buffers_events() {
let mut writer = ClickHouseWriter::new("http://127.0.0.1:1");
writer.push(event(0)).await.expect("push must succeed");
assert_eq!(writer.pending(), 1, "push must not flush eagerly");
assert_eq!(writer.dropped(), 0);
}
#[tokio::test]
async fn empty_flush_is_a_noop() {
let mut writer = ClickHouseWriter::new("http://127.0.0.1:1");
writer.flush().await.expect("empty flush must not touch the network");
}
#[tokio::test]
async fn failed_flush_requeues_the_batch() {
let mut writer = ClickHouseWriter::new("http://127.0.0.1:1");
writer.push(event(1)).await.expect("push must succeed");
let result = writer.flush().await;
assert!(result.is_err(), "connection refused must surface as an error");
assert_eq!(writer.pending(), 1, "failed batch must be re-queued");
assert_eq!(writer.dropped(), 0, "a single failed batch is not a drop");
}
#[tokio::test]
async fn stalled_server_flush_is_bounded() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
let addr = listener.local_addr().expect("local addr");
let server = tokio::spawn(async move {
let (_stream, _) = listener.accept().await.expect("accept");
// Keep the connection open without ever answering.
std::future::pending::<()>().await;
});
let mut writer = ClickHouseWriter::new(&format!("http://{addr}/"));
writer.push(event(2)).await.expect("push must succeed");
let started = Instant::now();
let result = writer.flush().await;
let elapsed = started.elapsed();
server.abort();
assert!(result.is_err(), "a stalled server must fail the flush");
assert!(
elapsed < Duration::from_secs(5),
"flush must be bounded, took {elapsed:?}"
);
assert_eq!(writer.pending(), 1, "timed-out batch must be re-queued");
}
#[tokio::test]
async fn buffer_is_bounded_and_overflow_is_counted() {
let mut writer = ClickHouseWriter::new("http://127.0.0.1:1");
for seq in 0..MAX_BUFFER_EVENTS + 7 {
writer.push(event(seq)).await.expect("push must succeed");
}
assert_eq!(writer.pending(), MAX_BUFFER_EVENTS, "buffer must stay bounded");
assert_eq!(writer.dropped(), 7, "overflow must be counted");
}

View file

@ -142,3 +142,127 @@ events_enabled = false
assert!(!xdp.throttle_enabled);
assert!(!xdp.events_enabled);
}
#[test]
fn prefix_detect_defaults_disabled() {
let config = Config::parse_str("").expect("empty config must parse");
assert!(!config.detect.prefix.enabled);
assert_eq!(config.detect.prefix.syn_threshold, 500);
assert_eq!(config.detect.prefix.window_secs, 10);
assert_eq!(config.detect.prefix.min_unique_sources, 16);
}
#[test]
fn prefix_detect_section_parses() {
let config = Config::parse_str(
r#"
[detect.prefix]
enabled = true
syn_threshold = 1000
window_secs = 5
min_unique_sources = 8
"#,
)
.expect("detect.prefix section must parse");
assert!(config.detect.prefix.enabled);
assert_eq!(config.detect.prefix.syn_threshold, 1000);
assert_eq!(config.detect.prefix.window_secs, 5);
assert_eq!(config.detect.prefix.min_unique_sources, 8);
}
#[test]
fn prefix_detect_zero_threshold_rejected_when_enabled() {
let err = Config::parse_str("[detect.prefix]\nenabled = true\nsyn_threshold = 0\n")
.expect_err("zero threshold must be rejected");
assert!(err.to_string().contains("detect.prefix.syn_threshold"));
}
#[test]
fn syn_challenge_requires_a_secret() {
let err = Config::parse_str("[xdp]\nsyn_challenge_enabled = true\n")
.expect_err("missing challenge secret must be rejected");
let message = err.to_string();
assert!(message.contains("challenge_secret_hex"));
assert!(message.contains("openssl rand -hex 8"));
}
#[test]
fn syn_challenge_rejects_every_placeholder_spelling() {
for secret in [
"a5a5a5a5a5a5a5a5",
"A5A5A5A5A5A5A5A5",
"0xA5A5A5A5A5A5A5A5",
"a5a5-5a5a-5a5a-a5a5",
"a5a55a5a5a5aa5a5",
"A5A5_5A5A_5A5A_A5A5",
"0xa5a55a5a5a5aa5a5",
] {
let toml = format!("[xdp]\nsyn_challenge_enabled = true\nchallenge_secret_hex = \"{secret}\"\n");
let err = Config::parse_str(&toml).expect_err("placeholder secret must be rejected");
assert!(
err.to_string().contains("placeholder"),
"secret '{secret}' must be rejected"
);
}
}
#[test]
fn syn_challenge_accepts_a_generated_secret() {
let config =
Config::parse_str("[xdp]\nsyn_challenge_enabled = true\nchallenge_secret_hex = \"9f3c71a0b2d84e65\"\n")
.expect("random challenge secret must be accepted");
assert_eq!(config.xdp.challenge_secret_hex.as_deref(), Some("9f3c71a0b2d84e65"));
}
#[test]
fn rejects_non_positive_rate_limit() {
for pps in ["0.0", "-1.0", "nan", "inf"] {
let toml = format!("[limits]\nrate_limit_pps = {pps}\n");
let err = Config::parse_str(&toml).expect_err("rate_limit_pps must be positive and finite");
assert!(
err.to_string().contains("limits.rate_limit_pps"),
"pps '{pps}' must be rejected"
);
}
}
#[test]
fn rejects_rate_limit_burst_below_one() {
for burst in ["0.0", "0.5", "nan"] {
let toml = format!("[limits]\nrate_limit_burst = {burst}\n");
let err = Config::parse_str(&toml).expect_err("rate_limit_burst must be at least 1");
assert!(
err.to_string().contains("limits.rate_limit_burst"),
"burst '{burst}' must be rejected"
);
}
}
#[test]
fn rejects_out_of_range_ban_duration() {
let err = Config::parse_str("[ban]\nban_duration_secs = 0\n").expect_err("zero ban duration must be rejected");
assert!(err.to_string().contains("ban.ban_duration_secs"));
let err = Config::parse_str("[ban]\nban_duration_secs = 31536001\n")
.expect_err("ban duration above one year must be rejected");
assert!(err.to_string().contains("ban.ban_duration_secs"));
assert!(Config::parse_str("[ban]\nban_duration_secs = 31536000\n").is_ok());
}
#[test]
fn rejects_out_of_range_pow_difficulty() {
for difficulty in ["0", "11"] {
let toml = format!("[pow]\nenabled = true\ndifficulty = {difficulty}\n");
let err = Config::parse_str(&toml).expect_err("pow.difficulty must stay in 1..=10");
assert!(
err.to_string().contains("pow.difficulty"),
"difficulty '{difficulty}' must be rejected"
);
}
assert!(Config::parse_str("[pow]\ndifficulty = 10\n").is_ok());
}
#[test]
fn rejects_zero_workers() {
let err = Config::parse_str("[workers]\ncount = 0\n").expect_err("zero workers must be rejected");
assert!(err.to_string().contains("workers.count"));
}

313
tests/connection_limits.rs Normal file
View file

@ -0,0 +1,313 @@
//! Connection-path limits: filter order around the PoW gate, the whitelist
//! exemption from bans, accept-loop backoff and the idle relay timeout.
use rampart::config::Config;
use rampart::engine::challenge::DifficultyAdjuster;
use rampart::engine::listener::AcceptBackoff;
use rampart::engine::tunnel::Gateway;
use rampart::filter::blacklist::Blacklist;
use rampart::filter::rate_limit::RateLimiter;
use rampart::protocol::ProtocolRegistry;
use rampart::traffic::reputation::IpReputation;
use std::collections::HashSet;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicU64;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
/// Linux `EMFILE` (too many open files), the errno behind the accept spin.
#[cfg(target_os = "linux")]
const EMFILE: i32 = 24;
/// Builds a gateway with the cheap collaborators and no XDP/ClickHouse/protocol
/// handler, so every stage past the filters fails fast.
fn test_gateway(config: Config, whitelist: HashSet<IpAddr>) -> Arc<Gateway> {
Arc::new(Gateway::new(
Arc::new(config.clone()),
Arc::new(RateLimiter::new(
config.limits.rate_limit_pps,
config.limits.rate_limit_burst,
)),
Arc::new(Blacklist::new()),
Arc::new(Mutex::new(DifficultyAdjuster::default())),
Arc::new(whitelist),
Arc::new(IpReputation::new()),
None,
None,
Arc::new(AtomicU64::new(0)),
Arc::new(ProtocolRegistry::new()),
None,
))
}
/// Returns a connected client/server pair over loopback.
async fn loopback() -> (TcpStream, TcpStream) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback");
let addr = listener.local_addr().expect("local addr");
let (client, accepted) = tokio::join!(TcpStream::connect(addr), listener.accept());
(client.expect("connect"), accepted.expect("accept").0)
}
/// Reads one newline-terminated line without blocking past `limit`.
async fn read_line(stream: &mut TcpStream, limit: Duration) -> io::Result<Vec<u8>> {
let mut line = Vec::new();
let mut byte = [0u8; 1];
loop {
let read = tokio::time::timeout(limit, stream.read(&mut byte)).await??;
if read == 0 || byte[0] == b'\n' {
return Ok(line);
}
line.push(byte[0]);
}
}
/// A rate-limited client must be rejected before the PoW exchange starts, so
/// no challenge is written and the task never waits for a solver.
#[tokio::test]
async fn rate_limit_runs_before_pow() {
let mut config = Config::default();
config.limits.rate_limit_pps = 0.0;
config.limits.rate_limit_burst = 0.0;
config.pow.enabled = true;
config.pow.difficulty = 1;
let gateway = test_gateway(config, HashSet::new());
let (mut client, server) = loopback().await;
let peer = SocketAddr::from(([203, 0, 113, 7], 51_000));
let started = tokio::time::Instant::now();
let outcome = gateway.handle(server, peer).await;
assert!(outcome.result.is_ok(), "a rate-limited connection is dropped silently");
assert!(
started.elapsed() < Duration::from_millis(500),
"rate limit must short-circuit the PoW gate"
);
let mut scratch = [0u8; 64];
let read = tokio::time::timeout(Duration::from_secs(1), client.read(&mut scratch))
.await
.expect("read must not hang")
.expect("read must succeed");
assert_eq!(read, 0, "a rate-limited client must not receive a PoW challenge");
}
/// A client that never answers PoW must still burn its own token, so the next
/// attempt from the same source is rate limited instead of parked in PoW.
#[tokio::test]
async fn silent_pow_client_exhausts_budget_for_next_attempt() {
let mut config = Config::default();
config.limits.rate_limit_pps = 0.0;
config.limits.rate_limit_burst = 1.0;
config.pow.enabled = true;
config.pow.difficulty = 1;
let gateway = test_gateway(config, HashSet::new());
let peer = SocketAddr::from(([203, 0, 113, 8], 51_001));
let (mut first_client, first_server) = loopback().await;
let first_gateway = Arc::clone(&gateway);
let first = tokio::spawn(async move { first_gateway.handle(first_server, peer).await.result });
let challenge = read_line(&mut first_client, Duration::from_secs(2))
.await
.expect("first attempt must reach the PoW gate");
assert!(!challenge.is_empty(), "PoW gate issues a challenge line");
let (mut second_client, second_server) = loopback().await;
let started = tokio::time::Instant::now();
let outcome = gateway.handle(second_server, peer).await;
assert!(outcome.result.is_ok());
assert!(
started.elapsed() < Duration::from_millis(500),
"second attempt must be rejected by the rate limiter, not queued behind PoW"
);
let mut scratch = [0u8; 1];
let read = second_client.read(&mut scratch).await.expect("read must succeed");
assert_eq!(read, 0, "second attempt is closed without a challenge");
first.abort();
}
/// A whitelisted source stays exempt from the rate limiter and is never
/// auto-banned, even after enough abuse to drive reputation below the ban
/// threshold, and an existing ban entry is ignored for it.
#[tokio::test]
async fn whitelisted_peer_is_exempt_from_rate_limit_and_ban() {
let mut config = Config::default();
config.limits.rate_limit_pps = 0.0;
config.limits.rate_limit_burst = 0.0;
let trusted = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 10));
let gateway = test_gateway(config, HashSet::from([trusted]));
let peer = SocketAddr::new(trusted, 51_002);
for _ in 0..8 {
let (_client, server) = loopback().await;
let outcome = gateway.handle(server, peer).await;
assert!(
outcome.result.is_err(),
"a trusted peer must pass every filter and reach the (empty) registry"
);
}
assert!(
!gateway.blacklist.is_blocked(trusted),
"a trusted peer must never be banned"
);
assert_eq!(
gateway.reputation.score(trusted),
0,
"trusted traffic is not scored as abusive"
);
gateway
.blacklist
.add(trusted, Duration::from_secs(60), "stale-test-ban");
let (_client, server) = loopback().await;
assert!(
gateway.handle(server, peer).await.result.is_err(),
"the whitelist overrides an existing blacklist entry"
);
}
/// The untrusted counterpart: repeated rate-limit hits drive reputation below
/// the threshold and the peer is banned.
#[tokio::test]
async fn repeated_rate_limit_hits_auto_ban_untrusted_peer() {
let mut config = Config::default();
config.limits.rate_limit_pps = 0.0;
config.limits.rate_limit_burst = 0.0;
let gateway = test_gateway(config, HashSet::new());
let peer_ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9));
let peer = SocketAddr::new(peer_ip, 51_003);
for _ in 0..5 {
let (_client, server) = loopback().await;
assert!(
gateway.handle(server, peer).await.result.is_ok(),
"a rate-limited connection is dropped silently"
);
}
assert!(
gateway.blacklist.is_blocked(peer_ip),
"reputation below -40 must ban the peer"
);
}
/// Backoff doubles from 50ms to a 500ms cap and restarts after a successful
/// accept.
#[cfg(target_os = "linux")]
#[test]
fn accept_backoff_grows_caps_and_resets() {
let mut backoff = AcceptBackoff::new();
let error = io::Error::from_raw_os_error(EMFILE);
let expected = [50u64, 100, 200, 400, 500, 500];
for milliseconds in expected {
assert_eq!(backoff.delay(&error), Some(Duration::from_millis(milliseconds)));
}
backoff.reset();
assert_eq!(
backoff.delay(&error),
Some(Duration::from_millis(50)),
"reset after a successful accept restarts at the minimum"
);
}
/// Peer-abort errors need no delay: retrying immediately is correct there.
#[test]
fn accept_backoff_skips_non_transient_errors() {
let mut backoff = AcceptBackoff::new();
assert_eq!(backoff.delay(&io::Error::from(io::ErrorKind::ConnectionAborted)), None);
assert_eq!(backoff.delay(&io::Error::from(io::ErrorKind::InvalidInput)), None);
}
/// Error logging is rate limited: first failure and then one per window.
#[cfg(target_os = "linux")]
#[test]
fn accept_backoff_rate_limits_error_logs() {
let mut backoff = AcceptBackoff::new();
let error = io::Error::from_raw_os_error(EMFILE);
assert!(backoff.delay(&error).is_some());
assert!(
backoff.should_log(),
"the first failure is always logged at error level"
);
assert!(backoff.delay(&error).is_some());
assert!(!backoff.should_log(), "repeated failures stay at debug level");
for _ in 2..32 {
assert!(backoff.delay(&error).is_some());
}
assert!(backoff.should_log(), "a periodic reminder keeps the condition visible");
}
/// The loop must spend real time sleeping instead of spinning. `tokio`'s
/// `test-util` feature is not compiled in, so this uses the real minimum
/// backoff (50ms) with a short iteration count.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn accept_backoff_sleeps_instead_of_spinning() {
let mut backoff = AcceptBackoff::new();
let error = io::Error::from_raw_os_error(EMFILE);
let started = tokio::time::Instant::now();
let mut slept = Duration::ZERO;
for _ in 0..3 {
let delay = backoff.delay(&error).expect("transient error must back off");
assert!(!delay.is_zero(), "a failed accept must yield a non-zero delay");
tokio::time::sleep(delay).await;
slept += delay;
}
assert!(slept >= Duration::from_millis(350), "50+100+200ms of mandatory backoff");
assert!(
started.elapsed() >= slept,
"the loop cannot advance faster than its backoff"
);
}
/// A silent pair is closed by the relay idle timeout instead of pinning two
/// descriptors forever.
#[tokio::test]
async fn relay_idle_timeout_closes_silent_pair() {
let gateway = test_gateway(Config::default(), HashSet::new());
let (_client_peer, gateway_side) = loopback().await;
let (backend_gateway_side, _backend_peer) = loopback().await;
let idle = Duration::from_millis(60);
let started = tokio::time::Instant::now();
let result = tokio::time::timeout(
Duration::from_secs(2),
gateway.relay_with_idle(gateway_side, backend_gateway_side, idle),
)
.await
.expect("relay must be cut by the idle timeout, not hang");
assert!(result.is_err(), "silent relay must be cut by the idle timeout");
assert!(started.elapsed() >= idle, "the idle budget must actually elapse");
}
/// The idle budget must not break normal forwarding in either direction.
#[tokio::test]
async fn relay_forwards_bytes_in_both_directions() {
let gateway = test_gateway(Config::default(), HashSet::new());
let (mut client_peer, client_side) = loopback().await;
let (backend_side, mut backend_peer) = loopback().await;
let relay = tokio::spawn(async move {
gateway
.relay_with_idle(client_side, backend_side, Duration::from_secs(5))
.await
});
client_peer.write_all(b"ping").await.expect("write to relay");
let mut buffer = [0u8; 4];
backend_peer.read_exact(&mut buffer).await.expect("backend read");
assert_eq!(&buffer, b"ping");
backend_peer.write_all(b"pong").await.expect("write from backend");
client_peer.read_exact(&mut buffer).await.expect("client read");
assert_eq!(&buffer, b"pong");
drop(client_peer);
assert!(
relay.await.expect("relay task").is_ok(),
"clean half-close is not an error"
);
}

View file

@ -57,3 +57,201 @@ fn blacklist_remove_clears_ban() {
blacklist.remove(ip(7));
assert!(!blacklist.is_blocked(ip(7)));
}
#[test]
fn blacklist_expired_cleanup_keeps_fresh_reban() {
let blacklist = Blacklist::new();
blacklist.add(ip(8), Duration::ZERO, "stale");
assert!(!blacklist.is_blocked(ip(8)), "zero-duration ban is already expired");
blacklist.add(ip(8), Duration::from_secs(60), "fresh");
assert!(
blacklist.is_blocked(ip(8)),
"expired-entry cleanup must not delete a fresh ban"
);
assert_eq!(blacklist.len(), 1);
}
#[test]
fn blacklist_expired_cleanup_does_not_race_with_reban() {
let blacklist = std::sync::Arc::new(Blacklist::new());
let reader = blacklist.clone();
let handle = std::thread::spawn(move || {
for _ in 0..2000 {
let _ = reader.is_blocked(ip(9));
std::thread::yield_now();
}
});
for _ in 0..2000 {
blacklist.add(ip(9), Duration::ZERO, "stale");
blacklist.add(ip(9), Duration::from_secs(60), "fresh");
}
handle.join().expect("reader thread must not panic");
assert!(
blacklist.is_blocked(ip(9)),
"a concurrently refreshed ban must survive stale cleanup"
);
}
#[test]
fn blacklist_clamps_huge_durations_without_panicking() {
let blacklist = Blacklist::new();
blacklist.add(ip(10), Duration::from_secs(u64::MAX), "hostile");
blacklist.add_redis(ip(11), Duration::from_secs(u64::MAX), "hostile");
assert!(blacklist.is_blocked(ip(10)), "local ban must be clamped, not dropped");
assert!(blacklist.is_blocked(ip(11)), "redis ban must be clamped, not dropped");
}
#[test]
fn replace_redis_keeps_new_bans_and_local_entries() {
let blacklist = Blacklist::new();
blacklist.add(ip(12), Duration::from_secs(60), "local");
blacklist.add_redis(ip(13), Duration::from_secs(60), "stale-upstream");
blacklist.replace_redis([
(ip(14), Duration::from_secs(60), "upstream".to_string()),
(ip(15), Duration::from_secs(60), "upstream".to_string()),
]);
assert!(blacklist.is_blocked(ip(14)), "new upstream ban must apply immediately");
assert!(blacklist.is_blocked(ip(15)), "new upstream ban must apply immediately");
assert!(!blacklist.is_blocked(ip(13)), "ban removed upstream must stop applying");
assert!(
blacklist.is_blocked(ip(12)),
"local bans must survive a Redis reconcile"
);
}
#[test]
fn replace_redis_can_clear_every_mirrored_ban() {
let blacklist = Blacklist::new();
blacklist.add_redis(ip(16), Duration::from_secs(60), "stale-upstream");
blacklist.replace_redis(std::iter::empty());
assert!(!blacklist.is_blocked(ip(16)));
assert!(blacklist.is_empty());
}
fn numbered(index: u32) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + index))
}
#[test]
fn rate_limiter_enforces_a_hard_bucket_cap() {
let limiter = RateLimiter::with_capacity(1.0, 1.0, 4, Duration::from_secs(600));
let admitted = (0..100).filter(|index| limiter.check(numbered(*index))).count();
assert_eq!(admitted, 4, "only max_buckets new sources may be admitted");
assert_eq!(limiter.len(), 4);
assert!(
!limiter.check(numbered(500)),
"a new source fails closed once the table is saturated"
);
assert_eq!(limiter.len(), 4, "a refused source must not allocate a bucket");
}
#[test]
fn rate_limiter_sweep_frees_capacity_and_keeps_active() {
let limiter = RateLimiter::with_capacity(1.0, 10.0, 2, Duration::from_millis(100));
assert!(limiter.check(ip(1)));
assert!(limiter.check(ip(2)));
std::thread::sleep(Duration::from_millis(200));
assert!(limiter.check(ip(2)), "the active source still has tokens");
for _ in 0..8 {
limiter.sweep();
}
assert_eq!(limiter.len(), 1, "idle bucket evicted, active bucket kept");
assert!(limiter.check(ip(3)), "eviction must free a slot for a new source");
}
#[test]
fn rate_limiter_sweep_is_incremental() {
let limiter = RateLimiter::with_capacity(1000.0, 1.0, 4096, Duration::from_millis(10));
for index in 0..4096 {
assert!(limiter.check(numbered(index)));
}
std::thread::sleep(Duration::from_millis(20));
let first = limiter.sweep();
assert!(first > 0, "the first sweep must reclaim idle buckets");
assert!(first < 4096, "one sweep must not scan the whole table");
assert!(!limiter.is_empty(), "a single sweep leaves work for the next tick");
for _ in 0..8 {
limiter.sweep();
}
assert!(limiter.is_empty(), "a full shard cycle reclaims every idle bucket");
}
#[test]
fn cidr_ban_covers_the_whole_range() {
let blacklist = Blacklist::new();
blacklist.add_cidr(
IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)),
24,
Duration::from_secs(60),
"subnet",
);
assert!(blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 1))));
assert!(blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 2, 255))));
assert!(!blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 1, 3, 1))));
}
#[test]
fn cidr_ban_normalises_host_bits_and_v4_mapped_addresses() {
let blacklist = Blacklist::new();
blacklist.add_cidr(
IpAddr::V4(Ipv4Addr::new(10, 7, 9, 200)),
24,
Duration::from_secs(60),
"subnet",
);
let mapped: IpAddr = "::ffff:10.7.9.1".parse().expect("mapped ipv4");
assert!(blacklist.is_blocked(mapped), "/24 ban must cover the mapped form too");
}
#[test]
fn cidr_ban_expires() {
let blacklist = Blacklist::new();
blacklist.add_cidr(
IpAddr::V4(Ipv4Addr::new(10, 8, 0, 0)),
16,
Duration::from_millis(1),
"subnet",
);
std::thread::sleep(Duration::from_millis(5));
assert!(!blacklist.is_blocked(IpAddr::V4(Ipv4Addr::new(10, 8, 0, 1))));
blacklist.clear_expired();
assert!(blacklist.is_empty());
}
#[test]
fn invalid_cidr_prefix_is_ignored() {
let blacklist = Blacklist::new();
blacklist.add_cidr(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
0,
Duration::from_secs(60),
"subnet",
);
blacklist.add_cidr(
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
33,
Duration::from_secs(60),
"subnet",
);
assert!(blacklist.is_empty(), "a /0 or /33 ban must not be installed");
}
#[test]
fn ipv6_cidr_ban_covers_the_range() {
let blacklist = Blacklist::new();
let prefix: IpAddr = "fd00:1234:5678:9abc::".parse().expect("ipv6 prefix");
blacklist.add_cidr(prefix, 64, Duration::from_secs(60), "subnet");
let inside: IpAddr = "fd00:1234:5678:9abc::42".parse().expect("ipv6 inside");
let outside: IpAddr = "fd00:1234:5678:9abd::1".parse().expect("ipv6 outside");
assert!(blacklist.is_blocked(inside));
assert!(!blacklist.is_blocked(outside));
}

124
tests/manager_security.rs Normal file
View file

@ -0,0 +1,124 @@
//! Management-plane security: API password/JWT policy and the CORS downgrade.
//!
//! Regression tests for the authentication bypass where an empty
//! `API_PASSWORD` matched an empty login (`verify_password("", "")`).
use dashmap::DashMap;
use rampart::manager::api::auth::allow_login_attempt;
use rampart::manager::security::{CorsPolicy, validate_api_password, validate_jwt_secret, verify_password};
use std::net::IpAddr;
const STRONG_PASSWORD: &str = "correct-horse-battery-staple";
const STRONG_SECRET: &str = "0123456789abcdef0123456789abcdef";
#[test]
fn rejects_empty_api_password() {
let err = validate_api_password("").expect_err("empty password must be rejected");
assert!(err.to_string().contains("must not be empty"));
}
#[test]
fn rejects_whitespace_only_api_password() {
assert!(validate_api_password(" ").is_err());
}
#[test]
fn rejects_short_api_password() {
let short = "a".repeat(15);
let err = validate_api_password(&short).expect_err("15 characters must be rejected");
assert!(err.to_string().contains("at least 16"));
assert!(validate_api_password(&"a".repeat(16)).is_ok());
}
#[test]
fn rejects_placeholder_api_password() {
assert!(validate_api_password("changeme").is_err());
assert!(validate_api_password("ChangeMe").is_err());
assert!(validate_api_password(" changeme ").is_err());
}
#[test]
fn accepts_strong_api_password() {
assert!(validate_api_password(STRONG_PASSWORD).is_ok());
}
#[test]
fn empty_stored_password_never_verifies() {
assert!(!verify_password("", ""));
assert!(!verify_password("anything", ""));
}
#[test]
fn verify_password_matches_exact_value_only() {
assert!(verify_password(STRONG_PASSWORD, STRONG_PASSWORD));
assert!(!verify_password("wrong-password", STRONG_PASSWORD));
assert!(!verify_password("short", STRONG_PASSWORD));
}
#[test]
fn rejects_empty_or_short_jwt_secret() {
assert!(validate_jwt_secret("").is_err());
assert!(validate_jwt_secret(&" ".repeat(64)).is_err());
assert!(validate_jwt_secret(&"a".repeat(31)).is_err());
let err = validate_jwt_secret(" \t\n").expect_err("whitespace must be rejected");
assert!(err.to_string().contains("non-whitespace"));
}
#[test]
fn accepts_strong_jwt_secret() {
assert!(validate_jwt_secret(STRONG_SECRET).is_ok());
assert!(validate_jwt_secret(&format!(" {STRONG_SECRET} ")).is_ok());
}
#[test]
fn cors_without_explicit_origin_is_denied() {
assert_eq!(CorsPolicy::parse(None).expect("unset is valid"), CorsPolicy::Deny);
assert_eq!(CorsPolicy::parse(Some("")).expect("empty is valid"), CorsPolicy::Deny);
assert_eq!(
CorsPolicy::parse(Some(" ")).expect("blank is valid"),
CorsPolicy::Deny
);
assert!(CorsPolicy::Deny.cors_layer().is_none());
}
#[test]
fn cors_wildcard_requires_explicit_flag() {
assert_eq!(
CorsPolicy::parse(Some("*")).expect("wildcard is valid"),
CorsPolicy::Any
);
assert!(CorsPolicy::Any.cors_layer().is_some());
}
#[test]
fn cors_origin_list_is_trimmed() {
let policy = CorsPolicy::parse(Some("https://a.example, https://b.example")).expect("list must parse");
assert_eq!(
policy,
CorsPolicy::AllowList(vec!["https://a.example".to_owned(), "https://b.example".to_owned()])
);
assert!(policy.cors_layer().is_some());
}
#[test]
fn cors_rejects_empty_entries_and_mixed_wildcard() {
assert!(CorsPolicy::parse(Some("https://a.example,")).is_err());
assert!(CorsPolicy::parse(Some("https://a.example,*")).is_err());
}
#[test]
fn cors_rejects_invalid_header_value() {
// A newline inside an origin is a header-injection attempt, not a valid value.
assert!(CorsPolicy::parse(Some("https://evil.example\nSet-Cookie: x")).is_err());
assert!(CorsPolicy::parse(Some("https://evil.example/\u{7f}")).is_err());
}
#[test]
fn login_limiter_blocks_after_five_attempts() {
let limiter = DashMap::new();
let ip = IpAddr::from([127, 0, 0, 1]);
for _ in 0..5 {
assert!(allow_login_attempt(&limiter, ip));
}
assert!(!allow_login_attempt(&limiter, ip));
}

80
tests/pow_difficulty.rs Normal file
View file

@ -0,0 +1,80 @@
//! Adaptive PoW difficulty: configured floor, range clamping and the rate
//! ladder. The adjuster lives in `src/engine/challenge/difficulty.rs`; these
//! tests are the only consumer of the range constants.
use rampart::engine::challenge::{DifficultyAdjuster, MAX_DIFFICULTY, MIN_DIFFICULTY};
#[test]
fn idle_uses_the_configured_floor() {
let adjuster = DifficultyAdjuster::new(4, 10);
assert_eq!(adjuster.current_difficulty(), 4);
}
#[test]
fn configured_pow_difficulty_is_the_starting_point() {
// `[pow].difficulty = 7` must not be ignored until the first connection.
assert_eq!(DifficultyAdjuster::with_floor(7).current_difficulty(), 7);
}
#[test]
fn configured_floor_can_be_lower_than_the_old_hardcoded_minimum() {
assert_eq!(DifficultyAdjuster::with_floor(2).current_difficulty(), 2);
}
#[test]
fn configured_floor_is_clamped_to_the_supported_range() {
assert_eq!(DifficultyAdjuster::with_floor(0).current_difficulty(), MIN_DIFFICULTY);
assert_eq!(DifficultyAdjuster::with_floor(250).current_difficulty(), MAX_DIFFICULTY);
}
#[test]
fn inverted_range_is_swapped_instead_of_breaking_the_clamp() {
let mut adjuster = DifficultyAdjuster::new(9, 5);
assert_eq!(adjuster.current_difficulty(), 5, "lower end is the starting point");
for _ in 0..600 {
adjuster.record_connection();
}
assert_eq!(
adjuster.current_difficulty(),
9,
"under load the swapped upper end applies"
);
}
#[test]
fn pinned_range_never_moves() {
let mut adjuster = DifficultyAdjuster::new(6, 6);
for _ in 0..600 {
adjuster.record_connection();
}
assert_eq!(adjuster.current_difficulty(), 6);
}
#[test]
fn rate_ladder_is_clamped_to_the_configured_range() {
let mut adjuster = DifficultyAdjuster::new(7, 8);
for _ in 0..60 {
adjuster.record_connection();
}
// Raw ladder step is 6, below the configured floor.
assert_eq!(adjuster.current_difficulty(), 7);
for _ in 60..201 {
adjuster.record_connection();
}
// Raw ladder step is 8 and fits the range.
assert_eq!(adjuster.current_difficulty(), 8);
for _ in 201..600 {
adjuster.record_connection();
}
// Raw ladder step is MAX_DIFFICULTY, above the configured ceiling.
assert_eq!(adjuster.current_difficulty(), 8);
}
#[test]
fn default_range_rises_to_ten_under_load() {
let mut adjuster = DifficultyAdjuster::default();
for _ in 0..600 {
adjuster.record_connection();
}
assert_eq!(adjuster.current_difficulty(), 10);
}

View file

@ -1,7 +1,11 @@
//! PoW roundtrip tests: solver output must satisfy the verifier, replays and
//! garbage must not.
//! garbage must not, and the nonce exchange must survive TCP framing quirks.
use rampart::engine::challenge::{Challenge, solve};
use rampart::engine::challenge::{Challenge, enforce, solve};
use std::net::IpAddr;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::time::{Duration, sleep};
/// Fixed 32-byte token: sha256(hex(token) || "garbage") starts with "ebc1",
/// so "garbage" provably fails the difficulty-2 check (first two hex chars
@ -9,6 +13,8 @@ use rampart::engine::challenge::{Challenge, solve};
/// per run, since any digest lands in the accepted prefix with p=(4/16)^2.
const FIXED_TOKEN: [u8; 32] = *b"rampart-pow-fixed-token-test-v1!";
const PEER: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1));
#[test]
fn solver_output_passes_verifier() {
let mut challenge = Challenge::generate(3);
@ -25,3 +31,104 @@ fn verifier_rejects_garbage_and_replay() {
assert!(challenge.verify(&nonce), "first use passes");
assert!(!challenge.verify(&nonce), "replay is rejected");
}
#[test]
fn verifier_rejects_oversized_nonce() {
let mut challenge = Challenge::with_token(FIXED_TOKEN, 2);
let big_nonce = "0".repeat(65);
assert!(!challenge.verify(&big_nonce));
}
/// Connects a server/client loopback pair; the first value is the server side.
async fn pair() -> (TcpStream, TcpStream) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback");
let addr = listener.local_addr().expect("local address");
let accept = tokio::spawn(async move { listener.accept().await.expect("accept").0 });
let client = TcpStream::connect(addr).await.expect("connect loopback");
let server = accept.await.expect("accept task");
(server, client)
}
/// Reads one newline-terminated server line byte by byte.
async fn read_line(stream: &mut TcpStream) -> String {
let mut line = Vec::new();
loop {
let mut byte = [0u8; 1];
let n = stream.read(&mut byte).await.expect("read line");
if n == 0 || byte[0] == b'\n' {
break;
}
line.push(byte[0]);
}
String::from_utf8(line).expect("challenge is hex")
}
#[tokio::test]
async fn nonce_coalesced_with_handshake_is_preserved() {
let (mut server, mut client) = pair().await;
let server_task = tokio::spawn(async move {
let passed = enforce(&mut server, PEER, 2).await.expect("enforce");
let mut tail = [0u8; 5];
server
.read_exact(&mut tail)
.await
.expect("handshake bytes after the nonce");
(passed, tail)
});
let challenge = read_line(&mut client).await;
let nonce = solve(&challenge, 2).expect("solved");
// One write: nonce delimiter and the first handshake bytes in one segment.
client
.write_all(format!("{nonce}\nHELLO").as_bytes())
.await
.expect("write nonce and handshake");
let (passed, tail) = server_task.await.expect("server task");
assert!(passed);
assert_eq!(&tail, b"HELLO", "bytes after the delimiter must reach the handshake");
}
#[tokio::test]
async fn nonce_split_across_segments_is_accepted() {
let (mut server, mut client) = pair().await;
let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") });
let challenge = read_line(&mut client).await;
let nonce = solve(&challenge, 2).expect("solved");
let split = nonce.len() / 2;
client
.write_all(&nonce.as_bytes()[..split])
.await
.expect("first segment");
sleep(Duration::from_millis(20)).await;
client
.write_all(&nonce.as_bytes()[split..])
.await
.expect("second segment");
client.write_all(b"\n").await.expect("delimiter");
assert!(server_task.await.expect("server task"));
}
#[tokio::test]
async fn eof_terminated_nonce_is_still_accepted() {
let (mut server, mut client) = pair().await;
let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") });
let challenge = read_line(&mut client).await;
let nonce = solve(&challenge, 2).expect("solved");
client.write_all(nonce.as_bytes()).await.expect("write nonce");
client.shutdown().await.expect("close write half");
assert!(server_task.await.expect("server task"));
}
#[tokio::test]
async fn oversized_nonce_without_delimiter_is_rejected() {
let (mut server, mut client) = pair().await;
let server_task = tokio::spawn(async move { enforce(&mut server, PEER, 2).await.expect("enforce") });
let _challenge = read_line(&mut client).await;
client.write_all(&[b'0'; 65]).await.expect("oversized nonce");
assert!(!server_task.await.expect("server task"));
}

25
tests/redis_backoff.rs Normal file
View file

@ -0,0 +1,25 @@
//! Integration tests for the Redis reconnect backoff policy.
// The backoff helpers live behind the optional `store-redis` feature, so this
// test target must be skipped when that feature is off (`cargo check
// --no-default-features --all-targets`, CI protocol-http job).
#![cfg(feature = "store-redis")]
use std::time::Duration;
use rampart::store::redis::{BACKOFF_MAX, BACKOFF_MIN, next_backoff};
#[test]
fn backoff_doubles_until_cap() {
let mut backoff = BACKOFF_MIN;
for expected_secs in [2, 4, 8, 16, 30, 30] {
backoff = next_backoff(backoff, BACKOFF_MAX);
assert_eq!(backoff, Duration::from_secs(expected_secs));
}
}
#[test]
fn backoff_never_exceeds_max() {
let backoff = next_backoff(Duration::from_secs(u64::MAX / 2), BACKOFF_MAX);
assert!(backoff <= BACKOFF_MAX);
}

View file

@ -1,12 +1,16 @@
//! Integration tests for subnet-level detection: tracker, detector and verdicts.
use rampart::config::Config;
use rampart::engine::subnet::monitor::enforce_tracker_verdicts;
use rampart::engine::subnet_tracker::SubnetTracker;
use rampart::filter::blacklist::Blacklist;
use rampart::traffic::prefix::{
PrefixKey, PrefixSnapshot, PrefixStatsSource, PrefixStatsVal, SubnetDetector, SubnetVerdict, prefix_of,
PrefixKey, PrefixSnapshot, PrefixStatsSource, PrefixStatsVal, PrefixVerdict, SubnetDetector, SubnetVerdict,
prefix_of,
};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::Duration;
fn v4(octets: [u8; 4]) -> IpAddr {
IpAddr::V4(Ipv4Addr::from(octets))
@ -194,6 +198,145 @@ fn spoof_gate_downgrades_block_to_challenge() {
assert_eq!(verdict_for(&detector, &unknown), SubnetVerdict::Challenge);
}
#[test]
fn tracker_groups_connections_by_prefix() {
let tracker = SubnetTracker::new();
tracker.record_connection(v4([203, 0, 113, 1]));
tracker.record_connection(v4([203, 0, 113, 2]));
tracker.record_connection(v4([198, 51, 100, 9]));
let by_prefix: HashMap<IpAddr, PrefixSnapshot> = tracker.take_snapshot().into_iter().collect();
assert_eq!(by_prefix.len(), 2);
assert_eq!(by_prefix[&v4([203, 0, 113, 0])].syn_count, 2);
assert_eq!(by_prefix[&v4([203, 0, 113, 0])].unique_sources, 2);
assert_eq!(by_prefix[&v4([198, 51, 100, 0])].syn_count, 1);
}
#[test]
fn tracker_snapshot_drains_window() {
let tracker = SubnetTracker::new();
tracker.record_connection(v4([10, 0, 0, 1]));
assert_eq!(tracker.take_snapshot().len(), 1);
assert!(tracker.take_snapshot().is_empty());
}
#[test]
fn tracker_mapped_addresses_share_v4_prefix() {
let tracker = SubnetTracker::new();
tracker.record_connection(v4([203, 0, 113, 5]));
// ::ffff:203.0.113.6
let mapped = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xcb00, 0x7106);
tracker.record_connection(IpAddr::V6(mapped));
let snaps = tracker.take_snapshot();
assert_eq!(snaps.len(), 1);
assert_eq!(snaps[0].0, v4([203, 0, 113, 0]));
assert_eq!(snaps[0].1.unique_sources, 2);
}
#[test]
fn tracker_prefix_cap_drops_new_prefixes_and_counts_them() {
let tracker = SubnetTracker::with_limits(2, 8);
tracker.record_connection(v4([10, 0, 0, 1]));
tracker.record_connection(v4([10, 0, 1, 1]));
tracker.record_connection(v4([10, 0, 2, 1]));
assert_eq!(tracker.dropped_prefixes(), 1);
// Existing prefixes keep accumulating even while the table is full.
tracker.record_connection(v4([10, 0, 0, 2]));
let snaps: HashMap<IpAddr, PrefixSnapshot> = tracker.take_snapshot().into_iter().collect();
assert_eq!(snaps.len(), 2);
assert_eq!(snaps[&v4([10, 0, 0, 0])].syn_count, 2);
assert!(
!snaps.contains_key(&v4([10, 0, 2, 0])),
"over-cap prefix was not stored"
);
}
#[test]
fn tracker_source_cap_bounds_per_prefix_memory() {
let tracker = SubnetTracker::with_limits(8, 3);
for last in 1..=100u8 {
tracker.record_connection(v4([203, 0, 113, last]));
}
assert_eq!(
tracker.dropped_sources(),
97,
"only the first three distinct sources are stored"
);
let snaps = tracker.take_snapshot();
assert_eq!(snaps.len(), 1);
assert_eq!(snaps[0].1.syn_count, 100, "the aggregate counter is not capped");
assert_eq!(snaps[0].1.unique_sources, 3);
}
#[test]
fn tracker_source_cap_counts_only_new_addresses() {
let tracker = SubnetTracker::with_limits(1, 2);
tracker.record_connection(v4([198, 51, 100, 1]));
tracker.record_connection(v4([198, 51, 100, 2]));
tracker.record_connection(v4([198, 51, 100, 3]));
assert_eq!(tracker.dropped_sources(), 1);
// Repeated traffic from a remembered source is not a dropped new source.
tracker.record_connection(v4([198, 51, 100, 1]));
assert_eq!(tracker.dropped_sources(), 1);
tracker.record_connection(v4([198, 51, 100, 4]));
assert_eq!(tracker.dropped_sources(), 2);
}
fn block_verdict(prefix: IpAddr) -> PrefixVerdict {
PrefixVerdict {
prefix,
verdict: SubnetVerdict::Block,
snapshot: PrefixSnapshot {
syn_count: 4000,
unique_sources: 64,
..PrefixSnapshot::default()
},
}
}
#[test]
fn trusted_tracker_block_reaches_the_blacklist_with_the_configured_ttl() {
let blacklist = Blacklist::new();
let verdicts = [block_verdict(v4([203, 0, 113, 0]))];
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), true);
assert_eq!(banned, 1);
assert!(blacklist.is_blocked(v4([203, 0, 113, 0])));
}
#[test]
fn untrusted_tracker_block_only_warns() {
let blacklist = Blacklist::new();
let verdicts = [block_verdict(v4([198, 51, 100, 0]))];
let banned = enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_secs(120), false);
assert_eq!(banned, 0);
assert!(blacklist.is_empty());
}
#[test]
fn tracker_ban_uses_the_given_duration() {
let blacklist = Blacklist::new();
let verdicts = [block_verdict(v4([192, 0, 2, 0]))];
enforce_tracker_verdicts(&verdicts, &blacklist, Duration::from_millis(1), true);
std::thread::sleep(Duration::from_millis(2));
assert!(
!blacklist.is_blocked(v4([192, 0, 2, 0])),
"ban must expire with its TTL"
);
}
#[test]
fn non_block_verdicts_do_not_ban() {
let blacklist = Blacklist::new();
let mut verdict = block_verdict(v4([203, 0, 113, 0]));
verdict.verdict = SubnetVerdict::Challenge;
assert_eq!(
enforce_tracker_verdicts(&[verdict], &blacklist, Duration::from_secs(60), true),
0
);
assert!(blacklist.is_empty());
}
#[test]
fn evaluate_skips_empty_prefixes() {
let detector = SubnetDetector::new(100, 0);
@ -213,3 +356,22 @@ fn evaluate_skips_empty_prefixes() {
assert_eq!(verdicts[0].prefix, v4([10, 0, 1, 0]));
assert_eq!(verdicts[0].verdict, SubnetVerdict::Block);
}
#[test]
fn prefix_key_normalises_ipv4_mapped_addresses() {
// ::ffff:1.2.3.4
let mapped = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304));
let plain = v4([1, 2, 3, 4]);
assert_eq!(
PrefixKey::new(mapped),
PrefixKey::new(plain),
"a mapped client must produce one key in XDP prefix stats and the user-space tracker"
);
assert_eq!(
PrefixKey::new(mapped).family,
rampart::traffic::prefix::PREFIX_FAMILY_V4
);
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(prefix_of(mapped)));
assert_eq!(PrefixKey::new(mapped).to_prefix(), Some(v4([1, 2, 3, 0])));
}

View file

@ -1,14 +1,15 @@
//! Integration tests for Traffic Intelligence on the hot path: auto-ban driven
//! by reputation, attack detection on a synthetic spike and alerts on state
//! transitions.
//! Integration tests for Traffic Intelligence on the hot path: EWMA sanity,
//! attack detection across a sustained flood, reputation decay/eviction and
//! auto-ban driven by reputation.
use rampart::config::DetectAutobanConfig;
use rampart::filter::blacklist::Blacklist;
use rampart::traffic::alert::AlertDispatcher;
use rampart::traffic::detector::{AttackDetector, AttackStatus};
use rampart::traffic::detector::{AttackDetector, AttackStatus, DetectorThresholds};
use rampart::traffic::ewma::Ewma;
use rampart::traffic::hook::TrafficHook;
use rampart::traffic::reputation::IpReputation;
use std::net::{IpAddr, Ipv4Addr};
use rampart::traffic::reputation::{IpReputation, ReputationPolicy};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;
@ -23,6 +24,363 @@ fn autoban_cfg(enabled: bool) -> DetectAutobanConfig {
}
}
fn quiet(detector: &mut AttackDetector) {
for _ in 0..12 {
detector.analyze(500.0, 50.0);
}
}
// EWMA
#[test]
fn ewma_starts_at_zero() {
assert_eq!(Ewma::new(0.125).value(), 0.0);
}
#[test]
fn ewma_alpha_one_follows_the_sample() {
let mut ewma = Ewma::new(1.0);
ewma.update(100.0);
assert!((ewma.value() - 100.0).abs() < 1.0);
}
#[test]
fn ewma_converges_to_a_constant_sample() {
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 ewma_falls_back_on_invalid_alpha() {
for alpha in [f64::NAN, f64::INFINITY, 0.0, -0.5] {
let mut ewma = Ewma::new(alpha);
ewma.update(100.0);
assert!(ewma.value().is_finite(), "alpha={alpha} must keep the average finite");
assert!(
ewma.value() > 0.0 && ewma.value() < 100.0,
"alpha={alpha} must fall back to the default smoothing"
);
}
}
#[test]
fn ewma_seed_primes_the_baseline() {
let mut ewma = Ewma::new(0.01);
ewma.seed(500.0);
assert_eq!(ewma.value(), 500.0, "a seeded baseline starts at the observed value");
ewma.update(500.0);
assert_eq!(ewma.value(), 500.0);
assert!(!ewma.value().is_nan());
}
#[test]
fn ewma_ignores_non_finite_samples() {
let mut ewma = Ewma::new(0.5);
ewma.update(10.0);
let before = ewma.value();
ewma.update(f64::NAN);
ewma.update(f64::INFINITY);
assert_eq!(ewma.value(), before, "non-finite samples must not move the average");
}
// Attack detector
#[test]
fn attack_detector_reports_normal_traffic() {
let mut detector = AttackDetector::new();
quiet(&mut detector);
assert_eq!(detector.analyze(500.0, 50.0), AttackStatus::Normal);
}
#[test]
fn attack_detector_flags_pps_spike_as_suspicious() {
let mut detector = AttackDetector::new();
for _ in 0..10 {
detector.analyze(1.0, 1.0);
}
assert_eq!(detector.analyze(5.0, 1.0), AttackStatus::Suspicious);
}
#[test]
fn attack_detector_flags_cps_spike_as_suspicious() {
let mut detector = AttackDetector::new();
for _ in 0..10 {
detector.analyze(1.0, 1.0);
}
assert_eq!(detector.analyze(1.0, 5.0), AttackStatus::Suspicious);
}
#[test]
fn attack_detector_escalates_after_three_anomalies() {
let mut detector = AttackDetector::new();
for _ in 0..10 {
detector.analyze(1.0, 1.0);
}
detector.analyze(10_000.0, 100.0);
detector.analyze(10_000.0, 100.0);
assert_eq!(detector.analyze(10_000.0, 100.0), AttackStatus::UnderAttack);
}
#[test]
fn attack_detector_resets_on_a_normal_window() {
let mut detector = AttackDetector::new();
for _ in 0..10 {
detector.analyze(1.0, 1.0);
}
detector.analyze(100.0, 10.0);
detector.analyze(100.0, 10.0);
detector.analyze(1.0, 1.0);
assert_eq!(detector.analyze(1.0, 1.0), AttackStatus::Normal);
}
#[test]
fn detector_flags_synthetic_traffic_spike() {
let mut detector = AttackDetector::new();
// Baseline: a quiet profile.
for _ in 0..12 {
detector.analyze(500.0, 50.0);
}
// Synthetic spike: 200x pps and cps for three consecutive windows.
assert_eq!(
detector.analyze(100_000.0, 10_000.0),
AttackStatus::Suspicious,
"first anomalous window is suspicious"
);
assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::Suspicious);
assert_eq!(
detector.analyze(100_000.0, 10_000.0),
AttackStatus::UnderAttack,
"three anomalous windows in a row must escalate to UnderAttack"
);
}
#[test]
fn sustained_flood_stays_under_attack_and_keeps_banning_offenders() {
let reputation = Arc::new(IpReputation::new());
let blacklist = Arc::new(Blacklist::new());
let hook = TrafficHook::new(Arc::clone(&reputation), Arc::clone(&blacklist), autoban_cfg(true), 60);
let mut detector = AttackDetector::new();
quiet(&mut detector);
for tick in 0..10u8 {
let status = detector.analyze(100_000.0, 10_000.0);
if tick < 2 {
assert_eq!(status, AttackStatus::Suspicious, "flood tick {tick}");
} else {
assert_eq!(
status,
AttackStatus::UnderAttack,
"flood tick {tick}: the detector must not learn the attack as normal"
);
}
// A fresh offender joins on every tick of the attack. The edge keeps
// banning them only while the detector stays in UnderAttack.
let offender = ip([203, 0, 113, tick + 1]);
for _ in 0..6 {
reputation.record_bad(offender);
}
assert!(hook.ban_offenders() >= 1, "flood tick {tick} must produce a ban");
assert!(
blacklist.is_blocked(offender),
"flood tick {tick}: offender must be banned"
);
}
}
#[test]
fn under_attack_exits_only_after_the_recovery_window() {
let mut detector = AttackDetector::new();
quiet(&mut detector);
for _ in 0..3 {
detector.analyze(100_000.0, 10_000.0);
}
assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::UnderAttack);
// Four calm windows are not enough: the exit hysteresis is five ticks.
for tick in 0..4 {
assert_eq!(
detector.analyze(500.0, 50.0),
AttackStatus::UnderAttack,
"calm tick {tick} must not end the attack"
);
}
assert_eq!(
detector.analyze(500.0, 50.0),
AttackStatus::Normal,
"the fifth calm tick ends the attack"
);
}
#[test]
fn detector_thresholds_are_configurable() {
let thresholds = DetectorThresholds {
suspicious_score: 1.5,
attack_score: 2.0,
escalate_after: 1,
recover_after: 2,
};
let mut detector = AttackDetector::with_thresholds(thresholds);
for _ in 0..10 {
detector.analyze(100.0, 10.0);
}
assert_eq!(
detector.analyze(1_000.0, 100.0),
AttackStatus::UnderAttack,
"escalate_after = 1 must escalate on the first anomalous window"
);
assert_eq!(detector.analyze(100.0, 10.0), AttackStatus::UnderAttack);
assert_ne!(
detector.analyze(100.0, 10.0),
AttackStatus::UnderAttack,
"recover_after = 2 must end the attack"
);
}
// Reputation
#[test]
fn reputation_initial_score_is_neutral() {
let rep = IpReputation::new();
assert_eq!(rep.score(ip([192, 168, 1, 1])), 0);
}
#[test]
fn reputation_good_and_bad_steps() {
let rep = IpReputation::new();
let good = ip([10, 0, 0, 1]);
let bad = ip([10, 0, 0, 2]);
rep.record_good(good);
rep.record_bad(bad);
assert_eq!(rep.score(good), 1);
assert_eq!(rep.score(bad), -10);
}
#[test]
fn reputation_scores_are_clamped() {
let rep = IpReputation::new();
let good = ip([10, 0, 0, 3]);
let bad = ip([10, 0, 0, 4]);
for _ in 0..200 {
rep.record_good(good);
}
for _ in 0..20 {
rep.record_bad(bad);
}
assert_eq!(rep.score(good), 100);
assert_eq!(rep.score(bad), -100);
}
#[test]
fn reputation_trusts_after_enough_good_connections() {
let rep = IpReputation::new();
let ip = ip([10, 0, 0, 5]);
assert!(!rep.is_trusted(ip));
for _ in 0..51 {
rep.record_good(ip);
}
assert!(rep.is_trusted(ip));
}
#[test]
fn reputation_tracks_ipv6() {
let rep = IpReputation::new();
let ip = IpAddr::V6(Ipv6Addr::LOCALHOST);
rep.record_bad(ip);
assert_eq!(rep.score(ip), -10);
}
#[test]
fn reputation_decays_toward_neutral() {
let policy = ReputationPolicy {
idle_ttl: Duration::from_secs(10),
decay_half_life: Duration::from_millis(20),
max_offenders: 64,
};
let rep = IpReputation::with_policy(policy);
let bad = ip([10, 0, 0, 6]);
for _ in 0..20 {
rep.record_bad(bad);
}
assert_eq!(rep.score(bad), -100);
std::thread::sleep(Duration::from_millis(40));
let decayed = rep.score(bad);
assert!(
decayed > -100 && decayed < 0,
"two half-lives must move the score toward neutral, got {decayed}"
);
}
#[test]
fn reputation_sweep_evicts_idle_and_keeps_active() {
let policy = ReputationPolicy {
idle_ttl: Duration::from_millis(20),
decay_half_life: Duration::from_secs(1800),
max_offenders: 64,
};
let rep = IpReputation::with_policy(policy);
let idle = ip([10, 0, 0, 7]);
let active = ip([10, 0, 0, 8]);
rep.record_bad(idle);
rep.record_bad(active);
std::thread::sleep(Duration::from_millis(40));
rep.record_bad(active);
for _ in 0..8 {
rep.sweep();
}
assert_eq!(rep.len(), 1, "only the idle source may be evicted");
assert_eq!(rep.score(idle), 0, "evicted source is neutral again");
assert!(rep.score(active) < 0, "active source keeps its score");
}
#[test]
fn offenders_are_capped_per_cycle() {
let policy = ReputationPolicy {
idle_ttl: Duration::from_secs(600),
decay_half_life: Duration::from_secs(1800),
max_offenders: 3,
};
let rep = IpReputation::with_policy(policy);
for last in 1..=20u8 {
let source = ip([198, 51, 100, last]);
for _ in 0..6 {
rep.record_bad(source);
}
}
assert_eq!(
rep.offenders_below(-50).len(),
3,
"one cycle must not return the whole offender table"
);
}
#[test]
fn offenders_below_returns_worst_sources() {
let rep = IpReputation::new();
let bad = ip([10, 0, 0, 1]);
let good = ip([10, 0, 0, 2]);
for _ in 0..6 {
rep.record_bad(bad);
}
rep.record_good(good);
assert_eq!(rep.offenders_below(-50), vec![bad]);
}
#[test]
fn offenders_below_is_empty_without_offenders() {
let rep = IpReputation::new();
assert!(rep.offenders_below(-50).is_empty());
}
// Traffic hook auto-ban
#[test]
fn reputation_fall_after_drops_triggers_autoban() {
let reputation = Arc::new(IpReputation::new());
@ -69,29 +427,6 @@ fn autoban_ttl_expires_ban() {
);
}
#[test]
fn detector_flags_synthetic_traffic_spike() {
let mut detector = AttackDetector::new();
// Baseline: a quiet profile.
for _ in 0..12 {
detector.analyze(500.0, 50.0);
}
// Synthetic spike: 200x pps and cps for three consecutive windows.
assert_eq!(
detector.analyze(100_000.0, 10_000.0),
AttackStatus::Suspicious,
"first anomalous window is suspicious"
);
assert_eq!(detector.analyze(100_000.0, 10_000.0), AttackStatus::Suspicious);
assert_eq!(
detector.analyze(100_000.0, 10_000.0),
AttackStatus::UnderAttack,
"three anomalous windows in a row must escalate to UnderAttack"
);
}
#[test]
fn alerts_fire_only_on_state_transitions() {
let dispatcher = AlertDispatcher::new();