diff --git a/TODO.md b/TODO.md index 6c1fcf5..791666a 100644 --- a/TODO.md +++ b/TODO.md @@ -71,7 +71,7 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) - [x] **E5** `GET /docker/ps`, `/docker/containers/{name}`, `/docker/containers/{name}/logs` (JSON, or SSE with `follow=1`) - [x] **E6** `GET /healthz` on the public router - [x] **E7** Consistent JSON error body from `AppError` -- [x] **E8** Handler tests against fake sources (`tower::ServiceExt::oneshot`) +- [x] **E8** Handler tests against fake sources (`tower::ServiceExt::oneshot`). Name/state validation is tested via a validating stub, not the fakes. - [x] **E9** Docker unavailable returns 503 on docker routes only ### WS-F MCP · [card](plan/workstreams/WS-F-mcp.md) diff --git a/src/api/behaviour_tests.rs b/src/api/behaviour_tests.rs new file mode 100644 index 0000000..3a5837e --- /dev/null +++ b/src/api/behaviour_tests.rs @@ -0,0 +1,229 @@ +//! Cross-cutting API tests: SSE lifecycle, 405 shape, name validation. + +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use axum::body::{to_bytes, Body}; +use axum::http::{Request, StatusCode}; +use tokio::sync::{mpsc, Notify}; +use tokio_util::sync::CancellationToken; +use tower::ServiceExt; + +use super::router; +use super::testutil::{get, json}; +use crate::config::Config; +use crate::error::AppError; +use crate::sources::fake::fake_state; +use crate::sources::{ + ContainerStatus, ContainerSummary, DockerSource, JournalEntry, JournalQuery, JournalSource, + LogLine, LogOptions, SystemdSource, TimerInfo, UnitStatus, UnitSummary, +}; + +/// Journal source whose producer sends one entry and then never closes, +/// signalling `closed` when the receiver is dropped. +struct Endless { + closed: Arc, +} + +#[async_trait] +impl JournalSource for Endless { + async fn query(&self, _: &JournalQuery) -> Result, AppError> { + Ok(vec![]) + } + async fn follow(&self, _: &JournalQuery) -> Result, AppError> { + let (tx, rx) = mpsc::channel(4); + let closed = self.closed.clone(); + tokio::spawn(async move { + let e = JournalEntry { + timestamp: "2026-10-15T08:00:00Z".parse().unwrap(), + priority: None, + unit: None, + identifier: None, + pid: None, + hostname: None, + message: "one".into(), + cursor: None, + }; + let _ = tx.send(e).await; + tx.closed().await; + closed.notify_one(); + }); + Ok(rx) + } +} + +fn endless_app(max_secs: u64) -> (axum::Router, Arc, CancellationToken) { + let mut cfg = Config::default(); + cfg.limits.max_follow_secs = max_secs; + let mut st = fake_state(cfg); + let closed = Arc::new(Notify::new()); + st.journal = Arc::new(Endless { + closed: closed.clone(), + }); + let token = st.shutdown.clone(); + (router(st), closed, token) +} + +async fn follow_body(app: &axum::Router) -> String { + let (s, b) = tokio::time::timeout(Duration::from_secs(5), get(app, "/journal/follow")) + .await + .expect("stream must end"); + assert_eq!(s, StatusCode::OK); + b +} + +#[tokio::test] +async fn sse_ends_on_shutdown_with_end_frame() { + let (app, _, token) = endless_app(60); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(150)).await; + token.cancel(); + }); + let b = follow_body(&app).await; + assert!(b.contains("event: journal"), "{b}"); + assert!(b.contains("event: end\ndata: shutdown"), "{b}"); +} + +#[tokio::test] +async fn sse_ends_at_deadline() { + let (app, _, _t) = endless_app(1); + let start = std::time::Instant::now(); + let b = follow_body(&app).await; + assert!(start.elapsed() >= Duration::from_millis(900)); + assert!(b.contains("event: end\ndata: deadline"), "{b}"); +} + +#[tokio::test] +async fn dropping_body_drops_receiver() { + let (app, closed, _t) = endless_app(60); + let resp = app + .oneshot(Request::get("/journal/follow").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + drop(resp); + tokio::time::timeout(Duration::from_secs(5), closed.notified()) + .await + .expect("producer must observe receiver drop"); +} + +#[tokio::test] +async fn wrong_method_is_json_405() { + let app = router(fake_state(Config::default())); + for m in ["POST", "PUT"] { + let resp = app + .clone() + .oneshot( + Request::builder() + .method(m) + .uri("/systemd/units") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); + let b = to_bytes(resp.into_body(), usize::MAX).await.unwrap(); + let v = json(std::str::from_utf8(&b).unwrap()); + assert_eq!(v["error"]["code"], "method_not_allowed"); + } +} + +/// Stub that validates names and states like the real sources do. The fakes +/// do not validate; real validation is covered by the source unit tests +/// (WS-A/B/C). These tests prove the handlers surface the source's 400 and +/// that percent-encoded `/` and `;` reach the source intact. +struct Strict; + +fn ok_name(n: &str) -> Result<(), AppError> { + let ok = !n.is_empty() + && n.chars() + .all(|c| c.is_ascii_alphanumeric() || "._-@:".contains(c)) + && n != ".."; + if ok { + Ok(()) + } else { + Err(AppError::BadRequest(format!("invalid name '{n}'"))) + } +} + +#[async_trait] +impl SystemdSource for Strict { + async fn list_units(&self, state: Option<&str>) -> Result, AppError> { + match state { + None | Some("active" | "inactive" | "failed") => Ok(vec![]), + Some(s) => Err(AppError::BadRequest(format!("unknown state '{s}'"))), + } + } + async fn list_timers(&self) -> Result, AppError> { + Ok(vec![]) + } + async fn unit_status(&self, name: &str) -> Result { + ok_name(name)?; + Err(AppError::NotFound(name.into())) + } +} + +#[async_trait] +impl JournalSource for Strict { + async fn query(&self, q: &JournalQuery) -> Result, AppError> { + if let Some(u) = &q.unit { + ok_name(u)?; + } + Ok(vec![]) + } + async fn follow(&self, q: &JournalQuery) -> Result, AppError> { + self.query(q).await?; + Ok(mpsc::channel(1).1) + } +} + +#[async_trait] +impl DockerSource for Strict { + async fn ps(&self, _: bool) -> Result, AppError> { + Ok(vec![]) + } + async fn container_status(&self, name: &str) -> Result { + ok_name(name)?; + Err(AppError::NotFound(name.into())) + } + async fn logs(&self, name: &str, _: &LogOptions) -> Result, AppError> { + ok_name(name)?; + Ok(vec![]) + } + async fn follow_logs( + &self, + name: &str, + _: &LogOptions, + ) -> Result, AppError> { + ok_name(name)?; + Ok(mpsc::channel(1).1) + } +} + +#[tokio::test] +async fn invalid_names_and_state_are_400() { + let mut st = fake_state(Config::default()); + st.systemd = Arc::new(Strict); + st.journal = Arc::new(Strict); + st.docker = Arc::new(Strict); + let app = router(st); + for u in [ + "/systemd/units?state=bogus", + "/systemd/units/a%3Bb.service", + "/systemd/units/..", + "/journal?unit=../x", + "/journal/follow?unit=a;b", + "/docker/containers/a%3Bb", + "/docker/containers/a%2Fb", + "/docker/containers/a%3Bb/logs", + "/docker/containers/a%2Fb/logs?follow=1", + ] { + let (s, b) = get(&app, u).await; + assert_eq!(s, StatusCode::BAD_REQUEST, "{u}: {b}"); + assert_eq!(json(&b)["error"]["code"], "bad_request"); + } + let (s, _) = get(&app, "/docker/containers/ok").await; + assert_eq!(s, StatusCode::NOT_FOUND); +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 8bac050..3fe2c0e 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -5,6 +5,8 @@ //! Handlers are thin: parse, call the source, serialize. All errors render //! through `AppError` as `{"error":{"code","message"}}`. +#[cfg(test)] +mod behaviour_tests; pub mod docker; pub mod journal; pub mod systemd; @@ -31,6 +33,7 @@ pub fn router(state: AppState) -> Router { .merge(journal::routes()) .merge(docker::routes()) .fallback(not_found) + .method_not_allowed_fallback(method_not_allowed) .with_state(state) } @@ -47,6 +50,21 @@ pub async fn not_found() -> AppError { AppError::NotFound("no such route".into()) } +/// 405 in the common error shape (`AppError` has no 405 variant, so this +/// renders the same JSON body with the right status). +pub async fn method_not_allowed() -> axum::response::Response { + use axum::http::StatusCode; + use axum::response::IntoResponse; + ( + StatusCode::METHOD_NOT_ALLOWED, + Json(serde_json::json!({"error": { + "code": "method_not_allowed", + "message": "method not allowed", + }})), + ) + .into_response() +} + /// Query extraction that reports failures as `AppError::BadRequest`. pub(crate) fn query( q: Result, QueryRejection>, @@ -66,14 +84,28 @@ pub(crate) fn sse_from( to_event: fn(&T) -> Event, ) -> Sse>> { let deadline = tokio::time::Instant::now() + Duration::from_secs(max_secs); - let stream = futures::stream::unfold((rx, shutdown), move |(mut rx, shutdown)| async move { - let item = tokio::select! { - () = shutdown.cancelled() => None, - () = tokio::time::sleep_until(deadline) => None, - item = rx.recv() => item, - }?; - Some((Ok(to_event(&item)), (rx, shutdown))) - }); + let stream = futures::stream::unfold( + (rx, shutdown, false), + move |(mut rx, shutdown, done)| async move { + if done { + return None; + } + // `Err(reason)` ends the stream with a final `event: end` frame + // so clients can tell a server-side cutoff from a failure. + let next: Result = tokio::select! { + () = shutdown.cancelled() => Err("shutdown"), + () = tokio::time::sleep_until(deadline) => Err("deadline"), + item = rx.recv() => item.ok_or("closed"), + }; + match next { + Ok(item) => Some((Ok(to_event(&item)), (rx, shutdown, false))), + Err(reason) => { + let ev = Event::default().event("end").data(reason); + Some((Ok(ev), (rx, shutdown, true))) + } + } + }, + ); Sse::new(stream).keep_alive(KeepAlive::default()) }