guard/src/bin/rampart-manager.rs
loki5512344 bd40a44980
Some checks are pending
CI / Rust — check & clippy (push) Waiting to run
CI / Rust — test (push) Waiting to run
CI / Repo — module size & default secrets (push) Waiting to run
CI / Rust — cargo-deny (push) Waiting to run
CI / Docker — build edge image (push) Blocked by required conditions
feat(xdp): auto-ban from ringbuf events; fix feature gating, exit path, pow flake
- xdp: real 24-byte xdp_event parsing (fixes LE byte-swap of src IP),
  opt-in [xdp] auto_ban (RATE_LIMIT always, CONN_DROP at fails>=threshold;
  EVENT_BAN/POLICY_DROP excluded by design), rampart_xdp_autobans_total;
  wired in app before load(); 10 tests in tests/xdp_events.rs
- build: --no-default-features compiles — redis paths cfg-gated behind
  store-redis, manager fail-fasts without it; CI gates the config now
- app: RunExit enum replaces process::exit in lib; single exit site in main
- tests: seed PoW roundtrip token (was ~1/16 flaky; 50 pre-fix fails -> 0)
- docs: TODO statuses refreshed (round 2)
2026-09-16 00:49:41 +02:00

95 lines
3.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use axum::{
Router,
http::HeaderValue,
middleware,
routing::{get, post},
};
use dashmap::DashMap;
#[cfg(feature = "store-redis")]
use rampart::manager::sync;
use rampart::manager::{AppState, api, auth};
use std::sync::Arc;
use tower_http::cors::CorsLayer;
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
.init();
// Manager живёт исключительно на redis-хранилище: без фичи стартовать
// нечего — fail-fast вместо полумёртвого API (features additive, TODO SOLID D).
if !cfg!(feature = "store-redis") {
anyhow::bail!("rampart-manager requires a redis state store: built without store-redis feature");
}
#[cfg(feature = "store-redis")]
let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379/0".to_string());
#[cfg(feature = "store-redis")]
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"))?;
if jwt_secret.len() < 32 {
return Err(anyhow::anyhow!("JWT_SECRET must be at least 32 bytes"));
}
let jwt_audience = std::env::var("JWT_AUDIENCE").unwrap_or_else(|_| "rampart".to_string());
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 api_password = std::env::var("API_PASSWORD").map_err(|_| anyhow::anyhow!("API_PASSWORD must be set"))?;
if api_password == "changeme" {
return Err(anyhow::anyhow!("API_PASSWORD must not be the default 'changeme'"));
}
let state = Arc::new(AppState {
#[cfg(feature = "store-redis")]
redis_client,
jwt_secret,
jwt_audience,
jwt_expiration,
api_password,
login_limiter: DashMap::new(),
});
#[cfg(feature = "store-redis")]
tokio::spawn(sync::heartbeat::start_heartbeat_check(state.clone()));
let public = Router::new()
.route("/api/v1/health", get(api::inventory::health::health_check))
.route("/api/v1/auth/login", post(api::auth::login));
// Redis-зависимые маршруты существуют только вместе с фичей; сам manager
// без неё bail'ит выше, поэтому 501-заглушки были бы недостижимым кодом.
let protected = Router::new();
#[cfg(feature = "store-redis")]
let protected = protected
.route("/api/v1/servers", get(api::inventory::servers::list_servers))
.route(
"/api/v1/blacklist",
get(api::blacklist::list_blacklist).post(api::blacklist::add_blacklist),
)
.route("/api/v1/nodes", get(api::inventory::nodes::list_nodes));
let protected = protected.route_layer(middleware::from_fn(auth::auth_middleware));
let cors = match std::env::var("CORS_ORIGIN") {
Ok(origin) if origin.is_empty() || origin == "*" => CorsLayer::new().allow_origin(tower_http::cors::Any),
Ok(origin) => CorsLayer::new().allow_origin(HeaderValue::from_str(&origin)?),
Err(_) => CorsLayer::new().allow_origin(HeaderValue::from_static("http://localhost:5173")),
};
let app = Router::new()
.merge(public)
.merge(protected)
.layer(cors)
.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?;
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
axum::serve(listener, app).await?;
Ok(())
}