Files
skyg-linux-tracker/src/peers/cli.rs
T
ari 92ad3c8128 A: wire peer check to the real client and probe a real socket in tests
B1/B2 are merged, so `real_transport` builds the `ReqwestTransport` with the
configured limits and deny list instead of bailing. Binary tests now probe a
real loopback server: ok with latency, rejected credential, unreachable peer
and an unknown name, none of which may print the token.
2026-10-19 22:31:29 -04:00

233 lines
7.7 KiB
Rust

//! `slinuxm peer list|check`, the read-only diagnostic CLI.
//!
//! Both subcommands work from configuration and (for `check`) the probed
//! peer's token file only; they never touch the database, start loops or print
//! a token value. `peer list` reads no token file at all.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use clap::Subcommand;
use crate::config::Config;
use crate::peers::config;
use crate::peers::health::check_once;
use crate::peers::registry::ReqwestTransport;
use crate::peers::transport::PeerTransport;
use crate::peers::types::{ApiStatus, AuthState, PeerConfig, PeersConfig, ServerStatus};
#[derive(Debug, Clone, Subcommand)]
pub enum PeerCmd {
/// List configured peers (config only; token files are not read).
List,
/// Probe one peer once over TCP and the authenticated API.
Check {
/// Configured peer name.
name: String,
},
}
pub async fn run(cmd: PeerCmd, config: &Config) -> Result<()> {
match cmd {
PeerCmd::List => print!("{}", list_report(&config.peers)),
PeerCmd::Check { name } => {
// Resolve the name before the transport exists, so a typo reads
// as an unknown peer rather than as a missing transport.
let peer = configured_peer(&config.peers, &name)?;
// Only this peer's credential is needed to probe it.
config::validate_peer_token(peer).map_err(|err| anyhow::anyhow!("{err}"))?;
let transport = real_transport(&config.peers)?;
print!(
"{}",
check_report(transport.as_ref(), &config.peers, &name).await?
);
}
}
Ok(())
}
/// The real client, built with the configured limits and deny list. One
/// process-wide instance is enough for a single probe.
fn real_transport(cfg: &PeersConfig) -> Result<Arc<dyn PeerTransport>> {
let transport = ReqwestTransport::new(cfg).context("building the peer client")?;
Ok(Arc::new(transport))
}
/// One row per configured peer, sorted by name. Shows the path of the token
/// file, never its contents.
pub fn list_report(cfg: &PeersConfig) -> String {
if cfg.peer.is_empty() {
return "no peers configured\n".to_owned();
}
let mut peers: Vec<&PeerConfig> = cfg.peer.iter().collect();
peers.sort_by(|a, b| a.name.cmp(&b.name));
let mut out = format!("{:<24} {:<8} {:<28} TOKEN FILE\n", "NAME", "ENABLED", "URL");
for peer in peers {
out.push_str(&format!(
"{:<24} {:<8} {:<28} {}\n",
peer.name.as_str(),
if peer.enabled { "yes" } else { "no" },
peer.display_url(),
peer.token_file.display()
));
}
out
}
/// Probe one configured peer and render the result. The transport reads the
/// token; nothing here can see or print it.
pub async fn check_report(
transport: &dyn PeerTransport,
cfg: &PeersConfig,
name: &str,
) -> Result<String> {
let peer = configured_peer(cfg, name)?;
let (server, api) = check_once(
transport,
peer,
Duration::from_secs(cfg.tcp_timeout_secs),
Duration::from_secs(cfg.api_timeout_secs),
)
.await;
Ok(format!(
"peer {}: {}\n {}\n {}\n",
peer.name,
peer.display_url(),
describe_server(&server),
describe_api(&api)
))
}
fn configured_peer<'a>(cfg: &'a PeersConfig, name: &str) -> Result<&'a PeerConfig> {
cfg.peer
.iter()
.find(|p| p.name.as_str() == name)
.ok_or_else(|| anyhow::anyhow!("unknown peer {name:?}"))
}
fn describe_server(status: &ServerStatus) -> String {
if status.up {
format!("server up ({})", latency(status.latency_ms))
} else {
format!("server down ({})", class(status.last_error.as_deref()))
}
}
fn describe_api(status: &ApiStatus) -> String {
let auth = match status.auth {
AuthState::Ok => "ok",
AuthState::Rejected => "rejected",
AuthState::Unknown => "unknown",
};
if status.up {
let latency = status
.latency_ms
.map(|ms| format!(", {ms} ms"))
.unwrap_or_default();
format!("api up, auth {auth}{latency}")
} else {
format!(
"api down ({}), auth {auth}",
class(status.last_error.as_deref())
)
}
}
fn latency(ms: Option<u64>) -> String {
ms.map(|ms| format!("{ms} ms"))
.unwrap_or_else(|| "-".into())
}
fn class(error: Option<&str>) -> &str {
error.unwrap_or("unknown")
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::peers::error::PeerError;
use crate::peers::testing::{fake_peers_config, FakeTransport};
const SECRET: &str = "slinuxm_PEER_TOKEN_SHOULD_NOT_LEAK";
fn config(names: &[&str]) -> PeersConfig {
fake_peers_config(names)
}
#[test]
fn list_is_sorted_and_shows_paths_not_contents() {
// `list_report` takes a config and never opens the file: a path that
// does not exist must still render, and no content can appear.
let missing = PathBuf::from("/run/credentials/skyg-linux-tracker.service/peer-gamma");
let mut cfg = config(&["gamma", "beta"]);
cfg.peer[0].token_file = missing.clone();
cfg.peer[1].enabled = false;
assert!(!missing.exists(), "fixture must not exist");
let report = list_report(&cfg);
assert!(report.contains("NAME"));
assert!(report.contains("http://beta:1984"));
assert!(report.contains(&missing.display().to_string()));
assert!(report.find("beta").unwrap() < report.find("gamma").unwrap());
assert!(report.contains(" no "), "disabled peer is marked: {report}");
assert!(!report.contains(SECRET));
}
#[test]
fn list_with_no_peers_says_so() {
assert_eq!(
list_report(&PeersConfig::default()),
"no peers configured\n"
);
}
#[tokio::test]
async fn check_reports_latency_and_auth() {
let fake = FakeTransport::new();
let report = check_report(fake.as_ref(), &config(&["beta"]), "beta")
.await
.unwrap();
assert!(report.contains("peer beta: http://beta:1984"));
assert!(report.contains("server up (1 ms)"), "{report}");
assert!(report.contains("api up, auth ok"), "{report}");
assert!(!report.contains(SECRET));
}
#[tokio::test]
async fn check_reports_rejected_credentials_as_api_up() {
let fake = FakeTransport::new();
fake.peer("beta")
.respond_err("/api/v1/ping", PeerError::Rejected);
let report = check_report(fake.as_ref(), &config(&["beta"]), "beta")
.await
.unwrap();
assert!(report.contains("api up, auth rejected"), "{report}");
}
#[tokio::test]
async fn check_reports_down_classes_without_token() {
let fake = FakeTransport::new();
fake.peer("beta").tcp(Err(PeerError::Timeout));
fake.peer("beta")
.respond_err("/api/v1/ping", PeerError::Tls);
let report = check_report(fake.as_ref(), &config(&["beta"]), "beta")
.await
.unwrap();
assert!(report.contains("server down (timeout)"), "{report}");
assert!(report.contains("api down (tls_error)"), "{report}");
assert!(report.contains("auth unknown"), "{report}");
assert!(!report.contains(SECRET));
}
#[tokio::test]
async fn unknown_peer_is_an_error_without_echoing_the_name_as_a_secret() {
let fake = FakeTransport::new();
let err = check_report(fake.as_ref(), &config(&["beta"]), "nope")
.await
.unwrap_err();
assert_eq!(err.to_string(), "unknown peer \"nope\"");
}
}