From acedb9522e2f50f5c27be783eac6675c7e95ad3d Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Thu, 15 Oct 2026 19:21:53 -0400 Subject: [PATCH 1/2] P3: wire serve end to end, integration tests, unit file, README Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs --- README.md | 145 ++++++++++++ TODO.md | 10 +- devenv.nix | 3 + plan/BOARD.md | 2 +- plan/workstreams/P3-integration.md | 2 + src/lib.rs | 1 + src/main.rs | 61 +++++- src/server.rs | 37 ++++ systemd/skyg-linux-tracker.service | 51 +++++ tests/integration.rs | 341 +++++++++++++++++++++++++++++ 10 files changed, 637 insertions(+), 16 deletions(-) create mode 100644 README.md create mode 100644 src/server.rs create mode 100644 systemd/skyg-linux-tracker.service create mode 100644 tests/integration.rs diff --git a/README.md b/README.md new file mode 100644 index 0000000..2a7e67e --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +# skyg-linux-tracker + +A small, read-only monitor for a single Linux host. One binary, `slinuxm`, serves: + +- a REST API (with Server-Sent Events for follow endpoints), +- an MCP server (Streamable HTTP) so agents can inspect the host, +- optional OpenTelemetry export (metrics and logs over OTLP). + +Data sources are systemd (D-Bus), the journal (libsystemd) and the Docker Engine API (unix socket). Nothing here can start, stop or modify anything. + +## Build + +```sh +devenv shell # toolchain, pkg-config, libsystemd, otelcol-contrib +cargo build --release # target/release/slinuxm +``` + +Without devenv you need a Rust toolchain, `pkg-config` and the libsystemd development files. + +## Install + +```sh +sudo install -m 0755 target/release/slinuxm /usr/local/bin/slinuxm +sudo useradd --system --no-create-home --shell /usr/sbin/nologin skyg +sudo install -m 0644 config.example.toml /etc/skyg-linux-tracker.toml # then edit +sudo install -m 0644 systemd/skyg-linux-tracker.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now skyg-linux-tracker +``` + +The unit runs as the `skyg` user with `SupplementaryGroups=systemd-journal` and a private `StateDirectory` (`/var/lib/skyg-linux-tracker`, mode 0700) holding the token database. Its sandbox options are listed in the unit file. + +### Config + +See `config.example.toml`; every value shown is the default. Precedence, lowest to highest: defaults, config file, `SKYG_*` environment variables (nesting with `__`, for example `SKYG_SERVER__PORT`), CLI flags. `slinuxm --print-config` prints the effective configuration with secrets redacted. + +Startup refuses `auth.enabled = false` on a non-loopback `server.bind`. + +## Tokens + +All `/api/v1/*` and `/mcp` requests need `Authorization: Bearer `. `/healthz` is public. Tokens are stored hashed (sha256) in SQLite, and the plaintext is shown once. + +Run the token CLI **as the service user** so the database keeps the right owner and mode: + +```sh +sudo -u skyg slinuxm token create my-laptop --config /etc/skyg-linux-tracker.toml +sudo -u skyg slinuxm token list --config /etc/skyg-linux-tracker.toml +sudo -u skyg slinuxm token revoke my-laptop --config /etc/skyg-linux-tracker.toml +``` + +Revocation takes effect immediately; no restart is needed. + +## REST + +Base: `http://127.0.0.1:9109`. Errors are `{"error":{"code","message"}}`. + +| Route | Notes | +|---|---| +| `GET /healthz` | public, `{"status":"ok","version":...}` | +| `GET /api/v1/systemd/units?state=failed` | `state` is an active state (`failed`, `active`, ...) | +| `GET /api/v1/systemd/units/{name}` | one unit with details | +| `GET /api/v1/systemd/timers` | | +| `GET /api/v1/journal?unit=&priority=err&lines=100` | priority by name or number | +| `GET /api/v1/journal/follow?unit=&priority=` | SSE, event `journal` | +| `GET /api/v1/docker/ps` | `503` when Docker is unavailable | +| `GET /api/v1/docker/containers/{name}` | | +| `GET /api/v1/docker/containers/{name}/logs?tail=&since=&follow=0\|1` | JSON, or SSE with events `stdout`/`stderr` | + +```sh +TOKEN=slinuxm_... +curl -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:9109/api/v1/systemd/units?state=failed' +curl -N -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:9109/api/v1/journal/follow?priority=err' +``` + +## MCP + +Endpoint: `http://127.0.0.1:9109/mcp` (Streamable HTTP). Eight tools (`list_systemd_units`, `get_systemd_unit`, `list_systemd_timers`, `get_journal_logs`, `tail_journal`, `list_containers`, `get_container`, `get_container_logs`), two prompts (`diagnose_unit`, `container_health_report`) and two resources (`systemd://units/failed`, `docker://containers`). Log content is untrusted data and is labelled as such in tool results. + +Generic client config (header-capable clients): + +```json +{ + "mcpServers": { + "linux-tracker": { + "url": "http://127.0.0.1:9109/mcp", + "headers": { "Authorization": "Bearer slinuxm_..." } + } + } +} +``` + +Claude Code: `claude mcp add --transport http linux-tracker http://127.0.0.1:9109/mcp --header "Authorization: Bearer $TOKEN"`. + +Inspector: `npx @modelcontextprotocol/inspector`, transport Streamable HTTP, add the bearer header. + +Raw handshake with curl: + +```sh +curl -si -X POST http://127.0.0.1:9109/mcp \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -H 'Accept: application/json, text/event-stream' \ + -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' +``` + +### Origin and Host checks + +`/mcp` validates `Origin` and `Host` to defend against DNS rebinding from browsers. Loopback names, `server.bind` and the configured port are accepted by default. Requests without an `Origin` header (non-browser clients) pass this check, so the bearer token remains the real gate. If you bind to `0.0.0.0` or serve behind a name, add the names clients use to `server.allowed_hosts` (for example `["monitor.lan:9109"]`) and any browser origins to `server.allowed_origins`. Terminate TLS in a reverse proxy if the host is reachable beyond a trusted network; the server itself speaks plain HTTP. + +## Docker access + +Reading the Docker socket directly requires group `docker`, which is root-equivalent. The unit file has this commented out. Prefer a read-only socket proxy that allows only `GET /containers/*`, `/events` and `/version`, for example [tecnativa/docker-socket-proxy](https://github.com/Tecnativa/docker-socket-proxy) with `CONTAINERS=1 EVENTS=1 POST=0`, exposed as a unix socket (or loopback TCP through a socat bridge), then: + +```toml +[sources] +docker_socket = "/run/docker-proxy/docker.sock" +``` + +If the socket is missing or unreadable, Docker routes return `503` and everything else keeps working. + +## OpenTelemetry + +```toml +[otel] +enabled = true +endpoint = "http://localhost:4317" # gRPC; or http://localhost:4318 with protocol = "http/protobuf" +export_logs = true +``` + +Metrics are polled every `metrics_interval_secs` (systemd unit active/failed/restarts and timer next elapse; container running/healthy/uptime/restarts). Logs fan out from the journal and from Docker containers. For a local collector with a debug exporter: `devenv up` (runs `otelcol-contrib --config dev/otelcol.yaml`). On SIGTERM pending records are flushed before exit. + +## Verifying a release binary + +```sh +ldd /usr/local/bin/slinuxm # libc, libm, libgcc_s, libsystemd and its dependencies only +``` + +## Development + +```sh +cargo test +cargo clippy --all-targets -- -D warnings +cargo fmt --check +``` + +The integration tests in `tests/` start the real router on an ephemeral port with fake sources. Design notes live in `plan.md` and `plan/`. diff --git a/TODO.md b/TODO.md index e0ff3c9..a53fd6e 100644 --- a/TODO.md +++ b/TODO.md @@ -96,9 +96,9 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) ## Phase 3 — Integration & hardening · [card](plan/workstreams/P3-integration.md) -- [ ] **I1** `main.rs` wiring: protected router (`/api/v1` + `/mcp` + auth) merged with the public `/healthz`, `TraceLayer`, SIGTERM/SIGINT leading to cancel, drain and OTel flush -- [ ] **I2** Automated negative tests (Verification #6) -- [ ] **I3** `systemd/skyg-linux-tracker.service` running `slinuxm serve`: `StateDirectory=`, `ProtectSystem=strict`, `NoNewPrivileges`, `SupplementaryGroups=systemd-journal`, docker group commented (DEC-6) -- [ ] **I4** README: install, config reference, token workflow, MCP client setup, hardened docker option -- [ ] **I5** Release build: `ldd` shows only libc + libsystemd and its deps. Record binary size. +- [x] **I1** `main.rs` wiring: protected router (`/api/v1` + `/mcp` + auth) merged with the public `/healthz`, `TraceLayer`, SIGTERM/SIGINT leading to cancel, drain and OTel flush +- [x] **I2** Automated negative tests (Verification #6) +- [x] **I3** `systemd/skyg-linux-tracker.service` running `slinuxm serve`: `StateDirectory=`, `ProtectSystem=strict`, `NoNewPrivileges`, `SupplementaryGroups=systemd-journal`, docker group commented (DEC-6) +- [x] **I4** README: install, config reference, token workflow, MCP client setup, hardened docker option +- [x] **I5** Release build: `ldd` shows only libc + libsystemd and its deps. Record binary size. - [ ] **I6** Full manual Verification #1–#6 from `plan.md` passes on a real host diff --git a/devenv.nix b/devenv.nix index b32d1d9..732ed50 100644 --- a/devenv.nix +++ b/devenv.nix @@ -13,6 +13,9 @@ languages.rust.enable = true; + # Local OTLP collector with a debug exporter: `devenv up`. + processes.otelcol.exec = "otelcol-contrib --config dev/otelcol.yaml"; + scripts.build.exec = ''cargo build "$@"''; scripts.run.exec = ''cargo run -- "$@"''; scripts.token.exec = ''cargo run -- token "$@"''; diff --git a/plan/BOARD.md b/plan/BOARD.md index 7ef17b0..ef7a940 100644 --- a/plan/BOARD.md +++ b/plan/BOARD.md @@ -53,5 +53,5 @@ Move a card by cutting its row into another column. Keep the card's own **Status |---|---|---| | M0 Skeleton | `slinuxm serve --print-config` works. Clippy and tests are clean. No openssl. | 🟨 in review | | M1 Sources live | All four Phase 1 examples run against a real host | ⬜ | -| M2 Surfaces | Verification #3, #4 and #5 pass | ⬜ | +| M2 Surfaces | Verification #3, #4 and #5 pass | 🟨 #3 and #4 verified live on 2026-10-15; #5 (OTel smoke test) not run, no otelcol-contrib binary | | M3 Release | Verification #1–#6 pass. Unit file and README shipped. | ⬜ | diff --git a/plan/workstreams/P3-integration.md b/plan/workstreams/P3-integration.md index b9bcc20..8f6b732 100644 --- a/plan/workstreams/P3-integration.md +++ b/plan/workstreams/P3-integration.md @@ -57,3 +57,5 @@ Tick these in [`TODO.md`](../../TODO.md). ## Log - 2026-10-15: Card created. +- 2026-10-15: Implemented on `p3/integration`. I1-I5 done; I6 partial. Router assembly lives in `src/server.rs` (`build_router`, `serve_listener`) so tests and `main` share it. Shutdown: signal -> cancel token -> graceful serve ends -> await exporter handles -> `guard.shutdown().await` -> close pool. `token` subcommand does not init telemetry. Unit uses a static `User=skyg` (not DynamicUser) so `sudo -u skyg slinuxm token ...` hits the same DB. I2: 8 tests in `tests/integration.rs` (raw HTTP client, no new deps). Release binary 19 MB; `ldd`: libsystemd, libgcc_s, libm, libc only. +- I6 live results (release binary, loopback, real token via CLI, real systemd/journal/docker on this host): #1 build/tests pass; #2 serve + token create pass; #3 REST incl. `curl -N` journal SSE pass (docker log follow SSE not exercised live); #4 MCP initialize, tools/list, prompts/list, resources/list, 5 tool calls, no-token 401, bad Origin 403 pass via curl (MCP Inspector not run; not all 8 tools called); #5 OTel NOT RUN (otelcol-contrib not on PATH, devenv shell not started via `devenv up`); #6 pass via tests (401, auth-off+0.0.0.0 refuses, SIGTERM with open SSE exits 0 in <1s); missing-docker-socket 503 covered by WS-E fake test, not live. Unit file not installed on a clean host (only `systemd-analyze verify`, which cannot fully run here). diff --git a/src/lib.rs b/src/lib.rs index 696e188..a1693f2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod config; pub mod db; pub mod error; pub mod mcp; +pub mod server; pub mod sources; pub mod state; pub mod telemetry; diff --git a/src/main.rs b/src/main.rs index 6c8214a..d4c8bce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,15 +1,18 @@ //! `slinuxm` entry point: parse CLI, load layered config, dispatch. -//! -//! Phase 3 (I1) replaces the body of `serve` with the real wiring. use std::net::IpAddr; use std::path::PathBuf; -use anyhow::{bail, Context, Result}; +use std::net::SocketAddr; + +use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; +use tokio_util::sync::CancellationToken; use skyg_linux_tracker::auth::tokens::{self, TokenCmd}; use skyg_linux_tracker::config::{CliOverrides, Config}; +use skyg_linux_tracker::state::AppState; +use skyg_linux_tracker::{db, server, telemetry}; #[derive(Debug, Parser)] #[command(name = "slinuxm", version, about = "Read-only Linux system monitor")] @@ -97,11 +100,49 @@ async fn main() -> Result<()> { } async fn serve(config: Config) -> Result<()> { - // Phase 3 (I1): telemetry::init, db::open, AppState::live, router wiring, - // graceful shutdown. Until then, config validation is all `serve` does. - bail!( - "server wiring is not implemented yet (P3 I1); config is valid, bind = {}:{}", - config.server.bind, - config.server.port - ) + let guard = telemetry::init(&config).context("initialising telemetry")?; + let db = if config.auth.enabled { + Some(db::open(&config).await?) + } else { + tracing::warn!("auth is disabled: all endpoints are open (loopback only)"); + None + }; + let addr = SocketAddr::new(config.server.bind, config.server.port); + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding {addr}"))?; + + let shutdown = CancellationToken::new(); + let state = AppState::live(config, db, shutdown.clone()); + let exporters = telemetry::spawn_exporters(state.clone()); + let pool = state.db.clone(); + let app = server::build_router(state); + + let signal_token = shutdown.clone(); + tokio::spawn(async move { + wait_for_signal().await; + tracing::info!("shutdown signal received"); + signal_token.cancel(); + }); + + let result = server::serve_listener(listener, app, shutdown.clone()).await; + // Reached on signal or server error: stop everything, then flush OTel. + shutdown.cancel(); + for h in exporters { + let _ = h.await; + } + guard.shutdown().await; + if let Some(pool) = pool { + pool.close().await; + } + result +} + +async fn wait_for_signal() { + use tokio::signal::unix::{signal, SignalKind}; + let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler"); + tokio::select! { + _ = term.recv() => {} + _ = tokio::signal::ctrl_c() => {} + } } diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..17d128c --- /dev/null +++ b/src/server.rs @@ -0,0 +1,37 @@ +//! Router assembly and the serve loop (P3). `build_router` is used by both +//! `slinuxm serve` and the integration tests. + +use anyhow::{Context, Result}; +use axum::routing::get; +use axum::Router; +use tokio_util::sync::CancellationToken; +use tower_http::trace::TraceLayer; + +use crate::state::AppState; +use crate::{api, auth, mcp}; + +/// `/healthz` public; `/api/v1/*` and `/mcp` behind the auth layer. +pub fn build_router(state: AppState) -> Router { + let protected = Router::new() + .nest("/api/v1", api::router(state.clone())) + .nest_service("/mcp", mcp::service(state.clone())) + .layer(auth::layer(state)); + Router::new() + .route("/healthz", get(api::healthz)) + .merge(protected) + .layer(TraceLayer::new_for_http()) +} + +/// Serve `app` on `listener` until `shutdown` is cancelled. +pub async fn serve_listener( + listener: tokio::net::TcpListener, + app: Router, + shutdown: CancellationToken, +) -> Result<()> { + let addr = listener.local_addr().context("local_addr")?; + tracing::info!(%addr, "listening"); + axum::serve(listener, app) + .with_graceful_shutdown(async move { shutdown.cancelled().await }) + .await + .context("server error") +} diff --git a/systemd/skyg-linux-tracker.service b/systemd/skyg-linux-tracker.service new file mode 100644 index 0000000..1a66f16 --- /dev/null +++ b/systemd/skyg-linux-tracker.service @@ -0,0 +1,51 @@ +[Unit] +Description=skyg-linux-tracker: read-only systemd, journal and Docker monitor (REST, MCP, OTel) +After=network.target docker.service +Wants=docker.service + +[Service] +Type=simple +ExecStart=/usr/local/bin/slinuxm serve --config /etc/skyg-linux-tracker.toml +Restart=on-failure +RestartSec=5 +TimeoutStopSec=15 + +# Dedicated user, created beforehand: useradd --system --no-create-home \ +# --shell /usr/sbin/nologin skyg +# A static user (not DynamicUser) so `sudo -u skyg slinuxm token ...` can open +# the same token database the service uses. +User=skyg +Group=skyg +# Read the journal. The tracker never writes to it. +SupplementaryGroups=systemd-journal +# WARNING: membership of the docker group is root-equivalent on the host (the +# Docker API can start privileged containers). Prefer pointing +# sources.docker_socket at a read-only socket proxy (see README) and leave this +# commented out. Uncomment only if you accept that risk (DEC-6). +#SupplementaryGroups=docker + +# /var/lib/skyg-linux-tracker, owned by the service user, mode 0700. +StateDirectory=skyg-linux-tracker +StateDirectoryMode=0700 + +# Hardening +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +ProtectClock=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +RestrictNamespaces=yes +RestrictRealtime=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +SystemCallArchitectures=native +CapabilityBoundingSet= +AmbientCapabilities= + +[Install] +WantedBy=multi-user.target diff --git a/tests/integration.rs b/tests/integration.rs new file mode 100644 index 0000000..17c94b0 --- /dev/null +++ b/tests/integration.rs @@ -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>, +} + +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)); + } +} From 533659dfc14e4087b62772a2a07db74d7e64fb27 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Thu, 15 Oct 2026 19:27:49 -0400 Subject: [PATCH 2/2] P3 review follow-ups: bounded shutdown, unit hardening, host guard, more tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs --- README.md | 9 +- TODO.md | 2 +- plan/workstreams/P3-integration.md | 3 +- src/config.rs | 17 +++ src/main.rs | 35 ++++- src/server.rs | 85 +++++++++++- systemd/skyg-linux-tracker.service | 9 +- tests/integration.rs | 209 ++++++++++++++++++++++++++++- 8 files changed, 355 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 2a7e67e..30d2ae2 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,11 @@ sudo -u skyg slinuxm token revoke my-laptop --config /etc/skyg-linux-tracker.tom Revocation takes effect immediately; no restart is needed. +Notes: + +- `auth.db_path` must stay under the unit's `StateDirectory` (`/var/lib/skyg-linux-tracker`). The unit uses `ProtectSystem=strict`, so any other location needs a matching `ReadWritePaths=`. +- `token create` needs the state directory to exist, so start the service once first (systemd creates it with the right owner), then run the CLI as `skyg`. + ## REST Base: `http://127.0.0.1:9109`. Errors are `{"error":{"code","message"}}`. @@ -104,7 +109,7 @@ curl -si -X POST http://127.0.0.1:9109/mcp \ ### Origin and Host checks -`/mcp` validates `Origin` and `Host` to defend against DNS rebinding from browsers. Loopback names, `server.bind` and the configured port are accepted by default. Requests without an `Origin` header (non-browser clients) pass this check, so the bearer token remains the real gate. If you bind to `0.0.0.0` or serve behind a name, add the names clients use to `server.allowed_hosts` (for example `["monitor.lan:9109"]`) and any browser origins to `server.allowed_origins`. Terminate TLS in a reverse proxy if the host is reachable beyond a trusted network; the server itself speaks plain HTTP. +`/mcp` validates `Origin` and `Host` to defend against DNS rebinding from browsers. Loopback names, `server.bind` and the configured port are accepted by default. Requests without an `Origin` header (non-browser clients) pass this check, so the bearer token remains the real gate. If you bind to `0.0.0.0` or serve behind a name, add the names clients use to `server.allowed_hosts` (for example `["monitor.lan:9109"]`) and any browser origins to `server.allowed_origins`. With `auth.enabled = false` (loopback only), REST requests are checked against a Host allowlist (loopback names, `server.bind` and `server.allowed_hosts`) and get `403` otherwise, to blunt DNS rebinding. There is no Origin check on REST and no token in that mode, so keep auth enabled on any multi-user host. Terminate TLS in a reverse proxy if the host is reachable beyond a trusted network; the server itself speaks plain HTTP. ## Docker access @@ -115,7 +120,7 @@ Reading the Docker socket directly requires group `docker`, which is root-equiva docker_socket = "/run/docker-proxy/docker.sock" ``` -If the socket is missing or unreadable, Docker routes return `503` and everything else keeps working. +A stock install does not add the `docker` group, so out of the box the Docker routes return `503` until you either grant access or configure a proxy. If the socket is missing or unreadable, Docker routes return `503` and everything else keeps working. ## OpenTelemetry diff --git a/TODO.md b/TODO.md index a53fd6e..2276010 100644 --- a/TODO.md +++ b/TODO.md @@ -98,7 +98,7 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) - [x] **I1** `main.rs` wiring: protected router (`/api/v1` + `/mcp` + auth) merged with the public `/healthz`, `TraceLayer`, SIGTERM/SIGINT leading to cancel, drain and OTel flush - [x] **I2** Automated negative tests (Verification #6) -- [x] **I3** `systemd/skyg-linux-tracker.service` running `slinuxm serve`: `StateDirectory=`, `ProtectSystem=strict`, `NoNewPrivileges`, `SupplementaryGroups=systemd-journal`, docker group commented (DEC-6) +- [x] **I3** `systemd/skyg-linux-tracker.service` running `slinuxm serve`: `StateDirectory=`, `ProtectSystem=strict`, `NoNewPrivileges`, `SupplementaryGroups=systemd-journal`, docker group commented (DEC-6) (verified only by systemd-analyze security --offline = 1.5 OK and a `systemd-run --user` run with the same sandbox properties; not installed as a system unit on a clean host) - [x] **I4** README: install, config reference, token workflow, MCP client setup, hardened docker option - [x] **I5** Release build: `ldd` shows only libc + libsystemd and its deps. Record binary size. - [ ] **I6** Full manual Verification #1–#6 from `plan.md` passes on a real host diff --git a/plan/workstreams/P3-integration.md b/plan/workstreams/P3-integration.md index 8f6b732..6cf88ef 100644 --- a/plan/workstreams/P3-integration.md +++ b/plan/workstreams/P3-integration.md @@ -2,7 +2,7 @@ | Field | Value | |---|---| -| Status | Backlog | +| Status | Review | | Owner | — | | Phase | 3 (single track) | | Depends on | WS-E, WS-F, WS-G (and transitively A–D) | @@ -59,3 +59,4 @@ Tick these in [`TODO.md`](../../TODO.md). - 2026-10-15: Card created. - 2026-10-15: Implemented on `p3/integration`. I1-I5 done; I6 partial. Router assembly lives in `src/server.rs` (`build_router`, `serve_listener`) so tests and `main` share it. Shutdown: signal -> cancel token -> graceful serve ends -> await exporter handles -> `guard.shutdown().await` -> close pool. `token` subcommand does not init telemetry. Unit uses a static `User=skyg` (not DynamicUser) so `sudo -u skyg slinuxm token ...` hits the same DB. I2: 8 tests in `tests/integration.rs` (raw HTTP client, no new deps). Release binary 19 MB; `ldd`: libsystemd, libgcc_s, libm, libc only. - I6 live results (release binary, loopback, real token via CLI, real systemd/journal/docker on this host): #1 build/tests pass; #2 serve + token create pass; #3 REST incl. `curl -N` journal SSE pass (docker log follow SSE not exercised live); #4 MCP initialize, tools/list, prompts/list, resources/list, 5 tool calls, no-token 401, bad Origin 403 pass via curl (MCP Inspector not run; not all 8 tools called); #5 OTel NOT RUN (otelcol-contrib not on PATH, devenv shell not started via `devenv up`); #6 pass via tests (401, auth-off+0.0.0.0 refuses, SIGTERM with open SSE exits 0 in <1s); missing-docker-socket 503 covered by WS-E fake test, not live. Unit file not installed on a clean host (only `systemd-analyze verify`, which cannot fully run here). +- 2026-10-15: Review follow-ups applied. Shutdown drain and exporter awaits are bounded (10s each) and the unit uses TimeoutStopSec=30; new test: SIGTERM with an open MCP session and an in-flight 60s `tail_journal` exits 0. Unit: SystemCallFilter, ProtectProc=invisible, ProcSubset=pid, RestrictSUIDSGID, UMask=0077; docker.service is `After=` only. Hardening was run via `systemd-run --user` with the same sandbox properties (REST systemd/journal/docker and SIGTERM all worked); not run as a system unit with User=skyg/StateDirectory. Host allowlist guard on `/api/v1` when auth is disabled (test). `server.port = 0` rejected (test). Integration tests extended (13 tests): unmatched paths (401 with auth on, route existence not disclosed), POST 401/405, GET/DELETE /mcp without token, revoked token, Basic scheme, good Origin, missing docker socket (503 vs 200). SIGTERM tests use env_clear; the pick-port-then-drop race remains (port 0 is now rejected by config). diff --git a/src/config.rs b/src/config.rs index 6e1c7c2..69611a5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -249,6 +249,11 @@ impl Config { /// Cross-field validation. pub fn validate(&self) -> Result<(), ConfigError> { + if self.server.port == 0 { + return Err(ConfigError::Invalid( + "server.port must be greater than zero".into(), + )); + } if !self.auth.enabled && !self.server.bind.is_loopback() { return Err(ConfigError::Invalid(format!( "auth.enabled = false is only allowed on a loopback bind address (server.bind = {})", @@ -291,6 +296,18 @@ mod tests { Config::load(file.map(Path::new), cli) } + #[test] + fn port_zero_rejected() { + Jail::expect_with(|_| { + let cli = CliOverrides { + port: Some(0), + ..Default::default() + }; + assert!(load(None, &cli).is_err()); + Ok(()) + }); + } + #[test] fn defaults_only() { Jail::expect_with(|_| { diff --git a/src/main.rs b/src/main.rs index d4c8bce..a155782 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,6 +99,11 @@ async fn main() -> Result<()> { } } +/// Upper bounds for shutdown phases (the OTel flush adds up to 5s per +/// provider, so the unit uses TimeoutStopSec=30). +const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +const EXPORTER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + async fn serve(config: Config) -> Result<()> { let guard = telemetry::init(&config).context("initialising telemetry")?; let db = if config.auth.enabled { @@ -125,11 +130,35 @@ async fn serve(config: Config) -> Result<()> { signal_token.cancel(); }); - let result = server::serve_listener(listener, app, shutdown.clone()).await; + // `serve_listener` returns once the shutdown token fires and connections + // drain. If the token has not fired it is a server error, so return + // immediately. Bound the drain so a stuck client cannot hang SIGTERM. + let serving = server::serve_listener(listener, app, shutdown.clone()); + tokio::pin!(serving); + let result = tokio::select! { + r = &mut serving => r, + _ = shutdown.cancelled() => { + match tokio::time::timeout(DRAIN_TIMEOUT, &mut serving).await { + Ok(r) => r, + Err(_) => { + tracing::warn!("graceful drain timed out; closing remaining connections"); + Ok(()) + } + } + } + }; // Reached on signal or server error: stop everything, then flush OTel. shutdown.cancel(); - for h in exporters { - let _ = h.await; + let join_all = async { + for h in exporters { + let _ = h.await; + } + }; + if tokio::time::timeout(EXPORTER_TIMEOUT, join_all) + .await + .is_err() + { + tracing::warn!("exporter tasks did not stop in time"); } guard.shutdown().await; if let Some(pool) = pool { diff --git a/src/server.rs b/src/server.rs index 17d128c..7948250 100644 --- a/src/server.rs +++ b/src/server.rs @@ -7,13 +7,33 @@ use axum::Router; use tokio_util::sync::CancellationToken; use tower_http::trace::TraceLayer; +use std::sync::Arc; + +use axum::extract::{Request, State}; +use axum::http::{header, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use axum::Json; + +use crate::config::Config; use crate::state::AppState; use crate::{api, auth, mcp}; /// `/healthz` public; `/api/v1/*` and `/mcp` behind the auth layer. pub fn build_router(state: AppState) -> Router { + // With auth off there is no bearer gate, so guard REST against DNS + // rebinding with a Host allowlist (MCP has its own check). + let rest = api::router(state.clone()); + let rest = if state.config.auth.enabled { + rest + } else { + rest.layer(axum::middleware::from_fn_with_state( + allowed_hosts(&state.config), + host_guard, + )) + }; let protected = Router::new() - .nest("/api/v1", api::router(state.clone())) + .nest("/api/v1", rest) .nest_service("/mcp", mcp::service(state.clone())) .layer(auth::layer(state)); Router::new() @@ -35,3 +55,66 @@ pub async fn serve_listener( .await .context("server error") } + +fn allowed_hosts(c: &Config) -> Arc> { + let mut v: Vec = ["localhost", "127.0.0.1", "::1"] + .into_iter() + .map(String::from) + .collect(); + if !c.server.bind.is_unspecified() { + v.push(c.server.bind.to_string()); + } + v.extend( + c.server + .allowed_hosts + .iter() + .map(|h| host_only(h).to_owned()), + ); + Arc::new(v) +} + +/// Strip an optional port and IPv6 brackets: `[::1]:9109` -> `::1`. +fn host_only(h: &str) -> &str { + let h = h.trim(); + if let Some(rest) = h.strip_prefix('[') { + return rest.split(']').next().unwrap_or(rest); + } + match h.rsplit_once(':') { + Some((host, port)) if !host.contains(':') && port.chars().all(|c| c.is_ascii_digit()) => { + host + } + _ => h, + } +} + +async fn host_guard(State(allowed): State>>, req: Request, next: Next) -> Response { + let host = req + .headers() + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .map(host_only); + match host { + Some(h) if !allowed.iter().any(|a| a.eq_ignore_ascii_case(h)) => ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({"error": { + "code": "forbidden_host", + "message": "Host header not allowed; add it to server.allowed_hosts", + }})), + ) + .into_response(), + _ => next.run(req).await, + } +} + +#[cfg(test)] +mod tests { + use super::host_only; + + #[test] + fn host_parsing() { + assert_eq!(host_only("localhost:9109"), "localhost"); + assert_eq!(host_only("[::1]:9109"), "::1"); + assert_eq!(host_only("::1"), "::1"); + assert_eq!(host_only("10.0.0.5"), "10.0.0.5"); + } +} diff --git a/systemd/skyg-linux-tracker.service b/systemd/skyg-linux-tracker.service index 1a66f16..098e0ce 100644 --- a/systemd/skyg-linux-tracker.service +++ b/systemd/skyg-linux-tracker.service @@ -1,14 +1,13 @@ [Unit] Description=skyg-linux-tracker: read-only systemd, journal and Docker monitor (REST, MCP, OTel) After=network.target docker.service -Wants=docker.service [Service] Type=simple ExecStart=/usr/local/bin/slinuxm serve --config /etc/skyg-linux-tracker.toml Restart=on-failure RestartSec=5 -TimeoutStopSec=15 +TimeoutStopSec=30 # Dedicated user, created beforehand: useradd --system --no-create-home \ # --shell /usr/sbin/nologin skyg @@ -44,6 +43,12 @@ RestrictRealtime=yes LockPersonality=yes MemoryDenyWriteExecute=yes SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources +ProtectProc=invisible +ProcSubset=pid +RestrictSUIDSGID=yes +UMask=0077 CapabilityBoundingSet= AmbientCapabilities= diff --git a/tests/integration.rs b/tests/integration.rs index 17c94b0..65c06d6 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -13,6 +13,7 @@ use tokio::net::{TcpListener, TcpStream}; use tokio_util::sync::CancellationToken; struct Harness { + state_db: Option, 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)); + } +}