P3: wire serve end to end, integration tests, unit file, README
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
1 parent
936efaf97e
commit
acedb9522e
10 files changed
+637
-16
No files matched your search
@@ -0,0 +1,341 @@
|
||||
//! Integration tests (P3 I2): the real assembled router on an ephemeral port
|
||||
//! with fake sources, plus the real binary for startup and SIGTERM checks.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use skyg_linux_tracker::auth::tokens;
|
||||
use skyg_linux_tracker::config::Config;
|
||||
use skyg_linux_tracker::server;
|
||||
use skyg_linux_tracker::sources::fake::fake_state;
|
||||
use sqlx::sqlite::SqlitePoolOptions;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
struct Harness {
|
||||
port: u16,
|
||||
token: String,
|
||||
shutdown: CancellationToken,
|
||||
join: tokio::task::JoinHandle<anyhow::Result<()>>,
|
||||
}
|
||||
|
||||
async fn start(auth: bool) -> Harness {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let mut config = Config::default();
|
||||
config.server.port = port;
|
||||
config.auth.enabled = auth;
|
||||
let mut state = fake_state(config);
|
||||
let mut token = String::new();
|
||||
if auth {
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect("sqlite::memory:")
|
||||
.await
|
||||
.unwrap();
|
||||
skyg_linux_tracker::db::migrate(&pool).await.unwrap();
|
||||
token = tokens::create(&pool, "test").await.unwrap();
|
||||
state.db = Some(pool);
|
||||
}
|
||||
let shutdown = state.shutdown.clone();
|
||||
let app = server::build_router(state);
|
||||
let join = tokio::spawn(server::serve_listener(listener, app, shutdown.clone()));
|
||||
Harness {
|
||||
port,
|
||||
token,
|
||||
shutdown,
|
||||
join,
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal HTTP/1.1 client: sends one request with `Connection: close` and
|
||||
/// reads until EOF or `wait` elapses. Returns (status, lowercase headers, body).
|
||||
async fn http(
|
||||
port: u16,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, &str)],
|
||||
body: Option<&str>,
|
||||
wait: Duration,
|
||||
) -> (u16, String, String) {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let mut req =
|
||||
format!("{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n");
|
||||
for (k, v) in headers {
|
||||
req.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
if let Some(b) = body {
|
||||
req.push_str(b);
|
||||
}
|
||||
s.write_all(req.as_bytes()).await.unwrap();
|
||||
let mut buf = Vec::new();
|
||||
let _ = tokio::time::timeout(wait, async {
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
match s.read(&mut chunk).await {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let text = String::from_utf8_lossy(&buf).into_owned();
|
||||
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
|
||||
let status = head
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
(status, head.to_lowercase(), body.to_owned())
|
||||
}
|
||||
|
||||
const SHORT: Duration = Duration::from_secs(2);
|
||||
|
||||
async fn get(h: &Harness, path: &str, bearer: bool) -> (u16, String, String) {
|
||||
let auth = format!("Bearer {}", h.token);
|
||||
let hdrs: Vec<(&str, &str)> = if bearer {
|
||||
vec![("Authorization", auth.as_str())]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
http(h.port, "GET", path, &hdrs, None, SHORT).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_and_healthz() {
|
||||
let h = start(true).await;
|
||||
assert_eq!(get(&h, "/healthz", false).await.0, 200);
|
||||
let (st, head, body) = get(&h, "/api/v1/systemd/units", false).await;
|
||||
assert_eq!(st, 401);
|
||||
assert!(head.contains("www-authenticate: bearer"));
|
||||
assert!(body.contains("unauthorized"));
|
||||
assert_eq!(
|
||||
http(
|
||||
h.port,
|
||||
"GET",
|
||||
"/api/v1/systemd/units",
|
||||
&[("Authorization", "Bearer slinuxm_nope")],
|
||||
None,
|
||||
SHORT
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
401
|
||||
);
|
||||
let (st, _, body) = get(&h, "/api/v1/systemd/units", true).await;
|
||||
assert_eq!(st, 200);
|
||||
assert!(body.contains("ssh") || body.contains(".service"), "{body}");
|
||||
// /mcp is protected too.
|
||||
let (st, _, _) = http(
|
||||
h.port,
|
||||
"POST",
|
||||
"/mcp",
|
||||
&[("Content-Type", "application/json")],
|
||||
Some("{}"),
|
||||
SHORT,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, 401);
|
||||
h.shutdown.cancel();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rest_routes() {
|
||||
let h = start(true).await;
|
||||
for p in [
|
||||
"/api/v1/systemd/units",
|
||||
"/api/v1/systemd/units?state=failed",
|
||||
"/api/v1/systemd/timers",
|
||||
"/api/v1/journal?lines=5",
|
||||
"/api/v1/journal?priority=err",
|
||||
"/api/v1/docker/ps",
|
||||
] {
|
||||
assert_eq!(get(&h, p, true).await.0, 200, "{p}");
|
||||
}
|
||||
assert_eq!(get(&h, "/api/v1/journal?lines=0", true).await.0, 400);
|
||||
assert_eq!(get(&h, "/api/v1/nope", true).await.0, 404);
|
||||
h.shutdown.cancel();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_streams_and_ends_on_shutdown() {
|
||||
let h = start(false).await;
|
||||
let (st, head, body) = http(
|
||||
h.port,
|
||||
"GET",
|
||||
"/api/v1/journal/follow",
|
||||
&[("Accept", "text/event-stream")],
|
||||
None,
|
||||
Duration::from_millis(800),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, 200);
|
||||
assert!(head.contains("text/event-stream"));
|
||||
assert!(
|
||||
body.contains("event: journal") || body.contains("data:"),
|
||||
"{body}"
|
||||
);
|
||||
h.shutdown.cancel();
|
||||
let r = tokio::time::timeout(Duration::from_secs(5), h.join).await;
|
||||
assert!(r.is_ok(), "server did not stop after shutdown");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_sse_client_does_not_block_shutdown() {
|
||||
let h = start(false).await;
|
||||
let mut s = TcpStream::connect(("127.0.0.1", h.port)).await.unwrap();
|
||||
s.write_all(
|
||||
format!(
|
||||
"GET /api/v1/journal/follow HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nAccept: text/event-stream\r\n\r\n",
|
||||
h.port
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = tokio::time::timeout(Duration::from_millis(500), s.read(&mut buf)).await;
|
||||
h.shutdown.cancel();
|
||||
let r = tokio::time::timeout(Duration::from_secs(5), h.join).await;
|
||||
assert!(r.is_ok(), "graceful shutdown hung on an open SSE client");
|
||||
}
|
||||
|
||||
const MCP_HEADERS: [(&str, &str); 2] = [
|
||||
("Content-Type", "application/json"),
|
||||
("Accept", "application/json, text/event-stream"),
|
||||
];
|
||||
|
||||
fn init_body() -> &'static str {
|
||||
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"it","version":"0"}}}"#
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_initialize_and_tools_list() {
|
||||
let h = start(true).await;
|
||||
let auth = format!("Bearer {}", h.token);
|
||||
let mut hdrs: Vec<(&str, &str)> = MCP_HEADERS.to_vec();
|
||||
hdrs.push(("Authorization", auth.as_str()));
|
||||
let (st, head, body) = http(
|
||||
h.port,
|
||||
"POST",
|
||||
"/mcp",
|
||||
&hdrs,
|
||||
Some(init_body()),
|
||||
Duration::from_secs(2),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, 200, "{head}\n{body}");
|
||||
assert!(body.contains("serverInfo"), "{body}");
|
||||
let sid = head
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("mcp-session-id: "))
|
||||
.expect("session id")
|
||||
.trim()
|
||||
.to_owned();
|
||||
|
||||
let mut h2 = hdrs.clone();
|
||||
h2.push(("Mcp-Session-Id", sid.as_str()));
|
||||
let (st, _, _) = http(
|
||||
h.port,
|
||||
"POST",
|
||||
"/mcp",
|
||||
&h2,
|
||||
Some(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#),
|
||||
SHORT,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, 202);
|
||||
let (st, _, body) = http(
|
||||
h.port,
|
||||
"POST",
|
||||
"/mcp",
|
||||
&h2,
|
||||
Some(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#),
|
||||
SHORT,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, 200);
|
||||
assert!(body.contains("list_systemd_units"), "{body}");
|
||||
assert!(body.contains("get_container_logs"), "{body}");
|
||||
h.shutdown.cancel();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_bad_origin_is_forbidden() {
|
||||
let h = start(true).await;
|
||||
let auth = format!("Bearer {}", h.token);
|
||||
let mut hdrs: Vec<(&str, &str)> = MCP_HEADERS.to_vec();
|
||||
hdrs.push(("Authorization", auth.as_str()));
|
||||
hdrs.push(("Origin", "http://evil.example"));
|
||||
let (st, _, _) = http(h.port, "POST", "/mcp", &hdrs, Some(init_body()), SHORT).await;
|
||||
assert_eq!(st, 403);
|
||||
h.shutdown.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonloopback_without_auth_exits_nonzero() {
|
||||
let out = std::process::Command::new(env!("CARGO_BIN_EXE_slinuxm"))
|
||||
.args(["serve", "--auth-enabled", "false", "--bind", "0.0.0.0"])
|
||||
.env_remove("SKYG_CONFIG")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!out.status.success());
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(err.contains("auth.enabled = false"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigterm_with_open_sse_client_exits_promptly() {
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream as StdStream;
|
||||
let port = {
|
||||
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
l.local_addr().unwrap().port()
|
||||
};
|
||||
let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_slinuxm"))
|
||||
.args(["serve", "--auth-enabled", "false", "--bind", "127.0.0.1"])
|
||||
.args(["--port", &port.to_string()])
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut conn = None;
|
||||
for _ in 0..50 {
|
||||
if let Ok(c) = StdStream::connect(("127.0.0.1", port)) {
|
||||
conn = Some(c);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
let mut conn = conn.expect("server did not start");
|
||||
conn.set_read_timeout(Some(Duration::from_millis(500)))
|
||||
.unwrap();
|
||||
write!(
|
||||
conn,
|
||||
"GET /api/v1/journal/follow HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nAccept: text/event-stream\r\n\r\n"
|
||||
)
|
||||
.unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let _ = conn.read(&mut buf);
|
||||
let pid = child.id().to_string();
|
||||
assert!(std::process::Command::new("kill")
|
||||
.args(["-TERM", &pid])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success());
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
if let Some(st) = child.try_wait().unwrap() {
|
||||
assert!(st.success(), "exit status {st}");
|
||||
break;
|
||||
}
|
||||
if start.elapsed() > Duration::from_secs(5) {
|
||||
let _ = child.kill();
|
||||
panic!("process did not exit within 5s of SIGTERM");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user