A0: review round 1 peer entry defaults and class strings

This commit is contained in:
ari committed 2026-10-19 20:02:17 -04:00
1 parent 4bfb097be6
commit 0dbaf58c8c
10 files changed
+276 -32

No files matched your search

+27 -2
View File
@@ -6,6 +6,11 @@
use crate::error::AppError;
use crate::peers::types::{CheckClass, PeerName};
/// What [`crate::peers::registry::PeerRegistry::reload`] returns.
///
/// Same error as startup configuration, so a bad reload uses that wording.
pub type PeerConfigError = crate::config::ConfigError;
#[derive(Debug, Clone)]
pub enum PeerError {
/// Peer answered 401/403: our credential was refused.
@@ -45,12 +50,15 @@ impl PeerError {
}
}
/// Short, secret-free class string used in status errors and messages.
/// Fixed class token for status fields such as `last_error`.
///
/// A `BadRequest` payload is the peer's own text, so it stays out of
/// this string. Callers that should see it use [`peer_error_to_app`].
pub fn class_str(&self) -> String {
match self {
Self::Rejected => "unauthorized".into(),
Self::NotFound => "not_found".into(),
Self::BadRequest(m) => m.clone(),
Self::BadRequest(_) => "bad_request".into(),
Self::Http(code) => format!("http_{code}"),
Self::Timeout => "timeout".into(),
Self::Unreachable => "unreachable".into(),
@@ -156,6 +164,23 @@ mod tests {
assert!(!app.message().contains("/run/credentials"));
}
#[test]
fn bad_request_class_string_drops_the_peer_message() {
let msg = "http://peer.example/path?token=abc";
let err = PeerError::BadRequest(msg.into());
assert_eq!(err.class_str(), "bad_request");
assert!(!err.class_str().contains("http://"));
assert!(!err.class_str().contains("token"));
let app = peer_error_to_app(&name(), &err);
assert_eq!(app.message(), format!("peer beta: {msg}"));
}
#[test]
fn peer_config_error_is_the_process_config_error() {
let err: PeerConfigError = crate::config::ConfigError::Invalid("peers".into());
assert!(matches!(err, crate::config::ConfigError::Invalid(_)));
}
#[test]
fn coarse_class() {
assert_eq!(PeerError::Rejected.class(), CheckClass::Unauthorized);
+22
View File
@@ -66,6 +66,8 @@ pub async fn check_once(
headers: Vec::new(),
accept: None,
};
// The GET is not timed, so `latency_ms` stays empty. The probe that
// replaces this stub measures it; `peer check` prints that value.
let api = match transport.get(peer, req, api_timeout).await {
Ok(resp) if (200..300).contains(&resp.status) => ApiStatus {
up: true,
@@ -161,4 +163,24 @@ mod tests {
assert!(!api.up);
assert_eq!(api.auth, AuthState::Unknown);
}
#[tokio::test]
async fn bad_request_last_error_is_a_class_string() {
let leaked = "http://10.1.2.3/path?token=abc";
let fake = FakeTransport::new();
fake.peer("beta")
.respond_err("/api/v1/ping", PeerError::BadRequest(leaked.into()));
let cfg = fake_peers_config(&["beta"]);
let (_, api) = check_once(
fake.as_ref(),
&cfg.peer[0],
Duration::from_secs(1),
Duration::from_secs(1),
)
.await;
assert_eq!(api.last_error.as_deref(), Some("bad_request"));
let stored = api.last_error.unwrap();
assert!(!stored.contains("token"));
assert!(!stored.contains("http://"));
}
}
+1 -1
View File
@@ -12,6 +12,6 @@ pub mod testing;
pub mod transport;
pub mod types;
pub use error::PeerError;
pub use error::{PeerConfigError, PeerError};
pub use registry::{PeerRegistry, ProxyOpts};
pub use types::{PeerConfig, PeerName, PeerStatus, PeersConfig, Secret};
+5 -3
View File
@@ -1,8 +1,10 @@
//! Proxy one GET to a peer.
//!
//! Path and query allowlists and caller header checks happen in the REST
//! layer; this layer builds the outbound request and maps peer failures. It
//! never forwards caller credentials.
//! The path allowlist, rejection of `..` and encoded slashes, and the query
//! allowlist belong in this module. They are not implemented yet: this stub
//! forwards the request and maps peer failures. REST and MCP share this
//! function, so those checks must not grow a second copy. Caller credentials
//! are never forwarded.
use std::time::Duration;
+25 -15
View File
@@ -5,8 +5,8 @@ use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use crate::config::ConfigError;
use crate::error::AppError;
use crate::peers::error::PeerConfigError;
use crate::peers::transport::{PeerResponse, PeerTransport};
use crate::peers::types::{ApiStatus, PeerConfig, PeerName, PeerStatus, PeersConfig, ServerStatus};
@@ -82,19 +82,21 @@ impl PeerRegistry {
}
pub fn status(&self, name: &str) -> Result<PeerStatus, AppError> {
let Ok(key) = PeerName::parse(name) else {
return Err(AppError::NotFound(format!("peer {name}: unknown peer")));
};
lock_read(&self.state)
.statuses
.values()
.find(|s| s.name.as_str() == name)
.get(&key)
.cloned()
.ok_or_else(|| AppError::NotFound(format!("peer {name}: unknown peer")))
}
pub fn contains(&self, name: &str) -> bool {
lock_read(&self.state)
.statuses
.keys()
.any(|n| n.as_str() == name)
let Ok(key) = PeerName::parse(name) else {
return false;
};
lock_read(&self.state).statuses.contains_key(&key)
}
pub fn config(&self) -> Arc<PeersConfig> {
@@ -109,14 +111,10 @@ impl PeerRegistry {
query: &[(String, String)],
opts: ProxyOpts,
) -> Result<PeerResponse, AppError> {
let key = PeerName::parse(name).ok();
let (peer, timeout) = {
let st = lock_read(&self.state);
let peer = st
.config
.peer
.iter()
.find(|p| p.name.as_str() == name)
.cloned();
let peer = key.and_then(|key| st.config.peer.iter().find(|p| p.name == key).cloned());
(peer, Duration::from_secs(st.config.request_timeout_secs))
};
let peer = peer.ok_or_else(|| AppError::NotFound(format!("peer {name}: unknown peer")))?;
@@ -126,7 +124,7 @@ impl PeerRegistry {
/// Replace the peer set. Statuses of peers that survive a reload are kept
/// so `since` survives a config change. Validation arrives with the
/// config and secrets tasks; this body only swaps state.
pub async fn reload(&self, new: PeersConfig) -> Result<(), ConfigError> {
pub async fn reload(&self, new: PeersConfig) -> Result<(), PeerConfigError> {
let mut st = lock_write(&self.state);
let old = std::mem::take(&mut st.statuses);
st.statuses = new
@@ -191,6 +189,11 @@ mod tests {
assert_eq!(err.message(), "peer nope: unknown peer");
assert!(reg.contains("beta"));
assert!(!reg.contains("nope"));
assert!(!reg.contains("Beta"));
assert!(!reg.contains("-beta"));
let err = reg.status("Beta").unwrap_err();
assert_eq!(err.code(), "not_found");
assert_eq!(err.message(), "peer Beta: unknown peer");
}
#[test]
@@ -226,6 +229,12 @@ mod tests {
.unwrap_err();
assert_eq!(err.code(), "not_found");
assert_eq!(err.message(), "peer nope: unknown peer");
let err = reg
.get("Beta", "/x", &[], ProxyOpts::default())
.await
.unwrap_err();
assert_eq!(err.message(), "peer Beta: unknown peer");
}
#[tokio::test]
@@ -241,7 +250,8 @@ mod tests {
}
let mut new = fake_peers_config(&["beta", "delta"]);
new.peer[0].enabled = false;
reg.reload(new).await.unwrap();
let reloaded: Result<(), PeerConfigError> = reg.reload(new).await;
reloaded.unwrap();
let snap = reg.snapshot();
assert_eq!(snap.len(), 2);
+12 -2
View File
@@ -400,7 +400,7 @@ mod tests {
}
}
#[tokio::test]
#[tokio::test(start_paused = true)]
async fn per_peer_isolation_and_delay() {
let fake = FakeTransport::new();
fake.peer("beta")
@@ -419,15 +419,25 @@ mod tests {
headers: vec![],
accept: None,
};
let started = tokio::time::Instant::now();
assert!(matches!(
fake.get(beta, get(), Duration::from_secs(1)).await,
Err(PeerError::Rejected)
));
// gamma keeps the default 404.
assert!(started.elapsed() >= Duration::from_millis(5));
let started = tokio::time::Instant::now();
let latency = fake.tcp_check(beta, Duration::from_secs(1)).await.unwrap();
assert_eq!(latency, Duration::from_millis(1));
assert!(started.elapsed() >= Duration::from_millis(5));
// gamma keeps the default 404 and is not delayed.
let started = tokio::time::Instant::now();
let r = fake
.get(gamma, get(), Duration::from_secs(1))
.await
.unwrap();
assert_eq!(r.status, 404);
assert_eq!(started.elapsed(), Duration::ZERO);
}
}
+36
View File
@@ -87,15 +87,25 @@ impl fmt::Display for Secret {
}
}
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,
}
@@ -280,6 +290,32 @@ mod tests {
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!(