Implements all remaining backend infrastructure for Corrosion platform.
Backend Services (5 new):
- license.rs: License validation, activation, check-in with NATS token generation
- map_manager.rs: Map upload/rotation with SHA-256 checksums, circular advancement
- health_checker.rs: Post-wipe verification with retry loop and backoff
- backup_manager.rs: Tar.gz backups with retention policy (last 10), recursive upload
- scheduler.rs: Tokio-cron integration for scheduled wipes with NATS events
WipeEngine Orchestration (wipe_engine.rs):
- execute_wipe(): Master orchestrator managing full lifecycle
- execute_pre_wipe(): Countdown warnings, backups, player kicks
- execute_wipe_actions(): Map/plugin deletion, seed rotation, Steam updates
- execute_post_wipe_verification(): Health checks with restart attempts
- execute_rollback(): Failure recovery with backup restore
- JSONB execution logs, NATS status events, service composition pattern
WebSocket/NATS Bridge (ws.rs):
- JWT authentication via query parameter
- License-scoped NATS subscriptions (corrosion.{license_id}.*)
- Bi-directional: NATS→WebSocket event forwarding, WebSocket→NATS publishing
- Axum 0.8 with ws feature, auto Ping/Pong handling
Panel Adapter Fixes:
- AMP/Pterodactyl/Companion adapters fully wired
- RCON command execution, file operations, Steam update triggers
Fixes:
- Added ws feature to Axum dependency
- Fixed Message::Text() type conversions (String→Utf8Bytes via .into())
- Fixed BackupInfo FromRow derive
- Fixed recursive async with Box::pin pattern
- Fixed async JobScheduler::new() constructor
- Removed manual WebSocket Ping/Pong handler
Compilation: 0 errors, 327 warnings (unused vars/functions)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
171 lines
5.3 KiB
Rust
171 lines
5.3 KiB
Rust
use std::sync::Arc;
|
|
|
|
use axum::Router;
|
|
use sqlx::postgres::PgPoolOptions;
|
|
use tokio::net::TcpListener;
|
|
use tower_http::cors::{Any, CorsLayer};
|
|
use tower_http::trace::TraceLayer;
|
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
|
|
|
mod api;
|
|
mod config;
|
|
mod db;
|
|
mod middleware;
|
|
mod models;
|
|
mod services;
|
|
|
|
use config::AppConfig;
|
|
|
|
/// Shared application state available to all handlers
|
|
pub struct AppState {
|
|
pub db: sqlx::PgPool,
|
|
pub nats: Option<async_nats::Client>,
|
|
pub config: AppConfig,
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> anyhow::Result<()> {
|
|
// Load environment variables
|
|
dotenvy::dotenv().ok();
|
|
|
|
// Initialize tracing
|
|
tracing_subscriber::registry()
|
|
.with(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
|
|
"corrosion_api=debug,tower_http=debug".into()
|
|
}))
|
|
.with(tracing_subscriber::fmt::layer())
|
|
.init();
|
|
|
|
let config = AppConfig::from_env()?;
|
|
|
|
// Database connection pool
|
|
let db = PgPoolOptions::new()
|
|
.max_connections(config.database_max_connections)
|
|
.connect(&config.database_url)
|
|
.await?;
|
|
|
|
tracing::info!("Connected to PostgreSQL");
|
|
|
|
// Run migrations
|
|
sqlx::migrate!("./migrations").run(&db).await?;
|
|
tracing::info!("Database migrations applied");
|
|
|
|
// NATS connection (optional for dev)
|
|
let nats = match async_nats::connect(&config.nats_url).await {
|
|
Ok(client) => {
|
|
tracing::info!("Connected to NATS at {}", config.nats_url);
|
|
Some(client)
|
|
}
|
|
Err(e) => {
|
|
tracing::warn!("NATS not available ({}), running without event bus", e);
|
|
None
|
|
}
|
|
};
|
|
|
|
// Bootstrap: create admin user + license on first run
|
|
bootstrap_admin(&db).await;
|
|
|
|
let state = Arc::new(AppState { db, nats, config });
|
|
|
|
// CORS — permissive in dev, locked down in production
|
|
let cors = CorsLayer::new()
|
|
.allow_origin(Any)
|
|
.allow_methods(Any)
|
|
.allow_headers(Any);
|
|
|
|
// Build router
|
|
let app = Router::new()
|
|
.nest("/api/auth", api::auth::router())
|
|
.nest("/api/servers", api::servers::router())
|
|
.nest("/api/wipes", api::wipes::router())
|
|
.nest("/api/maps", api::maps::router())
|
|
.nest("/api/plugins", api::plugins::router())
|
|
.nest("/api/panels", api::panels::router())
|
|
.nest("/api/schedules", api::schedules::router())
|
|
.nest("/api/logs", api::logs::router())
|
|
.nest("/api/public", api::public::router())
|
|
.nest("/api/team", api::team::router())
|
|
.nest("/api/notifications", api::notifications::router())
|
|
.nest("/api/license", api::license::router())
|
|
.nest("/api/store", api::store::router())
|
|
.nest("/api/early-access", api::early_access::router())
|
|
.nest("/api/admin", api::admin::router())
|
|
.nest("/api/ws", api::ws::router())
|
|
.layer(cors)
|
|
.layer(TraceLayer::new_for_http())
|
|
.with_state(state);
|
|
|
|
let bind_addr = "0.0.0.0:3000";
|
|
let listener = TcpListener::bind(bind_addr).await?;
|
|
tracing::info!("Corrosion API listening on {}", bind_addr);
|
|
|
|
axum::serve(listener, app).await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Bootstrap: if no users exist and ADMIN_EMAIL/ADMIN_PASSWORD are set,
|
|
/// create the initial admin user and a dev license key.
|
|
async fn bootstrap_admin(db: &sqlx::PgPool) {
|
|
let admin_email = std::env::var("ADMIN_EMAIL").unwrap_or_default();
|
|
let admin_password = std::env::var("ADMIN_PASSWORD").unwrap_or_default();
|
|
let admin_username = std::env::var("ADMIN_USERNAME").unwrap_or_else(|_| "Commander".to_string());
|
|
|
|
if admin_email.is_empty() || admin_password.is_empty() {
|
|
return;
|
|
}
|
|
|
|
// Check if any users exist
|
|
let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
|
|
.fetch_one(db)
|
|
.await
|
|
.unwrap_or((0,));
|
|
|
|
if count.0 > 0 {
|
|
tracing::debug!("Users already exist, skipping bootstrap");
|
|
return;
|
|
}
|
|
|
|
tracing::info!("No users found — bootstrapping admin user: {}", admin_email);
|
|
|
|
// Hash password
|
|
let password_hash = match services::auth::hash_password(&admin_password) {
|
|
Ok(h) => h,
|
|
Err(e) => {
|
|
tracing::error!("Failed to hash admin password: {e}");
|
|
return;
|
|
}
|
|
};
|
|
|
|
// Create admin user
|
|
let user_id = match db::users::create_user(db, &admin_email, &admin_username, &password_hash).await {
|
|
Ok(id) => id,
|
|
Err(e) => {
|
|
tracing::error!("Failed to create admin user: {e}");
|
|
return;
|
|
}
|
|
};
|
|
|
|
// Flag as super-admin
|
|
if let Err(e) = sqlx::query("UPDATE users SET is_super_admin = true WHERE id = $1")
|
|
.bind(user_id)
|
|
.execute(db)
|
|
.await
|
|
{
|
|
tracing::error!("Failed to set super-admin flag: {e}");
|
|
}
|
|
|
|
// Create a license for the admin
|
|
let license_key = std::env::var("ADMIN_LICENSE_KEY")
|
|
.unwrap_or_else(|_| format!("CORROSION-{}", services::encryption::generate_token(8).to_uppercase()));
|
|
|
|
match db::licenses::create_license(db, &license_key, user_id).await {
|
|
Ok(_) => {
|
|
tracing::info!("Bootstrap complete — admin: {}, license: {}", admin_email, license_key);
|
|
}
|
|
Err(e) => {
|
|
tracing::error!("Failed to create admin license: {e}");
|
|
}
|
|
}
|
|
}
|