refactor!: rename project from Xexéu to Harpia
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
Renames the whole project, after the harpy eagle: crates (xexeu-core/xexeu-cli -> harpia-core/harpia-cli), binary (xexeu -> harpia), admin token env var (XEXEU_ADMIN_TOKEN -> HARPIA_ADMIN_TOKEN), compose env vars (XEXEU_* -> HARPIA_*), container image (ciberfauna/xexeu -> ciberfauna/harpia) and the Gitea repository (ciberfauna/xexeu -> ciberfauna/harpia). Logo updated to the new brand artwork. All docs (EN/PT-BR), CI workflows, scripts, GUI strings and the openspec change history updated to match. BREAKING CHANGE: binary, crate, env var and image names all changed; existing .env files, scripts and deployments referencing the old xexeu/XEXEU names must be updated. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VAyr8cd6jzwpJM9cS1oGjy
This commit is contained in:
1 parent
1dc754a561
commit
5ed6cb2c95
93 files changed
+849
-826
No files matched your search
@@ -0,0 +1,224 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
const WEBHOOK_KEY: &str = "e2e-webhook-signing-key";
|
||||
|
||||
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 code = response
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|code| code.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
/// Accepts one POST, answers 200 and hands over its headers (lowercased) and body.
|
||||
fn webhook_receiver() -> (u16, mpsc::Receiver<(String, Vec<u8>)>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind webhook receiver");
|
||||
let port = listener.local_addr().expect("receiver address").port();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { break };
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut headers = String::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
headers.push_str(&line.to_ascii_lowercase());
|
||||
}
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.and_then(|value| value.trim().parse().ok())
|
||||
.unwrap_or(0);
|
||||
let mut body = vec![0; length];
|
||||
reader.read_exact(&mut body).expect("read webhook body");
|
||||
let mut stream = reader.into_inner();
|
||||
let _ = stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
let _ = sender.send((headers, body));
|
||||
}
|
||||
});
|
||||
(port, receiver)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ingested_sweep_triggers_signed_webhook_and_updates_metrics() {
|
||||
// Something to find: one open port on loopback.
|
||||
let target = TcpListener::bind("127.0.0.1:0").expect("bind target");
|
||||
let target_port = target.local_addr().expect("target address").port();
|
||||
std::thread::spawn(move || for _ in target.incoming() {});
|
||||
|
||||
let (hook_port, deliveries) = webhook_receiver();
|
||||
// Nothing listens here: deliveries fail and must be counted, not crash anything.
|
||||
let dead_port = TcpListener::bind("127.0.0.1:0")
|
||||
.expect("reserve a port")
|
||||
.local_addr()
|
||||
.expect("reserved address")
|
||||
.port();
|
||||
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.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"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{target_port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
|
||||
[[webhook]]
|
||||
url = "http://127.0.0.1:{hook_port}/hook/secret-path"
|
||||
eventos = ["porta_nova"]
|
||||
segredo_env = "HARPIA_E2E_WEBHOOK_KEY"
|
||||
|
||||
[[webhook]]
|
||||
url = "http://127.0.0.1:{dead_port}/down"
|
||||
formato = "slack"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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("HARPIA_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
let mut reader = BufReader::new(child.stdout.take().expect("take stdout"));
|
||||
let _guard = ChildGuard(child);
|
||||
let mut addr = None;
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(rest) = line.split("listening on http://").nth(1) {
|
||||
addr = Some(rest.trim().to_string());
|
||||
break;
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
let addr = addr.expect("server must print its address");
|
||||
std::thread::spawn(move || for _ in reader.lines() {});
|
||||
|
||||
// The API never shows the webhook URL's path: chat webhook URLs are credentials.
|
||||
let (status, body) = http_get(&addr, "/api/config");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains(&format!("http://127.0.0.1:{hook_port}/…")),
|
||||
"{body}"
|
||||
);
|
||||
assert!(!body.contains("secret-path"), "{body}");
|
||||
|
||||
let scan = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
assert!(
|
||||
scan.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&scan.stderr)
|
||||
);
|
||||
|
||||
let (headers, body) = deliveries
|
||||
.recv_timeout(Duration::from_secs(15))
|
||||
.expect("the webhook receives the sweep's changes");
|
||||
let payload: serde_json::Value = serde_json::from_slice(&body).expect("JSON body");
|
||||
assert_eq!(payload["grupo"], "local");
|
||||
let events = payload["eventos"].as_array().expect("events array");
|
||||
assert!(!events.is_empty());
|
||||
assert!(
|
||||
events.iter().all(|event| event["tipo"] == "porta_nova"),
|
||||
"only subscribed kinds are sent: {payload}"
|
||||
);
|
||||
let expected = harpia_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body);
|
||||
assert!(
|
||||
headers.contains(&format!("x-harpia-signature: {expected}")),
|
||||
"signature header in: {headers}"
|
||||
);
|
||||
|
||||
// The dead receiver is retried (2 s, then 4 s) before it counts as a failure.
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
let metrics = loop {
|
||||
let (status, body) = http_get(&addr, "/metrics");
|
||||
assert_eq!(status, 200);
|
||||
if body.contains("harpia_webhook_deliveries_total{resultado=\"falha\"} 1")
|
||||
|| Instant::now() > deadline
|
||||
{
|
||||
break body;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
};
|
||||
for expected in [
|
||||
"harpia_sweeps_ingested_total 1",
|
||||
"harpia_assets{status=\"ativo\"} 1",
|
||||
"harpia_open_ports 1",
|
||||
"harpia_last_sweep_complete{grupo=\"local\"} 1",
|
||||
"harpia_webhook_deliveries_total{resultado=\"ok\"} 1",
|
||||
"harpia_webhook_deliveries_total{resultado=\"falha\"} 1",
|
||||
"# TYPE harpia_findings gauge",
|
||||
] {
|
||||
assert!(
|
||||
metrics.contains(expected),
|
||||
"missing `{expected}` in:\n{metrics}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
const ADMIN_TOKEN: &str = "e2e-admin-token-0123456789";
|
||||
|
||||
fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
|
||||
let auth = format!("Authorization: Bearer {ADMIN_TOKEN}\r\n");
|
||||
http_request_with(addr, method, path, body, &auth)
|
||||
}
|
||||
|
||||
/// `extra_headers` is a raw block of `Name: value\r\n` lines.
|
||||
fn http_request_with(
|
||||
addr: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&str>,
|
||||
extra_headers: &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\n{extra_headers}Content-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("harpia.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 `harpia serve --bind 127.0.0.1:0`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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("HARPIA_ADMIN_TOKEN", ADMIN_TOKEN)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia 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\""));
|
||||
|
||||
// Writes need the admin token; a browser Origin must match Host.
|
||||
let group = r#"{"nome": "sem-token", "alvos": ["127.0.0.1"]}"#;
|
||||
let (code, headers, _) =
|
||||
http_request_with(&addr, "POST", "/api/config/groups", Some(group), "");
|
||||
assert_eq!(code, 401);
|
||||
assert!(headers.contains("www-authenticate: Bearer"));
|
||||
let wrong = "Authorization: Bearer e2e-admin-token-0123456788\r\n";
|
||||
let (code, _, _) = http_request_with(&addr, "POST", "/api/config/groups", Some(group), wrong);
|
||||
assert_eq!(code, 401);
|
||||
let (code, _, _) = http_request_with(&addr, "DELETE", "/api/config/groups/inicial", None, "");
|
||||
assert_eq!(code, 401);
|
||||
let cross_site =
|
||||
format!("Authorization: Bearer {ADMIN_TOKEN}\r\nOrigin: https://evil.example\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(group),
|
||||
&cross_site,
|
||||
);
|
||||
assert_eq!(code, 403);
|
||||
let same_site = format!("X-Harpia-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(r#"{"nome": "fora", "alvos": ["192.168.1.1"]}"#),
|
||||
&same_site,
|
||||
);
|
||||
assert_eq!(
|
||||
code, 400,
|
||||
"same-origin request with the custom header reaches the handler"
|
||||
);
|
||||
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(
|
||||
!body.contains("sem-token"),
|
||||
"rejected writes must not change the config"
|
||||
);
|
||||
|
||||
// 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=\"harpia-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=\"harpia-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=\"harpia-changes-"));
|
||||
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
|
||||
|
||||
// Executive Report HTML
|
||||
let (code, headers, body) = http_request(&addr, "GET", "/relatorio", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/html; charset=utf-8"));
|
||||
assert!(body.contains("Relatório Executivo de Segurança — Harpia"));
|
||||
assert!(body.contains("Indicadores-Chave de Exposição (KPIs)"));
|
||||
assert!(body.contains("Glossário e Metodologia de Avaliação"));
|
||||
|
||||
let (code, headers, _) = http_request(&addr, "GET", "/report", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/html; charset=utf-8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_hot_reload_on_config_file_change() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.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_harpia"))
|
||||
.env("HARPIA_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 harpia 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"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
use chrono::Utc;
|
||||
use harpia_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState};
|
||||
use harpia_core::storage::{SqliteStorage, Storage};
|
||||
use harpia_core::vuln::matcher::{Confidence, Finding, FindingType};
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn doctor_command_json_and_table_and_invalid_config() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let valid_config = workspace.path().join("harpia.toml");
|
||||
let invalid_config = workspace.path().join("invalid.toml");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&valid_config,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["10.0.0.0/8"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
|
||||
[[grupo]]
|
||||
nome = "servidores"
|
||||
alvos = ["10.0.0.1"]
|
||||
"#,
|
||||
)
|
||||
.expect("write valid config");
|
||||
|
||||
fs::write(&invalid_config, "invalid toml content !!").expect("write invalid config");
|
||||
|
||||
// 1. Valid doctor in table mode
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"expected success: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("Harpia v"));
|
||||
assert!(stdout.contains("versao"));
|
||||
assert!(stdout.contains("config"));
|
||||
assert!(stdout.contains("sqlite"));
|
||||
assert!(stdout.contains("Resultado: OK"));
|
||||
|
||||
// 2. Valid doctor in JSON mode
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--json",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor --json");
|
||||
|
||||
assert!(output_json.status.success());
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse json output");
|
||||
assert_eq!(parsed["ok"], true);
|
||||
assert!(parsed["checks"].is_array());
|
||||
let checks = parsed["checks"].as_array().unwrap();
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "config" && c["status"] == "ok"));
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "sqlite" && c["status"] == "ok"));
|
||||
|
||||
// 3. Invalid doctor mode exits with error code 1
|
||||
let output_invalid = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
invalid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor with invalid config");
|
||||
|
||||
assert!(!output_invalid.status.success());
|
||||
let stdout_invalid = String::from_utf8_lossy(&output_invalid.stdout);
|
||||
assert!(stdout_invalid.contains("Resultado: FALHA"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_command_json_and_csv_with_fixture() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
let db_path = data_dir.join("harpia.db");
|
||||
let mut storage = SqliteStorage::open(&db_path).expect("open sqlite storage");
|
||||
|
||||
let now = Utc::now();
|
||||
let diff = DiffResult {
|
||||
state: vec![AssetState {
|
||||
asset_key: "dmz/10.0.0.42".to_string(),
|
||||
network: "dmz".to_string(),
|
||||
ip: "10.0.0.42".parse().unwrap(),
|
||||
status: AssetStatus::Active,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
ports: vec![ServiceState {
|
||||
protocol: "tcp".to_string(),
|
||||
port: 80,
|
||||
status: PortStatus::Open,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
product: Some("nginx".to_string()),
|
||||
version: Some("1.18.0".to_string()),
|
||||
cpe: Some("cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*".to_string()),
|
||||
findings: vec![Finding {
|
||||
tipo: FindingType::Cve,
|
||||
id: "CVE-2021-23017".to_string(),
|
||||
cvss: Some(7.5),
|
||||
kev: false,
|
||||
confianca: Confidence::Alto,
|
||||
title: "1-byte memory overwrite in resolver".to_string(),
|
||||
description: "A 1-byte memory overwrite vulnerability exists in resolver."
|
||||
.to_string(),
|
||||
evidencia: serde_json::json!({ "banner": "nginx 1.18.0" }),
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
events: vec![],
|
||||
};
|
||||
|
||||
storage
|
||||
.apply_diff(&diff)
|
||||
.expect("apply fixture state to database");
|
||||
|
||||
// 1. Export JSON to stdout
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"json",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia export --format json");
|
||||
|
||||
assert!(
|
||||
output_json.status.success(),
|
||||
"export json failed: {}",
|
||||
String::from_utf8_lossy(&output_json.stderr)
|
||||
);
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse export json");
|
||||
assert!(parsed.is_array());
|
||||
let hosts = parsed.as_array().unwrap();
|
||||
assert_eq!(hosts.len(), 1);
|
||||
assert_eq!(hosts[0]["ip"], "10.0.0.42");
|
||||
assert_eq!(hosts[0]["network"], "dmz");
|
||||
assert_eq!(hosts[0]["ports"][0]["port"], 80);
|
||||
assert_eq!(hosts[0]["ports"][0]["product"], "nginx");
|
||||
assert_eq!(hosts[0]["ports"][0]["findings"][0]["id"], "CVE-2021-23017");
|
||||
|
||||
// 2. Export CSV to file with --out
|
||||
let out_csv_file = workspace.path().join("export.csv");
|
||||
let output_csv = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"csv",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
"--out",
|
||||
out_csv_file.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia export --format csv --out ...");
|
||||
|
||||
assert!(output_csv.status.success());
|
||||
let csv_content = fs::read_to_string(&out_csv_file).expect("read exported csv");
|
||||
assert!(csv_content.contains("Endereço IP,Grupo,Status do Host,Protocolo,Porta"));
|
||||
assert!(csv_content.contains("10.0.0.42,dmz,ativo,tcp,80,aberta,nginx,1.18.0,cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*,7.5,1"));
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
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("harpia.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 `harpia feeds import <feeds_dir> --data-dir <data_dir>`
|
||||
let import_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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 `harpia serve` and ensure /api/status displays the imported database
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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 harpia 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("harpia.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 `harpia feeds sync` using mock endpoints
|
||||
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"feeds",
|
||||
"sync",
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
|
||||
.env("HARPIA_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 `harpia serve` with auto-sync enabled
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
|
||||
.env("HARPIA_KEV_URL", format!("http://{mock_addr}/kev"))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia 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("harpia.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 `harpia feeds sync` pointing to an unreachable port (e.g. 127.0.0.1:1)
|
||||
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"feeds",
|
||||
"sync",
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.env("HARPIA_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 `harpia serve` pointing to unreachable port for auto_sync
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.env("HARPIA_KEV_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia 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"#));
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
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 harpia_core::batch::SweepBatch;
|
||||
use harpia_core::vuln::feeds::{Cpe, CpeMatchCriteria, CveRecord, VulnDatabase};
|
||||
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 fingerprint_and_vuln_matching_e2e() {
|
||||
// 1. Mock HTTP service returning Apache 2.4.49 Server header
|
||||
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() {
|
||||
let mut stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(_) => break,
|
||||
};
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = stream.read(&mut buf);
|
||||
let resp = "HTTP/1.1 200 OK\r\nServer: Apache/2.4.49 (Unix)\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK";
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Setup workspace, config, and fixture vuln_db.json
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
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");
|
||||
|
||||
let mut db = VulnDatabase::default();
|
||||
db.kev.cve_ids.insert("CVE-2021-41773".to_string());
|
||||
db.nvd.records.insert(
|
||||
"CVE-2021-41773".to_string(),
|
||||
CveRecord {
|
||||
id: "CVE-2021-41773".to_string(),
|
||||
description: "Path traversal and file disclosure in Apache HTTP Server 2.4.49"
|
||||
.to_string(),
|
||||
cvss_score: Some(7.5),
|
||||
cvss_vector: None,
|
||||
cpe_matches: vec![CpeMatchCriteria {
|
||||
criteria: "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*".to_string(),
|
||||
cpe: Cpe::parse("cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*").unwrap(),
|
||||
version_start_including: None,
|
||||
version_start_excluding: None,
|
||||
version_end_including: None,
|
||||
version_end_excluding: None,
|
||||
}],
|
||||
},
|
||||
);
|
||||
db.save_to_file(&data_dir.join("vuln_db.json"))
|
||||
.expect("save fixture vuln_db.json");
|
||||
|
||||
// 3. Run scan --once with --data-dir pointing to our fixture database
|
||||
let scan_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--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"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
|
||||
assert!(
|
||||
scan_output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&scan_output.stderr)
|
||||
);
|
||||
|
||||
// 4. Validate generated Parquet batch
|
||||
let group_dir = sweeps_dir.join("local");
|
||||
let sweep_dir = fs::read_dir(&group_dir)
|
||||
.expect("group directory")
|
||||
.next()
|
||||
.expect("one sweep")
|
||||
.expect("sweep entry")
|
||||
.path();
|
||||
|
||||
let batch = SweepBatch::read(&sweep_dir).expect("read batch");
|
||||
assert_eq!(batch.services.len(), 1, "expected 1 service observation");
|
||||
let service = &batch.services[0];
|
||||
assert_eq!(service.port, target_port);
|
||||
assert_eq!(service.product.as_deref(), Some("Apache HTTP Server"));
|
||||
assert_eq!(service.version.as_deref(), Some("2.4.49"));
|
||||
assert!(
|
||||
service
|
||||
.cpe
|
||||
.as_ref()
|
||||
.map(|s| s.contains("http_server"))
|
||||
.unwrap_or(false),
|
||||
"cpe should contain http_server: {:?}",
|
||||
service.cpe
|
||||
);
|
||||
assert_eq!(service.findings.len(), 1, "expected 1 finding on service");
|
||||
let finding = &service.findings[0];
|
||||
assert_eq!(finding.id, "CVE-2021-41773");
|
||||
assert!(finding.kev);
|
||||
assert_eq!(finding.cvss, Some(7.5));
|
||||
|
||||
// 5. Run serve and verify /api/hosts
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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 harpia 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);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(pos) = line.find("http://") {
|
||||
let rest = &line[pos + "http://".len()..];
|
||||
let addr = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server failed to output listening address");
|
||||
|
||||
// Poll /api/hosts until the sweep is ingested and host has findings
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut finding_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("CVE-2021-41773") && body.contains("Apache HTTP Server") {
|
||||
finding_found = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
|
||||
assert!(
|
||||
finding_found,
|
||||
"expected /api/hosts to return Apache HTTP Server and CVE-2021-41773"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use std::process::Command;
|
||||
|
||||
use harpia_core::batch::{SweepBatch, SweepStatus};
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn scan_once_writes_a_complete_batch_with_the_open_port() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let port = listener.local_addr().expect("listener address").port();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
if stream.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config = workspace.path().join("harpia.toml");
|
||||
fs::write(
|
||||
&config,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
let sweeps = workspace.path().join("sweeps");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("vivos: 1"), "unexpected stdout: {stdout}");
|
||||
|
||||
let group_dir = sweeps.join("local");
|
||||
let sweep_dir = fs::read_dir(&group_dir)
|
||||
.expect("group directory")
|
||||
.next()
|
||||
.expect("one sweep")
|
||||
.expect("sweep entry")
|
||||
.path();
|
||||
|
||||
let batch = SweepBatch::read(&sweep_dir).expect("read batch");
|
||||
assert_eq!(batch.manifest.status, SweepStatus::Complete);
|
||||
assert_eq!(batch.manifest.group, "local");
|
||||
assert_eq!(batch.alive_hosts().count(), 1);
|
||||
|
||||
let open: Vec<u16> = batch.open_ports("127.0.0.1".parse().expect("ip")).collect();
|
||||
assert_eq!(open, vec![port]);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
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("harpia.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 `harpia serve --bind 127.0.0.1:0 ...`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.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 harpia 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_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia 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, and static assets are served
|
||||
let (status, body) = http_get(&server_addr, "/");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"), "dashboard html: {body}");
|
||||
assert!(body.contains("app.css"), "dashboard html links css: {body}");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/dashboard");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"), "dashboard html: {body}");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.css");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("--sev-critical"),
|
||||
"app.css contains severity tokens"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("renderSeverityChart"),
|
||||
"app.js contains chart logic"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/i18n.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("export function tr"),
|
||||
"i18n.js contains tr function"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/i18n-en.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("export const EN"),
|
||||
"i18n-en.js contains dictionary"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
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 bytes = Vec::new();
|
||||
stream.read_to_end(&mut bytes).expect("read response");
|
||||
let response = String::from_utf8_lossy(&bytes).to_string();
|
||||
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_validates_against_real_dvwa_scan_data() {
|
||||
let validate_dir = Path::new("/tmp/harpia-validate");
|
||||
if !validate_dir.exists() {
|
||||
eprintln!("skip: /tmp/harpia-validate does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
let config_path = validate_dir.join("harpia.toml");
|
||||
let sweeps_dir = validate_dir.join("sweeps");
|
||||
let data_dir = validate_dir.join("data");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia 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);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(pos) = line.find("http://") {
|
||||
let rest = &line[pos + "http://".len()..];
|
||||
let addr = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server listening addr");
|
||||
|
||||
// Poll /api/hosts
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut dvwa_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("172.30.0.10") && body.contains("CVE-2017-3167") {
|
||||
dvwa_found = true;
|
||||
assert!(body.contains("Apache HTTP Server"));
|
||||
assert!(body.contains("2.4.25"));
|
||||
assert!(body.contains(r#""cvss":9.8"#));
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
|
||||
assert!(
|
||||
dvwa_found,
|
||||
"expected DVWA host 172.30.0.10 with CVE-2017-3167 in /api/hosts"
|
||||
);
|
||||
|
||||
// Check dashboard and static assets
|
||||
let (status, body) = http_get(&server_addr, "/");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"));
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.css");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("--sev-critical"));
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("renderSeverityChart"));
|
||||
|
||||
let (status, _) = http_get(&server_addr, "/logo.png");
|
||||
assert_eq!(status, 200);
|
||||
}
|
||||
Reference in new issue
Block a user