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

305 lines
9.3 KiB
Rust

use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::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_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
let mut stream = TcpStream::connect(addr).expect("connect to server");
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.expect("set read timeout");
let payload = body.unwrap_or("");
let request = format!(
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(request.as_bytes()).expect("write request");
let mut response = String::new();
stream.read_to_string(&mut response).expect("read response");
let parts: Vec<&str> = response.split("\r\n\r\n").collect();
let header_part = parts.first().copied().unwrap_or("");
let body_part = parts.get(1).copied().unwrap_or("").to_string();
let status_line = header_part.lines().next().unwrap_or("");
let code: u16 = status_line
.split_whitespace()
.nth(1)
.unwrap_or("0")
.parse()
.unwrap_or(0);
(code, header_part.to_string(), body_part)
}
#[test]
fn config_crud_and_export_e2e() {
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,
r#"
[escopo]
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
responsavel = "SecOps Test"
[padrao]
cron = "@daily"
hosts_simultaneos = 2
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "inicial"
alvos = ["127.0.0.1/32"]
"#,
)
.expect("write configuration");
// 1. 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(10);
while Instant::now() < deadline {
let mut line = String::new();
if reader.read_line(&mut line).is_ok() {
if let Some(pos) = line.find("http://") {
let addr = line[pos + 7..].trim();
server_addr = Some(addr.to_string());
break;
}
}
std::thread::sleep(Duration::from_millis(50));
}
let _server_guard = ChildGuard(child);
let addr = server_addr.expect("server must output listening address");
// 2. Test GET /api/config
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
assert_eq!(code, 200);
assert!(body.contains("\"escopo\""));
assert!(body.contains("\"inicial\""));
// 3. Test POST /api/config/groups - out of scope rejection
let (code, _, body) = http_request(
&addr,
"POST",
"/api/config/groups",
Some(r#"{"nome": "fora-escopo", "alvos": ["192.168.1.1"]}"#),
);
assert_eq!(code, 400);
assert!(body.contains("fora do escopo autorizado"));
// 4. Test POST /api/config/groups - invalid cron rejection
let (code, _, body) = http_request(
&addr,
"POST",
"/api/config/groups",
Some(r#"{"nome": "cron-ruim", "alvos": ["10.0.0.1"], "cron": "isto-nao-e-cron"}"#),
);
assert_eq!(code, 400);
assert!(body.contains("cron inválido"));
// 5. Test POST /api/config/groups - valid creation
let (code, _, body) = http_request(
&addr,
"POST",
"/api/config/groups",
Some(
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.10"], "cron": "0 3 * * *", "criticidade": "alta"}"#,
),
);
assert_eq!(code, 201);
assert!(body.contains("\"novo-grupo\""));
// Verify config file was updated on disk
let file_content = fs::read_to_string(&config_path).expect("read config file");
assert!(file_content.contains("novo-grupo"));
// 6. Test PUT /api/config/groups/novo-grupo - update group
let (code, _, body) = http_request(
&addr,
"PUT",
"/api/config/groups/novo-grupo",
Some(
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.20"], "cron": "0 4 * * *", "criticidade": "critica"}"#,
),
);
assert_eq!(code, 200);
assert!(body.contains("10.0.0.20"));
assert!(body.contains("critica"));
// 7. Test DELETE /api/config/groups/novo-grupo - delete group
let (code, _, _) = http_request(&addr, "DELETE", "/api/config/groups/novo-grupo", None);
assert_eq!(code, 200);
// Verify file on disk has only 1 group
let file_content = fs::read_to_string(&config_path).expect("read config file");
assert!(!file_content.contains("novo-grupo"));
// 8. Test DELETE /api/config/groups/inicial - cannot delete last group
let (code, _, body) = http_request(&addr, "DELETE", "/api/config/groups/inicial", None);
assert_eq!(code, 400);
assert!(body.contains("último grupo"));
// 9. Test CSV Exports
// Hosts CSV
let (code, headers, body) = http_request(&addr, "GET", "/api/export/hosts.csv", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-hosts-"));
assert!(body.starts_with("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados"));
// Findings CSV
let (code, headers, body) = http_request(&addr, "GET", "/api/export/findings.csv", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-findings-"));
assert!(body.starts_with("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição"));
// Changes CSV
let (code, headers, body) =
http_request(&addr, "GET", "/api/export/changes.csv?since=24h", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-changes-"));
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
}
#[test]
fn scanner_hot_reload_on_config_file_change() {
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,
r#"
[escopo]
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
[padrao]
cron = "@daily"
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "primeiro"
alvos = ["127.0.0.1/32"]
"#,
)
.expect("write initial configuration");
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
.env("XEXEU_SCANNER_TICK_SECS", "1")
.args([
"scanner",
"--config",
config_path.to_str().expect("config path"),
"--out",
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 scanner");
let stdout = child.stdout.take().expect("take stdout");
let mut reader = BufReader::new(stdout);
let _scanner_guard = ChildGuard(child);
// Read initial startup line
let mut initial_line = String::new();
reader
.read_line(&mut initial_line)
.expect("read initial line");
assert!(initial_line.contains("1 grupo(s) configurado(s)"));
// Sleep briefly so filesystem mtime changes
std::thread::sleep(Duration::from_millis(1100));
// Append second group to config file
fs::write(
&config_path,
r#"
[escopo]
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
[padrao]
cron = "@daily"
[perfis.padrao]
tcp = "80"
[[grupo]]
nome = "primeiro"
alvos = ["127.0.0.1/32"]
[[grupo]]
nome = "segundo"
alvos = ["10.0.0.1/32"]
"#,
)
.expect("update configuration");
// Wait for reload log message
let deadline = Instant::now() + Duration::from_secs(5);
let mut reloaded = false;
while Instant::now() < deadline {
let mut line = String::new();
if reader.read_line(&mut line).is_ok()
&& line.contains("configuração recarregada com sucesso (2 grupos)")
{
reloaded = true;
break;
}
}
assert!(
reloaded,
"scanner should detect modified config file and reload"
);
}