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
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue