Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
372 lines
12 KiB
Rust
372 lines
12 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();
|
|
}
|
|
}
|
|
|
|
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"
|
|
);
|
|
}
|