feat: add Minecraft proxy and refresh dependencies
This commit is contained in:
parent
a4d0880a0a
commit
cfaad47948
47 changed files with 2671 additions and 1005 deletions
|
|
@ -1,10 +1,4 @@
|
|||
#[cfg(feature = "store-redis")]
|
||||
use crate::manager::AppState;
|
||||
#[cfg(feature = "store-redis")]
|
||||
use axum::{Json, extract::State};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(feature = "store-redis")]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct BlacklistEntry {
|
||||
|
|
@ -32,68 +26,19 @@ pub struct AddBlacklistRequest {
|
|||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub async fn list_blacklist(State(state): State<Arc<AppState>>) -> Json<BlacklistResponse> {
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
return Json(BlacklistResponse {
|
||||
items: vec![],
|
||||
total: 0,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
let members: Vec<String> = match redis::cmd("SMEMBERS")
|
||||
.arg("rampart:blacklist")
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(m) => m,
|
||||
Err(_) => {
|
||||
return Json(BlacklistResponse {
|
||||
items: vec![],
|
||||
total: 0,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
let items: Vec<BlacklistEntry> = members
|
||||
.into_iter()
|
||||
.map(|target| BlacklistEntry {
|
||||
target,
|
||||
entry_type: "ip".to_string(),
|
||||
reason: "manual".to_string(),
|
||||
created_at: chrono::Utc::now().to_rfc3339(),
|
||||
expires_at: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let total = items.len();
|
||||
Json(BlacklistResponse { items, total })
|
||||
#[derive(Deserialize)]
|
||||
pub struct RemoveBlacklistRequest {
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub async fn add_blacklist(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(req): Json<AddBlacklistRequest>,
|
||||
) -> Json<serde_json::Value> {
|
||||
let mut conn = match state.redis_client.get_multiplexed_async_connection().await {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Json(serde_json::json!({"error": "redis unavailable"})),
|
||||
};
|
||||
mod common;
|
||||
#[cfg(feature = "store-redis")]
|
||||
mod list;
|
||||
#[cfg(feature = "store-redis")]
|
||||
mod mutate;
|
||||
|
||||
let _: () = redis::cmd("SADD")
|
||||
.arg("rampart:blacklist")
|
||||
.arg(&req.target)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
tracing::info!("Added to blacklist: {} ({})", req.target, req.reason);
|
||||
|
||||
Json(serde_json::json!({
|
||||
"status": "added",
|
||||
"target": req.target,
|
||||
"reason": req.reason
|
||||
}))
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub use list::list_blacklist;
|
||||
#[cfg(feature = "store-redis")]
|
||||
pub use mutate::{add_blacklist, remove_blacklist};
|
||||
|
|
|
|||
75
src/manager/api/blacklist/common.rs
Normal file
75
src/manager/api/blacklist/common.rs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
use axum::{Json, http::StatusCode};
|
||||
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>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub(super) struct BlacklistMetadata {
|
||||
pub created_at_unix: i64,
|
||||
pub expires_at_unix: i64,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
pub(super) const BLACKLIST_KEY: &str = "rampart:blacklist";
|
||||
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;
|
||||
pub(super) const ADD_BAN_SCRIPT: &str = "redis.call('HSET', KEYS[2], ARGV[1], ARGV[2]); redis.call('SADD', KEYS[1], ARGV[1]); redis.call('PUBLISH', KEYS[3], ARGV[3]); return 1";
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
pub(super) fn event_payload(
|
||||
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"))
|
||||
}
|
||||
|
||||
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"))
|
||||
}
|
||||
|
||||
pub(super) fn api_error(status: StatusCode, message: &str) -> (StatusCode, Json<serde_json::Value>) {
|
||||
(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")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
79
src/manager/api/blacklist/list.rs
Normal file
79
src/manager/api/blacklist/list.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
use super::common::{
|
||||
BLACKLIST_KEY, BLACKLIST_METADATA_KEY, BlacklistMetadata, format_timestamp, legacy_metadata, redis_error,
|
||||
redis_unavailable,
|
||||
};
|
||||
use super::{BlacklistEntry, BlacklistResponse};
|
||||
use crate::manager::AppState;
|
||||
use axum::{Json, extract::State, http::StatusCode};
|
||||
use redis::AsyncCommands;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub async fn list_blacklist(
|
||||
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());
|
||||
|
||||
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 }))
|
||||
}
|
||||
98
src/manager/api/blacklist/mutate.rs
Normal file
98
src/manager/api/blacklist/mutate.rs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
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,
|
||||
};
|
||||
use super::{AddBlacklistRequest, RemoveBlacklistRequest};
|
||||
use crate::manager::AppState;
|
||||
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>,
|
||||
) -> 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 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
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn remove_blacklist(
|
||||
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)?;
|
||||
|
||||
tracing::info!("Removed from blacklist: {target}");
|
||||
Ok(Json(serde_json::json!({"status": "removed", "target": target})))
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
use axum::Json;
|
||||
use axum::body::Body;
|
||||
use axum::extract::State;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
|
|
@ -36,6 +37,7 @@ pub fn verify_token(token: &str, secret: &str, audience: &str) -> Result<Claims,
|
|||
}
|
||||
|
||||
pub async fn auth_middleware(
|
||||
State(state): State<Arc<crate::manager::AppState>>,
|
||||
request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, (StatusCode, Json<serde_json::Value>)> {
|
||||
|
|
@ -55,16 +57,6 @@ pub async fn auth_middleware(
|
|||
},
|
||||
};
|
||||
|
||||
let state = match request.extensions().get::<Arc<crate::manager::AppState>>() {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": "internal error"})),
|
||||
));
|
||||
},
|
||||
};
|
||||
|
||||
if verify_token(token, &state.jwt_secret, &state.jwt_audience).is_err() {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ async fn collect_node_keys(conn: &mut redis::aio::MultiplexedConnection) -> anyh
|
|||
let mut iter = conn.scan_options::<String>(opts).await?;
|
||||
let mut keys = Vec::new();
|
||||
while let Some(key) = iter.next().await {
|
||||
keys.push(key);
|
||||
keys.push(key?);
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue