From 3fd7cc1b6038a162def61552ab09f5cbe1d602c1 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Fri, 16 Oct 2026 10:04:20 -0400 Subject: [PATCH] tests: smoke-test the real slinuxm binary against a temp SQLite DB Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs --- tests/binary_smoke.rs | 352 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 tests/binary_smoke.rs diff --git a/tests/binary_smoke.rs b/tests/binary_smoke.rs new file mode 100644 index 0000000..4453114 --- /dev/null +++ b/tests/binary_smoke.rs @@ -0,0 +1,352 @@ +//! End-to-end smoke test of the real `slinuxm` binary against a temp-dir +//! SQLite database: token CLI, `serve`, REST, MCP, revocation, SIGTERM. +//! +//! Run with `devenv shell -- smoke` or `cargo test --test binary_smoke -- --nocapture`. +//! Needs no root and no network (loopback only). Assertions that depend on +//! host data sources (D-Bus, journal) are skipped with a printed reason when +//! the source is unavailable; Docker is never required. + +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +mod common; + +const BIN: &str = env!("CARGO_BIN_EXE_slinuxm"); + +/// Owns the temp dir and the server child; both are cleaned up on drop, +/// including when an assertion panics. +struct Smoke { + dir: PathBuf, + child: Option, + port: u16, +} + +impl Drop for Smoke { + fn drop(&mut self) { + if let Some(mut c) = self.child.take() { + let _ = c.kill(); + let _ = c.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +impl Smoke { + fn new() -> Self { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .subsec_nanos(); + let dir = + std::env::temp_dir().join(format!("slinuxm-smoke-{}-{nanos}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + Smoke { + dir, + child: None, + port: 0, + } + } + + fn db(&self) -> PathBuf { + self.dir.join("db.sqlite") + } + + fn write_config(&self) { + let cfg = format!( + "[server]\nbind = \"127.0.0.1\"\nport = {}\n\n[server.tls]\nenabled = false\n\n\ + [auth]\nenabled = true\ndb_path = \"{}\"\n\n[otel]\nenabled = false\n", + self.port, + self.db().display() + ); + std::fs::write(self.dir.join("config.toml"), cfg).unwrap(); + } + + /// Run the binary with a clean environment (only PATH) and our config. + fn command(&self, args: &[&str]) -> Command { + let mut c = Command::new(BIN); + c.arg("--config") + .arg(self.dir.join("config.toml")) + .args(args) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()); + c + } + + fn cli(&self, args: &[&str]) -> String { + let out = self.command(args).output().unwrap(); + assert!( + out.status.success(), + "slinuxm {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).unwrap() + } + + /// Start `serve` on a fresh loopback port. A port picked by bind-then-drop + /// can be taken before the server binds it, so retry with a new port when + /// the child exits early or never answers. + fn start_server(&mut self) { + for attempt in 1..=5 { + self.port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + self.write_config(); + let mut child = self + .command(&["serve"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + if child.try_wait().unwrap().is_some() { + break; + } + if let Some((200, ..)) = try_get(self.port, "/healthz", &[]) { + self.child = Some(child); + return; + } + std::thread::sleep(Duration::from_millis(50)); + } + let _ = child.kill(); + let _ = child.wait(); + eprintln!( + "smoke: server start attempt {attempt} failed (port {}), retrying", + self.port + ); + } + panic!("server did not become healthy after 5 attempts"); + } +} + +fn exchange(port: u16, req: &str, timeout: Duration) -> Option<(u16, String, String)> { + let mut s = TcpStream::connect(("127.0.0.1", port)).ok()?; + s.set_read_timeout(Some(Duration::from_millis(300))).ok()?; + s.write_all(req.as_bytes()).ok()?; + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + match s.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + // SSE responses may stay open; stop once a JSON-RPC payload arrived. + if rpc_result(&String::from_utf8_lossy(&buf)).is_some() { + break; + } + } + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => {} + Err(_) => break, + } + } + if buf.is_empty() { + return None; + } + Some(common::parse_response(&buf)) +} + +fn try_get(port: u16, path: &str, headers: &[(&str, &str)]) -> Option<(u16, String, String)> { + let req = common::request("GET", path, &format!("127.0.0.1:{port}"), headers, None); + exchange(port, &req, Duration::from_secs(10)) +} + +fn get(port: u16, path: &str, headers: &[(&str, &str)]) -> (u16, String, String) { + try_get(port, path, headers).unwrap_or_else(|| panic!("no response for GET {path}")) +} + +/// First JSON value in `text` (a line, optionally `data:`-prefixed) that +/// carries a JSON-RPC `result`. +fn rpc_result(text: &str) -> Option { + text.lines().find_map(|l| { + let l = l.trim().strip_prefix("data:").unwrap_or(l.trim()).trim(); + let v: serde_json::Value = serde_json::from_str(l).ok()?; + v.get("result")?; + Some(v) + }) +} + +fn mcp_post(port: u16, token: &str, session: Option<&str>, body: &str) -> (u16, String, String) { + let auth = format!("Bearer {token}"); + let mut headers = vec![ + ("Authorization", auth.as_str()), + ("Content-Type", "application/json"), + ("Accept", "application/json, text/event-stream"), + ]; + if let Some(s) = session { + headers.push(("Mcp-Session-Id", s)); + } + let req = common::request( + "POST", + "/mcp", + &format!("127.0.0.1:{port}"), + &headers, + Some(body), + ); + exchange(port, &req, Duration::from_secs(10)).expect("no response to POST /mcp") +} + +fn skip(what: &str, status: u16, body: &str) { + println!( + "SKIP: {what}: host source unavailable (HTTP {status}: {})", + body.trim() + ); +} + +fn wait_exit(child: &mut Child, within: Duration) -> std::process::ExitStatus { + let start = Instant::now(); + loop { + if let Some(st) = child.try_wait().unwrap() { + return st; + } + assert!( + start.elapsed() < within, + "no exit within {within:?} of SIGTERM" + ); + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn assert_mode(path: &Path, want: u32) { + let mode = std::fs::metadata(path).unwrap().permissions().mode() & 0o777; + assert_eq!( + mode, + want, + "{} mode is {mode:o}, want {want:o}", + path.display() + ); +} + +#[test] +fn binary_end_to_end() { + let mut smoke = Smoke::new(); + // The token CLI needs a config; the port is rewritten when serve starts. + smoke.port = 1; // placeholder; start_server picks a real port + smoke.write_config(); + + let out = smoke.cli(&["token", "create", "smoke"]); + let token = out.trim().to_owned(); + assert!( + !token.is_empty() && !token.contains(char::is_whitespace), + "token: {out:?}" + ); + assert!( + smoke.db().exists(), + "token create did not create the database" + ); + assert!(smoke.cli(&["token", "list"]).contains("smoke")); + + smoke.start_server(); + let port = smoke.port; + println!("smoke: server healthy on 127.0.0.1:{port}"); + let auth = format!("Bearer {token}"); + let bearer = [("Authorization", auth.as_str())]; + + // Public health, protected API. + let (s, ..) = get(port, "/healthz", &[]); + assert_eq!(s, 200); + let (s, head, _) = get(port, "/api/v1/systemd/units", &[]); + assert_eq!(s, 401); + assert!(head.contains("www-authenticate"), "head: {head}"); + let (s, ..) = get( + port, + "/api/v1/systemd/units", + &[("Authorization", "Bearer slinuxm_bogus")], + ); + assert_eq!(s, 401); + + // Real host sources: tolerate absence of D-Bus / journal. + let (s, _, body) = get(port, "/api/v1/systemd/units", &bearer); + if s == 200 { + assert!( + serde_json::from_str::(&body).is_ok(), + "units body: {body}" + ); + println!("ok: systemd units list"); + } else { + skip("systemd units", s, &body); + } + let (s, _, body) = get(port, "/api/v1/journal?lines=5", &bearer); + if s == 200 { + assert!( + serde_json::from_str::(&body).is_ok(), + "journal body: {body}" + ); + println!("ok: journal query"); + } else { + skip("journal query", s, &body); + } + + // MCP: initialize, initialized, tools/list. + let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}"#; + let (s, head, body) = mcp_post(port, &token, None, init); + assert_eq!(s, 200, "initialize: {head} {body}"); + assert!(rpc_result(&body).is_some(), "initialize body: {body}"); + let sid = head + .lines() + .find_map(|l| l.strip_prefix("mcp-session-id:")) + .expect("mcp-session-id header") + .trim() + .to_owned(); + let (s, ..) = mcp_post( + port, + &token, + Some(&sid), + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + ); + assert_eq!(s, 202); + let (s, _, body) = mcp_post( + port, + &token, + Some(&sid), + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, + ); + assert_eq!(s, 200, "tools/list: {body}"); + let v = rpc_result(&body).expect("tools/list result"); + let tools = v["result"]["tools"].as_array().expect("tools array"); + assert_eq!(tools.len(), 8, "tools: {tools:?}"); + println!("ok: MCP initialize + tools/list ({} tools)", tools.len()); + + // MCP without a token is rejected. + let req = common::request( + "POST", + "/mcp", + &format!("127.0.0.1:{port}"), + &[ + ("Content-Type", "application/json"), + ("Accept", "application/json, text/event-stream"), + ], + Some(init), + ); + assert_eq!(exchange(port, &req, Duration::from_secs(5)).unwrap().0, 401); + + assert_mode(&smoke.db(), 0o600); + + // Revocation takes effect without a restart. + smoke.cli(&["token", "revoke", "smoke"]); + let (s, ..) = get(port, "/api/v1/systemd/units", &bearer); + assert_eq!(s, 401, "revoked token still accepted"); + + // Clean shutdown on SIGTERM. + let mut child = smoke.child.take().unwrap(); + assert!(Command::new("kill") + .args(["-TERM", &child.id().to_string()]) + .status() + .unwrap() + .success()); + let st = wait_exit(&mut child, Duration::from_secs(5)); + assert!(st.success(), "exit status {st}"); + println!("ok: clean SIGTERM exit"); +}