Implementa xexeu scanner (loop contínuo) e xexeu serve (API Axum + dashboard + ingestão automática de lotes)
This commit is contained in:
1 parent
a814e100fb
commit
b4d2c29d24
4 files changed
+1060
-26
No files matched your search
Generated
+259
@@ -164,12 +164,70 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||
dependencies = [
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde_core",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-core"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
@@ -499,6 +557,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
@@ -604,6 +671,85 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body-util"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
@@ -708,12 +854,24 @@ version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.4"
|
||||
@@ -801,6 +959,12 @@ dependencies = [
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
@@ -912,6 +1076,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
@@ -967,6 +1137,17 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.2"
|
||||
@@ -976,6 +1157,18 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -993,6 +1186,16 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
@@ -1080,6 +1283,12 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sync_wrapper"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -1152,6 +1361,7 @@ dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
@@ -1207,6 +1417,54 @@ version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
||||
|
||||
[[package]]
|
||||
name = "tower-service"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "twox-hash"
|
||||
version = "2.1.5"
|
||||
@@ -1407,6 +1665,7 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
name = "xexeu-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
"clap",
|
||||
"libc",
|
||||
|
||||
@@ -14,12 +14,13 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
xexeu-core = { path = "../xexeu-core" }
|
||||
axum = "0.8"
|
||||
chrono = { version = "0.4", features = ["clock"] }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
libc = "0.2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "time", "sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
+599
-25
@@ -1,19 +1,29 @@
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::fs;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Html;
|
||||
use axum::{Json, Router};
|
||||
use chrono::{DateTime, Utc};
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::Mutex;
|
||||
use xexeu_core::batch::{EngineMode, SweepBatch, SweepManifest, SweepStatus};
|
||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
||||
use xexeu_core::scan::{
|
||||
discover_hosts_tcp, scan_hosts_tcp_connect, DiscoveryConfig, HostState, PortScanConfig,
|
||||
PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||
};
|
||||
use xexeu_core::schedule::{next_runs, should_run_now, RunDecision, RunHistory};
|
||||
use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
use xexeu_core::targets::{
|
||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||
};
|
||||
@@ -130,14 +140,25 @@ async fn main() -> ExitCode {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Scanner { config, out } => match run_scanner(&config, &out).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Serve {
|
||||
bind,
|
||||
config,
|
||||
sweeps,
|
||||
data_dir,
|
||||
} => match run_serve(&bind, &config, &sweeps, &data_dir).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Changes { since, data_dir } => run_changes(&since, &data_dir),
|
||||
Command::Config { action } => match action {
|
||||
ConfigAction::Check { config } => run_config_check(&config),
|
||||
},
|
||||
Command::Doctor { json } => run_doctor(json),
|
||||
Command::Serve { .. } => not_implemented("serve"),
|
||||
Command::Scanner { .. } => not_implemented("scanner"),
|
||||
Command::Feeds { .. } => not_implemented("feeds"),
|
||||
Command::Changes { .. } => not_implemented("changes"),
|
||||
Command::Export { .. } => not_implemented("export"),
|
||||
}
|
||||
}
|
||||
@@ -250,21 +271,23 @@ fn ip_value(address: IpAddr) -> u128 {
|
||||
}
|
||||
}
|
||||
|
||||
async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
struct ScanSummary {
|
||||
batch: SweepBatch,
|
||||
directory: PathBuf,
|
||||
targets_count: usize,
|
||||
alive_count: usize,
|
||||
}
|
||||
|
||||
async fn execute_scan_for_group(
|
||||
config: &XexeuConfig,
|
||||
group_name: &str,
|
||||
out: &Path,
|
||||
) -> Result<(), String> {
|
||||
if !once {
|
||||
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
|
||||
}
|
||||
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
) -> Result<ScanSummary, String> {
|
||||
let group = config
|
||||
.group(&name)
|
||||
.ok_or_else(|| format!("grupo '{name}' não existe na configuração"))?;
|
||||
let expansion = expand_group(group).map_err(|error| format!("grupo '{name}': {error}"))?;
|
||||
.group(group_name)
|
||||
.ok_or_else(|| format!("grupo '{group_name}' não existe na configuração"))?;
|
||||
let expansion =
|
||||
expand_group(group).map_err(|error| format!("grupo '{group_name}': {error}"))?;
|
||||
let scope =
|
||||
scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?;
|
||||
|
||||
@@ -293,11 +316,12 @@ async fn scan_once(
|
||||
return Err("nenhum alvo dentro do escopo autorizado".to_string());
|
||||
}
|
||||
|
||||
let profile_name = group.effective_profile(&config);
|
||||
let profile_name = group.effective_profile(config);
|
||||
let profile = config
|
||||
.profiles
|
||||
.get(profile_name)
|
||||
.ok_or_else(|| format!("perfil '{profile_name}' não definido"))?;
|
||||
|
||||
if profile.engine != "nativo" && profile.engine != "nativo-sem-raw" {
|
||||
return Err(format!(
|
||||
"motor '{}' do perfil '{profile_name}' não implementado; use nativo",
|
||||
@@ -359,15 +383,40 @@ async fn scan_once(
|
||||
.write(out)
|
||||
.map_err(|error| format!("falha ao gravar o lote: {error}"))?;
|
||||
|
||||
Ok(ScanSummary {
|
||||
targets_count: targets.len(),
|
||||
alive_count: alive.len(),
|
||||
batch,
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
out: &Path,
|
||||
) -> Result<(), String> {
|
||||
if !once {
|
||||
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
|
||||
}
|
||||
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
let summary = execute_scan_for_group(&config, &name, out).await?;
|
||||
|
||||
let profile_name = summary.batch.manifest.profile.as_str();
|
||||
println!(
|
||||
"lote {} (grupo {}, perfil {}) gravado em {}",
|
||||
batch.manifest.sweep_id,
|
||||
group.name,
|
||||
summary.batch.manifest.sweep_id,
|
||||
name,
|
||||
profile_name,
|
||||
directory.display()
|
||||
summary.directory.display()
|
||||
);
|
||||
println!("alvos: {}; vivos: {}", targets.len(), alive.len());
|
||||
for result in &batch.ports {
|
||||
println!(
|
||||
"alvos: {}; vivos: {}",
|
||||
summary.targets_count, summary.alive_count
|
||||
);
|
||||
for result in &summary.batch.ports {
|
||||
let open: Vec<String> = result
|
||||
.ports
|
||||
.iter()
|
||||
@@ -382,6 +431,531 @@ async fn scan_once(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_scanner(config_path: &Path, out_dir: &Path) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
fs::create_dir_all(out_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
|
||||
|
||||
let mut histories: BTreeMap<String, RunHistory> = BTreeMap::new();
|
||||
for group in &config.groups {
|
||||
histories.insert(group.name.clone(), RunHistory::default());
|
||||
}
|
||||
|
||||
println!(
|
||||
"scanner contínuo iniciado com {} grupo(s) configurado(s)",
|
||||
config.groups.len()
|
||||
);
|
||||
|
||||
let tick_interval = std::env::var("XEXEU_SCANNER_TICK_SECS")
|
||||
.ok()
|
||||
.and_then(|val| val.parse().ok())
|
||||
.map(Duration::from_secs)
|
||||
.unwrap_or(Duration::from_secs(10));
|
||||
|
||||
loop {
|
||||
let now = Utc::now();
|
||||
for group in &config.groups {
|
||||
let history = histories.entry(group.name.clone()).or_default();
|
||||
|
||||
match should_run_now(group, &config, now, history) {
|
||||
Ok(RunDecision::Run) => {
|
||||
history.running = true;
|
||||
history.last_started = Some(now);
|
||||
|
||||
match execute_scan_for_group(&config, &group.name, out_dir).await {
|
||||
Ok(summary) => {
|
||||
history.running = false;
|
||||
history.last_finished = Some(Utc::now());
|
||||
let open_count = summary
|
||||
.batch
|
||||
.ports
|
||||
.iter()
|
||||
.flat_map(|r| &r.ports)
|
||||
.filter(|p| p.state == PortState::Open)
|
||||
.count();
|
||||
println!(
|
||||
"[{}] grupo {}: {} alvo(s), {} vivo(s), {} porta(s) aberta(s) (lote {})",
|
||||
Utc::now().to_rfc3339(),
|
||||
group.name,
|
||||
summary.targets_count,
|
||||
summary.alive_count,
|
||||
open_count,
|
||||
summary.batch.manifest.sweep_id
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
history.running = false;
|
||||
eprintln!("erro na varredura do grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RunDecision::Deferred { .. }) => {
|
||||
eprintln!(
|
||||
"aviso: execução do grupo {} adiada (anterior ainda em andamento)",
|
||||
group.name
|
||||
);
|
||||
}
|
||||
Ok(RunDecision::Wait { .. }) => {}
|
||||
Err(error) => {
|
||||
eprintln!("erro no agendador para o grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
println!("scanner encerrado graciosamente");
|
||||
break;
|
||||
}
|
||||
_ = tokio::time::sleep(tick_interval) => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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)]
|
||||
struct ServerState {
|
||||
config: Arc<XexeuConfig>,
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HealthResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
async fn health_handler() -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StatusResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
config_path: String,
|
||||
sweeps_ingested: usize,
|
||||
groups: Vec<GroupScheduleDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GroupScheduleDto {
|
||||
group: String,
|
||||
profile: String,
|
||||
cron: String,
|
||||
next_run: String,
|
||||
}
|
||||
|
||||
async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
||||
let now = Utc::now();
|
||||
let schedules = next_runs(&state.config, now).unwrap_or_default();
|
||||
let groups = state
|
||||
.config
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
let next_run = schedules
|
||||
.iter()
|
||||
.find(|s| s.group == group.name)
|
||||
.map(|s| s.next_run.to_rfc3339())
|
||||
.unwrap_or_default();
|
||||
GroupScheduleDto {
|
||||
group: group.name.clone(),
|
||||
profile: group.effective_profile(&state.config).to_string(),
|
||||
cron: group.effective_cron(&state.config).to_string(),
|
||||
next_run,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Json(StatusResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
config_path: state.config_path.display().to_string(),
|
||||
sweeps_ingested: state.sweeps_ingested.load(Ordering::SeqCst),
|
||||
groups,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HostDto {
|
||||
asset_key: String,
|
||||
network: String,
|
||||
ip: String,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
ports: Vec<PortDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PortDto {
|
||||
protocol: String,
|
||||
port: u16,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
product: Option<String>,
|
||||
version: Option<String>,
|
||||
cpe: Option<String>,
|
||||
}
|
||||
|
||||
async fn hosts_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<Json<Vec<HostDto>>, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let dtos = current_state
|
||||
.assets
|
||||
.into_iter()
|
||||
.map(|asset| HostDto {
|
||||
asset_key: asset.asset_key,
|
||||
network: asset.network,
|
||||
ip: asset.ip.to_string(),
|
||||
status: asset.status.as_str(),
|
||||
absences: asset.absences,
|
||||
first_seen: asset.first_seen.to_rfc3339(),
|
||||
last_seen: asset.last_seen.to_rfc3339(),
|
||||
ports: asset
|
||||
.ports
|
||||
.into_iter()
|
||||
.map(|port| PortDto {
|
||||
protocol: port.protocol,
|
||||
port: port.port,
|
||||
status: port.status.as_str(),
|
||||
absences: port.absences,
|
||||
first_seen: port.first_seen.to_rfc3339(),
|
||||
last_seen: port.last_seen.to_rfc3339(),
|
||||
product: port.product,
|
||||
version: port.version,
|
||||
cpe: port.cpe,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(dtos))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ChangesQuery {
|
||||
since: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_since(raw: &str) -> Option<DateTime<Utc>> {
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if raw.len() > 1 {
|
||||
let (num_str, unit) = raw.split_at(raw.len() - 1);
|
||||
if let Ok(number) = num_str.parse::<i64>() {
|
||||
let duration = match unit {
|
||||
"s" => Some(chrono::Duration::seconds(number)),
|
||||
"m" => Some(chrono::Duration::minutes(number)),
|
||||
"h" => Some(chrono::Duration::hours(number)),
|
||||
"d" => Some(chrono::Duration::days(number)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(dur) = duration {
|
||||
return Some(Utc::now() - dur);
|
||||
}
|
||||
}
|
||||
}
|
||||
DateTime::parse_from_rfc3339(raw)
|
||||
.ok()
|
||||
.map(|date_time| date_time.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
async fn changes_handler(
|
||||
State(state): State<ServerState>,
|
||||
Query(query): Query<ChangesQuery>,
|
||||
) -> Result<Json<Vec<xexeu_core::diff::Event>>, (StatusCode, String)> {
|
||||
let since = query.since.as_deref().and_then(parse_since);
|
||||
let storage = state.storage.lock().await;
|
||||
let events = storage.events(since).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar eventos: {error}"),
|
||||
)
|
||||
})?;
|
||||
Ok(Json(events))
|
||||
}
|
||||
|
||||
async fn dashboard_handler() -> Html<&'static str> {
|
||||
const HTML: &str = r#"<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Xexéu — Painel de Auditoria Contínua</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0f172a; color: #f8fafc; margin: 0; padding: 28px; }
|
||||
h1 { font-size: 1.6rem; margin-bottom: 6px; color: #38bdf8; }
|
||||
.subtitle { color: #94a3b8; font-size: 0.95rem; margin-bottom: 24px; }
|
||||
.card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 18px; margin-bottom: 20px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
|
||||
.badge { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; }
|
||||
.badge-active { background: #065f46; color: #34d399; }
|
||||
.badge-open { background: #0284c7; color: #bae6fd; margin-right: 4px; font-family: monospace; }
|
||||
table { width: 100%; border-collapse: collapse; margin-top: 14px; }
|
||||
th, td { text-align: left; padding: 12px; border-bottom: 1px solid #334155; font-size: 0.9rem; }
|
||||
th { color: #94a3b8; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.05em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Xexéu</h1>
|
||||
<div class="subtitle">Auditoria contínua de superfície de ataque e identificação de vulnerabilidades</div>
|
||||
<div id="status-card" class="card"><strong>Carregando status...</strong></div>
|
||||
<div class="card">
|
||||
<h2 style="font-size: 1.15rem; margin-top: 0; margin-bottom: 12px;">Ativos e Superfície Descoberta</h2>
|
||||
<div id="hosts-container">Carregando ativos...</div>
|
||||
</div>
|
||||
<script>
|
||||
async function loadData() {
|
||||
try {
|
||||
const sRes = await fetch('/api/status');
|
||||
const status = await sRes.json();
|
||||
document.getElementById('status-card').innerHTML = `
|
||||
<div><strong>Versão:</strong> ${status.version} | <strong>Lotes Ingeridos:</strong> ${status.sweeps_ingested}</div>
|
||||
<div style="margin-top: 6px; font-size: 0.85rem; color: #94a3b8;">Configuração: <code>${status.config_path}</code></div>
|
||||
`;
|
||||
const hRes = await fetch('/api/hosts');
|
||||
const hosts = await hRes.json();
|
||||
if (hosts.length === 0) {
|
||||
document.getElementById('hosts-container').innerHTML = '<p style="color: #94a3b8; margin: 0;">Nenhum ativo ingerido ainda.</p>';
|
||||
return;
|
||||
}
|
||||
let html = '<table><thead><tr><th>IP</th><th>Grupo</th><th>Status</th><th>Portas Abertas</th><th>Visto em</th></tr></thead><tbody>';
|
||||
for (const h of hosts) {
|
||||
const ports = h.ports.filter(p => p.status === 'aberta').map(p => `<span class="badge badge-open">${p.protocol}/${p.port}</span>`).join(' ') || '—';
|
||||
html += `<tr><td><strong>${h.ip}</strong></td><td>${h.network}</td><td><span class="badge badge-active">${h.status}</span></td><td>${ports}</td><td>${h.last_seen}</td></tr>`;
|
||||
}
|
||||
html += '</tbody></table>';
|
||||
document.getElementById('hosts-container').innerHTML = html;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
loadData();
|
||||
setInterval(loadData, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>"#;
|
||||
Html(HTML)
|
||||
}
|
||||
|
||||
async fn run_serve(
|
||||
bind: &str,
|
||||
config_path: &Path,
|
||||
sweeps_dir: &Path,
|
||||
data_dir: &Path,
|
||||
) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
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));
|
||||
|
||||
// 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;
|
||||
});
|
||||
|
||||
let state = ServerState {
|
||||
config: Arc::new(config),
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
};
|
||||
|
||||
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("/", axum::routing::get(dashboard_handler))
|
||||
.route("/dashboard", axum::routing::get(dashboard_handler))
|
||||
.with_state(state);
|
||||
|
||||
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}");
|
||||
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.map_err(|error| format!("erro no servidor HTTP: {error}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
if !db_path.exists() {
|
||||
return fail(&format!(
|
||||
"banco de dados não encontrado em {}",
|
||||
db_path.display()
|
||||
));
|
||||
}
|
||||
let storage = match SqliteStorage::open(&db_path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return fail(&format!("falha ao abrir banco: {e}")),
|
||||
};
|
||||
let since_dt = parse_since(since);
|
||||
match storage.events(since_dt) {
|
||||
Ok(events) => match serde_json::to_string_pretty(&events) {
|
||||
Ok(json) => {
|
||||
println!("{json}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => fail(&format!("falha ao serializar eventos: {e}")),
|
||||
},
|
||||
Err(e) => fail(&format!("falha ao consultar eventos: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
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 => {},
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DoctorReport {
|
||||
version: &'static str,
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
let status_line = response.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_ingests_sweeps_and_responds_to_api_and_dashboard() {
|
||||
// 1. Start a target listener on loopback.
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
|
||||
let target_port = target_listener.local_addr().expect("target address").port();
|
||||
std::thread::spawn(move || {
|
||||
for stream in target_listener.incoming() {
|
||||
if stream.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Setup workspace with config, sweeps dir, and data dir.
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("xexeu.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{target_port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
// 3. Spawn `xexeu serve --bind 127.0.0.1:0 ...`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn xexeu serve");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
let mut line = String::new();
|
||||
while Instant::now() < deadline {
|
||||
line.clear();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(n) if n > 0 => {
|
||||
if line.contains("listening on http://") {
|
||||
let addr = line
|
||||
.split("http://")
|
||||
.nth(1)
|
||||
.expect("server address part")
|
||||
.trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server must print listening address");
|
||||
|
||||
// 4. Test /api/health
|
||||
let (status, body) = http_get(&server_addr, "/api/health");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""status":"ok""#), "health body: {body}");
|
||||
|
||||
// 5. Test /api/status before sweep ingestion
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""status":"ok""#), "status body: {body}");
|
||||
|
||||
// 6. Run scan --once to produce a sweep batch into sweeps_dir
|
||||
let scan_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu scan");
|
||||
assert!(
|
||||
scan_output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&scan_output.stderr)
|
||||
);
|
||||
|
||||
// 7. Poll /api/hosts until the background poller ingests the sweep and exposes the host
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut host_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("127.0.0.1") && body.contains(&target_port.to_string()) {
|
||||
assert!(
|
||||
body.contains(r#""status":"ativo""#),
|
||||
"asset status in: {body}"
|
||||
);
|
||||
host_found = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
assert!(
|
||||
host_found,
|
||||
"expected host and port to be ingested and visible in /api/hosts"
|
||||
);
|
||||
|
||||
// 8. Verify /api/status now reflects the ingested sweep
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains(r#""sweeps_ingested":1"#),
|
||||
"status sweeps_ingested: {body}"
|
||||
);
|
||||
|
||||
// 9. Verify /api/changes?since=24h returns diff events
|
||||
let (status, body) = http_get(&server_addr, "/api/changes?since=24h");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("host_novo") || body.contains("porta_nova"),
|
||||
"changes events: {body}"
|
||||
);
|
||||
|
||||
// 10. Verify / and /dashboard return HTML
|
||||
let (status, body) = http_get(&server_addr, "/");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Xexéu"), "dashboard html: {body}");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/dashboard");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Xexéu"), "dashboard html: {body}");
|
||||
}
|
||||
Reference in new issue
Block a user