387 lines
12 KiB
Rust
387 lines
12 KiB
Rust
//! Types shared by peer configuration, the registry, proxying and fixtures.
|
|
|
|
use std::fmt;
|
|
use std::path::PathBuf;
|
|
|
|
use jiff::Timestamp;
|
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
use url::Url;
|
|
|
|
use crate::config::ConfigError;
|
|
|
|
/// Upper bound on configured peers; keeps health loops and snapshots bounded.
|
|
pub const MAX_PEERS: usize = 64;
|
|
|
|
/// Validated peer name, `^[a-z0-9][a-z0-9_-]{0,31}$`.
|
|
///
|
|
/// Names end up in URLs, MCP arguments and metric attributes, so the
|
|
/// character set is deliberately narrow.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, schemars::JsonSchema)]
|
|
#[schemars(transparent)]
|
|
pub struct PeerName(String);
|
|
|
|
impl PeerName {
|
|
pub fn parse(s: &str) -> Result<Self, ConfigError> {
|
|
let valid = !s.is_empty()
|
|
&& s.len() <= 32
|
|
&& s.bytes().enumerate().all(|(i, b)| match b {
|
|
b'a'..=b'z' | b'0'..=b'9' => true,
|
|
b'_' | b'-' => i > 0,
|
|
_ => false,
|
|
});
|
|
if !valid {
|
|
return Err(ConfigError::Invalid(format!(
|
|
"peer name {s:?} must match ^[a-z0-9][a-z0-9_-]{{0,31}}$"
|
|
)));
|
|
}
|
|
Ok(Self(s.to_owned()))
|
|
}
|
|
|
|
pub fn as_str(&self) -> &str {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for PeerName {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str(&self.0)
|
|
}
|
|
}
|
|
|
|
impl Serialize for PeerName {
|
|
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
|
s.serialize_str(&self.0)
|
|
}
|
|
}
|
|
|
|
impl<'de> Deserialize<'de> for PeerName {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
let s = String::deserialize(d)?;
|
|
Self::parse(&s).map_err(serde::de::Error::custom)
|
|
}
|
|
}
|
|
|
|
/// A token value that must never reach logs, `Debug` output or serialized
|
|
/// config. Only the transport may read it.
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
pub struct Secret(String);
|
|
|
|
impl Secret {
|
|
pub fn new(value: impl Into<String>) -> Self {
|
|
Self(value.into())
|
|
}
|
|
|
|
pub fn expose(&self) -> &str {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl fmt::Debug for Secret {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str("Secret(***)")
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Secret {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str("***")
|
|
}
|
|
}
|
|
|
|
fn peer_enabled_default() -> bool {
|
|
true
|
|
}
|
|
|
|
/// One validated `[[peers.peer]]` entry. The token itself is not held here;
|
|
/// only the path of the externally managed file.
|
|
///
|
|
/// `enabled` defaults to true, `allow_plain_http` to false, and `ca_file`
|
|
/// may be omitted: entries often carry only `name`, `url` and `token_file`.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct PeerConfig {
|
|
pub name: PeerName,
|
|
pub url: Url,
|
|
pub token_file: PathBuf,
|
|
#[serde(default)]
|
|
pub ca_file: Option<PathBuf>,
|
|
#[serde(default)]
|
|
pub allow_plain_http: bool,
|
|
#[serde(default = "peer_enabled_default")]
|
|
pub enabled: bool,
|
|
}
|
|
|
|
impl PeerConfig {
|
|
/// Display form for REST and MCP output. `Url` normalizes an empty path
|
|
/// to `/`; drop it so `http://beta:1984` does not render as `.../`.
|
|
pub fn display_url(&self) -> String {
|
|
let s = self.url.as_str();
|
|
if self.url.path() == "/" {
|
|
s.strip_suffix('/').unwrap_or(s).to_owned()
|
|
} else {
|
|
s.to_owned()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The `[peers]` config section. Defaults keep the feature off.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct PeersConfig {
|
|
pub enabled: bool,
|
|
pub tcp_interval_secs: u64,
|
|
pub tcp_timeout_secs: u64,
|
|
pub api_interval_secs: u64,
|
|
pub api_timeout_secs: u64,
|
|
pub fail_threshold: u32,
|
|
pub request_timeout_secs: u64,
|
|
pub max_response_bytes: u64,
|
|
pub max_concurrent_per_peer: usize,
|
|
pub max_concurrent_total: usize,
|
|
pub deny_cidrs: Vec<String>,
|
|
pub peer: Vec<PeerConfig>,
|
|
}
|
|
|
|
/// Refused by default: link-local and cloud metadata addresses in both
|
|
/// families, plus the unspecified address. Private LAN ranges stay allowed,
|
|
/// since that is where peers live.
|
|
pub const DEFAULT_DENY_CIDRS: [&str; 5] = [
|
|
"169.254.0.0/16",
|
|
"0.0.0.0/8",
|
|
"fe80::/10",
|
|
"::/128",
|
|
"fd00:ec2::254/128",
|
|
];
|
|
|
|
impl Default for PeersConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
enabled: false,
|
|
tcp_interval_secs: 10,
|
|
tcp_timeout_secs: 3,
|
|
api_interval_secs: 30,
|
|
api_timeout_secs: 5,
|
|
fail_threshold: 2,
|
|
request_timeout_secs: 10,
|
|
max_response_bytes: 8 * 1024 * 1024,
|
|
max_concurrent_per_peer: 4,
|
|
max_concurrent_total: 16,
|
|
deny_cidrs: DEFAULT_DENY_CIDRS.iter().map(|c| c.to_string()).collect(),
|
|
peer: Vec::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Registry snapshot entry, serialized as-is by REST and MCP.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
|
|
pub struct PeerStatus {
|
|
/// Configured peer name.
|
|
pub name: PeerName,
|
|
/// `false` for a peer kept in configuration but not checked.
|
|
pub enabled: bool,
|
|
/// Display form of the configured URL; never carries credentials.
|
|
pub url: String,
|
|
/// "Server up": a TCP connect to the peer's host and port.
|
|
pub server: ServerStatus,
|
|
/// "API running": an authenticated `GET /api/v1/ping`.
|
|
pub api: ApiStatus,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Default, Serialize, schemars::JsonSchema)]
|
|
pub struct ServerStatus {
|
|
pub up: bool,
|
|
/// Last change; `None` until the first check and reset on restart.
|
|
pub since: Option<Timestamp>,
|
|
pub last_checked: Option<Timestamp>,
|
|
/// Failure class such as `timeout` or `unreachable`; never a URL or a secret.
|
|
pub last_error: Option<String>,
|
|
pub latency_ms: Option<u64>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Default, Serialize, schemars::JsonSchema)]
|
|
pub struct ApiStatus {
|
|
pub up: bool,
|
|
/// Last change; `None` until the first check and reset on restart.
|
|
pub since: Option<Timestamp>,
|
|
pub last_checked: Option<Timestamp>,
|
|
/// Failure class such as `http_500` or `token_file`; never a URL or a secret.
|
|
pub last_error: Option<String>,
|
|
pub latency_ms: Option<u64>,
|
|
/// State of the consolidator's credential on the peer.
|
|
pub auth: AuthState,
|
|
/// Version the peer reported, when it has the ping route.
|
|
pub peer_version: Option<String>,
|
|
}
|
|
|
|
/// `Ok` and `Rejected` refer to our credential; `Unknown` is used before the
|
|
/// first check and for peers without the authenticated ping endpoint.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, schemars::JsonSchema)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum AuthState {
|
|
Ok,
|
|
Rejected,
|
|
#[default]
|
|
Unknown,
|
|
}
|
|
|
|
/// Coarse outcome of a check; the precise cause is in [`crate::peers::error::PeerError`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum CheckClass {
|
|
Ok,
|
|
Unauthorized,
|
|
HttpError,
|
|
Timeout,
|
|
Unreachable,
|
|
TlsError,
|
|
}
|
|
|
|
impl CheckClass {
|
|
pub fn as_str(&self) -> &'static str {
|
|
match self {
|
|
Self::Ok => "ok",
|
|
Self::Unauthorized => "unauthorized",
|
|
Self::HttpError => "http_error",
|
|
Self::Timeout => "timeout",
|
|
Self::Unreachable => "unreachable",
|
|
Self::TlsError => "tls_error",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn peer(name: &str, url: &str) -> PeerConfig {
|
|
PeerConfig {
|
|
name: PeerName::parse(name).unwrap(),
|
|
url: Url::parse(url).unwrap(),
|
|
token_file: PathBuf::from(format!("/run/peers/{name}.token")),
|
|
ca_file: None,
|
|
allow_plain_http: false,
|
|
enabled: true,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn peer_name_accepts_and_rejects() {
|
|
assert!(PeerName::parse("a").is_ok());
|
|
assert!(PeerName::parse("minipc1").is_ok());
|
|
assert!(PeerName::parse("a_b-c9").is_ok());
|
|
assert!(PeerName::parse(&"a".repeat(32)).is_ok());
|
|
for bad in ["", "-a", "_a", "Beta", "beta!", "a b", &"a".repeat(33)] {
|
|
assert!(PeerName::parse(bad).is_err(), "{bad:?} should be rejected");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn peer_name_serde_roundtrip_and_validation() {
|
|
let n = PeerName::parse("beta").unwrap();
|
|
let json = serde_json::to_string(&n).unwrap();
|
|
assert_eq!(json, "\"beta\"");
|
|
assert_eq!(serde_json::from_str::<PeerName>(&json).unwrap(), n);
|
|
assert!(serde_json::from_str::<PeerName>("\"Beta\"").is_err());
|
|
assert_eq!(n.to_string(), "beta");
|
|
}
|
|
|
|
#[test]
|
|
fn secret_redacts_debug_and_display() {
|
|
let s = Secret::new("slinuxm_super_secret");
|
|
assert_eq!(s.expose(), "slinuxm_super_secret");
|
|
assert!(!format!("{s:?}").contains("super"));
|
|
assert!(!format!("{s}").contains("super"));
|
|
assert_eq!(format!("{s:?}"), "Secret(***)");
|
|
}
|
|
|
|
#[test]
|
|
fn peer_defaults_are_off() {
|
|
let c = PeersConfig::default();
|
|
assert!(!c.enabled);
|
|
assert!(c.peer.is_empty());
|
|
assert_eq!(c.tcp_interval_secs, 10);
|
|
assert_eq!(c.request_timeout_secs, 10);
|
|
assert_eq!(c.max_response_bytes, 8 * 1024 * 1024);
|
|
assert_eq!(
|
|
c.deny_cidrs,
|
|
vec![
|
|
"169.254.0.0/16",
|
|
"0.0.0.0/8",
|
|
"fe80::/10",
|
|
"::/128",
|
|
"fd00:ec2::254/128",
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn partial_toml_keeps_defaults() {
|
|
let c: PeersConfig = toml::from_str("enabled = true\napi_interval_secs = 7\n").unwrap();
|
|
assert!(c.enabled);
|
|
assert_eq!(c.api_interval_secs, 7);
|
|
assert_eq!(c.tcp_interval_secs, 10);
|
|
}
|
|
|
|
#[test]
|
|
fn peer_entry_omits_optional_keys() {
|
|
let c: PeersConfig = toml::from_str(
|
|
r#"
|
|
[[peer]]
|
|
name = "beta"
|
|
url = "http://beta:1984"
|
|
token_file = "/run/credentials/skyg-linux-tracker.service/peer-beta"
|
|
allow_plain_http = true
|
|
|
|
[[peer]]
|
|
name = "delta"
|
|
url = "https://delta:1984"
|
|
token_file = "/run/credentials/skyg-linux-tracker.service/peer-delta"
|
|
enabled = false
|
|
"#,
|
|
)
|
|
.unwrap();
|
|
assert!(c.peer[0].enabled);
|
|
assert!(c.peer[0].allow_plain_http);
|
|
assert!(c.peer[0].ca_file.is_none());
|
|
assert!(!c.peer[1].enabled);
|
|
assert!(!c.peer[1].allow_plain_http);
|
|
assert!(c.peer[1].ca_file.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn display_url_drops_normalized_root_path() {
|
|
assert_eq!(
|
|
peer("beta", "http://beta:1984").display_url(),
|
|
"http://beta:1984"
|
|
);
|
|
assert_eq!(
|
|
peer("beta", "https://beta:1984/").display_url(),
|
|
"https://beta:1984"
|
|
);
|
|
assert_eq!(
|
|
peer("beta", "https://beta:1984/base").display_url(),
|
|
"https://beta:1984/base"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn status_json_shape() {
|
|
let st = PeerStatus {
|
|
name: PeerName::parse("beta").unwrap(),
|
|
enabled: true,
|
|
url: "http://beta:1984".into(),
|
|
server: ServerStatus::default(),
|
|
api: ApiStatus::default(),
|
|
};
|
|
let v = serde_json::to_value(&st).unwrap();
|
|
assert_eq!(v["name"], "beta");
|
|
assert_eq!(v["server"]["up"], serde_json::json!(false));
|
|
assert_eq!(v["server"]["since"], serde_json::Value::Null);
|
|
assert_eq!(v["api"]["auth"], "unknown");
|
|
assert_eq!(
|
|
serde_json::to_value(CheckClass::TlsError).unwrap(),
|
|
"tls_error"
|
|
);
|
|
assert_eq!(serde_json::to_value(AuthState::Ok).unwrap(), "ok");
|
|
}
|
|
}
|