Initial commit: Rampart v0.2.0
Multi-layer DDoS protection for Minecraft servers. - rampart-core: Edge node with XDP/eBPF + Rust L7 filtering - rampart-manager: REST API with JWT auth, Redis sync - rampart-cli: CLI tool for operators - velocity-plugin: Domain check, HMAC verify, server registry, load balancer - paper-plugin: Auto-registration, heartbeat, HMAC verify - dashboard: React + Vite web UI for management
This commit is contained in:
commit
cf9608ce5d
159 changed files with 15341 additions and 0 deletions
21
crates/rampart-manager/src/api/auth.rs
Normal file
21
crates/rampart-manager/src/api/auth.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
use crate::AppState;
|
||||
use axum::{Json, extract::State};
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginRequest {
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
pub async fn login(State(state): State<Arc<AppState>>, Json(req): Json<LoginRequest>) -> Json<serde_json::Value> {
|
||||
let api_password = std::env::var("API_PASSWORD").unwrap_or_else(|_| "changeme".to_string());
|
||||
if req.password != api_password {
|
||||
return Json(serde_json::json!({"error": "invalid password"}));
|
||||
}
|
||||
|
||||
match crate::auth::create_token(&state.jwt_secret, state.jwt_expiration) {
|
||||
Ok(token) => Json(serde_json::json!({"token": token})),
|
||||
Err(_) => Json(serde_json::json!({"error": "token creation failed"})),
|
||||
}
|
||||
}
|
||||
94
crates/rampart-manager/src/api/blacklist.rs
Normal file
94
crates/rampart-manager/src/api/blacklist.rs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
use crate::AppState;
|
||||
use axum::{Json, extract::State};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[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>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct BlacklistResponse {
|
||||
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 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 })
|
||||
}
|
||||
|
||||
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"})),
|
||||
};
|
||||
|
||||
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
|
||||
}))
|
||||
}
|
||||
18
crates/rampart-manager/src/api/health.rs
Normal file
18
crates/rampart-manager/src/api/health.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
use crate::AppState;
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct HealthResponse {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
5
crates/rampart-manager/src/api/mod.rs
Normal file
5
crates/rampart-manager/src/api/mod.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pub mod auth;
|
||||
pub mod blacklist;
|
||||
pub mod health;
|
||||
pub mod nodes;
|
||||
pub mod servers;
|
||||
43
crates/rampart-manager/src/api/nodes.rs
Normal file
43
crates/rampart-manager/src/api/nodes.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
use crate::AppState;
|
||||
use axum::{Json, extract::State};
|
||||
use redis::AsyncCommands;
|
||||
use serde::{Deserialize, Serialize};
|
||||
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,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct NodesResponse {
|
||||
pub nodes: Vec<NodeInfo>,
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
|
||||
Json(NodesResponse { nodes })
|
||||
}
|
||||
47
crates/rampart-manager/src/api/servers.rs
Normal file
47
crates/rampart-manager/src/api/servers.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
use crate::AppState;
|
||||
use axum::{Json, extract::State};
|
||||
use redis::AsyncCommands;
|
||||
use serde::{Deserialize, Serialize};
|
||||
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 online: u32,
|
||||
pub max_players: u32,
|
||||
pub tps: f64,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ServersResponse {
|
||||
pub servers: Vec<ServerEntry>,
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
|
||||
Json(ServersResponse { servers })
|
||||
}
|
||||
74
crates/rampart-manager/src/auth.rs
Normal file
74
crates/rampart-manager/src/auth.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
use axum::Json;
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::Response;
|
||||
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Claims {
|
||||
pub sub: String,
|
||||
pub exp: usize,
|
||||
pub iat: usize,
|
||||
}
|
||||
|
||||
pub fn create_token(secret: &str, expiration: u64) -> Result<String, jsonwebtoken::errors::Error> {
|
||||
let now = chrono::Utc::now().timestamp() as usize;
|
||||
let claims = Claims {
|
||||
sub: "rampart-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) -> Result<Claims, jsonwebtoken::errors::Error> {
|
||||
let token_data = decode::<Claims>(
|
||||
token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)?;
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
|
||||
pub async fn auth_middleware(
|
||||
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 token = match auth_header {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
},
|
||||
};
|
||||
|
||||
let state = match request.extensions().get::<Arc<crate::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).is_err() {
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
1
crates/rampart-manager/src/lib.rs
Normal file
1
crates/rampart-manager/src/lib.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
|
||||
66
crates/rampart-manager/src/main.rs
Normal file
66
crates/rampart-manager/src/main.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
use axum::{
|
||||
Router, middleware,
|
||||
routing::{get, post},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
mod api;
|
||||
mod auth;
|
||||
mod sync;
|
||||
|
||||
pub struct AppState {
|
||||
pub redis_client: redis::Client,
|
||||
pub jwt_secret: String,
|
||||
pub jwt_expiration: u64,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart_manager=info".parse()?))
|
||||
.init();
|
||||
|
||||
let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379/0".to_string());
|
||||
let redis_client = redis::Client::open(redis_url)?;
|
||||
|
||||
let jwt_secret = std::env::var("JWT_SECRET").map_err(|_| anyhow::anyhow!("JWT_SECRET must be set"))?;
|
||||
let jwt_expiration = std::env::var("JWT_EXPIRATION_SECS")
|
||||
.unwrap_or_else(|_| "86400".to_string())
|
||||
.parse::<u64>()
|
||||
.map_err(|_| anyhow::anyhow!("JWT_EXPIRATION_SECS must be a valid u64"))?;
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
redis_client,
|
||||
jwt_secret,
|
||||
jwt_expiration,
|
||||
});
|
||||
|
||||
tokio::spawn(sync::heartbeat::start_heartbeat_check(state.clone()));
|
||||
|
||||
let public = Router::new()
|
||||
.route("/api/v1/health", get(api::health::health_check))
|
||||
.route("/api/v1/auth/login", post(api::auth::login));
|
||||
|
||||
let protected = Router::new()
|
||||
.route("/api/v1/servers", get(api::servers::list_servers))
|
||||
.route(
|
||||
"/api/v1/blacklist",
|
||||
get(api::blacklist::list_blacklist).post(api::blacklist::add_blacklist),
|
||||
)
|
||||
.route("/api/v1/nodes", get(api::nodes::list_nodes))
|
||||
.route_layer(middleware::from_fn(auth::auth_middleware));
|
||||
|
||||
let app = Router::new()
|
||||
.merge(public)
|
||||
.merge(protected)
|
||||
.layer(CorsLayer::permissive())
|
||||
.with_state(state);
|
||||
|
||||
let addr = "0.0.0.0:8080";
|
||||
tracing::info!("Manager API listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
44
crates/rampart-manager/src/sync/heartbeat.rs
Normal file
44
crates/rampart-manager/src/sync/heartbeat.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use crate::AppState;
|
||||
use redis::AsyncCommands;
|
||||
use std::sync::Arc;
|
||||
use tokio::time::{Duration, interval};
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_nodes(state: &AppState) -> anyhow::Result<()> {
|
||||
let mut conn = state.redis_client.get_multiplexed_async_connection().await?;
|
||||
let keys: Vec<String> = redis::cmd("KEYS").arg("rampart:nodes:*").query_async(&mut conn).await?;
|
||||
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
|
||||
for key in &keys {
|
||||
let raw: Option<String> = conn.get(key).await?;
|
||||
if let Some(json) = raw
|
||||
&& let Ok(mut node) = serde_json::from_str::<serde_json::Value>(&json)
|
||||
{
|
||||
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 > 60 {
|
||||
if let Some(obj) = node.as_object_mut() {
|
||||
obj.insert("status".to_string(), serde_json::Value::String("offline".to_string()));
|
||||
if let Ok(updated) = serde_json::to_string(&node) {
|
||||
let _: () = conn.set(key.as_str(), updated).await.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
tracing::warn!("Node {key} is offline (heartbeat expired)");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
1
crates/rampart-manager/src/sync/mod.rs
Normal file
1
crates/rampart-manager/src/sync/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod heartbeat;
|
||||
Loading…
Add table
Add a link
Reference in a new issue