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.
This commit is contained in:
1 parent
e2ff40beae
commit
92ad3c8128
2 files changed
+142
-14
No files matched your search
+8
-6
@@ -7,12 +7,13 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{Context, Result};
|
||||||
use clap::Subcommand;
|
use clap::Subcommand;
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::peers::config;
|
use crate::peers::config;
|
||||||
use crate::peers::health::check_once;
|
use crate::peers::health::check_once;
|
||||||
|
use crate::peers::registry::ReqwestTransport;
|
||||||
use crate::peers::transport::PeerTransport;
|
use crate::peers::transport::PeerTransport;
|
||||||
use crate::peers::types::{ApiStatus, AuthState, PeerConfig, PeersConfig, ServerStatus};
|
use crate::peers::types::{ApiStatus, AuthState, PeerConfig, PeersConfig, ServerStatus};
|
||||||
|
|
||||||
@@ -36,7 +37,7 @@ pub async fn run(cmd: PeerCmd, config: &Config) -> Result<()> {
|
|||||||
let peer = configured_peer(&config.peers, &name)?;
|
let peer = configured_peer(&config.peers, &name)?;
|
||||||
// Only this peer's credential is needed to probe it.
|
// Only this peer's credential is needed to probe it.
|
||||||
config::validate_peer_token(peer).map_err(|err| anyhow::anyhow!("{err}"))?;
|
config::validate_peer_token(peer).map_err(|err| anyhow::anyhow!("{err}"))?;
|
||||||
let transport = real_transport()?;
|
let transport = real_transport(&config.peers)?;
|
||||||
print!(
|
print!(
|
||||||
"{}",
|
"{}",
|
||||||
check_report(transport.as_ref(), &config.peers, &name).await?
|
check_report(transport.as_ref(), &config.peers, &name).await?
|
||||||
@@ -46,10 +47,11 @@ pub async fn run(cmd: PeerCmd, config: &Config) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The real transport lands with the peer client workstream. Until then the
|
/// The real client, built with the configured limits and deny list. One
|
||||||
/// binary can list peers but cannot contact one.
|
/// process-wide instance is enough for a single probe.
|
||||||
fn real_transport() -> Result<Arc<dyn PeerTransport>> {
|
fn real_transport(cfg: &PeersConfig) -> Result<Arc<dyn PeerTransport>> {
|
||||||
bail!("peer check: transport not available (the peer client is not wired yet)")
|
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
|
/// One row per configured peer, sorted by name. Shows the path of the token
|
||||||
|
|||||||
+134
-8
@@ -264,20 +264,146 @@ async fn peer_check_reports_a_probe_through_the_fake_transport() {
|
|||||||
assert!(!report.contains(SECRET), "{report}");
|
assert!(!report.contains(SECRET), "{report}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
/// A minimal `slinuxm` peer on a real socket: answers the API probe on
|
||||||
fn peer_check_binary_reports_the_missing_transport_without_the_token() {
|
/// `/api/v1/ping` and ignores the bare TCP check's connection.
|
||||||
let fixture = PeerFixture::new("");
|
struct FakePeer {
|
||||||
let cfg = fixture.config();
|
port: u16,
|
||||||
|
handle: Option<std::thread::JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
let out = slinuxm(cfg, &["peer", "check", "beta"]);
|
impl FakePeer {
|
||||||
|
fn new(expect_token: &str) -> Self {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let expect = format!("authorization: bearer {expect_token}").to_lowercase();
|
||||||
|
let handle = std::thread::spawn(move || {
|
||||||
|
// One connection for the TCP check, one for the API request.
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
||||||
|
listener.set_nonblocking(true).unwrap();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let (mut sock, _) = loop {
|
||||||
|
match listener.accept() {
|
||||||
|
Ok(pair) => break pair,
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
|
||||||
|
if std::time::Instant::now() > deadline {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
Err(_) => return,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
|
let Ok(n) = sock.read(&mut buf) else { continue };
|
||||||
|
let head = String::from_utf8_lossy(&buf[..n]).to_lowercase();
|
||||||
|
if !head.starts_with("get ") {
|
||||||
|
continue; // the TCP check connects and closes
|
||||||
|
}
|
||||||
|
let (code, body) = if head.contains(&expect) {
|
||||||
|
("200 OK", r#"{"status":"ok","version":"9.9.9"}"#)
|
||||||
|
} else {
|
||||||
|
("401 Unauthorized", r#"{"error":"unauthorized"}"#)
|
||||||
|
};
|
||||||
|
let resp = format!(
|
||||||
|
"HTTP/1.1 {code}\r\ncontent-type: application/json\r\n\
|
||||||
|
content-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
let _ = sock.write_all(resp.as_bytes());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self {
|
||||||
|
port,
|
||||||
|
handle: Some(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A config naming `beta` at this peer, with a private token file.
|
||||||
|
fn config(&self) -> (TempDir, PathBuf) {
|
||||||
|
let dir = TempDir::new("peers-live");
|
||||||
|
let token = dir.write("peer.token", SECRET.as_bytes(), 0o600);
|
||||||
|
let config = dir.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&config,
|
||||||
|
format!(
|
||||||
|
"[peers]\nenabled = true\n\
|
||||||
|
[[peers.peer]]\n\
|
||||||
|
name = \"beta\"\n\
|
||||||
|
url = \"http://127.0.0.1:{}\"\n\
|
||||||
|
token_file = \"{}\"\n",
|
||||||
|
self.port,
|
||||||
|
token.display()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
(dir, config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for FakePeer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Detach the listener thread: it may still be waiting for a probe
|
||||||
|
// that never comes and gives up on its own.
|
||||||
|
self.handle.take();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peer_check_binary_probes_a_real_peer_and_prints_latency() {
|
||||||
|
let peer = FakePeer::new(SECRET);
|
||||||
|
let (_dir, cfg) = peer.config();
|
||||||
|
|
||||||
|
let out = slinuxm(&cfg, &["peer", "check", "beta"]);
|
||||||
let stdout = String::from_utf8(out.stdout).unwrap();
|
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||||
assert!(!out.status.success(), "no transport yet: {stdout}");
|
assert!(out.status.success(), "peer check failed: {stderr}");
|
||||||
assert!(stderr.contains("transport not available"), "{stderr}");
|
assert!(stdout.contains("peer beta"), "{stdout}");
|
||||||
|
assert!(stdout.contains("server up ("), "{stdout}");
|
||||||
|
assert!(stdout.contains("api up, auth ok"), "{stdout}");
|
||||||
|
assert!(stdout.contains(" ms"), "latency is printed: {stdout}");
|
||||||
assert!(!stdout.contains(SECRET), "{stdout}");
|
assert!(!stdout.contains(SECRET), "{stdout}");
|
||||||
assert!(!stderr.contains(SECRET), "{stderr}");
|
assert!(!stderr.contains(SECRET), "{stderr}");
|
||||||
|
}
|
||||||
|
|
||||||
let out = slinuxm(cfg, &["peer", "check", "nope"]);
|
#[test]
|
||||||
|
fn peer_check_binary_reports_a_rejected_credential_as_api_up() {
|
||||||
|
let peer = FakePeer::new("some-other-token");
|
||||||
|
let (_dir, cfg) = peer.config();
|
||||||
|
|
||||||
|
let out = slinuxm(&cfg, &["peer", "check", "beta"]);
|
||||||
|
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||||
|
assert!(out.status.success(), "{stdout}");
|
||||||
|
assert!(stdout.contains("api up, auth rejected"), "{stdout}");
|
||||||
|
assert!(!stdout.contains(SECRET), "{stdout}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peer_check_binary_reports_an_unreachable_peer_without_the_token() {
|
||||||
|
let peer = FakePeer::new(SECRET);
|
||||||
|
let (_dir, cfg) = peer.config();
|
||||||
|
// Nothing listens on the port once the fake peer is gone.
|
||||||
|
let port = peer.port;
|
||||||
|
drop(peer);
|
||||||
|
let cfg_text = std::fs::read_to_string(&cfg)
|
||||||
|
.unwrap()
|
||||||
|
.replace(&format!(":{port}\""), ":1\"");
|
||||||
|
std::fs::write(&cfg, cfg_text).unwrap();
|
||||||
|
|
||||||
|
let out = slinuxm(&cfg, &["peer", "check", "beta"]);
|
||||||
|
let stdout = String::from_utf8(out.stdout).unwrap();
|
||||||
|
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||||
|
assert!(out.status.success(), "{stderr}");
|
||||||
|
assert!(stdout.contains("server down ("), "{stdout}");
|
||||||
|
assert!(stdout.contains("api down ("), "{stdout}");
|
||||||
|
assert!(!stdout.contains(SECRET), "{stdout}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peer_check_binary_rejects_an_unknown_peer_without_the_token() {
|
||||||
|
let fixture = PeerFixture::new("");
|
||||||
|
let out = slinuxm(fixture.config(), &["peer", "check", "nope"]);
|
||||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||||
assert!(!out.status.success());
|
assert!(!out.status.success());
|
||||||
assert!(stderr.contains("unknown peer"), "{stderr}");
|
assert!(stderr.contains("unknown peer"), "{stderr}");
|
||||||
|
|||||||
Reference in new issue
Block a user