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:
parent
e456cb583f
commit
da87d2a11f
21 changed files with 600 additions and 521 deletions
22
TODO.md
22
TODO.md
|
|
@ -258,6 +258,9 @@ module-size, secrets, `cargo deny`, rustdoc без warning'ов, clang+verifier,
|
|||
исправленный v6 SYN-ACK, `inc_drop()` на всех DROP-путях, per-CPU инкремент без atomic.
|
||||
- XDP: VLAN/QinQ до L3, фрагменты проверяются по blacklist, неизвестный non-SYN поток → PASS
|
||||
(«stateless-фильтр, не firewall»), `whitelist6_map`, whitelist до state machine.
|
||||
- XDP spoof-gate: в `prefix_stats` добавлен 64-битный bitmap хешей source-адресов, userspace
|
||||
считает popcount и сбрасывает счётчики при чтении → `Block` работает и на XDP-пути, а окно
|
||||
детектора стало честным (раньше счётчики были кумулятивными и со временем «банили» всё).
|
||||
- XDP: протухшие префиксные баны удаляются userspace-reaper'ом раз в 60 с (пакетный путь
|
||||
больше не пытается удалить `/24` ключом `/32`).
|
||||
- Загрузчик: запоминается фактический attach-флаг (native/skb) и проверяется detach;
|
||||
|
|
@ -284,22 +287,27 @@ module-size, secrets, `cargo deny`, rustdoc без warning'ов, clang+verifier,
|
|||
|
||||
### Осталось (следующий раунд)
|
||||
|
||||
- [ ] API manager'а: `KEYS` → `SCAN`, batch `MGET` вместо N+1, ошибки Redis → 503 (а не
|
||||
`200 []`), `DefaultBodyLimit`/`TimeoutLayer`, лимит длины `reason`, graceful shutdown,
|
||||
эвикция login-лимитера, ключ по `X-Forwarded-For` за доверенным прокси.
|
||||
- [x] API manager'а: `SCAN`+`MGET` вместо `KEYS`/N+1, 503 вместо `200 []`, пагинация
|
||||
`limit`/`offset` (100 по умолчанию, 1000 максимум), GET без записи (бэкфилл метаданных
|
||||
вынесен в стартовую задачу), `DefaultBodyLimit` 8 КиБ, `TimeoutLayer` 10 с, rate-limit
|
||||
на все мутирующие ручки, graceful shutdown с SIGTERM и join heartbeat, эвикция
|
||||
login-лимитера, `MANAGER_TRUSTED_PROXIES` для `X-Forwarded-For`. Тесты —
|
||||
`tests/manager_api.rs` (9) и `tests/manager_security.rs` (23).
|
||||
- [ ] `trusted_cidrs` + PROXY-header IP как ключ всех политик: банить/лимитировать по
|
||||
transport-IP, header-IP — только после валидации (ban-amplification через LB).
|
||||
- [ ] XDP spoof-gate: `unique_sources = 0` на XDP-пути делает `Block` недостижимым —
|
||||
либо counting в ядре, либо явная документация (сейчас логируется).
|
||||
|
||||
- [ ] IPv6 bind в listener (`Domain::IPV4` + строковый парсинг адреса).
|
||||
- [ ] `relay_idle_timeout_secs` в `[limits]` (сейчас константа 300 с) и семафор бюджета
|
||||
полем `Gateway` вместо `OnceLock`.
|
||||
- [ ] Оставшиеся инлайн-тесты (10 файлов) мигрировать в `tests/`.
|
||||
- [x] Инлайн-тесты мигрированы: `grep -rn "#\[cfg(test)\]" src/` пуст, 41 тест переехал в
|
||||
10 новых сюит (`manager_auth`, `manager_heartbeat`, `protocol_http_*`, `traffic_*`,
|
||||
`tui_prometheus`); счётчик тестов не изменился.
|
||||
|
||||
## 3. Backlog
|
||||
|
||||
- [ ] Мигрировать существующие инлайн-тесты (`#[cfg(test)]` в src/) в `tests/` —
|
||||
- [x] Мигрировать существующие инлайн-тесты (`#[cfg(test)]` в src/) в `tests/` —
|
||||
правило §0.7; при миграции хелперы, нужные тестам, получают `pub` с потребителем.
|
||||
Сделано 2026-11-16: в `src/` не осталось ни одного `#[cfg(test)]`.
|
||||
- [ ] protocol-gRPC plugin (после http)
|
||||
- [ ] BPF hook #1 реальный: HTTP поверх XDP (rate-limit до userspace)
|
||||
- [ ] GeoIP/ASN reputation (enum есть, реализации нет)
|
||||
|
|
|
|||
|
|
@ -58,6 +58,31 @@ clickhouse-client --query "SELECT count() FROM rampart.events WHERE event_type='
|
|||
> Честно: hot-reload конфига не реализован — изменения применяются рестартом.
|
||||
> ASN/CIDR-баны, GeoIP-блокировки стран и выбор типов challenge через CLI не
|
||||
> реализованы; blacklist принимает цели в том виде, в котором их хранит Manager.
|
||||
|
||||
---
|
||||
|
||||
## 2. Сигналы деградации — что смотреть
|
||||
|
||||
| Метрика / лог | Что значит | Что делать |
|
||||
|---------------|-----------|------------|
|
||||
| `rampart_connections_total{result="overloaded"}` | исчерпан глобальный бюджет соединений (4×workers×max_connections_per_ip) | проверить, не атака ли; при легитимной нагрузке — поднять `max_connections_per_ip`/`workers.count` |
|
||||
| `rampart_xdp_dropped_total` растёт, `passed_total` — нет | XDP дропает всё | проверить `protected_port_start/end`, баны и `xdp_feature_*`; смотреть `stats_map` через `bpftool` |
|
||||
| `rampart_clickhouse_dropped_total` > 0 | события не успевают уходить в ClickHouse | проверить доступность/латентность ClickHouse; события потеряны, защита работает |
|
||||
| `rampart_xdp_whitelist_total` растёт | трафик от whitelist-адресов | норма, но если это неожиданно — проверить `whitelist` в конфиге |
|
||||
| лог `global connection budget exhausted` | то же, что `overloaded` | см. выше |
|
||||
| лог `accept error ... backing off` | кончились fd (`EMFILE`) или память под сокеты | поднять `ulimit -n`, проверить утечки соединений |
|
||||
| лог `XDP filter attached ... (mode: generic (skb))` | драйвер не умеет native XDP | ожидаемо для virtio/veth; generic дороже по CPU |
|
||||
| лог `XDP .rodata map expects N bytes` | рассинхрон `config.h` и `XdpGlobals` | это баг сборки: не запускать, сообщить с числами из лога |
|
||||
|
||||
Проверить, что XDP действительно снят после остановки демона:
|
||||
|
||||
```bash
|
||||
bpftool net show dev eth0 # не должно быть xdp-программы
|
||||
ip link show eth0 | grep xdp # пусто
|
||||
```
|
||||
|
||||
Если программа осталась — это регрессия загрузчика, а не норма: снимать вручную
|
||||
`ip link set dev eth0 xdp off` и заводить баг.
|
||||
> Команды `emergency`, `drain` и `config set` пока не реализованы и завершатся
|
||||
> явной ошибкой вместо изменения состояния.
|
||||
|
||||
|
|
|
|||
|
|
@ -19,6 +19,31 @@ clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/uf.o
|
|||
# Не помогло — отключи XDP в config.toml ([xdp] enabled = false) и рестарт.
|
||||
```
|
||||
|
||||
### "accept error: ... backing off" / "Too many open files"
|
||||
|
||||
```bash
|
||||
# Кончились дескрипторы: демон сам делает backoff, но сервис уже деградирует
|
||||
ulimit -n # для процесса
|
||||
systemctl show rampart -p LimitNOFILE
|
||||
journalctl -u rampart | grep -E "accept error|EMFILE|backing off"
|
||||
ss -s | head -5
|
||||
```
|
||||
|
||||
Поднять `LimitNOFILE` (например, 65535), перезапустить, проверить утечки
|
||||
соединений (`ss -tan state established | wc -l`). Backoff в списке логов — это
|
||||
симптом, а не причина.
|
||||
|
||||
### "XDP не снимается после остановки демона"
|
||||
|
||||
```bash
|
||||
bpftool net show dev eth0
|
||||
ip link show eth0 | grep -i xdp
|
||||
```
|
||||
|
||||
Если программа осталась — загрузчик не снял её (регрессия), снять вручную
|
||||
`ip link set dev eth0 xdp off` и завести баг с режимом attach из лога
|
||||
(`native (drv)` / `generic (skb)`).
|
||||
|
||||
### "Rate limit блокирует реальных клиентов"
|
||||
|
||||
```bash
|
||||
|
|
@ -31,7 +56,6 @@ curl -s http://EDGE_IP:9090/metrics | grep rate_limit
|
|||
```
|
||||
|
||||
### "Высокое CPU на edge ноде"
|
||||
|
||||
```bash
|
||||
top -p $(pgrep rampart)
|
||||
perf top -p $(pgrep rampart)
|
||||
|
|
@ -63,6 +87,16 @@ export REDIS_URL="redis://127.0.0.1:6379/0" # опционально
|
|||
rampart-manager
|
||||
```
|
||||
|
||||
### "Manager не стартует: API_PASSWORD must be ..."
|
||||
|
||||
`API_PASSWORD` должен быть непустым и не короче 16 символов, `JWT_SECRET` —
|
||||
не короче 32 непробельных байт. Пустой пароль раньше принимался как валидный,
|
||||
поэтому теперь это ошибка старта, а не тихий вход без пароля.
|
||||
|
||||
```bash
|
||||
systemctl show rampart-manager -p Environment | tr ' ' '\n' | grep -E "API_PASSWORD|JWT_SECRET" | sed 's/=.*/=<redacted>/'
|
||||
```
|
||||
|
||||
### "Manager отдаёт 401"
|
||||
|
||||
Токен истёк (`JWT_EXPIRATION_SECS`, дефолт 86400) — перелогинься:
|
||||
|
|
@ -108,7 +142,15 @@ df -h /var/lib/clickhouse
|
|||
```
|
||||
|
||||
Запись настраивается `store.clickhouse_url` в config.toml. Ошибки записи не
|
||||
роняют edge — они уходят в debug-лог.
|
||||
роняют edge: события складываются в bounded-буфер (10 000) и при переполнении
|
||||
или таймауте учитываются в `rampart_clickhouse_dropped_total`.
|
||||
|
||||
```bash
|
||||
curl -s http://EDGE_IP:9090/metrics | grep clickhouse_dropped
|
||||
```
|
||||
|
||||
Растущий счётчик = ClickHouse не успевает; защита при этом работает, но
|
||||
аналитика теряет события.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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:*");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 { .. }));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
34
tests/manager_auth.rs
Normal file
34
tests/manager_auth.rs
Normal 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());
|
||||
}
|
||||
50
tests/manager_heartbeat.rs
Normal file
50
tests/manager_heartbeat.rs
Normal 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:*");
|
||||
}
|
||||
23
tests/protocol_http_handler.rs
Normal file
23
tests/protocol_http_handler.rs
Normal 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);
|
||||
}
|
||||
92
tests/protocol_http_parser.rs
Normal file
92
tests/protocol_http_parser.rs
Normal 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 { .. }));
|
||||
}
|
||||
41
tests/protocol_registry_contract.rs
Normal file
41
tests/protocol_registry_contract.rs
Normal 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
127
tests/traffic_hook.rs
Normal 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");
|
||||
}
|
||||
58
tests/traffic_profile_alert.rs
Normal file
58
tests/traffic_profile_alert.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
38
tests/traffic_profile_profiler.rs
Normal file
38
tests/traffic_profile_profiler.rs
Normal 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
48
tests/tui_prometheus.rs
Normal 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));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue