Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
533 lines
16 KiB
Rust
533 lines
16 KiB
Rust
//! Integration tests: the real assembled router on an ephemeral port
|
|
//! with fake sources, plus the real binary for startup and SIGTERM checks.
|
|
|
|
use std::time::Duration;
|
|
|
|
mod common;
|
|
|
|
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 {
|
|
state_db: Option<sqlx::SqlitePool>,
|
|
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 state_db = state.db.clone();
|
|
let app = server::build_router(state);
|
|
let join = tokio::spawn(server::serve_listener(
|
|
listener,
|
|
None,
|
|
app,
|
|
shutdown.clone(),
|
|
server::Limits::default(),
|
|
));
|
|
Harness {
|
|
state_db,
|
|
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 req = common::request(method, path, &format!("127.0.0.1:{port}"), headers, body);
|
|
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;
|
|
common::parse_response(&buf)
|
|
}
|
|
|
|
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("\"name\":") && body.contains("active_state"),
|
|
"{body}"
|
|
);
|
|
// /mcp is protected too.
|
|
let (st, _, _) = http(
|
|
h.port,
|
|
"POST",
|
|
"/mcp",
|
|
&[("Content-Type", "application/json")],
|
|
Some("{}"),
|
|
SHORT,
|
|
)
|
|
.await;
|
|
assert_eq!(st, 401);
|
|
// Unmatched paths are 401 without a token too (the auth layer also wraps
|
|
// the fallback, so route existence is not disclosed).
|
|
assert_eq!(get(&h, "/foo", false).await.0, 401);
|
|
assert_eq!(get(&h, "/api/v1/nope", false).await.0, 401);
|
|
assert_eq!(get(&h, "/api/v1/nope", true).await.0, 404);
|
|
let auth = format!("Bearer {}", h.token);
|
|
// POST to a REST route: 401 without a token, 405 with one.
|
|
let (st, _, _) = http(h.port, "POST", "/api/v1/systemd/units", &[], None, SHORT).await;
|
|
assert_eq!(st, 401);
|
|
let (st, _, _) = http(
|
|
h.port,
|
|
"POST",
|
|
"/api/v1/systemd/units",
|
|
&[("Authorization", auth.as_str())],
|
|
None,
|
|
SHORT,
|
|
)
|
|
.await;
|
|
assert_eq!(st, 405);
|
|
// GET and DELETE /mcp without a token.
|
|
assert_eq!(get(&h, "/mcp", false).await.0, 401);
|
|
assert_eq!(
|
|
http(h.port, "DELETE", "/mcp", &[], None, SHORT).await.0,
|
|
401
|
|
);
|
|
// Non-Bearer scheme carrying a valid token string.
|
|
let basic = format!("Basic {}", h.token);
|
|
let (st, _, _) = http(
|
|
h.port,
|
|
"GET",
|
|
"/api/v1/systemd/units",
|
|
&[("Authorization", basic.as_str())],
|
|
None,
|
|
SHORT,
|
|
)
|
|
.await;
|
|
assert_eq!(st, 401);
|
|
h.shutdown.cancel();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn revoked_token_is_rejected() {
|
|
let h = start(true).await;
|
|
assert_eq!(get(&h, "/api/v1/systemd/timers", true).await.0, 200);
|
|
tokens::revoke(h.state_db.as_ref().unwrap(), "test")
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(get(&h, "/api/v1/systemd/timers", true).await.0, 401);
|
|
h.shutdown.cancel();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn host_allowlist_when_auth_disabled() {
|
|
let h = start(false).await;
|
|
assert_eq!(get(&h, "/api/v1/systemd/timers", false).await.0, 200);
|
|
let (st, _, _) = http(
|
|
h.port,
|
|
"GET",
|
|
"/api/v1/systemd/timers",
|
|
&[("Host", "evil.example")],
|
|
None,
|
|
SHORT,
|
|
)
|
|
.await;
|
|
assert_eq!(st, 403);
|
|
h.shutdown.cancel();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn docker_unavailable_does_not_affect_systemd() {
|
|
use skyg_linux_tracker::sources::docker::BollardDocker;
|
|
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 = false;
|
|
config.sources.docker_socket = "/nonexistent/docker.sock".into();
|
|
let mut state = fake_state(config);
|
|
state.docker = std::sync::Arc::new(BollardDocker::new(&state.config, state.shutdown.clone()));
|
|
let shutdown = state.shutdown.clone();
|
|
tokio::spawn(server::serve_listener(
|
|
listener,
|
|
None,
|
|
server::build_router(state),
|
|
shutdown.clone(),
|
|
server::Limits::default(),
|
|
));
|
|
let (st, _, _) = http(port, "GET", "/api/v1/docker/ps", &[], None, SHORT).await;
|
|
assert_eq!(st, 503);
|
|
let (st, _, _) = http(port, "GET", "/api/v1/systemd/units", &[], None, SHORT).await;
|
|
assert_eq!(st, 200);
|
|
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();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn mcp_good_origin_is_accepted() {
|
|
let h = start(true).await;
|
|
let auth = format!("Bearer {}", h.token);
|
|
let origin = format!("http://127.0.0.1:{}", h.port);
|
|
let mut hdrs: Vec<(&str, &str)> = MCP_HEADERS.to_vec();
|
|
hdrs.push(("Authorization", auth.as_str()));
|
|
hdrs.push(("Origin", origin.as_str()));
|
|
let (st, _, _) = http(h.port, "POST", "/mcp", &hdrs, Some(init_body()), SHORT).await;
|
|
assert_eq!(st, 200);
|
|
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_clear()
|
|
.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()])
|
|
.env_clear()
|
|
.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));
|
|
}
|
|
}
|
|
|
|
/// Real binary: an open MCP session with an in-flight `tail_journal` call
|
|
/// (60s requested) must not stop SIGTERM from exiting 0 within the bound.
|
|
#[test]
|
|
fn sigterm_with_inflight_mcp_tail_exits_within_bound() {
|
|
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()])
|
|
.env_clear()
|
|
.stderr(std::process::Stdio::null())
|
|
.spawn()
|
|
.unwrap();
|
|
let post = |body: &str, sid: Option<&str>, read_resp: bool| -> (StdStream, String) {
|
|
let mut c = None;
|
|
for _ in 0..50 {
|
|
if let Ok(s) = StdStream::connect(("127.0.0.1", port)) {
|
|
c = Some(s);
|
|
break;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
let mut c = c.expect("server did not start");
|
|
c.set_read_timeout(Some(Duration::from_millis(1500)))
|
|
.unwrap();
|
|
let sid_h = sid
|
|
.map(|s| format!("Mcp-Session-Id: {s}\r\n"))
|
|
.unwrap_or_default();
|
|
write!(
|
|
c,
|
|
"POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\n{sid_h}Content-Length: {}\r\n\r\n{body}",
|
|
body.len()
|
|
)
|
|
.unwrap();
|
|
let mut out = Vec::new();
|
|
if read_resp {
|
|
let mut buf = [0u8; 4096];
|
|
while let Ok(n) = c.read(&mut buf) {
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
out.extend_from_slice(&buf[..n]);
|
|
}
|
|
} else {
|
|
let mut buf = [0u8; 512];
|
|
let _ = c.read(&mut buf);
|
|
}
|
|
(c, String::from_utf8_lossy(&out).to_lowercase())
|
|
};
|
|
let (_c1, head) = post(init_body(), None, true);
|
|
let sid = head
|
|
.lines()
|
|
.find_map(|l| l.strip_prefix("mcp-session-id: "))
|
|
.expect("session id")
|
|
.trim()
|
|
.to_owned();
|
|
let _ = post(
|
|
r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
|
|
Some(&sid),
|
|
true,
|
|
);
|
|
let _inflight = post(
|
|
r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"tail_journal","arguments":{"unit":"nonexistent.service","seconds":60}}}"#,
|
|
Some(&sid),
|
|
false,
|
|
);
|
|
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(25) {
|
|
let _ = child.kill();
|
|
panic!("process did not exit within the shutdown bound");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
}
|