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