P3 review follow-ups: bounded shutdown, unit hardening, host guard, more tests
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
acedb9522e
commit
533659dfc1
8 files changed
+355
-14
No files matched your search
+205
-4
@@ -13,6 +13,7 @@ use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
struct Harness {
|
||||
state_db: Option<sqlx::SqlitePool>,
|
||||
port: u16,
|
||||
token: String,
|
||||
shutdown: CancellationToken,
|
||||
@@ -38,9 +39,11 @@ async fn start(auth: bool) -> Harness {
|
||||
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, app, shutdown.clone()));
|
||||
Harness {
|
||||
state_db,
|
||||
port,
|
||||
token,
|
||||
shutdown,
|
||||
@@ -59,8 +62,10 @@ async fn http(
|
||||
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");
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nConnection: close\r\n");
|
||||
if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("host")) {
|
||||
req.push_str(&format!("Host: 127.0.0.1:{port}\r\n"));
|
||||
}
|
||||
for (k, v) in headers {
|
||||
req.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
@@ -128,7 +133,10 @@ async fn auth_and_healthz() {
|
||||
);
|
||||
let (st, _, body) = get(&h, "/api/v1/systemd/units", true).await;
|
||||
assert_eq!(st, 200);
|
||||
assert!(body.contains("ssh") || body.contains(".service"), "{body}");
|
||||
assert!(
|
||||
body.contains("\"name\":") && body.contains("active_state"),
|
||||
"{body}"
|
||||
);
|
||||
// /mcp is protected too.
|
||||
let (st, _, _) = http(
|
||||
h.port,
|
||||
@@ -140,9 +148,98 @@ async fn auth_and_healthz() {
|
||||
)
|
||||
.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,
|
||||
server::build_router(state),
|
||||
shutdown.clone(),
|
||||
));
|
||||
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;
|
||||
@@ -276,11 +373,24 @@ async fn mcp_bad_origin_is_forbidden() {
|
||||
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_remove("SKYG_CONFIG")
|
||||
.env_clear()
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!out.status.success());
|
||||
@@ -299,6 +409,7 @@ fn sigterm_with_open_sse_client_exits_promptly() {
|
||||
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();
|
||||
@@ -339,3 +450,93 @@ fn sigterm_with_open_sse_client_exits_promptly() {
|
||||
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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user