Files
skyg-linux-tracker/src/api/peers.rs
T

377 lines
14 KiB
Rust

//! Peer status and GET-only pass-through routes.
//!
//! Merged only when `state.peers` is set, so a peer-less instance has no
//! peers routes at all. Pass-through lives in `crate::peers::proxy` so MCP
//! calls the same code.
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Path, Request, State};
use axum::http::{header, HeaderName, HeaderValue};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use crate::error::AppError;
use crate::openapi::ErrorBody;
use crate::peers::proxy::{self, PreparedBody, PreparedResponse};
use crate::peers::types::{PeerName, PeerStatus};
use crate::peers::{PeerRegistry, ProxyOpts};
use crate::state::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/peers", get(list))
.route("/peers/{peer}", get(one))
.route("/peers/{peer}/{*path}", get(pass))
}
#[derive(Serialize, utoipa::ToSchema)]
pub(crate) struct PeerList {
peers: Vec<PeerStatus>,
}
/// Only reachable with a registry: `api::router` merges these routes on
/// `state.peers.is_some()` and the field is fixed for the process lifetime.
fn registry(st: &AppState) -> &PeerRegistry {
st.peers
.as_deref()
.expect("peer routes are mounted only with a peer registry")
}
#[utoipa::path(
get,
path = "/api/v1/peers",
operation_id = "list_peers",
tag = "peers",
summary = "Peer status list",
description = "Every configured peer, sorted by name, including disabled ones. Present only \
when `[peers] enabled = true`.",
responses(
(status = 200, body = PeerList, description = "Peer status, sorted by name"),
(status = 401, body = ErrorBody, description = "Missing or unknown bearer token"),
(status = 503, body = ErrorBody, description = "The token database is unavailable"),
)
)]
pub(crate) async fn list(State(st): State<AppState>) -> Json<PeerList> {
Json(PeerList {
peers: registry(&st).snapshot(),
})
}
#[utoipa::path(
get,
path = "/api/v1/peers/{peer}",
operation_id = "get_peer",
tag = "peers",
summary = "Status of one peer",
params((
"peer" = String,
Path,
description = "Configured peer name"
)),
responses(
(status = 200, body = PeerStatus, description = "The peer, not wrapped in an object"),
(status = 401, body = ErrorBody, description = "Missing or unknown bearer token"),
(status = 404, body = ErrorBody, description = "Unknown peer"),
(status = 503, body = ErrorBody, description = "The token database is unavailable"),
)
)]
pub(crate) async fn one(
State(st): State<AppState>,
Path(peer): Path<String>,
) -> Result<Json<PeerStatus>, AppError> {
Ok(Json(registry(&st).status(&peer)?))
}
/// Pass-through of one peer's read routes. The wildcard is documented as one
/// operation because the peer's own routes are the peer's business; the
/// allowlist below is what this instance forwards.
#[utoipa::path(
get,
path = "/api/v1/peers/{peer}/{path}",
operation_id = "proxy_peer_get",
tag = "peers",
summary = "GET-only pass-through to a peer",
description = "Forwards a GET to the same path on the peer and returns the peer's status and \
body unchanged for 2xx. Allowed paths: `systemd/units`, \
`systemd/units/{name}`, `systemd/timers`, `journal`, `journal/follow`, \
`docker/ps`, `docker/containers/{name}`, `docker/containers/{name}/logs`. \
`ping` and `peers/...` are not forwarded, nor is any other path. Query keys \
are those the local route accepts (`state`, `unit`, `priority`, `lines`, \
`since`, `all`, `tail`, `follow`). Only GET is accepted. A peer failure is a \
503 naming the peer, never a 401: a peer rejecting the consolidator's token \
does not mean the caller must re-authenticate here. Peer data is untrusted.",
params((
"peer" = String,
Path,
description = "Configured peer name"
), (
"path" = String,
Path,
description = "Peer route below `/api/v1`, e.g. `systemd/units`"
)),
responses(
(status = 200,
description = "The peer's body with the peer's status and `x-slinuxm-peer`; JSON, or `text/event-stream` for a follow",
content((String = "application/json"), (String = "text/event-stream"))),
(status = 400, body = ErrorBody, description = "Path or query not allowed, or a chained request (`x-slinuxm-hop`)"),
(status = 401, body = ErrorBody, description = "Missing or unknown bearer token"),
(status = 404, body = ErrorBody, description = "Unknown peer, or the peer answered 404"),
(status = 405, body = ErrorBody, description = "Not a GET"),
(status = 503, body = ErrorBody, description = "Peer unreachable, timed out, rejected the consolidator's token, exceeded the size cap, or answered another error status"),
)
)]
pub(crate) async fn pass(
State(st): State<AppState>,
Path((peer, _path)): Path<(String, String)>,
request: Request,
) -> Response {
let reg = registry(&st);
// The registry parses and looks the name up in one call, so an unknown or
// malformed name gets the contract's 404 and no peer header: the response
// does not come from a peer.
let name = match reg.status(&peer) {
Ok(status) => status.name,
Err(err) => return err.into_response(),
};
with_peer_header(&name, pass_through(reg, &name, &st, request).await)
}
/// Every outcome for a proxy call names the peer, including consolidator-side
/// errors (bad path, dead peer), so a client can tell which peer failed.
fn with_peer_header(name: &PeerName, mut response: Response) -> Response {
let value = HeaderValue::from_str(name.as_str()).expect("validated peer name");
response
.headers_mut()
.insert(HeaderName::from_static(proxy::PEER_HEADER), value);
response
}
async fn pass_through(
reg: &PeerRegistry,
name: &PeerName,
st: &AppState,
request: Request,
) -> Response {
if let Err(err) = proxy::reject_inbound_hop(name.as_str(), request.headers()) {
return err.into_response();
}
let Some(raw_path) = raw_peer_path(request.uri().path()) else {
return AppError::BadRequest(format!("peer {name}: path not allowed")).into_response();
};
let query = match proxy::query_from_raw(name.as_str(), request.uri().query()) {
Ok(query) => query,
Err(err) => return err.into_response(),
};
let opts = ProxyOpts {
traceparent: inbound_traceparent(request.headers()),
accept_sse: accepts_event_stream(request.headers()),
};
let resp = match reg.get(name.as_str(), raw_path, &query, opts).await {
Ok(resp) => resp,
Err(err) => return err.into_response(),
};
let deadline =
tokio::time::Instant::now() + Duration::from_secs(st.config.limits.max_follow_secs);
match proxy::prepare_response(
name,
resp,
reg.config().max_response_bytes,
deadline,
st.shutdown.clone(),
) {
Ok(prepared) => prepared_response(prepared),
Err(err) => err.into_response(),
}
}
fn prepared_response(prepared: PreparedResponse) -> Response {
let sse = prepared
.content_type
.as_ref()
.is_some_and(|value| value.as_bytes() == b"text/event-stream");
let body = match prepared.body {
PreparedBody::Bytes(bytes) => Body::from(bytes),
PreparedBody::Stream(stream) => Body::from_stream(stream),
};
let mut response = Response::new(body);
*response.status_mut() = prepared.status;
if let Some(content_type) = prepared.content_type {
response
.headers_mut()
.insert(header::CONTENT_TYPE, content_type);
}
// A follow must not be buffered or cached by an intermediary; the local
// routes get this from axum's `Sse`.
if sse {
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
}
response
}
/// Path after `/peers/{name}/`, still percent-encoded. Nesting strips
/// `/api/v1` before this runs, so both the mounted server and the bare API
/// router yield `/peers/...`.
fn raw_peer_path(uri_path: &str) -> Option<&str> {
let mut rest = uri_path;
while let Some(stripped) = rest.strip_prefix('/') {
if let Some(after) = stripped.strip_prefix("peers/") {
let (_name, path) = after.split_once('/')?;
return Some(path);
}
rest = &stripped[stripped.find('/')?..];
}
None
}
fn inbound_traceparent(headers: &axum::http::HeaderMap) -> Option<String> {
let value = headers.get("traceparent")?.to_str().ok()?;
if (1..=128).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_graphic()) {
Some(value.to_owned())
} else {
None
}
}
fn accepts_event_stream(headers: &axum::http::HeaderMap) -> bool {
headers
.get(header::ACCEPT)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value
.split(',')
.any(|part| part.trim().starts_with("text/event-stream"))
})
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use super::super::router;
use super::super::testutil::{get, json};
use crate::config::Config;
use crate::peers::testing::{fake_state_with_peers, static_registry};
use crate::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus};
use crate::sources::fake::fake_state;
fn status(name: &str, enabled: bool, up: bool, auth: AuthState) -> PeerStatus {
PeerStatus {
name: PeerName::parse(name).unwrap(),
enabled,
url: format!("http://{name}:1984"),
server: ServerStatus {
up,
since: Some("2026-10-19T10:00:00Z".parse().unwrap()),
last_checked: Some("2026-10-19T10:00:09Z".parse().unwrap()),
last_error: None,
latency_ms: Some(1),
},
api: ApiStatus {
up,
since: Some("2026-10-19T10:00:00Z".parse().unwrap()),
last_checked: Some("2026-10-19T10:00:05Z".parse().unwrap()),
last_error: None,
latency_ms: Some(7),
auth,
peer_version: Some("0.1.0".into()),
},
}
}
fn app(statuses: Vec<PeerStatus>) -> axum::Router {
router(fake_state_with_peers(
Config::default(),
static_registry(statuses),
))
}
#[tokio::test]
async fn list_is_sorted_and_shaped() {
let app = app(vec![
status("gamma", false, false, AuthState::Unknown),
status("beta", true, true, AuthState::Ok),
]);
let (s, b) = get(&app, "/peers").await;
assert_eq!(s, StatusCode::OK);
let v = json(&b);
let peers = v["peers"].as_array().unwrap();
assert_eq!(peers.len(), 2);
assert_eq!(peers[0]["name"], "beta");
assert_eq!(peers[1]["name"], "gamma");
assert_eq!(peers[0]["enabled"], true);
assert_eq!(peers[1]["enabled"], false);
assert_eq!(peers[0]["url"], "http://beta:1984");
assert_eq!(peers[0]["server"]["up"], true);
assert_eq!(peers[0]["server"]["since"], "2026-10-19T10:00:00Z");
assert_eq!(peers[0]["server"]["last_checked"], "2026-10-19T10:00:09Z");
assert_eq!(peers[0]["server"]["last_error"], serde_json::Value::Null);
assert_eq!(peers[0]["server"]["latency_ms"], 1);
assert_eq!(peers[0]["api"]["up"], true);
assert_eq!(peers[0]["api"]["auth"], "ok");
assert_eq!(peers[0]["api"]["peer_version"], "0.1.0");
assert_eq!(peers[1]["api"]["auth"], "unknown");
assert_eq!(peers[1]["server"]["up"], false);
}
#[tokio::test]
async fn one_peer_is_the_object_not_a_list() {
let app = app(vec![status("beta", true, true, AuthState::Rejected)]);
let (s, b) = get(&app, "/peers/beta").await;
assert_eq!(s, StatusCode::OK);
let v = json(&b);
assert!(v.get("peers").is_none());
assert_eq!(v["name"], "beta");
assert_eq!(v["server"]["up"], true);
assert_eq!(v["api"]["up"], true);
assert_eq!(v["api"]["auth"], "rejected");
}
#[tokio::test]
async fn unknown_peer_is_not_found() {
let app = app(vec![status("beta", true, true, AuthState::Ok)]);
for name in ["nope", "Beta", "-beta"] {
let (s, b) = get(&app, &format!("/peers/{name}")).await;
assert_eq!(s, StatusCode::NOT_FOUND, "{name}");
assert_eq!(json(&b)["error"]["code"], "not_found");
assert_eq!(
json(&b)["error"]["message"],
format!("peer {name}: unknown peer")
);
}
}
#[tokio::test]
async fn empty_registry_lists_nothing() {
let (s, b) = get(&app(vec![]), "/peers").await;
assert_eq!(s, StatusCode::OK);
assert_eq!(json(&b)["peers"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn routes_are_absent_when_peers_are_disabled() {
let app = router(fake_state(Config::default()));
for path in ["/peers", "/peers/beta"] {
let (s, b) = get(&app, path).await;
assert_eq!(s, StatusCode::NOT_FOUND, "{path}");
assert_eq!(json(&b)["error"]["code"], "not_found");
}
let (s, _) = get(&app, "/systemd/units").await;
assert_eq!(s, StatusCode::OK);
}
#[tokio::test]
async fn local_routes_stay_available() {
let app = app(vec![status("beta", true, true, AuthState::Ok)]);
let (s, _) = get(&app, "/systemd/units").await;
assert_eq!(s, StatusCode::OK);
let (s, _) = get(&app, "/journal").await;
assert_eq!(s, StatusCode::OK);
}
}