Files
skyg-linux-tracker/tests/openapi.rs
T

292 lines
10 KiB
Rust

//! The generated OpenAPI description against the real router.
//!
//! axum does not expose its route table, so the router side of the drift
//! guard is a scan of the route literals in the source plus one request per
//! documented path: a route that exists but is not documented fails the scan,
//! and a documented path the router does not know fails the request (it gets
//! the fallback's `no such route`).
use std::fs;
use std::path::Path;
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use axum::Router;
use serde_json::Value;
use skyg_linux_tracker::auth::tokens;
use skyg_linux_tracker::config::Config;
use skyg_linux_tracker::mcp::TrackerService;
use skyg_linux_tracker::openapi::{self, document};
use skyg_linux_tracker::peers::testing::{fake_state_with_peers, static_registry};
use skyg_linux_tracker::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus};
use skyg_linux_tracker::server;
use sqlx::sqlite::SqlitePoolOptions;
use tower::ServiceExt;
const MANIFEST: &str = env!("CARGO_MANIFEST_DIR");
/// The router with peer routes mounted, so every documented path is present.
fn app() -> Router {
let status = PeerStatus {
name: PeerName::parse("beta").unwrap(),
enabled: true,
url: "http://beta:1984".into(),
server: ServerStatus::default(),
api: ApiStatus {
auth: AuthState::Unknown,
..Default::default()
},
};
server::build_router(fake_state_with_peers(
Config::default(),
static_registry(vec![status]),
))
}
/// axum spells a wildcard `{*path}`, OpenAPI `{path}`.
fn openapi_path(route: &str) -> String {
route.replace("{*", "{")
}
/// A request that reaches a route, with concrete values for its parameters.
fn sample(path: &str) -> String {
path.replace("{name}", "sshd.service")
.replace("{peer}", "beta")
.replace("{path}", "systemd/units")
}
/// Status and body of one GET through the assembled router.
async fn get(app: &Router, uri: &str) -> (StatusCode, Value) {
let request = Request::get(uri)
.header("host", "127.0.0.1")
.body(Body::empty())
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
let status = response.status();
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
let json = serde_json::from_slice(&body).unwrap_or(Value::Null);
(status, json)
}
/// Route literals under `src/api`, which `server.rs` nests at `/api/v1`.
fn api_route_literals() -> Vec<String> {
let dir = Path::new(MANIFEST).join("src/api");
let mut out = Vec::new();
let mut files: Vec<_> = fs::read_dir(&dir)
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|e| e == "rs"))
.collect();
files.sort();
for file in files {
let source = fs::read_to_string(&file).unwrap();
out.extend(route_literals(&source).into_iter().map(|route| {
assert!(route.starts_with('/'), "{}: {route}", file.display());
format!("/api/v1{route}")
}));
}
out
}
/// Route literals declared outside the API router: `/healthz` and the `/mcp`
/// mount in `server.rs`.
fn server_route_literals() -> Vec<String> {
let source = fs::read_to_string(Path::new(MANIFEST).join("src/server.rs")).unwrap();
let mut out = route_literals(&source);
let mount = ".nest_service(\"/mcp\"";
assert!(source.contains(mount), "server.rs no longer mounts /mcp");
out.push("/mcp".to_owned());
out.sort();
out
}
/// The path argument of every `.route("...")` call. Splitting on the marker
/// keeps this independent of how the call is formatted. Mount points
/// (`.nest`, `.nest_service`) are added by the caller.
fn route_literals(source: &str) -> Vec<String> {
let marker = ".route(\"";
source
.match_indices(marker)
.map(|(index, _)| {
let rest = &source[index + marker.len()..];
let end = rest.find('"').expect("a route literal ends");
rest[..end].to_owned()
})
.collect()
}
#[tokio::test]
async fn every_router_route_is_documented() {
let doc = document(true);
let mut routes = api_route_literals();
routes.extend(server_route_literals());
// A scan that stops matching would make the check below vacuous.
assert!(
routes.len() >= 13,
"route scan found too little: {routes:?}"
);
for route in routes {
let route = openapi_path(&route);
assert!(
doc.paths.paths.contains_key(&route),
"{route} is routed but missing from the OpenAPI document"
);
}
}
#[tokio::test]
async fn every_documented_path_is_routed() {
let doc = document(true);
let app = app();
for path in doc.paths.paths.keys() {
let (status, body) = get(&app, &sample(path)).await;
let fallback = body["error"]["message"] == "no such route";
assert!(!fallback, "{path} is documented but not routed ({status})");
}
}
/// The tools in `x-mcp-tools` are the ones `tools/list` serves in that mode.
#[test]
fn mcp_tools_match_the_tool_router() {
for peers in [false, true] {
let spec = serde_json::to_value(document(peers)).unwrap();
let documented = spec["x-mcp-tools"]["tools"].as_array().unwrap();
let advertised = TrackerService::advertised_tools(peers);
assert_eq!(
documented.len(),
advertised.len(),
"x-mcp-tools has a different number of tools (peers = {peers})"
);
for (entry, tool) in documented.iter().zip(&advertised) {
assert_eq!(
entry["name"],
tool.name.as_ref(),
"tool order or names differ"
);
assert_eq!(
entry["description"],
tool.description.as_deref().unwrap_or_default(),
"{} has a different description",
tool.name
);
assert_eq!(
entry["inputSchema"],
Value::Object((*tool.input_schema).clone()),
"{} has a different input schema",
tool.name
);
}
}
}
/// The tool count is part of the contract: 8 without peers, 10 with them.
#[test]
fn mcp_tool_count_follows_the_peers_flag() {
let names = |peers: bool| -> Vec<String> {
let spec = serde_json::to_value(document(peers)).unwrap();
spec["x-mcp-tools"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool["name"].as_str().unwrap().to_owned())
.collect()
};
let off = names(false);
assert_eq!(off.len(), 8);
assert!(!off
.iter()
.any(|name| name == "list_peers" || name == "get_peer"));
let on = names(true);
assert_eq!(on.len(), 10);
assert!(on.iter().any(|name| name == "list_peers"));
assert!(on.iter().any(|name| name == "get_peer"));
}
#[test]
fn the_spec_is_valid_json_with_the_expected_shape() {
let doc = document(true);
let spec = serde_json::to_value(&doc).unwrap();
assert_eq!(spec["openapi"], "3.1.0");
assert!(spec["info"]["title"].is_string());
assert!(spec["components"]["securitySchemes"][openapi::BEARER_SCHEME].is_object());
assert!(spec["paths"].is_object());
// Peer routes are present in this mode and absent in the other.
assert!(spec["paths"].get("/api/v1/peers").is_some());
let off = serde_json::to_value(document(false)).unwrap();
assert!(off["paths"].get("/api/v1/peers").is_none());
assert!(off["paths"].get("/api/v1/systemd/units").is_some());
}
/// The served document is the generated one, and only a token opens it.
#[tokio::test]
async fn openapi_route_is_authenticated_and_serves_the_document() {
let mut config = Config::default();
config.auth.enabled = true;
let mut state = fake_state_with_peers(config, static_registry(Vec::new()));
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect("sqlite::memory:")
.await
.unwrap();
skyg_linux_tracker::db::migrate(&pool).await.unwrap();
let token = tokens::create(&pool, "openapi-test").await.unwrap();
state.db = Some(pool);
let app = server::build_router(state);
let anonymous = Request::get("/api/v1/openapi.json")
.header("host", "127.0.0.1")
.body(Body::empty())
.unwrap();
let anonymous = app.clone().oneshot(anonymous).await.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let authorized = Request::get("/api/v1/openapi.json")
.header("host", "127.0.0.1")
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let response = app.clone().oneshot(authorized).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok()),
Some("application/json")
);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
let served: Value = serde_json::from_slice(&body).unwrap();
// This router has a registry, so the served document is the peer one.
assert_eq!(served, serde_json::to_value(&*document(true)).unwrap());
assert!(served["paths"].get("/api/v1/peers").is_some());
}
/// `slinuxm openapi` prints the same document the route serves, without a
/// config file: the server is never started and no token is read.
#[test]
fn cli_prints_the_same_document_offline() {
let run = |args: &[&str]| -> Value {
let output = std::process::Command::new(env!("CARGO_BIN_EXE_slinuxm"))
.args(args)
.arg("--config")
.arg("/nonexistent/slinuxm-openapi.toml")
.output()
.expect("the slinuxm binary runs");
assert!(
output.status.success(),
"slinuxm {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("the output is JSON")
};
for (peers, extra) in [(false, None), (true, Some("--peers"))] {
let args: Vec<&str> = ["openapi"].into_iter().chain(extra).collect();
let printed = run(&args);
assert_eq!(
printed,
serde_json::to_value(&*document(peers)).unwrap(),
"the CLI and the served route must share one generation"
);
}
}