feat: webhook alerts for surface changes and Prometheus /metrics
[[webhook]] receivers get each ingested sweep's changes, filtered by kind and group, as Xexéu JSON or a Slack/Discord message, optionally signed with HMAC-SHA256 from an environment variable. Delivery runs in the background with retries and never blocks ingestion. GET /api/config and the logs show webhook URLs as scheme://host/… because chat webhook URLs are credentials. /metrics exposes hosts, ports, findings by severity, feed state, per-group last sweep and webhook delivery counters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8b6e0d4a3f
commit
cd1f3d0e8c
17 files changed
+1158
-7
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("xexeu.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
|
||||
[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 = "XEXEU_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_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_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn xexeu 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_xexeu"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu scan");
|
||||
assert!(
|
||||
scan.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 = xexeu_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body);
|
||||
assert!(
|
||||
headers.contains(&format!("x-xexeu-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("xexeu_webhook_deliveries_total{resultado=\"falha\"} 1")
|
||||
|| Instant::now() > deadline
|
||||
{
|
||||
break body;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
};
|
||||
for expected in [
|
||||
"xexeu_sweeps_ingested_total 1",
|
||||
"xexeu_assets{status=\"ativo\"} 1",
|
||||
"xexeu_open_ports 1",
|
||||
"xexeu_last_sweep_complete{grupo=\"local\"} 1",
|
||||
"xexeu_webhook_deliveries_total{resultado=\"ok\"} 1",
|
||||
"xexeu_webhook_deliveries_total{resultado=\"falha\"} 1",
|
||||
"# TYPE xexeu_findings gauge",
|
||||
] {
|
||||
assert!(
|
||||
metrics.contains(expected),
|
||||
"missing `{expected}` in:\n{metrics}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user