test: move the last inline test modules to tests/, document new signals

- All remaining #[cfg(test)] modules left src/ (manager auth/heartbeat,
  protocol registry and HTTP parser, traffic hook/prefix/profile, TUI
  Prometheus); 41 tests moved into 10 integration suites with the same names
  and assertions, so `grep -rn '#[cfg(test)]' src/` is now empty.
- runbook.md: degradation signals (overloaded connections, ClickHouse drops,
  XDP drops, generic mode, EMFILE backoff) and how to verify XDP was detached.
- troubleshooting.md: accept backoff, orphaned XDP, password/JWT startup
  requirements, ClickHouse event loss.
- TODO: review round recorded as fixed/deferred.
This commit is contained in:
Loki 2026-11-16 12:36:29 +01:00
parent e456cb583f
commit da87d2a11f
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
21 changed files with 600 additions and 521 deletions

34
tests/manager_auth.rs Normal file
View file

@ -0,0 +1,34 @@
//! Manager JWT authentication: token round-trip and rejection of tokens signed
//! for a different audience or with a different secret.
use rampart::manager::auth::{create_token, verify_token};
fn valid_secret() -> String {
"this-is-a-test-secret-32-bytes-long!".to_string()
}
#[test]
fn create_verify_roundtrip_passes() {
let secret = valid_secret();
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
let claims = verify_token(&token, &secret, "rampart").expect("verification should succeed");
assert_eq!(claims.sub, "rampart-admin");
assert_eq!(claims.aud, "rampart");
assert_eq!(claims.role, "admin");
assert!(claims.exp > claims.iat);
}
#[test]
fn verify_rejects_wrong_audience() {
let secret = valid_secret();
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
assert!(verify_token(&token, &secret, "other").is_err());
}
#[test]
fn verify_rejects_wrong_secret() {
let secret = valid_secret();
let other_secret = "another-test-secret-also-32-bytes-long!".to_string();
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
assert!(verify_token(&token, &other_secret, "rampart").is_err());
}

View file

@ -0,0 +1,50 @@
//! Node heartbeat expiry: a stale, missing or unparsable `last_heartbeat`
//! marks the node offline, while a fresh heartbeat leaves the record untouched.
#![cfg(feature = "store-redis")]
use rampart::manager::sync::heartbeat::{NODES_KEY_PATTERN, offline_update};
fn rfc3339(ts: i64) -> String {
chrono::DateTime::from_timestamp(ts, 0)
.expect("in-range timestamp")
.to_rfc3339()
}
#[test]
fn expired_heartbeat_is_marked_offline() {
let now = 2_000_000_i64;
let raw = format!(
r#"{{"name":"edge1","last_heartbeat":"{}","status":"online"}}"#,
rfc3339(now - 120)
);
let updated = offline_update(&raw, now).expect("expired node should be marked offline");
assert!(updated.contains("offline"));
assert!(updated.contains("edge1"));
}
#[test]
fn fresh_heartbeat_is_left_untouched() {
let now = 2_000_000_i64;
let raw = format!(r#"{{"last_heartbeat":"{}","status":"online"}}"#, rfc3339(now - 5));
assert!(offline_update(&raw, now).is_none());
}
#[test]
fn missing_or_broken_timestamp_counts_as_expired() {
let now = 2_000_000_i64;
let updated = offline_update(r#"{"status":"online"}"#, now).expect("missing heartbeat counts as expired");
assert!(updated.contains("offline"));
let updated = offline_update(r#"{"last_heartbeat":"garbage","status":"online"}"#, now)
.expect("unparseable heartbeat counts as expired");
assert!(updated.contains("offline"));
}
#[test]
fn invalid_json_is_ignored() {
assert!(offline_update("not json", 2_000_000).is_none());
}
#[test]
fn node_key_pattern_targets_rampart_nodes() {
assert_eq!(NODES_KEY_PATTERN, "rampart:nodes:*");
}

View file

@ -0,0 +1,23 @@
//! HTTP protocol handler: a zero `max_header_bytes` fails on the public
//! handshake path before any socket I/O happens.
#![cfg(feature = "protocol-http")]
use rampart::config::HttpProtocolConfig;
use rampart::protocol::ProtocolHandler;
use rampart::protocol::http::HttpProtocolHandler;
#[tokio::test]
async fn zero_limit_fails_fast_without_io() {
let config = HttpProtocolConfig::default();
let mut broken = config.clone();
broken.max_header_bytes = 0;
let handler = HttpProtocolHandler::new(&broken, &[]);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
let client = tokio::net::TcpStream::connect(listener.local_addr().expect("addr"))
.await
.expect("connect");
let (mut server, _) = listener.accept().await.expect("accept");
drop(listener);
assert!(handler.handshake(&mut server).await.is_err());
drop(client);
}

View file

@ -0,0 +1,92 @@
//! Pure HTTP/1.x request-head parser: head scanning, method/host/version
//! validation, path blocklist and the user-agent requirement.
#![cfg(feature = "protocol-http")]
use rampart::protocol::http::parser::{Policy, Verdict, evaluate, scan_head};
fn policy() -> Policy {
Policy {
max_header_bytes: 8192,
blocked_paths: Vec::new(),
require_user_agent: false,
}
}
#[test]
fn scan_finds_full_head_length() {
assert_eq!(scan_head(b"GET / HTTP/1.1\r\n\r\n"), Some(18));
assert_eq!(scan_head(b"GET / HTTP/1.1\r\n"), None);
}
#[test]
fn valid_request_is_allowed() {
let head = b"POST /api/items?limit=5 HTTP/1.1\r\nHost: example.com\r\n\r\n";
let verdict = evaluate(head, &policy());
assert_eq!(
verdict,
Verdict::Allow {
method: "POST".to_string(),
path: "/api/items".to_string(),
host: "example.com".to_string()
}
);
}
#[test]
fn unknown_method_is_rejected() {
let head = b"TRACE / HTTP/1.1\r\nHost: h\r\n\r\n";
assert!(matches!(evaluate(head, &policy()), Verdict::Reject { .. }));
}
#[test]
fn missing_host_is_rejected() {
let head = b"GET / HTTP/1.1\r\nUser-Agent: t\r\n\r\n";
assert!(matches!(evaluate(head, &policy()), Verdict::Reject { .. }));
}
#[test]
fn http2_version_is_rejected() {
let head = b"GET / HTTP/2.0\r\nHost: h\r\n\r\n";
assert!(matches!(evaluate(head, &policy()), Verdict::Reject { .. }));
}
#[test]
fn malformed_line_is_rejected() {
assert!(matches!(
evaluate(b"nonsense\r\n\r\n", &policy()),
Verdict::Reject { .. }
));
assert!(matches!(
evaluate(b"GET / HTTP/1.1\r\nbroken\r\n\r\n", &policy()),
Verdict::Reject { .. }
));
}
#[test]
fn non_utf8_head_is_rejected() {
assert!(matches!(evaluate(&[0xff, 0xfe], &policy()), Verdict::Reject { .. }));
}
#[test]
fn blocked_path_prefix_is_rejected() {
let mut custom = policy();
custom.blocked_paths = vec!["/admin".to_string()];
assert!(matches!(
evaluate(b"GET /admin/panel HTTP/1.1\r\nHost: h\r\n\r\n", &custom),
Verdict::Reject { .. }
));
assert!(matches!(
evaluate(b"GET /public HTTP/1.1\r\nHost: h\r\n\r\n", &custom),
Verdict::Allow { .. }
));
}
#[test]
fn required_user_agent_enforced() {
let mut custom = policy();
custom.require_user_agent = true;
let head = b"GET / HTTP/1.1\r\nHost: h\r\n\r\n";
assert!(matches!(evaluate(head, &custom), Verdict::Reject { .. }));
let head_with_ua = b"GET / HTTP/1.1\r\nHost: h\r\nUser-Agent: curl/8\r\n\r\n";
assert!(matches!(evaluate(head_with_ua, &custom), Verdict::Allow { .. }));
}

View file

@ -0,0 +1,41 @@
//! Protocol registry contract: an empty registry fails fast at startup and a
//! registered handler resolves by name.
use std::future::Future;
use std::pin::Pin;
use rampart::protocol::{HandshakeResult, ProtocolHandler, ProtocolRegistry, Upstream};
use tokio::net::TcpStream;
struct DummyHandler;
impl ProtocolHandler for DummyHandler {
fn name(&self) -> &'static str {
"dummy"
}
fn handshake<'a>(
&'a self,
_stream: &'a mut TcpStream,
) -> Pin<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + Send + 'a>> {
Box::pin(async { Ok(HandshakeResult::new(Upstream::new("127.0.0.1:9000"))) })
}
}
#[test]
fn empty_registry_fails_fast() {
let registry = ProtocolRegistry::new();
assert!(registry.is_empty());
assert!(registry.primary().is_err());
}
#[test]
fn registered_handler_is_resolvable() {
let mut registry = ProtocolRegistry::new();
registry.register(Box::new(DummyHandler));
assert_eq!(registry.len(), 1);
assert_eq!(registry.names(), vec!["dummy"]);
assert!(registry.primary().is_ok());
assert!(registry.get("dummy").is_some());
assert!(registry.get("missing").is_none());
}

