style: switch rustfmt to hard tabs; document tests-separate rule in TODO
- rustfmt.toml: hard_tabs = true. - TODO §0.7: tests live in tests/, no #[cfg(test)] modules in code files.
This commit is contained in:
parent
d8393e0f39
commit
a90f0da226
96 changed files with 6542 additions and 6537 deletions
|
|
@ -1,15 +1,15 @@
|
|||
use crate::manager::AppState;
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{ConnectInfo, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
extract::{ConnectInfo, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use dashmap::DashMap;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
|
|
@ -18,87 +18,87 @@ const LOGIN_MAX_ATTEMPTS: u32 = 5;
|
|||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginRequest {
|
||||
pub password: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(state): State<Arc<AppState>>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
Json(req): Json<LoginRequest>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
Json(req): Json<LoginRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
if !allow_login_attempt(&state.login_limiter, addr.ip()) {
|
||||
return Err((
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Json(serde_json::json!({"error": "too many requests"})),
|
||||
));
|
||||
}
|
||||
if !allow_login_attempt(&state.login_limiter, addr.ip()) {
|
||||
return Err((
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Json(serde_json::json!({"error": "too many requests"})),
|
||||
));
|
||||
}
|
||||
|
||||
if !verify_password(&req.password, &state.api_password) {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "invalid password"})),
|
||||
));
|
||||
}
|
||||
if !verify_password(&req.password, &state.api_password) {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "invalid password"})),
|
||||
));
|
||||
}
|
||||
|
||||
match crate::manager::auth::create_token(&state.jwt_secret, state.jwt_expiration, &state.jwt_audience) {
|
||||
Ok(token) => Ok(Json(serde_json::json!({"token": token}))),
|
||||
Err(_) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": "token creation failed"})),
|
||||
)),
|
||||
}
|
||||
match crate::manager::auth::create_token(&state.jwt_secret, state.jwt_expiration, &state.jwt_audience) {
|
||||
Ok(token) => Ok(Json(serde_json::json!({"token": token}))),
|
||||
Err(_) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": "token creation failed"})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_password(provided: &str, expected: &str) -> bool {
|
||||
let provided = provided.as_bytes();
|
||||
let expected = expected.as_bytes();
|
||||
let len_match = (provided.len() as u64).ct_eq(&(expected.len() as u64));
|
||||
let min_len = provided.len().min(expected.len());
|
||||
let bytes_match = provided[..min_len].ct_eq(&expected[..min_len]);
|
||||
bool::from(len_match & bytes_match)
|
||||
let provided = provided.as_bytes();
|
||||
let expected = expected.as_bytes();
|
||||
let len_match = (provided.len() as u64).ct_eq(&(expected.len() as u64));
|
||||
let min_len = provided.len().min(expected.len());
|
||||
let bytes_match = provided[..min_len].ct_eq(&expected[..min_len]);
|
||||
bool::from(len_match & bytes_match)
|
||||
}
|
||||
|
||||
fn allow_login_attempt(limiter: &DashMap<IpAddr, (Instant, u32)>, ip: IpAddr) -> bool {
|
||||
let now = Instant::now();
|
||||
let mut slot = limiter.entry(ip).or_insert((now, 0));
|
||||
let (last_reset, attempts) = &mut *slot;
|
||||
if now.duration_since(*last_reset) >= LOGIN_WINDOW {
|
||||
*last_reset = now;
|
||||
*attempts = 1;
|
||||
} else if *attempts >= LOGIN_MAX_ATTEMPTS {
|
||||
return false;
|
||||
} else {
|
||||
*attempts += 1;
|
||||
}
|
||||
true
|
||||
let now = Instant::now();
|
||||
let mut slot = limiter.entry(ip).or_insert((now, 0));
|
||||
let (last_reset, attempts) = &mut *slot;
|
||||
if now.duration_since(*last_reset) >= LOGIN_WINDOW {
|
||||
*last_reset = now;
|
||||
*attempts = 1;
|
||||
} else if *attempts >= LOGIN_MAX_ATTEMPTS {
|
||||
return false;
|
||||
} else {
|
||||
*attempts += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verify_password_matches() {
|
||||
assert!(verify_password("s3cret-pass", "s3cret-pass"));
|
||||
}
|
||||
#[test]
|
||||
fn verify_password_matches() {
|
||||
assert!(verify_password("s3cret-pass", "s3cret-pass"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_password_rejects_wrong() {
|
||||
assert!(!verify_password("wrong-pass", "s3cret-pass"));
|
||||
}
|
||||
#[test]
|
||||
fn verify_password_rejects_wrong() {
|
||||
assert!(!verify_password("wrong-pass", "s3cret-pass"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_password_rejects_different_length() {
|
||||
assert!(!verify_password("short", "a-longer-password"));
|
||||
}
|
||||
#[test]
|
||||
fn verify_password_rejects_different_length() {
|
||||
assert!(!verify_password("short", "a-longer-password"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allow_login_attempt_respects_limit() {
|
||||
let limiter = DashMap::new();
|
||||
let ip = IpAddr::from([127, 0, 0, 1]);
|
||||
for _ in 0..LOGIN_MAX_ATTEMPTS {
|
||||
assert!(allow_login_attempt(&limiter, ip));
|
||||
}
|
||||
assert!(!allow_login_attempt(&limiter, ip));
|
||||
}
|
||||
#[test]
|
||||
fn allow_login_attempt_respects_limit() {
|
||||
let limiter = DashMap::new();
|
||||
let ip = IpAddr::from([127, 0, 0, 1]);
|
||||
for _ in 0..LOGIN_MAX_ATTEMPTS {
|
||||
assert!(allow_login_attempt(&limiter, ip));
|
||||
}
|
||||
assert!(!allow_login_attempt(&limiter, ip));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,33 +2,33 @@ use serde::{Deserialize, Serialize};
|
|||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct BlacklistEntry {
|
||||
pub target: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub reason: String,
|
||||
pub created_at: String,
|
||||
pub expires_at: Option<String>,
|
||||
pub target: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub reason: String,
|
||||
pub created_at: String,
|
||||
pub expires_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct BlacklistResponse {
|
||||
pub items: Vec<BlacklistEntry>,
|
||||
pub total: usize,
|
||||
pub items: Vec<BlacklistEntry>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct AddBlacklistRequest {
|
||||
pub target: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub reason: String,
|
||||
pub duration_secs: Option<u64>,
|
||||
pub target: String,
|
||||
#[serde(rename = "type")]
|
||||
pub entry_type: String,
|
||||
pub reason: String,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RemoveBlacklistRequest {
|
||||
pub target: String,
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
|
|
|
|||
|
|
@ -3,18 +3,18 @@ use serde::{Deserialize, Serialize};
|
|||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct BlacklistEvent<'a> {
|
||||
ip: &'a str,
|
||||
action: &'a str,
|
||||
duration_secs: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
expires_at_unix: Option<i64>,
|
||||
ip: &'a str,
|
||||
action: &'a str,
|
||||
duration_secs: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
expires_at_unix: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub(super) struct BlacklistMetadata {
|
||||
pub created_at_unix: i64,
|
||||
pub expires_at_unix: i64,
|
||||
pub reason: String,
|
||||
pub created_at_unix: i64,
|
||||
pub expires_at_unix: i64,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
pub(super) const BLACKLIST_KEY: &str = "rampart:blacklist";
|
||||
|
|
@ -27,49 +27,49 @@ pub(super) const ADD_BAN_SCRIPT: &str = "redis.call('HSET', KEYS[2], ARGV[1], AR
|
|||
pub(super) const REMOVE_BAN_SCRIPT: &str = "redis.call('SREM', KEYS[1], ARGV[1]); redis.call('HDEL', KEYS[2], ARGV[1]); redis.call('PUBLISH', KEYS[3], ARGV[2]); return 1";
|
||||
|
||||
pub(super) fn legacy_metadata(now: i64) -> BlacklistMetadata {
|
||||
BlacklistMetadata {
|
||||
created_at_unix: now,
|
||||
expires_at_unix: now.saturating_add(LEGACY_BAN_DURATION_SECS as i64),
|
||||
reason: "legacy_unverified".to_string(),
|
||||
}
|
||||
BlacklistMetadata {
|
||||
created_at_unix: now,
|
||||
expires_at_unix: now.saturating_add(LEGACY_BAN_DURATION_SECS as i64),
|
||||
reason: "legacy_unverified".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn format_timestamp(timestamp: i64) -> String {
|
||||
chrono::DateTime::from_timestamp(timestamp, 0)
|
||||
.map(|value| value.to_rfc3339())
|
||||
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339())
|
||||
chrono::DateTime::from_timestamp(timestamp, 0)
|
||||
.map(|value| value.to_rfc3339())
|
||||
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339())
|
||||
}
|
||||
|
||||
pub(super) fn event_payload(
|
||||
ip: &str,
|
||||
action: &str,
|
||||
duration_secs: u64,
|
||||
expires_at_unix: Option<i64>,
|
||||
ip: &str,
|
||||
action: &str,
|
||||
duration_secs: u64,
|
||||
expires_at_unix: Option<i64>,
|
||||
) -> Result<String, (StatusCode, Json<serde_json::Value>)> {
|
||||
serde_json::to_string(&BlacklistEvent {
|
||||
ip,
|
||||
action,
|
||||
duration_secs,
|
||||
expires_at_unix,
|
||||
})
|
||||
.map_err(|_| api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to serialize blacklist event"))
|
||||
serde_json::to_string(&BlacklistEvent {
|
||||
ip,
|
||||
action,
|
||||
duration_secs,
|
||||
expires_at_unix,
|
||||
})
|
||||
.map_err(|_| api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to serialize blacklist event"))
|
||||
}
|
||||
|
||||
pub(super) fn parse_ip(target: &str) -> Result<std::net::IpAddr, (StatusCode, Json<serde_json::Value>)> {
|
||||
target
|
||||
.parse()
|
||||
.map_err(|_| api_error(StatusCode::BAD_REQUEST, "target must be an IP address"))
|
||||
target
|
||||
.parse()
|
||||
.map_err(|_| api_error(StatusCode::BAD_REQUEST, "target must be an IP address"))
|
||||
}
|
||||
|
||||
pub(super) fn api_error(status: StatusCode, message: &str) -> (StatusCode, Json<serde_json::Value>) {
|
||||
(status, Json(serde_json::json!({"error": message})))
|
||||
(status, Json(serde_json::json!({"error": message})))
|
||||
}
|
||||
|
||||
pub(super) fn redis_unavailable(_: redis::RedisError) -> (StatusCode, Json<serde_json::Value>) {
|
||||
api_error(StatusCode::SERVICE_UNAVAILABLE, "redis unavailable")
|
||||
api_error(StatusCode::SERVICE_UNAVAILABLE, "redis unavailable")
|
||||
}
|
||||
|
||||
pub(super) fn redis_error(error: redis::RedisError) -> (StatusCode, Json<serde_json::Value>) {
|
||||
tracing::error!("Blacklist Redis operation failed: {error}");
|
||||
api_error(StatusCode::SERVICE_UNAVAILABLE, "redis operation failed")
|
||||
tracing::error!("Blacklist Redis operation failed: {error}");
|
||||
api_error(StatusCode::SERVICE_UNAVAILABLE, "redis operation failed")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::common::{
|
||||
BLACKLIST_KEY, BLACKLIST_METADATA_KEY, BlacklistMetadata, format_timestamp, legacy_metadata, redis_error,
|
||||
redis_unavailable,
|
||||
BLACKLIST_KEY, BLACKLIST_METADATA_KEY, BlacklistMetadata, format_timestamp, legacy_metadata, redis_error,
|
||||
redis_unavailable,
|
||||
};
|
||||
use super::{BlacklistEntry, BlacklistResponse};
|
||||
use crate::manager::AppState;
|
||||
|
|
@ -10,70 +10,70 @@ use std::collections::HashMap;
|
|||
use std::sync::Arc;
|
||||
|
||||
pub async fn list_blacklist(
|
||||
State(state): State<Arc<AppState>>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
) -> Result<Json<BlacklistResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let members: Vec<String> = redis::cmd("SMEMBERS")
|
||||
.arg(BLACKLIST_KEY)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
let metadata: HashMap<String, String> = conn.hgetall(BLACKLIST_METADATA_KEY).await.map_err(redis_error)?;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let mut items = Vec::with_capacity(members.len());
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let members: Vec<String> = redis::cmd("SMEMBERS")
|
||||
.arg(BLACKLIST_KEY)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
let metadata: HashMap<String, String> = conn.hgetall(BLACKLIST_METADATA_KEY).await.map_err(redis_error)?;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let mut items = Vec::with_capacity(members.len());
|
||||
|
||||
for target in members {
|
||||
let Ok(ip) = target.parse::<std::net::IpAddr>() else {
|
||||
continue;
|
||||
};
|
||||
let record = match metadata.get(&target) {
|
||||
Some(encoded) => match serde_json::from_str::<BlacklistMetadata>(encoded) {
|
||||
Ok(record) => record,
|
||||
Err(_) => continue,
|
||||
},
|
||||
None => {
|
||||
let legacy = legacy_metadata(now);
|
||||
let encoded = serde_json::to_string(&legacy).map_err(|_| {
|
||||
super::common::api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to encode blacklist metadata")
|
||||
})?;
|
||||
let inserted: i64 = redis::cmd("HSETNX")
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(&target)
|
||||
.arg(encoded)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
if inserted == 1 {
|
||||
legacy
|
||||
} else {
|
||||
let current: Option<String> =
|
||||
conn.hget(BLACKLIST_METADATA_KEY, &target).await.map_err(redis_error)?;
|
||||
match current.and_then(|value| serde_json::from_str(&value).ok()) {
|
||||
Some(record) => record,
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
if record.expires_at_unix <= now
|
||||
|| chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none()
|
||||
|| chrono::DateTime::from_timestamp(record.expires_at_unix, 0).is_none()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
items.push(BlacklistEntry {
|
||||
target: ip.to_string(),
|
||||
entry_type: "ip".to_string(),
|
||||
reason: record.reason,
|
||||
created_at: format_timestamp(record.created_at_unix),
|
||||
expires_at: Some(format_timestamp(record.expires_at_unix)),
|
||||
});
|
||||
}
|
||||
for target in members {
|
||||
let Ok(ip) = target.parse::<std::net::IpAddr>() else {
|
||||
continue;
|
||||
};
|
||||
let record = match metadata.get(&target) {
|
||||
Some(encoded) => match serde_json::from_str::<BlacklistMetadata>(encoded) {
|
||||
Ok(record) => record,
|
||||
Err(_) => continue,
|
||||
},
|
||||
None => {
|
||||
let legacy = legacy_metadata(now);
|
||||
let encoded = serde_json::to_string(&legacy).map_err(|_| {
|
||||
super::common::api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to encode blacklist metadata")
|
||||
})?;
|
||||
let inserted: i64 = redis::cmd("HSETNX")
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(&target)
|
||||
.arg(encoded)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
if inserted == 1 {
|
||||
legacy
|
||||
} else {
|
||||
let current: Option<String> =
|
||||
conn.hget(BLACKLIST_METADATA_KEY, &target).await.map_err(redis_error)?;
|
||||
match current.and_then(|value| serde_json::from_str(&value).ok()) {
|
||||
Some(record) => record,
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
if record.expires_at_unix <= now
|
||||
|| chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none()
|
||||
|| chrono::DateTime::from_timestamp(record.expires_at_unix, 0).is_none()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
items.push(BlacklistEntry {
|
||||
target: ip.to_string(),
|
||||
entry_type: "ip".to_string(),
|
||||
reason: record.reason,
|
||||
created_at: format_timestamp(record.created_at_unix),
|
||||
expires_at: Some(format_timestamp(record.expires_at_unix)),
|
||||
});
|
||||
}
|
||||
|
||||
let total = items.len();
|
||||
Ok(Json(BlacklistResponse { items, total }))
|
||||
let total = items.len();
|
||||
Ok(Json(BlacklistResponse { items, total }))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
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, parse_ip, redis_error, redis_unavailable,
|
||||
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, parse_ip, redis_error, redis_unavailable,
|
||||
};
|
||||
use super::{AddBlacklistRequest, RemoveBlacklistRequest};
|
||||
use crate::manager::AppState;
|
||||
|
|
@ -8,91 +8,91 @@ use axum::{Json, extract::State, http::StatusCode};
|
|||
use std::sync::Arc;
|
||||
|
||||
pub async fn add_blacklist(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(req): Json<AddBlacklistRequest>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(req): Json<AddBlacklistRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let ip = parse_ip(&req.target)?;
|
||||
if req.entry_type != "ip" {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"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 ip = parse_ip(&req.target)?;
|
||||
if req.entry_type != "ip" {
|
||||
return Err(api_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"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 target = ip.to_string();
|
||||
let created_at_unix = chrono::Utc::now().timestamp();
|
||||
let metadata = super::common::BlacklistMetadata {
|
||||
created_at_unix,
|
||||
expires_at_unix: created_at_unix + duration_secs as i64,
|
||||
reason: req.reason.clone(),
|
||||
};
|
||||
let encoded_metadata = serde_json::to_string(&metadata)
|
||||
.map_err(|_| api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to encode blacklist metadata"))?;
|
||||
let event = event_payload(&target, "ban", duration_secs, Some(metadata.expires_at_unix))?;
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let _: i64 = redis::cmd("EVAL")
|
||||
.arg(ADD_BAN_SCRIPT)
|
||||
.arg(3)
|
||||
.arg(BLACKLIST_KEY)
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(BLACKLIST_CHANNEL)
|
||||
.arg(&target)
|
||||
.arg(encoded_metadata)
|
||||
.arg(event)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
let target = ip.to_string();
|
||||
let created_at_unix = chrono::Utc::now().timestamp();
|
||||
let metadata = super::common::BlacklistMetadata {
|
||||
created_at_unix,
|
||||
expires_at_unix: created_at_unix + duration_secs as i64,
|
||||
reason: req.reason.clone(),
|
||||
};
|
||||
let encoded_metadata = serde_json::to_string(&metadata)
|
||||
.map_err(|_| api_error(StatusCode::INTERNAL_SERVER_ERROR, "failed to encode blacklist metadata"))?;
|
||||
let event = event_payload(&target, "ban", duration_secs, Some(metadata.expires_at_unix))?;
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let _: i64 = redis::cmd("EVAL")
|
||||
.arg(ADD_BAN_SCRIPT)
|
||||
.arg(3)
|
||||
.arg(BLACKLIST_KEY)
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(BLACKLIST_CHANNEL)
|
||||
.arg(&target)
|
||||
.arg(encoded_metadata)
|
||||
.arg(event)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
|
||||
tracing::info!("Added to blacklist: {} ({})", target, req.reason);
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "added",
|
||||
"target": target,
|
||||
"reason": req.reason,
|
||||
"duration_secs": duration_secs
|
||||
})))
|
||||
tracing::info!("Added to blacklist: {} ({})", target, req.reason);
|
||||
Ok(Json(serde_json::json!({
|
||||
"status": "added",
|
||||
"target": target,
|
||||
"reason": req.reason,
|
||||
"duration_secs": duration_secs
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn remove_blacklist(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(req): Json<RemoveBlacklistRequest>,
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(req): Json<RemoveBlacklistRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let ip = parse_ip(&req.target)?;
|
||||
let target = ip.to_string();
|
||||
let event = event_payload(&target, "unban", 0, None)?;
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let _: i64 = redis::cmd("EVAL")
|
||||
.arg(REMOVE_BAN_SCRIPT)
|
||||
.arg(3)
|
||||
.arg(BLACKLIST_KEY)
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(BLACKLIST_CHANNEL)
|
||||
.arg(&target)
|
||||
.arg(event)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
let ip = parse_ip(&req.target)?;
|
||||
let target = ip.to_string();
|
||||
let event = event_payload(&target, "unban", 0, None)?;
|
||||
let mut conn = state
|
||||
.redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.map_err(redis_unavailable)?;
|
||||
let _: i64 = redis::cmd("EVAL")
|
||||
.arg(REMOVE_BAN_SCRIPT)
|
||||
.arg(3)
|
||||
.arg(BLACKLIST_KEY)
|
||||
.arg(BLACKLIST_METADATA_KEY)
|
||||
.arg(BLACKLIST_CHANNEL)
|
||||
.arg(&target)
|
||||
.arg(event)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.map_err(redis_error)?;
|
||||
|
||||
tracing::info!("Removed from blacklist: {target}");
|
||||
Ok(Json(serde_json::json!({"status": "removed", "target": target})))
|
||||
tracing::info!("Removed from blacklist: {target}");
|
||||
Ok(Json(serde_json::json!({"status": "removed", "target": target})))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,13 +6,13 @@ use std::sync::Arc;
|
|||
|
||||
#[derive(Serialize)]
|
||||
pub struct HealthResponse {
|
||||
pub status: String,
|
||||
pub version: String,
|
||||
pub status: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub async fn health_check(State(_state): State<Arc<AppState>>) -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
status: "healthy".to_string(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
Json(HealthResponse {
|
||||
status: "healthy".to_string(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,39 +10,39 @@ use std::sync::Arc;
|
|||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct NodeInfo {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub ip: String,
|
||||
pub status: String,
|
||||
pub last_heartbeat: String,
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub ip: String,
|
||||
pub status: String,
|
||||
pub last_heartbeat: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct NodesResponse {
|
||||
pub nodes: Vec<NodeInfo>,
|
||||
pub nodes: Vec<NodeInfo>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub async fn list_nodes(State(state): State<Arc<AppState>>) -> Json<NodesResponse> {
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Json(NodesResponse { nodes: vec![] }),
|
||||
};
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Json(NodesResponse { nodes: vec![] }),
|
||||
};
|
||||
|
||||
let keys: Vec<String> = match redis::cmd("KEYS").arg("rampart:nodes:*").query_async(&mut conn).await {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Json(NodesResponse { nodes: vec![] }),
|
||||
};
|
||||
let keys: Vec<String> = match redis::cmd("KEYS").arg("rampart:nodes:*").query_async(&mut conn).await {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Json(NodesResponse { nodes: vec![] }),
|
||||
};
|
||||
|
||||
let mut nodes = Vec::with_capacity(keys.len());
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await.unwrap_or(None);
|
||||
if let Some(json) = raw
|
||||
&& let Ok(node) = serde_json::from_str::<NodeInfo>(&json)
|
||||
{
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
let mut nodes = Vec::with_capacity(keys.len());
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await.unwrap_or(None);
|
||||
if let Some(json) = raw
|
||||
&& let Ok(node) = serde_json::from_str::<NodeInfo>(&json)
|
||||
{
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
Json(NodesResponse { nodes })
|
||||
Json(NodesResponse { nodes })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,40 +10,40 @@ use std::sync::Arc;
|
|||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ServerEntry {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub server_type: String,
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
pub status: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub server_type: String,
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ServersResponse {
|
||||
pub servers: Vec<ServerEntry>,
|
||||
pub servers: Vec<ServerEntry>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub async fn list_servers(State(state): State<Arc<AppState>>) -> Json<ServersResponse> {
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Json(ServersResponse { servers: vec![] }),
|
||||
};
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Json(ServersResponse { servers: vec![] }),
|
||||
};
|
||||
|
||||
let keys: Vec<String> = match redis::cmd("KEYS").arg("rampart:servers:*").query_async(&mut conn).await {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Json(ServersResponse { servers: vec![] }),
|
||||
};
|
||||
let keys: Vec<String> = match redis::cmd("KEYS").arg("rampart:servers:*").query_async(&mut conn).await {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Json(ServersResponse { servers: vec![] }),
|
||||
};
|
||||
|
||||
let mut servers = Vec::with_capacity(keys.len());
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await.unwrap_or(None);
|
||||
if let Some(json) = raw
|
||||
&& let Ok(server) = serde_json::from_str::<ServerEntry>(&json)
|
||||
{
|
||||
servers.push(server);
|
||||
}
|
||||
}
|
||||
let mut servers = Vec::with_capacity(keys.len());
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await.unwrap_or(None);
|
||||
if let Some(json) = raw
|
||||
&& let Ok(server) = serde_json::from_str::<ServerEntry>(&json)
|
||||
{
|
||||
servers.push(server);
|
||||
}
|
||||
}
|
||||
|
||||
Json(ServersResponse { servers })
|
||||
Json(ServersResponse { servers })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,94 +10,94 @@ use std::sync::Arc;
|
|||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Claims {
|
||||
pub sub: String,
|
||||
pub aud: String,
|
||||
pub role: String,
|
||||
pub exp: usize,
|
||||
pub iat: usize,
|
||||
pub sub: String,
|
||||
pub aud: String,
|
||||
pub role: String,
|
||||
pub exp: usize,
|
||||
pub iat: usize,
|
||||
}
|
||||
|
||||
pub fn create_token(secret: &str, expiration: u64, audience: &str) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
let now = chrono::Utc::now().timestamp() as usize;
|
||||
let claims = Claims {
|
||||
sub: "rampart-admin".to_string(),
|
||||
aud: audience.to_string(),
|
||||
role: "admin".to_string(),
|
||||
exp: now + expiration as usize,
|
||||
iat: now,
|
||||
};
|
||||
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref()))
|
||||
let now = chrono::Utc::now().timestamp() as usize;
|
||||
let claims = Claims {
|
||||
sub: "rampart-admin".to_string(),
|
||||
aud: audience.to_string(),
|
||||
role: "admin".to_string(),
|
||||
exp: now + expiration as usize,
|
||||
iat: now,
|
||||
};
|
||||
encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref()))
|
||||
}
|
||||
|
||||
pub fn verify_token(token: &str, secret: &str, audience: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
|
||||
let mut validation = Validation::default();
|
||||
validation.set_audience(&[audience]);
|
||||
let token_data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &validation)?;
|
||||
Ok(token_data.claims)
|
||||
let mut validation = Validation::default();
|
||||
validation.set_audience(&[audience]);
|
||||
let token_data = decode::<Claims>(token, &DecodingKey::from_secret(secret.as_ref()), &validation)?;
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
|
||||
pub async fn auth_middleware(
|
||||
State(state): State<Arc<crate::manager::AppState>>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
State(state): State<Arc<crate::manager::AppState>>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, (StatusCode, Json<serde_json::Value>)> {
|
||||
let auth_header = request
|
||||
.headers()
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.strip_prefix("Bearer "));
|
||||
let auth_header = request
|
||||
.headers()
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.strip_prefix("Bearer "));
|
||||
|
||||
let token = match auth_header {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
},
|
||||
};
|
||||
let token = match auth_header {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
},
|
||||
};
|
||||
|
||||
if verify_token(token, &state.jwt_secret, &state.jwt_audience).is_err() {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
}
|
||||
if verify_token(token, &state.jwt_secret, &state.jwt_audience).is_err() {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::*;
|
||||
|
||||
fn valid_secret() -> String {
|
||||
"this-is-a-test-secret-32-bytes-long!".to_string()
|
||||
}
|
||||
fn valid_secret() -> String {
|
||||
"this-is-a-test-secret-32-bytes-long!".to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_verify_roundtrip_passes() {
|
||||
let secret = valid_secret();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
let claims = verify_token(&token, &secret, "rampart").expect("verification should succeed");
|
||||
assert_eq!(claims.sub, "rampart-admin");
|
||||
assert_eq!(claims.aud, "rampart");
|
||||
assert_eq!(claims.role, "admin");
|
||||
assert!(claims.exp > claims.iat);
|
||||
}
|
||||
#[test]
|
||||
fn create_verify_roundtrip_passes() {
|
||||
let secret = valid_secret();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
let claims = verify_token(&token, &secret, "rampart").expect("verification should succeed");
|
||||
assert_eq!(claims.sub, "rampart-admin");
|
||||
assert_eq!(claims.aud, "rampart");
|
||||
assert_eq!(claims.role, "admin");
|
||||
assert!(claims.exp > claims.iat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_rejects_wrong_audience() {
|
||||
let secret = valid_secret();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
assert!(verify_token(&token, &secret, "other").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn verify_rejects_wrong_audience() {
|
||||
let secret = valid_secret();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
assert!(verify_token(&token, &secret, "other").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_rejects_wrong_secret() {
|
||||
let secret = valid_secret();
|
||||
let other_secret = "another-test-secret-also-32-bytes-long!".to_string();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
assert!(verify_token(&token, &other_secret, "rampart").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn verify_rejects_wrong_secret() {
|
||||
let secret = valid_secret();
|
||||
let other_secret = "another-test-secret-also-32-bytes-long!".to_string();
|
||||
let token = create_token(&secret, 3600, "rampart").expect("token creation should succeed");
|
||||
assert!(verify_token(&token, &other_secret, "rampart").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,15 +10,15 @@ use std::time::Instant;
|
|||
|
||||
/// Общее состояние management-API.
|
||||
pub struct AppState {
|
||||
/// Redis-клиент управления состоянием; присутствует только при собранной
|
||||
/// фиче `store-redis` (manager требует её на старте — см. bin/rampart-manager).
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub redis_client: redis::Client,
|
||||
pub jwt_secret: String,
|
||||
pub jwt_audience: String,
|
||||
pub jwt_expiration: u64,
|
||||
pub api_password: String,
|
||||
pub login_limiter: DashMap<IpAddr, (Instant, u32)>,
|
||||
/// Redis-клиент управления состоянием; присутствует только при собранной
|
||||
/// фиче `store-redis` (manager требует её на старте — см. bin/rampart-manager).
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub redis_client: redis::Client,
|
||||
pub jwt_secret: String,
|
||||
pub jwt_audience: String,
|
||||
pub jwt_expiration: u64,
|
||||
pub api_password: String,
|
||||
pub login_limiter: DashMap<IpAddr, (Instant, u32)>,
|
||||
}
|
||||
|
||||
pub type SharedState = Arc<AppState>;
|
||||
|
|
|
|||
|
|
@ -23,45 +23,45 @@ const NODE_TTL_SECS: i64 = 60;
|
|||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub async fn start_heartbeat_check(state: Arc<AppState>) {
|
||||
let mut ticker = interval(Duration::from_secs(30));
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
if let Err(e) = check_nodes(&state).await {
|
||||
tracing::warn!("heartbeat check failed: {e}");
|
||||
}
|
||||
}
|
||||
let mut ticker = interval(Duration::from_secs(30));
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
if let Err(e) = check_nodes(&state).await {
|
||||
tracing::warn!("heartbeat check failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
async fn check_nodes(state: &AppState) -> anyhow::Result<()> {
|
||||
let mut conn = state.redis_client.get_multiplexed_async_connection().await?;
|
||||
let keys = collect_node_keys(&mut conn).await?;
|
||||
let mut conn = state.redis_client.get_multiplexed_async_connection().await?;
|
||||
let keys = collect_node_keys(&mut conn).await?;
|
||||
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await?;
|
||||
let Some(updated) = raw.and_then(|json| offline_update(&json, now)) else {
|
||||
continue;
|
||||
};
|
||||
tracing::warn!("Node {key} is offline (heartbeat expired)");
|
||||
let _: () = conn.set(key.as_str(), updated).await.unwrap_or_default();
|
||||
}
|
||||
Ok(())
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await?;
|
||||
let Some(updated) = raw.and_then(|json| offline_update(&json, now)) else {
|
||||
continue;
|
||||
};
|
||||
tracing::warn!("Node {key} is offline (heartbeat expired)");
|
||||
let _: () = conn.set(key.as_str(), updated).await.unwrap_or_default();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Incrementally iterates the keyspace via SCAN (cursor-based, non-blocking).
|
||||
#[cfg(feature = "store-redis")]
|
||||
async fn collect_node_keys(conn: &mut redis::aio::MultiplexedConnection) -> anyhow::Result<Vec<String>> {
|
||||
let opts = ScanOptions::default()
|
||||
.with_pattern(NODES_KEY_PATTERN)
|
||||
.with_count(SCAN_BATCH);
|
||||
let mut iter = conn.scan_options::<String>(opts).await?;
|
||||
let mut keys = Vec::new();
|
||||
while let Some(key) = iter.next().await {
|
||||
keys.push(key?);
|
||||
}
|
||||
Ok(keys)
|
||||
let opts = ScanOptions::default()
|
||||
.with_pattern(NODES_KEY_PATTERN)
|
||||
.with_count(SCAN_BATCH);
|
||||
let mut iter = conn.scan_options::<String>(opts).await?;
|
||||
let mut keys = Vec::new();
|
||||
while let Some(key) = iter.next().await {
|
||||
keys.push(key?);
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// Pure decision: returns the updated node JSON with `status: "offline"` when
|
||||
|
|
@ -70,67 +70,67 @@ async fn collect_node_keys(conn: &mut redis::aio::MultiplexedConnection) -> anyh
|
|||
/// `None` when the node is fresh, unparsable, or not a JSON object.
|
||||
#[cfg(any(feature = "store-redis", test))]
|
||||
fn offline_update(raw: &str, now: i64) -> Option<String> {
|
||||
let mut node = serde_json::from_str::<serde_json::Value>(raw).ok()?;
|
||||
let hb = node["last_heartbeat"]
|
||||
.as_str()
|
||||
.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
|
||||
.map(|t| t.timestamp())
|
||||
.unwrap_or(0);
|
||||
if now - hb <= NODE_TTL_SECS {
|
||||
return None;
|
||||
}
|
||||
node.as_object_mut()?
|
||||
.insert("status".to_string(), serde_json::Value::String("offline".to_string()));
|
||||
serde_json::to_string(&node).ok()
|
||||
let mut node = serde_json::from_str::<serde_json::Value>(raw).ok()?;
|
||||
let hb = node["last_heartbeat"]
|
||||
.as_str()
|
||||
.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
|
||||
.map(|t| t.timestamp())
|
||||
.unwrap_or(0);
|
||||
if now - hb <= NODE_TTL_SECS {
|
||||
return None;
|
||||
}
|
||||
node.as_object_mut()?
|
||||
.insert("status".to_string(), serde_json::Value::String("offline".to_string()));
|
||||
serde_json::to_string(&node).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::*;
|
||||
|
||||
fn rfc3339(ts: i64) -> String {
|
||||
chrono::DateTime::from_timestamp(ts, 0)
|
||||
.expect("in-range timestamp")
|
||||
.to_rfc3339()
|
||||
}
|
||||
fn rfc3339(ts: i64) -> String {
|
||||
chrono::DateTime::from_timestamp(ts, 0)
|
||||
.expect("in-range timestamp")
|
||||
.to_rfc3339()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_heartbeat_is_marked_offline() {
|
||||
let now = 2_000_000_i64;
|
||||
let raw = format!(
|
||||
r#"{{"name":"edge1","last_heartbeat":"{}","status":"online"}}"#,
|
||||
rfc3339(now - 120)
|
||||
);
|
||||
let updated = offline_update(&raw, now).expect("expired node should be marked offline");
|
||||
assert!(updated.contains("offline"));
|
||||
assert!(updated.contains("edge1"));
|
||||
}
|
||||
#[test]
|
||||
fn expired_heartbeat_is_marked_offline() {
|
||||
let now = 2_000_000_i64;
|
||||
let raw = format!(
|
||||
r#"{{"name":"edge1","last_heartbeat":"{}","status":"online"}}"#,
|
||||
rfc3339(now - 120)
|
||||
);
|
||||
let updated = offline_update(&raw, now).expect("expired node should be marked offline");
|
||||
assert!(updated.contains("offline"));
|
||||
assert!(updated.contains("edge1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_heartbeat_is_left_untouched() {
|
||||
let now = 2_000_000_i64;
|
||||
let raw = format!(r#"{{"last_heartbeat":"{}","status":"online"}}"#, rfc3339(now - 5));
|
||||
assert!(offline_update(&raw, now).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn fresh_heartbeat_is_left_untouched() {
|
||||
let now = 2_000_000_i64;
|
||||
let raw = format!(r#"{{"last_heartbeat":"{}","status":"online"}}"#, rfc3339(now - 5));
|
||||
assert!(offline_update(&raw, now).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_broken_timestamp_counts_as_expired() {
|
||||
let now = 2_000_000_i64;
|
||||
let updated = offline_update(r#"{"status":"online"}"#, now).expect("missing heartbeat counts as expired");
|
||||
assert!(updated.contains("offline"));
|
||||
let updated = offline_update(r#"{"last_heartbeat":"garbage","status":"online"}"#, now)
|
||||
.expect("unparseable heartbeat counts as expired");
|
||||
assert!(updated.contains("offline"));
|
||||
}
|
||||
#[test]
|
||||
fn missing_or_broken_timestamp_counts_as_expired() {
|
||||
let now = 2_000_000_i64;
|
||||
let updated = offline_update(r#"{"status":"online"}"#, now).expect("missing heartbeat counts as expired");
|
||||
assert!(updated.contains("offline"));
|
||||
let updated = offline_update(r#"{"last_heartbeat":"garbage","status":"online"}"#, now)
|
||||
.expect("unparseable heartbeat counts as expired");
|
||||
assert!(updated.contains("offline"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_json_is_ignored() {
|
||||
assert!(offline_update("not json", 2_000_000).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn invalid_json_is_ignored() {
|
||||
assert!(offline_update("not json", 2_000_000).is_none());
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
#[test]
|
||||
fn node_key_pattern_targets_rampart_nodes() {
|
||||
assert_eq!(NODES_KEY_PATTERN, "rampart:nodes:*");
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
#[test]
|
||||
fn node_key_pattern_targets_rampart_nodes() {
|
||||
assert_eq!(NODES_KEY_PATTERN, "rampart:nodes:*");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue