guard/docs/testing.md
loki5512344 918e561a61
feat(xdp): IPv6 UDP rate limit, working loader; English JavaDoc comments
XDP behaviour:
- udp_rate_limit6 (LRU, 128-bit source key) + throttle_hit6, so
  udp_policy = "rate-limit" now applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

XDP loader (was completely broken, never reached the verifier):
- .rodata is now one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Previously a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and the image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs: verifies map names and .rodata size without root;
  the real binary was confirmed to attach in a netns.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  decorative banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, TOC and
  copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6 coverage;
  testing.md describes the real-kernel smoke; stale research links removed.
2026-11-15 23:44:07 +01:00

106 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Testing - Rampart
> Как тестировать: unit, integration, нагрузочное, DDoS simulation.
---
## 1. Unit и integration тесты (Rust)
```bash
cargo test # все тесты
cargo test --test config_parse
cargo test -- --nocapture # с выводом
```
Существующие наборы (tests/):
| Тест | Что покрывает |
|------|---------------|
| `config_parse` | Парсинг и валидация единого конфига (src/config) |
| `filter_logic` | Blacklist, rate limit, geo-фильтры |
| `pow_roundtrip` | Выдача/решение/проверка PoW challenge |
| `protocol_registry` | Реестр протокольных плагинов |
---
## 2. Статический анализ
```bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo deny check
```
XDP: smoke-check компиляции BPF-программы:
```bash
clang -O2 -g -target bpf -c xdp/core/universal_filter.c -o /tmp/universal_filter.o
```
Функциональные проверки на реальном ядре (нужен root: CAP_BPF + CAP_NET_ADMIN,
`bpftool`, `clang`, `python3`):
```bash
sudo bash scripts/xdp_ipv6_smoke.sh
```
Поднимает netns + veth, грузит программу через verifier и проверяет: бан IPv6 и IPv4
(включая короткие UDP-датаграммы), снятие бана, истечение TTL по монотонным часам и
`udp_policy = "rate-limit"` для IPv6 (политика патчится в `.rodata` до загрузки).
`scripts/xdp_netns_smoke.sh` дополнительно гоняет реальный бинарь `rampart` end-to-end
(требует `hping3`).
---
## 3. Локальный integration-стенд (Docker)
```bash
bash deploy/test/run_test.sh
```
Поднимает backend-stub (TCP echo), edge (`rampart` с config.test.toml) и
attacker-контейнер. Сценарии — в [deploy/test/README.md](../deploy/test/README.md).
---
## 4. Нагрузочное тестирование
### Много-IP TCP flood на VDS (edge-only)
`deploy/test/stress/` — полный цикл без Redis/ClickHouse: edge-контейнер с
stub-бэкендом (socat echo) + attacker-контейнер со 100 source IP.
`flood.py` шлёт чистые TCP-соединения (connect / slowloris / keepalive),
во время флуда параллельно подключаются generic TCP-клиенты (`legit.py`),
замеряющие RTT.
```bash
git clone https://github.com/loki5512344ss/guard.git && cd guard
cargo build --release --bin rampart
cd deploy/test/stress && bash run-stress.sh
```
Фазы: A — сырая пропускная способность (лимиты сняты), B — защита (per-IP rate
limit + reputation bans), C — SYN flood hping3, D — активные соединения.
### tcpkali / hping3
```bash
tcpkali --connections 1000 --connect-rate 5000 --duration 60s EDGE_IP:25565
hping3 -S --flood -p 25565 --rand-source EDGE_IP # только на свои серверы!
```
---
## 5. Метрики для проверки во время теста
```bash
curl -s http://localhost:9090/metrics | grep rampart_
# rampart_connections_total{result="allowed|blocked"}
# rampart_rate_limit_hits
# rampart_pow_challenges_total{result=...}
# rampart_attack_status
```
---
*Версия: 2.0 | Август 2026*