127
tests/traffic_hook.rs Normal file
View file

@ -0,0 +1,127 @@
//! Traffic hook on the hot path: the cps window, reputation-driven auto-ban,
//! the attack-detector escalation and the ban TTL.
use rampart::config::DetectAutobanConfig;
use rampart::filter::blacklist::Blacklist;
use rampart::traffic::hook::TrafficHook;
use rampart::traffic::reputation::IpReputation;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
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,
)
}
#[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_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_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,
},
// Zero TTL as a time mock: the ban must be dead on arrival.
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

@ -0,0 +1,58 @@
//! Alert formatting and the deduplicating dispatcher: alerts fire only on the
//! detector's attack-boundary transitions, never on every tick.
use rampart::traffic::alert::{Alert, AlertDispatcher, AlertLevel};
use rampart::traffic::detector::AttackStatus;
use std::net::Ipv4Addr;
#[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_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);
}
}

View file

@ -0,0 +1,38 @@
//! Hourly EWMA traffic profiler: baseline warming and the capped anomaly score.
use rampart::traffic::profiler::TrafficProfiler;
#[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_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);
}

48
tests/tui_prometheus.rs Normal file
View file

@ -0,0 +1,48 @@
//! Prometheus exposition parser: labeled series, comments, timestamps,
//! special float values and label values containing spaces or escapes.
use rampart::tui::prometheus::parse;
#[test]
fn parses_simple_and_labeled_lines() {
let set = parse("up 1\nxdp_total{iface=\"eth0\"} 42\n");
assert_eq!(set.sum("up"), 1.0);
assert_eq!(set.labeled("xdp_total", "iface", "eth0"), Some(42.0));
}
#[test]
fn skips_comments_help_type_and_empty_lines() {
let input = "# HELP rampart_xdp_total Total\n# TYPE rampart_xdp_total gauge\n\nrampart_xdp_total 7\n";
let set = parse(input);
assert_eq!(set.samples().len(), 1);
assert_eq!(set.sum("rampart_xdp_total"), 7.0);
}
#[test]
fn ignores_timestamp_and_special_values() {
let set = parse("m1 10 1700000000000\nm2 +Inf\nm3 NaN\nbroken_line_no_value\nbad{} \nm4 -2.5e3\n");
assert_eq!(set.sum("m1"), 10.0);
assert_eq!(set.sum("m2"), f64::INFINITY);
assert!(set.labeled("m3", "x", "y").is_none());
assert_eq!(set.sum("m4"), -2500.0);
}
#[test]
fn sums_series_with_same_name() {
let input = "bans{reason=\"cps\"} 3\nbans{reason=\"syn\"} 4\nbans 5\n";
assert_eq!(parse(input).sum("bans"), 12.0);
}
#[test]
fn handles_spaces_in_label_values() {
let set = parse("m{k=\"a b\", j=\"v w\"} 1\n");
assert_eq!(set.labeled("m", "k", "a b"), Some(1.0));
assert_eq!(set.labeled("m", "j", "v w"), Some(1.0));
}
#[test]
fn handles_escaped_quotes_and_backslashes_in_labels() {
let set = parse("m{q=\"a\\\"b\", s=\"c\\\\d\"} 1\n");
assert_eq!(set.labeled("m", "q", "a\"b"), Some(1.0));
assert_eq!(set.labeled("m", "s", "c\\d"), Some(1.0));
}