diff --git a/docs/api.md b/docs/api.md index 0976aac..bc08866 100644 --- a/docs/api.md +++ b/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; новые diff --git a/docs/roadmap/v0.5-control-plane-bans.md b/docs/roadmap/v0.5-control-plane-bans.md index c9f4dcb..b7e746c 100644 --- a/docs/roadmap/v0.5-control-plane-bans.md +++ b/docs/roadmap/v0.5-control-plane-bans.md @@ -42,7 +42,7 @@ - [ ] Дропы по тегам видны в метриках; тег виден в `list`. - [ ] Замена набора не затрагивает баны других источников (тест). -- [ ] `rampart-cli ban --for 1h30m` работает; `--for 90` отвергается с подсказкой. +- [x] `rampart-cli blacklist add --for 1h30m` работает; `--for 90` отвергается с подсказкой (команда называется `blacklist add`, не `ban`). - [ ] Scoped-токен read-only не может создать бан (тест). ## Верификация diff --git a/docs/runbook.md b/docs/runbook.md index 46b0529..9a95fcd 100644 --- a/docs/runbook.md +++ b/docs/runbook.md @@ -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 diff --git a/src/bin/rampart-cli.rs b/src/bin/rampart-cli.rs index 8412554..c329276 100644 --- a/src/bin/rampart-cli.rs +++ b/src/bin/rampart-cli.rs @@ -41,8 +41,22 @@ enum Commands { #[derive(Subcommand)] enum BlacklistAction { - Add { target: String, reason: Option }, - 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, + /// 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, + }, + /// 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, }, diff --git a/src/cli/commands/blacklist.rs b/src/cli/commands/blacklist.rs index fa0a20e..9495b2a 100644 --- a/src/cli/commands/blacklist.rs +++ b/src/cli/commands/blacklist.rs @@ -13,6 +13,7 @@ struct AddResponse { struct BlacklistItem { target: String, reason: String, + expires_at: Option, } #[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) -> 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 { + 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 { + 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, duration_secs: Option) -> 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(()) } diff --git a/src/cli/duration.rs b/src/cli/duration.rs new file mode 100644 index 0000000..b924834 --- /dev/null +++ b/src/cli/duration.rs @@ -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 `` 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 { + 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() +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index d67522d..6b26541 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,3 +1,4 @@ //! CLI commands used by `bin/rampart-cli`. #[allow(clippy::print_stdout, clippy::print_stderr)] pub mod commands; +pub mod duration; diff --git a/src/manager/api/blacklist.rs b/src/manager/api/blacklist.rs index e8a0f11..2af9db6 100644 --- a/src/manager/api/blacklist.rs +++ b/src/manager/api/blacklist.rs @@ -32,6 +32,8 @@ pub struct AddBlacklistRequest { pub entry_type: String, pub reason: String, pub duration_secs: Option, + /// Absolute expiry in unix seconds; mutually exclusive with `duration_secs`. + pub expires_at: Option, } #[derive(Deserialize)] diff --git a/src/manager/api/blacklist/common.rs b/src/manager/api/blacklist/common.rs index 8805e80..659cfbd 100644 --- a/src/manager/api/blacklist/common.rs +++ b/src/manager/api/blacklist/common.rs @@ -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)> { - let target = target.trim(); - if let Ok(ip) = target.parse::() { - 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. diff --git a/src/manager/api/blacklist/mutate.rs b/src/manager/api/blacklist/mutate.rs index 9acb83f..56c0129 100644 --- a/src/manager/api/blacklist/mutate.rs +++ b/src/manager/api/blacklist/mutate.rs @@ -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 }))) } diff --git a/src/manager/input.rs b/src/manager/input.rs new file mode 100644 index 0000000..8c980e8 --- /dev/null +++ b/src/manager/input.rs @@ -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, +} + +/// 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 { + 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 { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return Err("port must be decimal digits".into()); + } + match text.parse::() { + 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, + expires_at: Option, + 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))) +} diff --git a/src/manager/mod.rs b/src/manager/mod.rs index 4ccaf84..b3afdd7 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -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; diff --git a/tests/cli_duration.rs b/tests/cli_duration.rs new file mode 100644 index 0000000..13be226 --- /dev/null +++ b/tests/cli_duration.rs @@ -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"); + } +} diff --git a/tests/manager_api.rs b/tests/manager_api.rs index 2dbd045..3d402cb 100644 --- a/tests/manager_api.rs +++ b/tests/manager_api.rs @@ -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}"); + } +} diff --git a/tests/manager_input.rs b/tests/manager_input.rs new file mode 100644 index 0000000..b4453a3 --- /dev/null +++ b/tests/manager_input.rs @@ -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()); +}