refactor(cli): split main.rs into modules
server/ (state, ingestion, API, CSV exports, embedded assets), scanner, feeds_cmd, config_cmd and commands. Code moved as is; no behavior change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b70f36da09
commit
d231033e42
9 files changed
+1797
-1689
No files matched your search
@@ -0,0 +1,354 @@
|
||||
//! `xexeu serve`: background batch ingestion, feed sync and the HTTP server.
|
||||
|
||||
mod api;
|
||||
mod assets;
|
||||
pub(crate) mod export;
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::{auth, validated_config};
|
||||
use api::{
|
||||
changes_handler, create_group_handler, delete_group_handler, get_config_handler,
|
||||
health_handler, hosts_handler, report_handler, status_handler, update_group_handler,
|
||||
};
|
||||
use assets::{
|
||||
css_handler, i18n_en_js_handler, i18n_js_handler, index_handler, js_handler, logo_handler,
|
||||
paged_js_handler,
|
||||
};
|
||||
use axum::Router;
|
||||
use chrono::{DateTime, Utc};
|
||||
use export::{export_changes_csv_handler, export_findings_csv_handler, export_hosts_csv_handler};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use xexeu_core::batch::SweepBatch;
|
||||
use xexeu_core::config::XexeuConfig;
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
||||
use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
use xexeu_core::vuln::{sync_feeds, SyncOptions, VulnDatabase};
|
||||
|
||||
fn find_sweep_manifests(sweeps_dir: &Path) -> Vec<PathBuf> {
|
||||
let mut manifests = Vec::new();
|
||||
let group_entries = match fs::read_dir(sweeps_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => return manifests,
|
||||
};
|
||||
for group_entry in group_entries.flatten() {
|
||||
if !group_entry.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let sweep_entries = match fs::read_dir(group_entry.path()) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for sweep_entry in sweep_entries.flatten() {
|
||||
let sweep_path = sweep_entry.path();
|
||||
if sweep_path.is_dir() && sweep_path.join("manifest.json").exists() {
|
||||
manifests.push(sweep_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Lexicographical sorting by ULID directory name orders sweeps chronologically.
|
||||
manifests.sort();
|
||||
manifests
|
||||
}
|
||||
|
||||
async fn poll_sweeps(
|
||||
sweeps_dir: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
) {
|
||||
loop {
|
||||
let manifests = find_sweep_manifests(&sweeps_dir);
|
||||
for sweep_path in manifests {
|
||||
match SweepBatch::read(&sweep_path) {
|
||||
Ok(batch) => {
|
||||
let mut storage_guard = storage.lock().await;
|
||||
match storage_guard.load_state(&[]) {
|
||||
Ok(current_state) => {
|
||||
match diff_batch(¤t_state, &batch, &DiffOptions::default()) {
|
||||
Ok(diff) => match storage_guard.ingest(&batch, &diff) {
|
||||
Ok(true) => {
|
||||
sweeps_ingested.fetch_add(1, Ordering::SeqCst);
|
||||
println!(
|
||||
"lote {} (grupo {}) ingerido com sucesso ({} eventos)",
|
||||
batch.manifest.sweep_id,
|
||||
batch.manifest.group,
|
||||
diff.events.len()
|
||||
);
|
||||
}
|
||||
Ok(false) => {
|
||||
// Sweep already recorded.
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ingerir lote {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao calcular diff de {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("aviso: falha ao carregar estado do banco: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ler lote em {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ServerState {
|
||||
config: Arc<RwLock<XexeuConfig>>,
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
vuln_db: Arc<RwLock<VulnDatabase>>,
|
||||
feeds_last_sync: Arc<RwLock<Option<DateTime<Utc>>>>,
|
||||
}
|
||||
|
||||
fn parse_duration_str(raw: &str) -> Option<Duration> {
|
||||
let raw = raw.trim();
|
||||
if raw.len() > 1 {
|
||||
let (num_str, unit) = raw.split_at(raw.len() - 1);
|
||||
if let Ok(n) = num_str.parse::<u64>() {
|
||||
match unit {
|
||||
"s" => return Some(Duration::from_secs(n)),
|
||||
"m" => return Some(Duration::from_secs(n * 60)),
|
||||
"h" => return Some(Duration::from_secs(n * 3600)),
|
||||
"d" => return Some(Duration::from_secs(n * 86400)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) async fn run_serve(
|
||||
bind: &str,
|
||||
config_path: &Path,
|
||||
sweeps_dir: &Path,
|
||||
data_dir: &Path,
|
||||
admin_token: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
// An empty XEXEU_ADMIN_TOKEN (compose's default) means "generate one".
|
||||
let admin_token = admin_token.map(str::trim).filter(|token| !token.is_empty());
|
||||
let (admin_token, token_generated) = match admin_token {
|
||||
Some(token) if token.len() >= auth::MIN_TOKEN_LEN => (auth::AdminToken::new(token), false),
|
||||
Some(_) => {
|
||||
return Err(format!(
|
||||
"XEXEU_ADMIN_TOKEN precisa ter pelo menos {} caracteres",
|
||||
auth::MIN_TOKEN_LEN
|
||||
))
|
||||
}
|
||||
None => (
|
||||
auth::AdminToken::generate()
|
||||
.map_err(|error| format!("falha ao gerar token de administração: {error}"))?,
|
||||
true,
|
||||
),
|
||||
};
|
||||
fs::create_dir_all(sweeps_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
|
||||
fs::create_dir_all(data_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", data_dir.display()))?;
|
||||
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
let storage = SqliteStorage::open(&db_path).map_err(|error| {
|
||||
format!(
|
||||
"falha ao abrir banco de dados em {}: {error}",
|
||||
db_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let shared_storage = Arc::new(Mutex::new(storage));
|
||||
let sweeps_ingested = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
// Load initial vulnerability database if present on disk
|
||||
let vuln_db_path = data_dir.join("vuln_db.json");
|
||||
let (initial_db, last_sync) = if vuln_db_path.exists() {
|
||||
match VulnDatabase::load_from_file(&vuln_db_path) {
|
||||
Ok(db) => {
|
||||
println!(
|
||||
"Base de vulnerabilidades carregada: {} CVEs ({} no KEV)",
|
||||
db.cve_count(),
|
||||
db.kev_count()
|
||||
);
|
||||
(db, None)
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao carregar {}: {err}; iniciando base vazia",
|
||||
vuln_db_path.display()
|
||||
);
|
||||
(VulnDatabase::default(), None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(VulnDatabase::default(), None)
|
||||
};
|
||||
|
||||
let shared_vuln_db = Arc::new(RwLock::new(initial_db));
|
||||
let shared_last_sync = Arc::new(RwLock::new(last_sync));
|
||||
|
||||
// Spawn background poller for incoming sweeps.
|
||||
let poller_storage = Arc::clone(&shared_storage);
|
||||
let poller_ingested = Arc::clone(&sweeps_ingested);
|
||||
let poller_sweeps = sweeps_dir.to_path_buf();
|
||||
tokio::spawn(async move {
|
||||
poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await;
|
||||
});
|
||||
|
||||
// Spawn periodic background sync if auto_sync is enabled in config
|
||||
if config.defaults.feeds.auto_sync {
|
||||
let timer_db = Arc::clone(&shared_vuln_db);
|
||||
let timer_last_sync = Arc::clone(&shared_last_sync);
|
||||
let timer_db_path = vuln_db_path.clone();
|
||||
let interval_str = config.defaults.feeds.sync_interval.clone();
|
||||
tokio::spawn(async move {
|
||||
let interval = parse_duration_str(&interval_str).unwrap_or(Duration::from_secs(86400));
|
||||
println!("Sincronizador automático de feeds ativo (intervalo: {interval_str})");
|
||||
loop {
|
||||
tokio::time::sleep(interval).await;
|
||||
println!("Iniciando sincronização periódica de feeds de vulnerabilidade...");
|
||||
let sync_opts = SyncOptions::default();
|
||||
match sync_feeds(&sync_opts).await {
|
||||
Ok(downloaded) => {
|
||||
let mut db_guard = timer_db.write().await;
|
||||
db_guard.merge(downloaded);
|
||||
if let Err(e) = db_guard.save_to_file(&timer_db_path) {
|
||||
eprintln!(
|
||||
"aviso: falha ao salvar base de vulnerabilidades atualizada: {e}"
|
||||
);
|
||||
}
|
||||
let mut sync_guard = timer_last_sync.write().await;
|
||||
*sync_guard = Some(Utc::now());
|
||||
println!(
|
||||
"Feeds sincronizados periodicamente com sucesso ({} CVEs)",
|
||||
db_guard.cve_count()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("aviso: falha na sincronização periódica de feeds: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let state = ServerState {
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
vuln_db: shared_vuln_db,
|
||||
feeds_last_sync: shared_last_sync,
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/health", axum::routing::get(health_handler))
|
||||
.route("/api/status", axum::routing::get(status_handler))
|
||||
.route("/api/hosts", axum::routing::get(hosts_handler))
|
||||
.route("/api/changes", axum::routing::get(changes_handler))
|
||||
.route("/api/config", axum::routing::get(get_config_handler))
|
||||
.route(
|
||||
"/api/config/groups",
|
||||
axum::routing::post(create_group_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/config/groups/{nome}",
|
||||
axum::routing::put(update_group_handler).delete(delete_group_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/hosts.csv",
|
||||
axum::routing::get(export_hosts_csv_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/findings.csv",
|
||||
axum::routing::get(export_findings_csv_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/changes.csv",
|
||||
axum::routing::get(export_changes_csv_handler),
|
||||
)
|
||||
.route("/relatorio", axum::routing::get(report_handler))
|
||||
.route("/report", axum::routing::get(report_handler))
|
||||
.route("/", axum::routing::get(index_handler))
|
||||
.route("/dashboard", axum::routing::get(index_handler))
|
||||
.route("/app.css", axum::routing::get(css_handler))
|
||||
.route("/app.js", axum::routing::get(js_handler))
|
||||
.route("/i18n.js", axum::routing::get(i18n_js_handler))
|
||||
.route("/i18n-en.js", axum::routing::get(i18n_en_js_handler))
|
||||
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
|
||||
.route("/logo.png", axum::routing::get(logo_handler))
|
||||
.with_state(state)
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
admin_token.clone(),
|
||||
auth::require_admin,
|
||||
));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(bind)
|
||||
.await
|
||||
.map_err(|error| format!("falha ao vincular endereço {bind}: {error}"))?;
|
||||
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
|
||||
|
||||
println!("Xexéu listening on http://{local_addr}");
|
||||
if token_generated {
|
||||
println!(
|
||||
"Token de administração gerado nesta execução (defina XEXEU_ADMIN_TOKEN para fixá-lo): \
|
||||
http://{local_addr}/?token={}",
|
||||
admin_token.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.map_err(|error| format!("erro no servidor HTTP: {error}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("falha ao registrar listener de Ctrl+C");
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
Ok(mut signal) => signal.recv().await,
|
||||
Err(_) => std::future::pending::<Option<()>>().await,
|
||||
};
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user