G: G3 Serving and CLI serve the spec behind auth and print it offline

This commit is contained in:
ari committed 2026-10-20 15:54:13 -04:00
1 parent 7078ed15b1
commit 869b6818e9
7 files changed
+192 -12

No files matched your search

+4
View File
@@ -33,3 +33,7 @@ Reuse existing DTOs, do not duplicate types for the doc. Read-only, no secrets i
- 2026-10-20: **G2 MCP description.** MCP is JSON-RPC, so it is documented as one operation `POST /mcp` (declared on a doc-only `mcp_endpoint()` in `src/openapi.rs`; the real handler is rmcp's `StreamableHttpService`, which has no axum handler fn to annotate) with the request body, the `application/json` + `text/event-stream` response, and the 400/401/403/404/406/415 codes rmcp and the auth layer really return. `x-mcp-tools` is generated from the tool router itself: `TrackerService::advertised_tools(peers)` builds the same `ToolRouter` that `TrackerService::new` stores (extracted into `router_for`, so there is one place that applies the peer gating) and returns `name`, `description` and `input_schema` for every tool, sorted, so the extension cannot drift from `tools/list`. Tool count stays 8 without peers and 10 with them; the existing peers-off snapshot test is untouched and still passes.
Tests: `mcp_endpoint_is_documented_in_both_modes` and `mcp_extension_lists_tools_sorted_with_schemas` in `src/openapi.rs`; `mcp_tools_match_the_tool_router` (every entry equal to the router's name/description/input schema, both modes), `mcp_tool_count_follows_the_peers_flag` and the `/mcp` mount added to the route scan in `tests/openapi.rs`. `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` and `cargo test` green.
- 2026-10-20: **G3 Serving and CLI.** `document(peers)` now returns a cached `Arc<OpenApi>` (one `OnceLock` per mode; generation walks every DTO and the whole tool router, and the result cannot change while the process runs), with `build`/`to_pretty_json` behind it so one function is shared by every consumer. `GET /api/v1/openapi.json` is mounted in `api::router`, i.e. under `/api/v1` and therefore behind the existing auth layer; no new public route, no change to `server::build_router` or `/healthz`. It serves the mode of the running instance (`state.peers.is_some()`), so a peer-less instance advertises no peer paths. New `slinuxm openapi [--peers]` (`src/cli.rs`, `Command::Openapi`) prints the pretty document; `main` returns before `Config::load`, so it needs no config file, no token file and no socket and cannot start a server or bind a port. `--print-config` still wins if combined. The `peers::cli` import in `main.rs` is now aliased to `peer_cli` because `cli` is the new module.
Tests: `render_is_valid_json_for_both_modes`, `generation_is_deterministic` (bytes, not just values, because the committed file is compared) in the unit tests; `openapi_route_is_authenticated_and_serves_the_document` (401 without a token, 200 with one, body equals the generated peers-on document, `application/json`) and `cli_prints_the_same_document_offline` (real binary, `--config /nonexistent/...`, both modes, output equals the generated document) in `tests/openapi.rs`.
+26 -3
View File
@@ -17,17 +17,19 @@ use std::convert::Infallible;
use std::time::Duration;
use axum::extract::rejection::QueryRejection;
use axum::extract::Query;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::routing::get;
use axum::{Json, Router};
use futures::Stream;
use serde::de::DeserializeOwned;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use utoipa::openapi::OpenApi;
use crate::error::{error_response, AppError};
use crate::openapi::Health;
use crate::openapi::{self, ErrorBody, Health};
use crate::state::AppState;
/// Routes under `/api/v1`, already bound to `state`.
@@ -36,7 +38,8 @@ pub fn router(state: AppState) -> Router {
.merge(systemd::routes())
.merge(journal::routes())
.merge(docker::routes())
.merge(ping::routes());
.merge(ping::routes())
.route("/openapi.json", get(openapi_json));
// Peer routes are absent entirely when the feature is off.
let router = if state.peers.is_some() {
router.merge(peers::routes())
@@ -68,6 +71,26 @@ pub async fn healthz() -> Json<serde_json::Value> {
}))
}
/// The generated description of this instance, behind the normal auth: it
/// names every route, so it is not public like `/healthz`.
#[utoipa::path(
get,
path = "/api/v1/openapi.json",
operation_id = "get_openapi",
tag = "meta",
summary = "This OpenAPI document",
description = "The description of this instance as served. Peer routes and the peer MCP \
tools appear only when `[peers] enabled = true`; `slinuxm openapi` prints \
the same document offline.",
responses(
(status = 200, body = serde_json::Value, content_type = "application/json", description = "The OpenAPI 3.1 document"),
(status = 401, body = ErrorBody, description = "Missing or unknown bearer token"),
)
)]
pub(crate) async fn openapi_json(State(st): State<AppState>) -> Json<std::sync::Arc<OpenApi>> {
Json(openapi::document(st.peers.is_some()))
}
/// Route-level 404 in the common error shape.
pub async fn not_found() -> AppError {
AppError::NotFound("no such route".into())
+43
View File
@@ -0,0 +1,43 @@
//! `slinuxm openapi`: print the generated REST and MCP description.
//!
//! Offline by construction: the document is generated from the code, so this
//! reads no config file, no token file and no socket, and starts no server.
//! The bytes match what `GET /api/v1/openapi.json` serves for the same mode.
use anyhow::{Context, Result};
use crate::openapi;
/// Pretty-printed description, with a trailing newline.
pub fn render(peers: bool) -> Result<String> {
let json = openapi::to_pretty_json(peers).context("serializing the OpenAPI document")?;
Ok(format!("{json}\n"))
}
/// Print the description of a peer-less or a consolidator instance.
pub fn print_openapi(peers: bool) -> Result<()> {
print!("{}", render(peers)?);
Ok(())
}
#[cfg(test)]
mod tests {
use serde_json::Value;
use super::*;
#[test]
fn render_is_valid_json_for_both_modes() {
for peers in [false, true] {
let text = render(peers).unwrap();
assert!(text.ends_with("}\n"));
let spec: Value = serde_json::from_str(&text).unwrap();
assert_eq!(spec["openapi"], "3.1.0");
assert_eq!(
spec["paths"].get("/api/v1/peers").is_some(),
peers,
"peer routes follow the mode"
);
}
}
}
+1
View File
@@ -5,6 +5,7 @@
pub mod api;
pub mod auth;
pub mod cli;
pub mod config;
pub mod db;
pub mod error;
+18 -4
View File
@@ -11,11 +11,11 @@ use tokio_util::sync::CancellationToken;
use skyg_linux_tracker::auth::tokens::{self, TokenCmd};
use skyg_linux_tracker::config::{CliOverrides, Config};
use skyg_linux_tracker::peers::cli::{self, PeerCmd};
use skyg_linux_tracker::peers::cli::{self as peer_cli, PeerCmd};
use skyg_linux_tracker::peers::registry::PeersReloader;
use skyg_linux_tracker::peers::PeerRegistry;
use skyg_linux_tracker::state::AppState;
use skyg_linux_tracker::{db, server, telemetry, tls};
use skyg_linux_tracker::{cli, db, server, telemetry, tls};
#[derive(Debug, Parser)]
#[command(name = "slinuxm", version, about = "Read-only Linux system monitor")]
@@ -71,6 +71,12 @@ enum Command {
#[command(subcommand)]
cmd: PeerCmd,
},
/// Print the generated OpenAPI description (REST and MCP) and exit.
Openapi {
/// Describe a consolidator: includes the peer routes and peer tools.
#[arg(long)]
peers: bool,
},
}
impl Cli {
@@ -91,9 +97,9 @@ impl Cli {
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
if cli.print_config {
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
print!(
"{}",
config.to_toml_redacted().context("serializing config")?
@@ -101,12 +107,20 @@ async fn main() -> Result<()> {
return Ok(());
}
// The spec is generated from the code, so this runs without a config
// file, a token file or any socket.
if let Some(Command::Openapi { peers }) = &cli.command {
return cli::print_openapi(*peers);
}
let config = Config::load(cli.config.as_deref(), &cli.overrides())?;
let overrides = cli.overrides();
let config_path = cli.config.clone();
match cli.command.unwrap_or(Command::Serve) {
Command::Serve => serve(config, config_path, overrides).await,
Command::Token { cmd } => tokens::run(cmd, &config).await,
Command::Peer { cmd } => cli::run(cmd, &config).await,
Command::Peer { cmd } => peer_cli::run(cmd, &config).await,
Command::Openapi { peers } => cli::print_openapi(peers),
}
}
+25 -5
View File
@@ -15,6 +15,7 @@
//! produces, so a field cannot go missing quietly.
use std::borrow::Cow;
use std::sync::{Arc, OnceLock};
use schemars::generate::SchemaSettings;
use schemars::{JsonSchema, SchemaGenerator};
@@ -60,6 +61,7 @@ pub const BEARER_SCHEME: &str = "bearer_auth";
crate::api::peers::list,
crate::api::peers::one,
crate::api::peers::pass,
crate::api::openapi_json,
mcp_endpoint,
),
components(schemas(
@@ -81,11 +83,26 @@ pub const BEARER_SCHEME: &str = "bearer_auth";
)]
struct ApiDoc;
/// The description of one instance.
/// The description of one instance, built once per peer mode.
///
/// `peers` is `state.peers.is_some()`, the flag that also decides whether the
/// router merges the peer routes and whether MCP advertises the peer tools.
pub fn document(peers: bool) -> OpenApi {
/// Building it walks every DTO and the whole tool router, and the result
/// cannot change while the process runs, so both modes are cached.
pub fn document(peers: bool) -> Arc<OpenApi> {
static OFF: OnceLock<Arc<OpenApi>> = OnceLock::new();
static ON: OnceLock<Arc<OpenApi>> = OnceLock::new();
let cache = if peers { &ON } else { &OFF };
cache.get_or_init(|| Arc::new(build(peers))).clone()
}
/// The document as JSON text, the form the committed `docs/openapi.json` and
/// `slinuxm openapi` use.
pub fn to_pretty_json(peers: bool) -> serde_json::Result<String> {
serde_json::to_string_pretty(&*document(peers))
}
fn build(peers: bool) -> OpenApi {
let mut doc = ApiDoc::openapi();
doc.info = info();
doc.servers = Some(vec![ServerBuilder::new()
@@ -905,10 +922,13 @@ mod tests {
}
#[test]
fn document_is_deterministic() {
fn generation_is_deterministic() {
// The committed `docs/openapi.json` is compared with this output, so
// two builds must produce the same bytes.
assert_eq!(
serde_json::to_value(document(true)).unwrap(),
serde_json::to_value(document(true)).unwrap()
serde_json::to_value(build(true)).unwrap(),
serde_json::to_value(build(true)).unwrap()
);
assert_eq!(to_pretty_json(true).unwrap(), to_pretty_json(true).unwrap());
}
}
+75
View File
@@ -13,12 +13,14 @@ 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");
@@ -214,3 +216,76 @@ fn the_spec_is_valid_json_with_the_expected_shape() {
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"
);
}
}