feat(cli,api): human-readable ban durations, absolute expires_at, strict target/port validation
This commit is contained in:
parent
e2adf8601c
commit
da85225070
15 changed files with 570 additions and 36 deletions
22
docs/api.md
22
docs/api.md
|
|
@ -102,6 +102,28 @@ manager (или при восстановлении снимка edge).
|
|||
`target` — одиночный IPv4/IPv6-адрес (CIDR не поддерживается), `reason` — не
|
||||
длиннее 256 байт; иначе `400 Bad Request`.
|
||||
|
||||
Парсинг `target` строгий: пустая строка, пробелы (в том числе по краям), мусор после
|
||||
адреса, префикс `/0`, префикс больше 32 (IPv4) или 128 (IPv6) и нецифровой префикс
|
||||
(`/+8`) дают `400`. Порт, где он принимается, — только десятичные цифры, `1..=65535`.
|
||||
|
||||
Срок бана задаётся одним из двух полей (оба сразу — `400`; ни одного — 300 секунд):
|
||||
|
||||
- `duration_secs` — относительная длительность, `1..=31536000`;
|
||||
- `expires_at` — абсолютный срок в unix-секундах: должен быть в будущем, не дальше
|
||||
`MAX_BAN_DURATION_SECS` (один год) от текущего момента и представим как дата.
|
||||
|
||||
```json
|
||||
// Request: бан до конкретного момента
|
||||
{"target": "1.2.3.4", "type": "ip", "reason": "manual_ban", "expires_at": 1800003600}
|
||||
|
||||
// Response 200 (ответ дополнительно содержит вычисленный expires_at)
|
||||
{"status": "added", "target": "1.2.3.4", "reason": "manual_ban",
|
||||
"duration_secs": 3600, "expires_at": 1800003600}
|
||||
```
|
||||
|
||||
Запросы без `expires_at` работают как раньше. Ответ теперь всегда содержит поле
|
||||
`expires_at` (unix-секунды).
|
||||
|
||||
Edge подписывается на Pub/Sub перед загрузкой снимка из Redis. Поэтому события,
|
||||
пришедшие во время загрузки, будут применены после снимка. При старте и после
|
||||
переподключения активные Redis-баны восстанавливаются с оставшимся TTL; новые
|
||||
|
|
|
|||
50
docs/roadmap/v0.5-control-plane-bans.md
Normal file
50
docs/roadmap/v0.5-control-plane-bans.md
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# v0.5 — Управление банами: теги, наборы, API и CLI
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Milestone | v0.5 |
|
||||
| Status | idea |
|
||||
| Priority | P2 |
|
||||
| Depends on | v0.5-pinned-maps-openapi |
|
||||
|
||||
## Цель
|
||||
|
||||
Видно, кто и почему банит; внешние списки подключаются атомарно; CLI и API удобны и
|
||||
безопасны для интеграций.
|
||||
|
||||
## Зачем
|
||||
|
||||
Идеи из couic (Apache-2.0) и ebpfsentinel (AGPL — только идеи). Сейчас баны не
|
||||
различаются по источнику (детектор, ручной, Redis, GeoIP), внешние списки (тема v0.5) негде
|
||||
хранить отдельно от ручных банов, а API защищён одним паролем с JWT.
|
||||
|
||||
## Scope
|
||||
|
||||
- **Теги банов** (источник/детектор) и счётчики дропов по тегу в Prometheus.
|
||||
- **Именованные наборы** (импортированные списки: ASN, abuse-фиды): заменяются атомарно и
|
||||
удаляются, не трогая ручные баны.
|
||||
- **Batch-обновление карт** (`BPF_MAP_UPDATE_BATCH`, ядро 5.6+) порциями с откатом на
|
||||
поэлементную запись; важно для больших фидов и GeoIP.
|
||||
- **Сроки:** человекочитаемые длительности в CLI (`30s`, `1h30m`, голое число отвергается),
|
||||
абсолютный `expires_at` в API; строгая валидация ввода CLI/API (хвост после порта, `/0`,
|
||||
перевёрнутые диапазоны).
|
||||
- **Доступ:** локальный admin-сокет для CLI без JWT и scoped-токены для интеграций
|
||||
(read-only для Grafana, ban-only для детекторов).
|
||||
- **Персистентность:** авторитетное хранилище — userspace/Redis, pinned maps — лишь
|
||||
представление (так делает couic); учесть в [v0.5-pinned-maps-openapi.md](v0.5-pinned-maps-openapi.md).
|
||||
- **API-тесты** HTTP-контрактов (hurl-файлы) рядом с OpenAPI conformance-тестом.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Вторая схема синхронизации узлов (есть Redis); полный RBAC с ролями-ресурсами.
|
||||
|
||||
## Критерии приёмки
|
||||
|
||||
- [ ] Дропы по тегам видны в метриках; тег виден в `list`.
|
||||
- [ ] Замена набора не затрагивает баны других источников (тест).
|
||||
- [x] `rampart-cli blacklist add --for 1h30m` работает; `--for 90` отвергается с подсказкой (команда называется `blacklist add`, не `ban`).
|
||||
- [ ] Scoped-токен read-only не может создать бан (тест).
|
||||
|
||||
## Верификация
|
||||
|
||||
Интеграционный прогон manager API + загрузка набора на 100k записей с замером времени.
|
||||
|
|
@ -34,7 +34,12 @@ systemctl restart rampart
|
|||
|
||||
# B) Атака с известных подсетей → внести в blacklist через Manager API или CLI:
|
||||
rampart-cli blacklist add 1.2.3.4 "ddos source"
|
||||
rampart-cli blacklist list
|
||||
rampart-cli blacklist add 1.2.3.4 "ddos source" --for 1h30m # 30s, 5m, 1h30m, 2d
|
||||
# Голое число (--for 90) отвергается: единицы указываются явно (s, m, h, d).
|
||||
# Без --for действует срок по умолчанию manager API (300 с).
|
||||
# Отдельного старого флага --duration-secs в CLI нет; в API поле duration_secs
|
||||
# остаётся (и появился альтернативный абсолютный expires_at).
|
||||
rampart-cli blacklist list # показывает оставшееся время, например [1h29m left]
|
||||
|
||||
# C) Доверенные IP (мониторинг, админы) → whitelist в config.toml
|
||||
# (только IP-адреса), затем systemctl restart rampart
|
||||
|
|
|
|||
|
|
@ -41,8 +41,22 @@ enum Commands {
|
|||
|
||||
#[derive(Subcommand)]
|
||||
enum BlacklistAction {
|
||||
Add { target: String, reason: Option<String> },
|
||||
Remove { target: String },
|
||||
/// Ban an address, optionally for a limited time (`--for 1h30m`)
|
||||
Add {
|
||||
/// Single IPv4/IPv6 address
|
||||
#[arg(value_parser = commands::blacklist::parse_target_arg)]
|
||||
target: String,
|
||||
reason: Option<String>,
|
||||
/// Ban duration: 30s, 5m, 1h30m, 2d (a bare number is rejected)
|
||||
#[arg(long = "for", value_name = "DURATION", value_parser = commands::blacklist::parse_duration_arg)]
|
||||
duration: Option<u64>,
|
||||
},
|
||||
/// Remove a ban
|
||||
Remove {
|
||||
#[arg(value_parser = commands::blacklist::parse_target_arg)]
|
||||
target: String,
|
||||
},
|
||||
/// List active bans with remaining time
|
||||
List,
|
||||
}
|
||||
|
||||
|
|
@ -61,7 +75,11 @@ async fn main() -> anyhow::Result<()> {
|
|||
Commands::Doctor => commands::doctor::run().await,
|
||||
Commands::Config { key, value } => commands::config::run(key, value).await,
|
||||
Commands::Blacklist { action } => match action {
|
||||
BlacklistAction::Add { target, reason } => commands::blacklist::add(target, reason).await,
|
||||
BlacklistAction::Add {
|
||||
target,
|
||||
reason,
|
||||
duration,
|
||||
} => commands::blacklist::add(target, reason, duration).await,
|
||||
BlacklistAction::Remove { target } => commands::blacklist::remove(target).await,
|
||||
BlacklistAction::List => commands::blacklist::list().await,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ struct AddResponse {
|
|||
struct BlacklistItem {
|
||||
target: String,
|
||||
reason: String,
|
||||
expires_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
|
@ -46,14 +47,51 @@ async fn authenticated_client() -> anyhow::Result<(reqwest::Client, String, Stri
|
|||
Ok((client, manager_url, token))
|
||||
}
|
||||
|
||||
pub async fn add(target: String, reason: Option<String>) -> anyhow::Result<()> {
|
||||
/// clap value parser: a single address, strictly validated.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the validation message for anything but a bare IPv4/IPv6 address.
|
||||
pub fn parse_target_arg(text: &str) -> Result<String, String> {
|
||||
let parsed = crate::manager::input::parse_target(text)?;
|
||||
if parsed.prefix.is_some() {
|
||||
return Err("CIDR targets are not supported; ban a single IP address".into());
|
||||
}
|
||||
Ok(parsed.ip.to_string())
|
||||
}
|
||||
|
||||
/// clap value parser for `--for`: a human duration that must be non-zero.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the parser message (with the valid units) or a zero-duration message.
|
||||
pub fn parse_duration_arg(text: &str) -> Result<u64, String> {
|
||||
match crate::cli::duration::parse_duration_secs(text)? {
|
||||
0 => Err("duration must be greater than zero".into()),
|
||||
secs => Ok(secs),
|
||||
}
|
||||
}
|
||||
|
||||
fn remaining(expires_at: Option<&str>) -> String {
|
||||
let Some(at) = expires_at.and_then(crate::timeutil::parse_rfc3339_unix) else {
|
||||
return "permanent".to_string();
|
||||
};
|
||||
let left = at.saturating_sub(crate::timeutil::unix_now());
|
||||
match u64::try_from(left) {
|
||||
Ok(secs) if secs > 0 => format!("{} left", crate::cli::duration::format_duration_secs(secs)),
|
||||
_ => "expired".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add(target: String, reason: Option<String>, duration_secs: Option<u64>) -> anyhow::Result<()> {
|
||||
let (client, manager_url, token) = authenticated_client().await?;
|
||||
|
||||
let body = serde_json::json!({
|
||||
let mut body = serde_json::json!({
|
||||
"target": target,
|
||||
"type": "ip",
|
||||
"reason": reason.unwrap_or_else(|| "manual".to_string()),
|
||||
});
|
||||
if let Some(secs) = duration_secs {
|
||||
body["duration_secs"] = secs.into();
|
||||
}
|
||||
|
||||
let resp = client
|
||||
.post(format!("{manager_url}/api/v1/blacklist"))
|
||||
|
|
@ -95,7 +133,12 @@ pub async fn list() -> anyhow::Result<()> {
|
|||
println!("Blacklist ({} entries)", list.total);
|
||||
println!("----------------------");
|
||||
for item in &list.items {
|
||||
println!(" {} ({})", item.target, item.reason);
|
||||
println!(
|
||||
" {} ({}) [{}]",
|
||||
item.target,
|
||||
item.reason,
|
||||
remaining(item.expires_at.as_deref())
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
74
src/cli/duration.rs
Normal file
74
src/cli/duration.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
//! Human-readable durations for CLI flags: `30s`, `5m`, `1h30m`, `2d`.
|
||||
|
||||
/// Hint appended to every rejection so a unit mistake is fixed on the first retry.
|
||||
const UNITS_HINT: &str = "valid units: s (seconds), m (minutes), h (hours), d (days); e.g. 30s, 5m, 1h30m, 2d";
|
||||
|
||||
/// Parses a duration into seconds.
|
||||
///
|
||||
/// Grammar: one or more `<digits><unit>` parts with units `d`, `h`, `m`, `s` in
|
||||
/// strictly descending order, each at most once, no whitespace. A bare number is
|
||||
/// rejected (seconds versus minutes is a classic mistake); only a bare `0` is
|
||||
/// accepted and yields zero, which callers treat as "no duration".
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a message with the valid units on any deviation or on overflow.
|
||||
pub fn parse_duration_secs(text: &str) -> Result<u64, String> {
|
||||
if text.is_empty() {
|
||||
return Err(format!("duration must not be empty ({UNITS_HINT})"));
|
||||
}
|
||||
if text == "0" {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut total: u64 = 0;
|
||||
let mut rest = text;
|
||||
let mut last_rank = u8::MAX;
|
||||
while !rest.is_empty() {
|
||||
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
|
||||
if digits == 0 {
|
||||
return Err(format!("invalid duration '{text}' ({UNITS_HINT})"));
|
||||
}
|
||||
let (number, tail) = rest.split_at(digits);
|
||||
let mut chars = tail.chars();
|
||||
let (rank, factor) = match chars.next() {
|
||||
Some('d') => (3, 86_400),
|
||||
Some('h') => (2, 3_600),
|
||||
Some('m') => (1, 60),
|
||||
Some('s') => (0, 1),
|
||||
Some(_) => return Err(format!("invalid unit in '{text}' ({UNITS_HINT})")),
|
||||
None => return Err(format!("duration '{text}' needs a unit ({UNITS_HINT})")),
|
||||
};
|
||||
if rank >= last_rank {
|
||||
return Err(format!(
|
||||
"units in '{text}' must be unique and descending ({UNITS_HINT})"
|
||||
));
|
||||
}
|
||||
last_rank = rank;
|
||||
let value: u64 = number.parse().map_err(|_| format!("duration '{text}' is too large"))?;
|
||||
total = value
|
||||
.checked_mul(factor)
|
||||
.and_then(|part| total.checked_add(part))
|
||||
.ok_or_else(|| format!("duration '{text}' is too large"))?;
|
||||
rest = chars.as_str();
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Formats seconds with the two largest non-zero units, e.g. `1h30m`.
|
||||
#[must_use]
|
||||
pub fn format_duration_secs(secs: u64) -> String {
|
||||
if secs == 0 {
|
||||
return "0s".to_string();
|
||||
}
|
||||
let parts = [
|
||||
(secs / 86_400, 'd'),
|
||||
(secs % 86_400 / 3_600, 'h'),
|
||||
(secs % 3_600 / 60, 'm'),
|
||||
(secs % 60, 's'),
|
||||
];
|
||||
parts
|
||||
.iter()
|
||||
.filter(|(value, _)| *value > 0)
|
||||
.take(2)
|
||||
.map(|(value, unit)| format!("{value}{unit}"))
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
//! CLI commands used by `bin/rampart-cli`.
|
||||
#[allow(clippy::print_stdout, clippy::print_stderr)]
|
||||
pub mod commands;
|
||||
pub mod duration;
|
||||
|
|
|
|||
|
|
@ -32,6 +32,8 @@ pub struct AddBlacklistRequest {
|
|||
pub entry_type: String,
|
||||
pub reason: String,
|
||||
pub duration_secs: Option<u64>,
|
||||
/// Absolute expiry in unix seconds; mutually exclusive with `duration_secs`.
|
||||
pub expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ pub(super) const BLACKLIST_METADATA_KEY: &str = "rampart:blacklist:metadata";
|
|||
pub(super) const BLACKLIST_CHANNEL: &str = "rampart:blacklist:events";
|
||||
pub(super) const DEFAULT_BAN_DURATION_SECS: u64 = 300;
|
||||
pub(super) const LEGACY_BAN_DURATION_SECS: u64 = 300;
|
||||
pub(super) const MAX_BAN_DURATION_SECS: u64 = 31_536_000;
|
||||
/// Maximum accepted length of a ban reason, in bytes.
|
||||
pub(super) const MAX_REASON_BYTES: usize = 256;
|
||||
/// Batch size of SSCAN/HMGET/MGET calls on the blacklist.
|
||||
|
|
@ -70,20 +69,15 @@ pub(super) fn event_payload(
|
|||
/// syntactically valid but unsupported and is rejected with an explicit message
|
||||
/// instead of being stored as an entry the edges cannot apply.
|
||||
pub(super) fn validate_target(target: &str) -> Result<IpAddr, (StatusCode, Json<serde_json::Value>)> {
|
||||
let target = target.trim();
|
||||
if let Ok(ip) = target.parse::<IpAddr>() {
|
||||
return Ok(ip);
|
||||
}
|
||||
if crate::manager::security::IpNet::parse(target).is_ok() {
|
||||
let parsed =
|
||||
crate::manager::input::parse_target(target).map_err(|message| api_error(StatusCode::BAD_REQUEST, &message))?;
|
||||
if parsed.prefix.is_some() {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"CIDR targets are not supported; ban a single IP address",
|
||||
));
|
||||
}
|
||||
Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"target must be a valid IPv4 or IPv6 address",
|
||||
))
|
||||
Ok(parsed.ip)
|
||||
}
|
||||
|
||||
/// Rejects a `reason` longer than [`MAX_REASON_BYTES`] bytes.
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
use super::common::{
|
||||
ADD_BAN_SCRIPT, BLACKLIST_CHANNEL, BLACKLIST_KEY, BLACKLIST_METADATA_KEY, DEFAULT_BAN_DURATION_SECS,
|
||||
MAX_BAN_DURATION_SECS, REMOVE_BAN_SCRIPT, api_error, event_payload, redis_error, redis_unavailable,
|
||||
validate_reason, validate_target,
|
||||
REMOVE_BAN_SCRIPT, api_error, event_payload, redis_error, redis_unavailable, validate_reason, validate_target,
|
||||
};
|
||||
use super::{AddBlacklistRequest, RemoveBlacklistRequest};
|
||||
use crate::manager::AppState;
|
||||
use crate::manager::input::resolve_ban_window;
|
||||
use axum::{Json, extract::State, http::StatusCode};
|
||||
use std::sync::Arc;
|
||||
|
||||
|
|
@ -22,25 +22,19 @@ pub async fn add_blacklist(
|
|||
"only IP blacklist entries are supported",
|
||||
));
|
||||
}
|
||||
let duration_secs = req.duration_secs.unwrap_or(DEFAULT_BAN_DURATION_SECS);
|
||||
if duration_secs == 0 {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"duration_secs must be greater than zero",
|
||||
));
|
||||
}
|
||||
if duration_secs > MAX_BAN_DURATION_SECS {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"duration_secs must not exceed one year",
|
||||
));
|
||||
}
|
||||
let created_at_unix = crate::timeutil::unix_now();
|
||||
let (duration_secs, expires_at_unix) = resolve_ban_window(
|
||||
req.duration_secs,
|
||||
req.expires_at,
|
||||
DEFAULT_BAN_DURATION_SECS,
|
||||
created_at_unix,
|
||||
)
|
||||
.map_err(|message| api_error(StatusCode::BAD_REQUEST, message))?;
|
||||
|
||||
let target = ip.to_string();
|
||||
let created_at_unix = crate::timeutil::unix_now();
|
||||
let metadata = super::common::BlacklistMetadata {
|
||||
created_at_unix,
|
||||
expires_at_unix: created_at_unix + duration_secs as i64,
|
||||
expires_at_unix,
|
||||
reason: req.reason.clone(),
|
||||
};
|
||||
let encoded_metadata = serde_json::to_string(&metadata)
|
||||
|
|
@ -69,7 +63,8 @@ pub async fn add_blacklist(
|
|||
"status": "added",
|
||||
"target": target,
|
||||
"reason": req.reason,
|
||||
"duration_secs": duration_secs
|
||||
"duration_secs": duration_secs,
|
||||
"expires_at": expires_at_unix
|
||||
})))
|
||||
}
|
||||
|
||||
|
|
|
|||
107
src/manager/input.rs
Normal file
107
src/manager/input.rs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
//! Strict parsing of operator input shared by the manager API and the CLI.
|
||||
//!
|
||||
//! Everything here rejects instead of normalising: no surrounding whitespace, no
|
||||
//! sign characters, no trailing garbage. Untrusted text must name exactly one
|
||||
//! thing, otherwise a typo could ban a different address than the one intended.
|
||||
|
||||
use crate::filter::blacklist::MAX_BAN_DURATION_SECS;
|
||||
use std::net::IpAddr;
|
||||
|
||||
/// A ban target: one address, optionally written with a CIDR prefix.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
pub ip: IpAddr,
|
||||
/// `None` for a bare address; `Some(1..=width)` for a network.
|
||||
pub prefix: Option<u8>,
|
||||
}
|
||||
|
||||
/// Parses `1.2.3.4`, `::1`, `10.0.0.0/8` or `2001:db8::/32`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Rejects empty input, whitespace anywhere, a malformed address, a prefix that is
|
||||
/// not plain decimal digits, `/0` (it would match every address) and a prefix
|
||||
/// beyond 32 (IPv4) or 128 (IPv6).
|
||||
pub fn parse_target(text: &str) -> Result<Target, String> {
|
||||
if text.is_empty() {
|
||||
return Err("target must not be empty".into());
|
||||
}
|
||||
if text.chars().any(char::is_whitespace) {
|
||||
return Err("target must not contain whitespace".into());
|
||||
}
|
||||
let (addr, prefix) = match text.split_once('/') {
|
||||
Some((addr, prefix)) => (addr, Some(prefix)),
|
||||
None => (text, None),
|
||||
};
|
||||
let ip: IpAddr = addr
|
||||
.parse()
|
||||
.map_err(|_| "target must be a valid IPv4 or IPv6 address".to_string())?;
|
||||
let Some(prefix) = prefix else {
|
||||
return Ok(Target { ip, prefix: None });
|
||||
};
|
||||
let width: u8 = if ip.is_ipv4() { 32 } else { 128 };
|
||||
if prefix.is_empty() || !prefix.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err("prefix length must be decimal digits".into());
|
||||
}
|
||||
let len: u8 = prefix
|
||||
.parse()
|
||||
.map_err(|_| format!("prefix length exceeds the {width}-bit address width"))?;
|
||||
if len == 0 {
|
||||
return Err("prefix length /0 is not allowed".into());
|
||||
}
|
||||
if len > width {
|
||||
return Err(format!("prefix length exceeds the {width}-bit address width"));
|
||||
}
|
||||
Ok(Target { ip, prefix: Some(len) })
|
||||
}
|
||||
|
||||
/// Parses a TCP/UDP port: decimal digits only, `1..=65535`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Rejects empty input, signs, whitespace, `0` and values above 65535.
|
||||
pub fn parse_port(text: &str) -> Result<u16, String> {
|
||||
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err("port must be decimal digits".into());
|
||||
}
|
||||
match text.parse::<u16>() {
|
||||
Ok(0) | Err(_) => Err("port must be between 1 and 65535".into()),
|
||||
Ok(port) => Ok(port),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the ban window of a request into `(duration_secs, expires_at_unix)`.
|
||||
///
|
||||
/// Exactly one of `duration_secs` and `expires_at` may be set; with neither,
|
||||
/// `default_secs` applies.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when both are set, a duration is zero or above the one-year cap, or
|
||||
/// `expires_at` is unrepresentable, not in the future, or beyond the cap.
|
||||
pub fn resolve_ban_window(
|
||||
duration_secs: Option<u64>,
|
||||
expires_at: Option<i64>,
|
||||
default_secs: u64,
|
||||
now: i64,
|
||||
) -> Result<(u64, i64), &'static str> {
|
||||
let secs = match (duration_secs, expires_at) {
|
||||
(Some(_), Some(_)) => return Err("specify either duration_secs or expires_at, not both"),
|
||||
(None, Some(at)) => {
|
||||
if !crate::timeutil::is_valid_unix(at) {
|
||||
return Err("expires_at is not a valid unix timestamp");
|
||||
}
|
||||
if at <= now {
|
||||
return Err("expires_at must be in the future");
|
||||
}
|
||||
u64::try_from(at.saturating_sub(now)).map_err(|_| "expires_at must be in the future")?
|
||||
},
|
||||
(Some(secs), None) => secs,
|
||||
(None, None) => default_secs,
|
||||
};
|
||||
if secs == 0 {
|
||||
return Err("duration_secs must be greater than zero");
|
||||
}
|
||||
if secs > MAX_BAN_DURATION_SECS {
|
||||
return Err("ban duration must not exceed one year");
|
||||
}
|
||||
let secs_i = i64::try_from(secs).map_err(|_| "ban duration must not exceed one year")?;
|
||||
Ok((secs, now.saturating_add(secs_i)))
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
//! Owns [`AppState`], the handle shared by every handler through [`SharedState`].
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod input;
|
||||
pub mod security;
|
||||
pub mod sync;
|
||||
|
||||
|
|
|
|||
66
tests/cli_duration.rs
Normal file
66
tests/cli_duration.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
//! Human-readable duration parser of `rampart-cli` and its clap value parsers.
|
||||
|
||||
use rampart::cli::commands::blacklist::{parse_duration_arg, parse_target_arg};
|
||||
use rampart::cli::duration::{format_duration_secs, parse_duration_secs};
|
||||
|
||||
#[test]
|
||||
fn accepts_single_and_compound_units() {
|
||||
assert_eq!(parse_duration_secs("30s"), Ok(30));
|
||||
assert_eq!(parse_duration_secs("5m"), Ok(300));
|
||||
assert_eq!(parse_duration_secs("1h30m"), Ok(5400));
|
||||
assert_eq!(parse_duration_secs("2d"), Ok(172_800));
|
||||
assert_eq!(parse_duration_secs("1d2h3m4s"), Ok(93_784));
|
||||
assert_eq!(parse_duration_secs("0"), Ok(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_numbers_are_rejected_with_a_unit_hint() {
|
||||
for text in ["90", "1", "3600"] {
|
||||
let error = parse_duration_secs(text).expect_err(text);
|
||||
assert!(error.contains("valid units"), "{text}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_input_is_rejected() {
|
||||
for text in [
|
||||
"", " ", "5 m", " 5m", "5m ", "m", "-5m", "+5m", "1.5h", "5x", "5M", "1h1h", "30s5m", "5m30", "1h-5m", "0x10s",
|
||||
"5m", "5mm",
|
||||
] {
|
||||
assert!(parse_duration_secs(text).is_err(), "'{text}' must be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_is_an_error_not_a_wrap() {
|
||||
assert!(parse_duration_secs("99999999999999999999s").is_err());
|
||||
assert!(parse_duration_secs("999999999999999999d").is_err());
|
||||
assert!(parse_duration_secs("18446744073709551615h").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ban_flag_rejects_zero_and_formats_remaining_time() {
|
||||
assert_eq!(parse_duration_arg("1h30m"), Ok(5400));
|
||||
assert!(parse_duration_arg("0").is_err());
|
||||
assert!(parse_duration_arg("90").is_err());
|
||||
assert_eq!(format_duration_secs(5400), "1h30m");
|
||||
assert_eq!(format_duration_secs(90_061), "1d1h");
|
||||
assert_eq!(format_duration_secs(45), "45s");
|
||||
assert_eq!(format_duration_secs(0), "0s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_target_is_a_single_strict_address() {
|
||||
assert_eq!(parse_target_arg("1.2.3.4"), Ok("1.2.3.4".to_string()));
|
||||
for text in [
|
||||
"",
|
||||
" 1.2.3.4",
|
||||
"1.2.3.4 ",
|
||||
"1.2.3.4x",
|
||||
"10.0.0.0/8",
|
||||
"1.2.3.4/0",
|
||||
"1.2.3.4/33",
|
||||
] {
|
||||
assert!(parse_target_arg(text).is_err(), "'{text}' must be rejected");
|
||||
}
|
||||
}
|
||||
|
|
@ -102,7 +102,19 @@ async fn protected_routes_require_a_token() {
|
|||
#[tokio::test]
|
||||
async fn blacklist_rejects_invalid_targets() {
|
||||
let router = app();
|
||||
for target in ["not-an-ip", "10.0.0.0/8", "999.1.1.1", ""] {
|
||||
for target in [
|
||||
"not-an-ip",
|
||||
"10.0.0.0/8",
|
||||
"999.1.1.1",
|
||||
"",
|
||||
" 1.2.3.4",
|
||||
"1.2.3.4 ",
|
||||
"1.2.3.4x",
|
||||
"1.2.3.4/0",
|
||||
"1.2.3.4/33",
|
||||
"::1/129",
|
||||
"1.2.3.4/+8",
|
||||
] {
|
||||
let body = format!(r#"{{"target":"{target}","type":"ip","reason":"manual_ban"}}"#);
|
||||
let response = status(
|
||||
&router,
|
||||
|
|
@ -280,3 +292,49 @@ fn list_query_is_capped_regardless_of_the_request() {
|
|||
(0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
async fn post_ban(router: &Router, extra: &str) -> StatusCode {
|
||||
let body = format!(r#"{{"target":"1.2.3.4","type":"ip","reason":"manual_ban"{extra}}}"#);
|
||||
status(
|
||||
router,
|
||||
authorized(request(Method::POST, "/api/v1/blacklist", Body::from(body))),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ban_accepts_absolute_expiry_as_an_alternative_to_duration() {
|
||||
let router = app();
|
||||
let now = rampart::timeutil::unix_now();
|
||||
// Valid requests pass validation and fail only at the unreachable Redis (503).
|
||||
for extra in [
|
||||
String::new(),
|
||||
r#","duration_secs":3600"#.to_string(),
|
||||
format!(r#","expires_at":{}"#, now + 3600),
|
||||
format!(r#","expires_at":{}"#, now + 31_536_000 - 5),
|
||||
] {
|
||||
assert_eq!(
|
||||
post_ban(&router, &extra).await,
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"{extra}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ban_rejects_invalid_expiry_combinations() {
|
||||
let router = app();
|
||||
let now = rampart::timeutil::unix_now();
|
||||
for extra in [
|
||||
format!(r#","duration_secs":60,"expires_at":{}"#, now + 60),
|
||||
format!(r#","expires_at":{}"#, now - 10),
|
||||
r#","expires_at":0"#.to_string(),
|
||||
r#","expires_at":-5"#.to_string(),
|
||||
format!(r#","expires_at":{}"#, now + 31_536_000 + 60),
|
||||
format!(r#","expires_at":{}"#, i64::MAX),
|
||||
r#","duration_secs":0"#.to_string(),
|
||||
r#","duration_secs":31536001"#.to_string(),
|
||||
] {
|
||||
assert_eq!(post_ban(&router, &extra).await, StatusCode::BAD_REQUEST, "{extra}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
98
tests/manager_input.rs
Normal file
98
tests/manager_input.rs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
//! Strict input validation for ban targets, ports and ban windows.
|
||||
|
||||
use rampart::manager::input::{parse_port, parse_target, resolve_ban_window};
|
||||
|
||||
const NOW: i64 = 1_800_000_000;
|
||||
const YEAR: i64 = 31_536_000;
|
||||
|
||||
#[test]
|
||||
fn accepts_addresses_and_valid_prefixes() {
|
||||
assert_eq!(parse_target("1.2.3.4").map(|t| t.prefix), Ok(None));
|
||||
assert_eq!(parse_target("::1").map(|t| t.prefix), Ok(None));
|
||||
assert_eq!(parse_target("10.0.0.0/8").map(|t| t.prefix), Ok(Some(8)));
|
||||
assert_eq!(parse_target("1.2.3.4/32").map(|t| t.prefix), Ok(Some(32)));
|
||||
assert_eq!(parse_target("2001:db8::/128").map(|t| t.prefix), Ok(Some(128)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_targets() {
|
||||
for text in [
|
||||
"",
|
||||
" ",
|
||||
" 1.2.3.4",
|
||||
"1.2.3.4 ",
|
||||
"1.2.3.4\n",
|
||||
"1. 2.3.4",
|
||||
"1.2.3.4x",
|
||||
"1.2.3.4:80",
|
||||
"1.2.3.4/",
|
||||
"1.2.3.4/0",
|
||||
"::/0",
|
||||
"1.2.3.4/33",
|
||||
"::1/129",
|
||||
"1.2.3.4/+8",
|
||||
"1.2.3.4/8x",
|
||||
"1.2.3.4/-1",
|
||||
"1.2.3.4/256",
|
||||
"1.2.3.4/8/8",
|
||||
"999.1.1.1",
|
||||
"not-an-ip",
|
||||
] {
|
||||
assert!(parse_target(text).is_err(), "'{text}' must be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_are_strict_decimal_in_range() {
|
||||
assert_eq!(parse_port("1"), Ok(1));
|
||||
assert_eq!(parse_port("443"), Ok(443));
|
||||
assert_eq!(parse_port("65535"), Ok(65535));
|
||||
for text in [
|
||||
"",
|
||||
"0",
|
||||
"00",
|
||||
"65536",
|
||||
"99999999999",
|
||||
"-1",
|
||||
"+80",
|
||||
" 80",
|
||||
"80 ",
|
||||
"80x",
|
||||
"0x50",
|
||||
"8.0",
|
||||
] {
|
||||
assert!(parse_port(text).is_err(), "'{text}' must be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_defaults_and_duration_are_unchanged() {
|
||||
assert_eq!(resolve_ban_window(None, None, 300, NOW), Ok((300, NOW + 300)));
|
||||
assert_eq!(resolve_ban_window(Some(3600), None, 300, NOW), Ok((3600, NOW + 3600)));
|
||||
assert!(resolve_ban_window(Some(0), None, 300, NOW).is_err());
|
||||
assert!(resolve_ban_window(Some(YEAR as u64 + 1), None, 300, NOW).is_err());
|
||||
assert_eq!(
|
||||
resolve_ban_window(Some(YEAR as u64), None, 300, NOW),
|
||||
Ok((YEAR as u64, NOW + YEAR))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_expiry_is_validated() {
|
||||
assert_eq!(resolve_ban_window(None, Some(NOW + 60), 300, NOW), Ok((60, NOW + 60)));
|
||||
assert_eq!(
|
||||
resolve_ban_window(None, Some(NOW + YEAR), 300, NOW),
|
||||
Ok((YEAR as u64, NOW + YEAR))
|
||||
);
|
||||
for at in [NOW, NOW - 1, 0, -1, i64::MIN, i64::MAX, NOW + YEAR + 1] {
|
||||
assert!(
|
||||
resolve_ban_window(None, Some(at), 300, NOW).is_err(),
|
||||
"{at} must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duration_and_expiry_are_mutually_exclusive() {
|
||||
assert!(resolve_ban_window(Some(60), Some(NOW + 60), 300, NOW).is_err());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue