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

View file

@ -66,38 +66,3 @@ pub async fn auth_middleware(
Ok(next.run(request).await)
}
#[cfg(test)]
mod tests {
use super::*;
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

@ -13,12 +13,12 @@ use tokio::time::{Duration, interval};
/// SCAN pattern for node records (blocking KEYS is forbidden under load).
#[cfg(feature = "store-redis")]
const NODES_KEY_PATTERN: &str = "rampart:nodes:*";
pub const NODES_KEY_PATTERN: &str = "rampart:nodes:*";
/// SCAN COUNT hint per round.
#[cfg(feature = "store-redis")]
const SCAN_BATCH: usize = 100;
/// Node is offline when the last heartbeat is older than this.
#[cfg(any(feature = "store-redis", test))]
#[cfg(feature = "store-redis")]
const NODE_TTL_SECS: i64 = 60;
#[cfg(feature = "store-redis")]
@ -68,8 +68,8 @@ async fn collect_node_keys(conn: &mut redis::aio::MultiplexedConnection) -> anyh
/// the RFC3339 `last_heartbeat` is older than `NODE_TTL_SECS` (a missing or
/// unparseable timestamp counts as expired, matching the previous behavior);
/// `None` when the node is fresh, unparsable, or not a JSON object.
#[cfg(any(feature = "store-redis", test))]
fn offline_update(raw: &str, now: i64) -> Option<String> {
#[cfg(feature = "store-redis")]
pub fn offline_update(raw: &str, now: i64) -> Option<String> {
let mut node = serde_json::from_str::<serde_json::Value>(raw).ok()?;
let hb = node["last_heartbeat"]
.as_str()
@ -83,54 +83,3 @@ fn offline_update(raw: &str, now: i64) -> Option<String> {
.insert("status".to_string(), serde_json::Value::String("offline".to_string()));
serde_json::to_string(&node).ok()
}
#[cfg(test)]
mod tests {
use super::*;
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());
}
#[cfg(feature = "store-redis")]
#[test]
fn node_key_pattern_targets_rampart_nodes() {
assert_eq!(NODES_KEY_PATTERN, "rampart:nodes:*");
}
}

View file

@ -8,7 +8,7 @@
//! The bytes already consumed for the head are forwarded to the upstream as the
//! initial tunnel payload, so the request is not lost.
mod parser;
pub mod parser;
use crate::config::HttpProtocolConfig;
use crate::protocol::{HandshakeResult, ProtocolHandler, Upstream};
@ -95,24 +95,3 @@ impl ProtocolHandler for HttpProtocolHandler {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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.read_head(&mut server).await.is_err());
drop(client);
}
}

View file

@ -103,95 +103,3 @@ fn reject(reason: &str) -> Verdict {
reason: reason.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
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

@ -126,41 +126,3 @@ impl ProtocolRegistry {
Ok(handler.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
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());
}
}

View file

@ -100,127 +100,3 @@ impl TrafficHook {
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};
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

@ -115,60 +115,3 @@ pub async fn send_webhook(url: String, alert: Alert) {
tracing::warn!("webhook delivery failed: {e}");
}
}
#[cfg(test)]
mod tests {
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_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

@ -43,43 +43,3 @@ impl TrafficProfiler {
(pps / base).min(10.0)
}
}
#[cfg(test)]
mod tests {
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_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);
}
}

View file

@ -190,52 +190,3 @@ fn parse_value(value: &str) -> Option<f64> {
v => v.parse::<f64>().ok(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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));
}
}