Files
skyg-linux-tracker/src/peers/config.rs
T
ari a02e4f181b A: open peer token files only from serve and peer check
`Config::load` now runs structural checks only (names, URLs, CIDRs, paths,
timeouts) and never touches the host, so `token create|list`, `peer list`,
`peer check` and `--print-config` work where the credential is absent, e.g.
outside the unit. `Config::validate_token_readiness` opens the enabled peers'
files and runs at the top of `serve`; `peer check` checks the probed peer.
Also canonicalise IPv4-mapped IPv6 literals against the deny list and stop
putting the host in the plain-http error while the warning omits it.
2026-10-19 22:31:29 -04:00

474 lines
16 KiB
Rust

//! Validation for the `[peers]` section.
//!
//! Structural checks run on every load, even when the feature is off, so a
//! bad entry is not silent until someone flips `enabled`. They never touch
//! the host: token management, `peer list` and `--print-config` must work
//! where the credential is not in place yet. Opening token files is a
//! separate check that only the processes contacting peers run.
use std::collections::BTreeSet;
use std::net::IpAddr;
use ipnet::IpNet;
use url::Url;
use crate::config::ConfigError;
use crate::peers::types::{PeerConfig, PeersConfig, MAX_PEERS};
/// Structural checks: names, URLs, CIDRs, paths and timeouts. No file reads.
pub fn validate(cfg: &PeersConfig) -> Result<(), ConfigError> {
timeout_below("tcp", cfg.tcp_timeout_secs, cfg.tcp_interval_secs)?;
timeout_below("api", cfg.api_timeout_secs, cfg.api_interval_secs)?;
let deny = parse_deny(&cfg.deny_cidrs)?;
if cfg.peer.len() > MAX_PEERS {
return Err(ConfigError::Invalid(format!(
"at most {MAX_PEERS} peers may be configured (got {})",
cfg.peer.len()
)));
}
let mut seen = BTreeSet::new();
for peer in &cfg.peer {
if !seen.insert(peer.name.clone()) {
return Err(ConfigError::Invalid(format!(
"duplicate peer name '{}'",
peer.name
)));
}
validate_peer(cfg.enabled, peer, &deny)?;
}
if cfg.enabled && cfg.peer.is_empty() {
tracing::warn!("peers.enabled is true but no peers are configured");
}
Ok(())
}
/// Opens the token file of every peer this process would contact.
///
/// Run at startup (`serve`) and by `peer check`, never from `Config::load`:
/// a credential installed after the service starts, or a shell that cannot
/// read `$CREDENTIALS_DIRECTORY`, must not block token or config commands.
pub fn validate_tokens(cfg: &PeersConfig) -> Result<(), ConfigError> {
if !cfg.enabled {
return Ok(());
}
cfg.peer
.iter()
.filter(|peer| peer.enabled)
.try_for_each(validate_peer_token)
}
/// Same check for one peer, whether or not the section is enabled.
pub fn validate_peer_token(peer: &PeerConfig) -> Result<(), ConfigError> {
// The value is dropped here; every use reads the file again so rotation
// needs no restart and the config never retains it.
crate::peers::secrets::load_token(peer)
.map(drop)
.map_err(|err| token_file_error(peer, err))
}
fn timeout_below(kind: &str, timeout: u64, interval: u64) -> Result<(), ConfigError> {
if interval == 0 || timeout == 0 || timeout >= interval {
return Err(ConfigError::Invalid(format!(
"{kind}_timeout_secs ({timeout}) must be greater than zero and below {kind}_interval_secs ({interval})"
)));
}
Ok(())
}
fn parse_deny(cidrs: &[String]) -> Result<Vec<IpNet>, ConfigError> {
cidrs
.iter()
.map(|cidr| {
cidr.parse::<IpNet>().map_err(|err| {
ConfigError::Invalid(format!("deny_cidrs entry {cidr:?} is not a CIDR ({err})"))
})
})
.collect()
}
fn validate_peer(
section_enabled: bool,
peer: &PeerConfig,
deny: &[IpNet],
) -> Result<(), ConfigError> {
validate_url(section_enabled, peer, deny)?;
if let Some(ca) = &peer.ca_file {
if !ca.is_absolute() {
return Err(ConfigError::Invalid(format!(
"peer {}: ca_file must be an absolute path",
peer.name
)));
}
}
if !peer.token_file.is_absolute() {
return Err(ConfigError::Invalid(format!(
"peer {}: token_file must be an absolute path",
peer.name
)));
}
Ok(())
}
fn token_file_error(peer: &PeerConfig, err: crate::peers::PeerError) -> ConfigError {
let reason = match err {
crate::peers::PeerError::TokenFile(reason) => reason,
_ => "could not be read".into(),
};
ConfigError::Invalid(format!(
"peer {}: token_file {}: {reason}",
peer.name,
peer.token_file.display()
))
}
fn validate_url(
section_enabled: bool,
peer: &PeerConfig,
deny: &[IpNet],
) -> Result<(), ConfigError> {
let url = &peer.url;
if url.scheme() != "http" && url.scheme() != "https" {
return Err(ConfigError::Invalid(format!(
"peer {}: url scheme must be http or https",
peer.name
)));
}
// Userinfo and query can carry a credential. The message stays generic
// so the rejected value is not copied into logs.
if !url.username().is_empty() || url.password().is_some() {
return Err(ConfigError::Invalid(format!(
"peer {}: url must not contain userinfo",
peer.name
)));
}
if url.query().is_some() {
return Err(ConfigError::Invalid(format!(
"peer {}: url must not contain a query",
peer.name
)));
}
if url.fragment().is_some() {
return Err(ConfigError::Invalid(format!(
"peer {}: url must not contain a fragment",
peer.name
)));
}
if url.host_str().is_none() {
return Err(ConfigError::Invalid(format!(
"peer {}: url is missing a host",
peer.name
)));
}
// A name is not an address yet, so it cannot be matched here.
if let Some(ip) = host_ip(url) {
if deny.iter().any(|net| net.contains(&ip)) {
return Err(ConfigError::Invalid(format!(
"peer {}: host {ip} is in deny_cidrs",
peer.name
)));
}
}
if url.scheme() == "http" && !is_loopback(url) {
if !peer.allow_plain_http {
return Err(ConfigError::Invalid(format!(
"peer {}: plain http to a non-loopback host requires allow_plain_http = true",
peer.name
)));
}
if section_enabled && peer.enabled {
tracing::warn!(
peer = %peer.name,
"plain http to a non-loopback host; the bearer token travels in cleartext"
);
}
}
Ok(())
}
fn host_ip(url: &Url) -> Option<IpAddr> {
// An IPv4-mapped IPv6 literal (`[::ffff:169.254.169.254]`) must be
// matched against the IPv4 deny list, so canonicalise before comparing.
match url.host()? {
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip).to_canonical()),
url::Host::Domain(_) => None,
}
}
fn is_loopback(url: &Url) -> bool {
match url.host() {
Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).to_canonical().is_loopback(),
None => false,
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::peers::testing::{capture::logged, TempDir};
use crate::peers::types::PeerName;
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,
}
}
fn disabled_section(peers: Vec<PeerConfig>) -> PeersConfig {
PeersConfig {
enabled: false,
peer: peers,
..PeersConfig::default()
}
}
fn message(err: ConfigError) -> String {
match err {
ConfigError::Invalid(message) => message,
other => panic!("expected Invalid, got {other}"),
}
}
#[test]
fn defaults_and_loopback_http_are_valid() {
validate(&PeersConfig::default()).unwrap();
let mut beta = peer("beta", "http://127.0.0.1:1984");
beta.token_file = PathBuf::from("/tmp/does-not-need-to-exist");
validate(&disabled_section(vec![beta])).unwrap();
validate(&disabled_section(vec![peer(
"beta",
"http://localhost:1984",
)]))
.unwrap();
validate(&disabled_section(vec![peer("beta", "http://[::1]:1984")])).unwrap();
validate(&disabled_section(vec![peer(
"beta",
"https://minipc1:1984/base",
)]))
.unwrap();
}
fn timings(
tcp_timeout: u64,
tcp_interval: u64,
api_timeout: u64,
api_interval: u64,
) -> PeersConfig {
PeersConfig {
tcp_timeout_secs: tcp_timeout,
tcp_interval_secs: tcp_interval,
api_timeout_secs: api_timeout,
api_interval_secs: api_interval,
..PeersConfig::default()
}
}
#[test]
fn timeouts_must_be_below_their_interval() {
let err = message(validate(&timings(10, 10, 5, 30)).unwrap_err());
assert!(err.contains("tcp_timeout_secs"));
assert!(err.contains("below"));
assert!(
message(validate(&timings(3, 10, 30, 30)).unwrap_err()).contains("api_timeout_secs")
);
assert!(
message(validate(&timings(3, 10, 0, 30)).unwrap_err()).contains("greater than zero")
);
}
#[test]
fn names_are_unique_and_capped() {
let err = message(
validate(&disabled_section(vec![
peer("beta", "https://beta:1984"),
peer("beta", "https://beta:1985"),
]))
.unwrap_err(),
);
assert!(err.contains("duplicate"));
assert!(err.contains("beta"));
let peers = (0..MAX_PEERS + 1)
.map(|i| {
let mut p = peer("beta", "https://beta:1984");
p.name = PeerName::parse(&format!("p{i}")).unwrap();
p
})
.collect();
let err = message(validate(&disabled_section(peers)).unwrap_err());
assert!(err.contains("64"));
}
#[test]
fn url_rules_reject_scheme_userinfo_query_fragment_and_deny_list() {
let cases = [
("ftp://beta:1984", "scheme"),
("http://user:s3cret@127.0.0.1:1984", "userinfo"),
("https://beta:1984?token=s3cret", "query"),
("https://beta:1984#s3cret", "fragment"),
("http://169.254.169.254/latest", "deny_cidrs"),
("https://0.1.2.3:1984", "deny_cidrs"),
];
for (url, needle) in cases {
let err = message(validate(&disabled_section(vec![peer("beta", url)])).unwrap_err());
assert!(err.contains(needle), "{url} -> {err}");
assert!(err.contains("beta"), "{url} -> {err}");
assert!(!err.contains("s3cret"), "{url} leaked into {err}");
}
}
#[test]
fn plain_http_off_loopback_requires_the_flag_and_warns_when_set() {
let err = message(
validate(&disabled_section(vec![peer("beta", "http://minipc1:1984")])).unwrap_err(),
);
assert!(err.contains("beta"));
assert!(err.contains("allow_plain_http"));
assert!(!err.contains("token"));
let dir = TempDir::new("peer-cfg");
let mut allowed = peer("beta", "http://10.1.2.3:1984");
allowed.allow_plain_http = true;
allowed.token_file = dir.write_token("pending\n");
let cfg = PeersConfig {
enabled: true,
peer: vec![allowed],
..PeersConfig::default()
};
let logs = logged(|| validate(&cfg).unwrap());
assert!(logs.contains("cleartext"), "{logs}");
assert!(logs.contains("beta"), "{logs}");
assert!(!logs.contains("10.1.2.3"), "{logs}");
}
#[test]
fn deny_cidr_must_parse_and_ipv6_literals_match() {
let cfg = PeersConfig {
deny_cidrs: vec!["not-a-cidr".into()],
..PeersConfig::default()
};
assert!(message(validate(&cfg).unwrap_err()).contains("not-a-cidr"));
let mut beta = peer("beta", "http://[fe80::1]:1984");
beta.allow_plain_http = true;
let cfg = PeersConfig {
deny_cidrs: vec!["fe80::/10".into()],
peer: vec![beta],
..PeersConfig::default()
};
let err = message(validate(&cfg).unwrap_err());
assert!(err.contains("deny_cidrs"), "{err}");
assert!(err.contains("fe80::1"), "{err}");
}
#[test]
fn ipv4_mapped_ipv6_literals_match_the_v4_deny_list() {
let mut beta = peer("beta", "http://[::ffff:169.254.169.254]:80");
beta.allow_plain_http = true;
let cfg = PeersConfig {
peer: vec![beta],
..PeersConfig::default()
};
let err = message(validate(&cfg).unwrap_err());
assert!(err.contains("deny_cidrs"), "{err}");
// Same for loopback: a mapped literal is loopback, so plain http is
// allowed without the flag.
let cfg = disabled_section(vec![peer("beta", "http://[::ffff:127.0.0.1]:1984")]);
validate(&cfg).unwrap();
}
#[test]
fn token_file_must_be_absolute_but_is_not_opened_by_structural_checks() {
let mut relative = peer("beta", "https://beta:1984");
relative.token_file = PathBuf::from("peer-beta");
let err = message(validate(&disabled_section(vec![relative])).unwrap_err());
assert!(err.contains("beta"));
assert!(err.contains("absolute"));
// A missing credential is not a config error: token management,
// `peer list` and `--print-config` load this config successfully.
let cfg = PeersConfig {
enabled: true,
peer: vec![peer("beta", "https://beta:1984")],
..PeersConfig::default()
};
validate(&cfg).unwrap();
}
#[test]
fn token_readiness_is_checked_only_for_peers_that_are_contacted() {
let mut cfg = PeersConfig {
enabled: true,
peer: vec![peer("beta", "https://beta:1984")],
..PeersConfig::default()
};
let err = message(validate_tokens(&cfg).unwrap_err());
assert!(err.contains("peer beta"), "{err}");
assert!(err.contains("not readable"), "{err}");
cfg.peer[0].enabled = false;
validate_tokens(&cfg).unwrap();
cfg.enabled = false;
cfg.peer[0].enabled = true;
validate_tokens(&cfg).unwrap();
let dir = TempDir::new("peer-cfg");
cfg.enabled = true;
cfg.peer[0].token_file = dir.write_token("pending\n");
validate_tokens(&cfg).unwrap();
validate_peer_token(&cfg.peer[0]).unwrap();
}
#[test]
fn ca_file_must_be_absolute_when_set() {
let mut beta = peer("beta", "https://beta:1984");
beta.ca_file = Some(PathBuf::from("ca.pem"));
let err = message(validate(&disabled_section(vec![beta])).unwrap_err());
assert!(err.contains("ca_file"));
assert!(err.contains("beta"));
}
#[test]
fn token_readiness_rejects_an_empty_token_file() {
let dir = TempDir::new("peer-cfg");
let mut beta = peer("beta", "http://127.0.0.1:1984");
beta.token_file = dir.write_token("");
let cfg = PeersConfig {
enabled: true,
peer: vec![beta],
..PeersConfig::default()
};
let err = message(validate_tokens(&cfg).unwrap_err());
assert!(err.contains("peer beta"), "{err}");
assert!(err.contains("empty"), "{err}");
}
#[test]
fn enabled_with_no_peers_warns_and_is_not_an_error() {
let cfg = PeersConfig {
enabled: true,
..PeersConfig::default()
};
let logs = logged(|| validate(&cfg).unwrap());
assert!(logs.contains("no peers are configured"), "{logs}");
}
#[test]
fn loopback_detection_covers_localhost_and_127() {
assert!(is_loopback(&Url::parse("http://LOCALHOST:1984").unwrap()));
assert!(is_loopback(&Url::parse("http://127.0.0.2:1984").unwrap()));
assert!(!is_loopback(&Url::parse("http://10.0.0.1:1984").unwrap()));
}
}