Require the child's own listening line for the probed port before it is signalled; a 200 from /healthz proves liveness only, since another slinuxm answers it too. Retry a lost bind race instead of signalling a dead child, and add a squatter that answers 200.
703 lines
23 KiB
Rust
703 lines
23 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() {
|
|
// The port is probed before the child binds it, so a stranger can take it
|
|
// first. Identity, not liveness, decides whether to signal: see
|
|
// `spawn_listening`.
|
|
let mut started = false;
|
|
for _ in 0..3 {
|
|
if sse_stream_then_sigterm() {
|
|
started = true;
|
|
break;
|
|
}
|
|
}
|
|
assert!(started, "server did not stay up on any of three ports");
|
|
}
|
|
|
|
const STARTUP_BOUND: Duration = Duration::from_secs(10);
|
|
|
|
/// Signals the child and waits for a successful exit. Anything still running
|
|
/// after `bound` is killed and the test fails with `panic_msg`.
|
|
fn sigterm_and_wait(child: &mut std::process::Child, bound: Duration, panic_msg: &str) {
|
|
if let Some(st) = child.try_wait().unwrap() {
|
|
panic!("server exited before SIGTERM: {st}");
|
|
}
|
|
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}");
|
|
return;
|
|
}
|
|
if start.elapsed() > bound {
|
|
let _ = child.kill();
|
|
panic!("{panic_msg}");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
}
|
|
|
|
fn free_port() -> u16 {
|
|
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
l.local_addr().unwrap().port()
|
|
}
|
|
|
|
/// A child whose own startup line says it listens on `127.0.0.1:port`, or
|
|
/// `None` when the child exited before binding, which happens when another
|
|
/// process holds the probed port.
|
|
///
|
|
/// A 200 from `/healthz` proves nothing: another `slinuxm` (or any squatter)
|
|
/// answers it too. The child's stderr is the only statement about which socket
|
|
/// is its own; once it listens there, nothing else can hold the port, so a
|
|
/// later SIGTERM cannot reach the wrong process.
|
|
fn spawn_listening(port: u16) -> Option<std::process::Child> {
|
|
use std::io::{BufRead, BufReader};
|
|
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::piped())
|
|
.spawn()
|
|
.unwrap();
|
|
let stderr = child.stderr.take().unwrap();
|
|
let (tx, rx) = std::sync::mpsc::channel::<String>();
|
|
// The pipe is drained for the child's lifetime: a full buffer would block it.
|
|
let reader = std::thread::spawn(move || {
|
|
for line in BufReader::new(stderr).lines().map_while(Result::ok) {
|
|
if tx.send(line).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
let found = |rx: &std::sync::mpsc::Receiver<String>| {
|
|
rx.try_iter().any(|line| logs_listening(&line, port))
|
|
};
|
|
let deadline = std::time::Instant::now() + STARTUP_BOUND;
|
|
loop {
|
|
if found(&rx) {
|
|
return Some(child);
|
|
}
|
|
if child.try_wait().unwrap().is_some() {
|
|
// Read what is left before calling it a lost race.
|
|
let _ = reader.join();
|
|
return found(&rx).then_some(child);
|
|
}
|
|
if std::time::Instant::now() > deadline {
|
|
let _ = child.kill();
|
|
let _ = child.wait();
|
|
panic!("server never logged listening on 127.0.0.1:{port}");
|
|
}
|
|
std::thread::sleep(Duration::from_millis(25));
|
|
}
|
|
}
|
|
|
|
/// The startup record: `listening addr=127.0.0.1:<port> tls=false`.
|
|
fn logs_listening(line: &str, port: u16) -> bool {
|
|
let line = without_ansi(line);
|
|
line.contains("listening")
|
|
&& line
|
|
.split_whitespace()
|
|
.find_map(|w| w.strip_prefix("addr="))
|
|
.and_then(|addr| addr.parse::<std::net::SocketAddr>().ok())
|
|
== Some(std::net::SocketAddr::from(([127, 0, 0, 1], port)))
|
|
}
|
|
|
|
/// The log is written to a pipe, but tracing still colourises it.
|
|
fn without_ansi(line: &str) -> String {
|
|
let mut out = String::with_capacity(line.len());
|
|
let mut rest = line.chars();
|
|
while let Some(c) = rest.next() {
|
|
if c != '\u{1b}' {
|
|
out.push(c);
|
|
continue;
|
|
}
|
|
// CSI: `ESC [ params… final`; the final byte ends the sequence.
|
|
for c in rest.by_ref() {
|
|
if !matches!(c, '[' | '0'..='9' | ';' | ':') {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A running child on a free port, retrying a port a stranger won.
|
|
fn start_listening() -> (std::process::Child, u16) {
|
|
for _ in 0..3 {
|
|
let port = free_port();
|
|
if let Some(child) = spawn_listening(port) {
|
|
return (child, port);
|
|
}
|
|
}
|
|
panic!("server did not start");
|
|
}
|
|
|
|
fn sse_stream_then_sigterm() -> bool {
|
|
sse_stream_then_sigterm_on(free_port())
|
|
}
|
|
|
|
/// One attempt on `port`. `false` means the child exited before it served,
|
|
/// which only happens when the probed port was taken by someone else.
|
|
fn sse_stream_then_sigterm_on(port: u16) -> bool {
|
|
use std::io::{Read, Write};
|
|
use std::net::TcpStream as StdStream;
|
|
|
|
let Some(mut child) = spawn_listening(port) else {
|
|
return false;
|
|
};
|
|
let mut conn = StdStream::connect(("127.0.0.1", port)).unwrap();
|
|
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);
|
|
sigterm_and_wait(
|
|
&mut child,
|
|
Duration::from_secs(10),
|
|
"process did not exit within 10s of SIGTERM",
|
|
);
|
|
true
|
|
}
|
|
|
|
#[test]
|
|
fn only_the_childs_own_listening_line_counts() {
|
|
let line = "\u{1b}[2m2026-10-20T20:22:10.228194Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mskyg_linux_tracker::server\u{1b}[0m\u{1b}[2m:\u{1b}[0m listening \u{1b}[3maddr\u{1b}[0m\u{1b}[2m=\u{1b}[0m127.0.0.1:40001 \u{1b}[3mtls\u{1b}[0m\u{1b}[2m=\u{1b}[0mfalse";
|
|
assert!(logs_listening(line, 40001));
|
|
// A neighbouring port shares the prefix; the address must match whole.
|
|
assert!(!logs_listening(line, 4000));
|
|
assert!(!logs_listening(line, 40002));
|
|
assert!(!logs_listening(
|
|
"listening addr=127.0.0.2:40001 tls=false",
|
|
40001
|
|
));
|
|
assert!(!logs_listening("HTTP/1.1 200 OK", 40001));
|
|
}
|
|
|
|
/// A port held by a listener that answers `/healthz` with 200 is still not
|
|
/// ours: liveness is not identity, so the helper retries instead of
|
|
/// signalling a child that lost the bind and exited.
|
|
#[test]
|
|
fn a_probed_port_held_by_a_lying_squatter_is_retried() {
|
|
use std::io::{Read, Write};
|
|
let squatter = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let port = squatter.local_addr().unwrap().port();
|
|
squatter.set_nonblocking(true).unwrap();
|
|
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
|
let serving = {
|
|
let stop = std::sync::Arc::clone(&stop);
|
|
std::thread::spawn(move || {
|
|
while !stop.load(std::sync::atomic::Ordering::SeqCst) {
|
|
match squatter.accept() {
|
|
Ok((mut sock, _)) => {
|
|
let mut buf = [0u8; 1024];
|
|
let _ = sock.read(&mut buf);
|
|
let _ = sock.write_all(
|
|
b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
|
|
);
|
|
}
|
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
Err(_) => break,
|
|
}
|
|
}
|
|
})
|
|
};
|
|
// The squatter really does hand out 200s, so the helper cannot lean on them.
|
|
assert!(healthz_answers(port));
|
|
assert!(
|
|
!sse_stream_then_sigterm_on(port),
|
|
"a 200-answering squatter must not be taken for our server"
|
|
);
|
|
stop.store(true, std::sync::atomic::Ordering::SeqCst);
|
|
serving.join().unwrap();
|
|
}
|
|
|
|
/// True when `port` answers `/healthz` with a 200. Not proof of identity.
|
|
fn healthz_answers(port: u16) -> bool {
|
|
use std::io::{Read, Write};
|
|
let Ok(mut conn) = std::net::TcpStream::connect(("127.0.0.1", port)) else {
|
|
return false;
|
|
};
|
|
conn.set_read_timeout(Some(Duration::from_millis(500)))
|
|
.unwrap();
|
|
if write!(
|
|
conn,
|
|
"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"
|
|
)
|
|
.is_err()
|
|
{
|
|
return false;
|
|
}
|
|
let mut buf = [0u8; 32];
|
|
match conn.read(&mut buf) {
|
|
Ok(n) => String::from_utf8_lossy(&buf[..n]).starts_with("HTTP/1.1 200"),
|
|
Err(_) => false,
|
|
}
|
|
}
|
|
|
|
/// 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 (mut child, port) = start_listening();
|
|
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,
|
|
);
|
|
sigterm_and_wait(
|
|
&mut child,
|
|
Duration::from_secs(25),
|
|
"process did not exit within the shutdown bound",
|
|
);
|
|
}
|