Files
harpia/crates/xexeu-cli/tests/feeds_e2e.rs
T

506 lines
16 KiB
Rust

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)
}
fn start_mock_feed_server() -> (String, std::thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
let addr = listener.local_addr().expect("mock address").to_string();
let handle = std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = match stream {
Ok(s) => s,
Err(_) => break,
};
let mut buf = [0u8; 2048];
let n = stream.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]);
if req.contains("/cves") {
let body = r#"{
"format": "NVD_CVE",
"version": "2.0",
"vulnerabilities": [
{
"cve": {
"id": "CVE-2021-41773",
"descriptions": [
{"lang": "en", "value": "Apache HTTP Server path traversal"}
],
"metrics": {
"cvssMetricV31": [
{"cvssData": {"baseScore": 7.5}}
]
},
"configurations": [
{
"nodes": [
{
"cpeMatch": [
{
"criteria": "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*",
"vulnerable": true
}
]
}
]
}
]
}
}
]
}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(resp.as_bytes());
} else if req.contains("/kev") {
let body = r#"{
"title": "CISA KEV",
"vulnerabilities": [
{"cveID": "CVE-2021-41773"}
]
}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(resp.as_bytes());
} else {
let resp =
"HTTP/1.1 404 NOT FOUND\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
let _ = stream.write_all(resp.as_bytes());
}
}
});
(addr, handle)
}
#[test]
fn feeds_import_command_and_serve_loads_database() {
let workspace = TempDir::new().expect("temporary directory");
let feeds_dir = workspace.path().join("feeds_in");
let data_dir = workspace.path().join("data");
let config_path = workspace.path().join("xexeu.toml");
let sweeps_dir = workspace.path().join("sweeps");
fs::create_dir_all(&feeds_dir).expect("create feeds dir");
let nvd_content = r#"{
"format": "NVD_CVE",
"version": "2.0",
"vulnerabilities": [
{
"cve": {
"id": "CVE-2024-6387",
"descriptions": [{"lang": "en", "value": "regreSSHion"}],
"configurations": []
}
},
{
"cve": {
"id": "CVE-2021-41773",
"descriptions": [{"lang": "en", "value": "Apache traversal"}],
"configurations": []
}
}
]
}"#;
fs::write(feeds_dir.join("nvd.json"), nvd_content).expect("write nvd.json");
let kev_content = r#"{"vulnerabilities": [{"cveID": "CVE-2021-41773"}]}"#;
fs::write(feeds_dir.join("kev.json"), kev_content).expect("write kev.json");
fs::write(
&config_path,
r#"
[escopo]
autorizado = ["127.0.0.1/32"]
responsavel = "teste"
[padrao]
cron = "@daily"
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "local"
alvos = ["127.0.0.1/32"]
"#,
)
.expect("write config");
// 1. Run `xexeu feeds import <feeds_dir> --data-dir <data_dir>`
let import_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"feeds",
"import",
feeds_dir.to_str().expect("feeds dir"),
"--data-dir",
data_dir.to_str().expect("data dir"),
"--config",
config_path.to_str().expect("config path"),
])
.output()
.expect("run feeds import");
assert!(
import_output.status.success(),
"import failed: {}",
String::from_utf8_lossy(&import_output.stderr)
);
let stdout = String::from_utf8_lossy(&import_output.stdout);
assert!(stdout.contains("2 CVEs (1 no KEV)"), "stdout: {stdout}");
let db_path = data_dir.join("vuln_db.json");
assert!(db_path.exists(), "vuln_db.json must exist");
// 2. Start `xexeu serve` and ensure /api/status displays the imported database
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_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
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 address");
let (status, body) = http_get(&server_addr, "/api/status");
assert_eq!(status, 200);
assert!(body.contains(r#""feeds_cve_count":2"#), "body: {body}");
assert!(body.contains(r#""feeds_kev_count":1"#), "body: {body}");
}
#[test]
fn feeds_sync_mock_http_and_periodic_serve_timer() {
let (mock_addr, _mock_handle) = start_mock_feed_server();
let workspace = TempDir::new().expect("temporary directory");
let data_dir = workspace.path().join("data");
let sweeps_dir = workspace.path().join("sweeps");
let config_path = workspace.path().join("xexeu.toml");
fs::write(
&config_path,
r#"
[escopo]
autorizado = ["127.0.0.1/32"]
responsavel = "teste"
[padrao]
cron = "@daily"
[padrao.feeds]
sincronizar_automaticamente = true
intervalo_sincronizacao = "1s"
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "local"
alvos = ["127.0.0.1/32"]
"#,
)
.expect("write config");
// 1. Run `xexeu feeds sync` using mock endpoints
let sync_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"feeds",
"sync",
"--data-dir",
data_dir.to_str().expect("data dir"),
"--config",
config_path.to_str().expect("config path"),
])
.env("XEXEU_NVD_URL", format!("http://{mock_addr}/cves"))
.env("XEXEU_KEV_URL", format!("http://{mock_addr}/kev"))
.output()
.expect("run feeds sync");
assert!(
sync_output.status.success(),
"sync failed: {}",
String::from_utf8_lossy(&sync_output.stderr)
);
let stdout = String::from_utf8_lossy(&sync_output.stdout);
assert!(
stdout.contains("1 CVEs totais (1 no KEV)"),
"stdout: {stdout}"
);
// 2. Start `xexeu serve` with auto-sync enabled
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"),
])
.env("XEXEU_NVD_URL", format!("http://{mock_addr}/cves"))
.env("XEXEU_KEV_URL", format!("http://{mock_addr}/kev"))
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
let stdout_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
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 address");
// Wait 1.5s for the 1s auto-sync timer to fire
std::thread::sleep(Duration::from_millis(1500));
let (status, body) = http_get(&server_addr, "/api/status");
assert_eq!(status, 200);
assert!(body.contains(r#""feeds_cve_count":1"#), "body: {body}");
assert!(
body.contains(r#""feeds_last_sync":""#),
"body must have last sync timestamp: {body}"
);
}
#[test]
fn feeds_sync_network_failure_does_not_corrupt_existing_database_and_server_stays_healthy() {
let workspace = TempDir::new().expect("temporary directory");
let data_dir = workspace.path().join("data");
let sweeps_dir = workspace.path().join("sweeps");
let config_path = workspace.path().join("xexeu.toml");
fs::create_dir_all(&data_dir).expect("create data dir");
// Pre-populate with initial database
let initial_db_content = r#"{
"nvd": {
"records": {
"CVE-1999-0001": {
"id": "CVE-1999-0001",
"description": "Historical vulnerability",
"cvss_score": 5.0,
"cvss_vector": null,
"cpe_matches": []
}
}
},
"kev": {
"cve_ids": []
}
}"#;
fs::write(data_dir.join("vuln_db.json"), initial_db_content).expect("write initial db");
fs::write(
&config_path,
r#"
[escopo]
autorizado = ["127.0.0.1/32"]
responsavel = "teste"
[padrao]
cron = "@daily"
[padrao.feeds]
sincronizar_automaticamente = true
intervalo_sincronizacao = "1s"
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "local"
alvos = ["127.0.0.1/32"]
"#,
)
.expect("write config");
// 1. Run `xexeu feeds sync` pointing to an unreachable port (e.g. 127.0.0.1:1)
let sync_output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.args([
"feeds",
"sync",
"--data-dir",
data_dir.to_str().expect("data dir"),
"--config",
config_path.to_str().expect("config path"),
])
.env("XEXEU_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("XEXEU_KEV_URL", "http://127.0.0.1:1/nonexistent")
.output()
.expect("run feeds sync");
// Must exit with failure
assert!(
!sync_output.status.success(),
"sync to unreachable address must fail with error code"
);
// Existing database must NOT be corrupted
let db_content = fs::read_to_string(data_dir.join("vuln_db.json")).expect("read db");
assert!(
db_content.contains("CVE-1999-0001"),
"original db must remain intact"
);
// 2. Start `xexeu serve` pointing to unreachable port for auto_sync
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"),
])
.env("XEXEU_NVD_URL", "http://127.0.0.1:1/nonexistent")
.env("XEXEU_KEV_URL", "http://127.0.0.1:1/nonexistent")
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn xexeu serve");
let stdout_pipe = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout_pipe);
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 address");
// Wait 1.5s for the timer to tick and fail network call
std::thread::sleep(Duration::from_millis(1500));
// Server must still be alive and respond HTTP 200 OK
let (health_status, health_body) = http_get(&server_addr, "/api/health");
assert_eq!(health_status, 200);
assert!(health_body.contains(r#""status":"ok""#));
// Status must still show the intact database
let (status_code, status_body) = http_get(&server_addr, "/api/status");
assert_eq!(status_code, 200);
assert!(status_body.contains(r#""feeds_cve_count":1"#));
}