153 lines
5.3 KiB
Rust
153 lines
5.3 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::config::Config;
|
|
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 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 (`server.rs`: `/healthz`).
|
|
fn server_route_literals() -> Vec<String> {
|
|
let source = fs::read_to_string(Path::new(MANIFEST).join("src/server.rs")).unwrap();
|
|
route_literals(&source)
|
|
}
|
|
|
|
/// 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})");
|
|
}
|
|
}
|
|
|
|
#[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());
|
|
}
|