feat!: universal redesign — drop Minecraft stack, single-crate architecture
- remove Java plugins (velocity/paper), dashboard, all MC-specific code
(handshake, death_code, varint, hostname-HMAC); available in history pre-v0.2
- merge crates/* into one package with src/bin/{rampart,rampart-manager,rampart-cli}
- ProtocolHandler trait + registry (no implementations yet), universal PoW kept
- XDP: universal L3/L4 filter (xdp/core/) + pluggable hook API (xdp/hooks/),
fix IPv6 saddr bug; clang build verified
- docs: bilingual knowledge base (docs/kb/: attacks x4, defense-levels,
practice x3), rewrite README/architecture for universal concept
- TODO.md v4.0: <=300-line module limit, competitor benchmark section (ref/)
- deploy/CI/docs cleanup: no MC references, new binary names
cargo build/clippy(-D warnings)/test green (55 tests)
This commit is contained in:
parent
7d15dfd45e
commit
08e26df73f
179 changed files with 5044 additions and 11519 deletions
104
src/manager/api/auth.rs
Normal file
104
src/manager/api/auth.rs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
use crate::manager::AppState;
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{ConnectInfo, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use dashmap::DashMap;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
const LOGIN_WINDOW: Duration = Duration::from_secs(60);
|
||||
const LOGIN_MAX_ATTEMPTS: u32 = 5;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginRequest {
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
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 !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"})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[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_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));
|
||||
}
|
||||
}
|
||||
94
src/manager/api/blacklist.rs
Normal file
94
src/manager/api/blacklist.rs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
use crate::manager::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
src/manager/api/health.rs
Normal file
18
src/manager/api/health.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
use crate::manager::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
src/manager/api/mod.rs
Normal file
5
src/manager/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
src/manager/api/nodes.rs
Normal file
43
src/manager/api/nodes.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
use crate::manager::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 })
|
||||
}
|
||||
44
src/manager/api/servers.rs
Normal file
44
src/manager/api/servers.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use crate::manager::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,
|
||||
}
|
||||
|
||||
#[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 })
|
||||
}
|
||||
111
src/manager/auth.rs
Normal file
111
src/manager/auth.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
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 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()))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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::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,
|
||||
Json(serde_json::json!({"error": "unauthorized"})),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
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 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());
|
||||
}
|
||||
}
|
||||
21
src/manager/mod.rs
Normal file
21
src/manager/mod.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
//! Management-плоскость Rampart: REST API, аутентификация, синхронизация узлов.
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod sync;
|
||||
|
||||
use dashmap::DashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Общее состояние management-API.
|
||||
pub struct AppState {
|
||||
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>;
|
||||
44
src/manager/sync/heartbeat.rs
Normal file
44
src/manager/sync/heartbeat.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use crate::manager::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
src/manager/sync/mod.rs
Normal file
1
src/manager/sync/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod heartbeat;
|
||||
Loading…
Add table
Add a link
Reference in a new issue