A: share tracing capture and peer config fixtures in tests (gate round 1)

This commit is contained in:
ari committed 2026-10-19 22:31:29 -04:00
1 parent 6bff60c210
commit d3bef6bd94
5 files changed
+106 -136

No files matched your search

+3
View File
@@ -78,3 +78,6 @@ Unit tests for validation and loader; a peer-less default config is byte-identic
- 2026-10-19 Handoff (WS-A): A1 to A4 are committed on `ws/A` in task order (`A: A1 ...`, `A: A2 ...`, `A: A3 ...`, `A: A4 ...`) on top of A0. `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test` and `cargo tree -i openssl` (no match) are clean. Owned files touched: `src/peers/{cli,config,secrets,mod}.rs`, `src/config.rs`, `src/main.rs`, `config.example.toml` `[peers]`, `tests/peers_config.rs`, plus `ipnet` in `Cargo.toml`/`Cargo.lock`. Nothing outside the owned list changed and `TODO.md` was left for the merger.
- Still open for others: `peer check` against a real peer (needs B1/B2 and `real_transport`); `PeerRegistry::reload` must call the loader (B4) for reload-time re-reads; the registry/serve wiring and SIGHUP fan-out are WS-B. No Nix files changed here, so no VM test was run; when one is needed the command is `nix build && nix flake check`.
- Contract issue carried over from A0 (unchanged): section 3's `PeerConfigError` is implemented as an alias of `config::ConfigError`; no contracts.md edit was made from this workstream.
- 2026-10-20 Gate round 1 (`loop/A/gate-2.log`):
- Duplication: the `tracing` capture layer both peer test modules used now lives once in `src/peers/testing.rs` as `capture::logged` (test-only, `#[cfg(test)]`), so `config.rs` and `secrets.rs` tests share it instead of each carrying `Capture`/`FieldVisit`. `tests/peers_config.rs` uses one `PeerFixture` (private token file plus the single-`beta` config, with a `scalars` argument for the timeout lines) instead of writing the same TOML three times.
- `Cargo.toml`: `ipnet` is the one dependency this workstream adds, and the plan allows it for A2 `deny_cidrs` (see the A2 entry above). No other dependency changed; `cargo tree -i openssl` is still empty. The gate's ownership step flags `Cargo.toml`, which the plan authorises; the file is listed in the shared-file seam for exactly this case.
+1 -33
View File
@@ -184,11 +184,10 @@ fn is_loopback(url: &Url) -> bool {
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use super::*;
use crate::peers::testing::capture::logged;
use crate::peers::types::PeerName;
use tracing_subscriber::layer::SubscriberExt;
fn peer(name: &str, url: &str) -> PeerConfig {
PeerConfig {
@@ -216,37 +215,6 @@ mod tests {
}
}
struct Capture(Arc<Mutex<Vec<String>>>);
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Capture {
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut msg = String::new();
event.record(&mut FieldVisit(&mut msg));
self.0.lock().expect("log lock").push(msg);
}
}
struct FieldVisit<'a>(&'a mut String);
impl tracing::field::Visit for FieldVisit<'_> {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
use std::fmt::Write;
let _ = write!(self.0, "{}={value:?} ", field.name());
}
}
fn logged(f: impl FnOnce()) -> String {
let buf = Arc::new(Mutex::new(Vec::new()));
let sub = tracing_subscriber::registry().with(Capture(buf.clone()));
tracing::subscriber::with_default(sub, f);
let text = buf.lock().expect("log lock").join("\n");
text
}
#[test]
fn defaults_and_loopback_http_are_valid() {
validate(&PeersConfig::default()).unwrap();
+5 -35
View File
@@ -98,11 +98,10 @@ fn trim_one_newline(buf: &mut Vec<u8>) {
mod tests {
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use super::*;
use crate::peers::testing::capture::logged;
use crate::peers::types::PeerName;
use tracing_subscriber::layer::SubscriberExt;
const SECRET: &str = "slinuxm_PEER_TOKEN_SHOULD_NOT_LEAK";
@@ -161,29 +160,6 @@ mod tests {
}
}
struct Capture(Arc<Mutex<Vec<String>>>);
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Capture {
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut msg = String::new();
event.record(&mut FieldVisit(&mut msg));
self.0.lock().expect("log lock").push(msg);
}
}
struct FieldVisit<'a>(&'a mut String);
impl tracing::field::Visit for FieldVisit<'_> {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
use std::fmt::Write;
let _ = write!(self.0, "{}={value:?} ", field.name());
}
}
#[test]
fn trims_one_newline_and_rereads_a_replaced_file() {
let dir = TempDir::new();
@@ -257,16 +233,10 @@ mod tests {
SECRET
);
let logs = {
let buf = Arc::new(Mutex::new(Vec::new()));
let sub = tracing_subscriber::registry().with(Capture(buf.clone()));
let private = dir.write("logged", format!("{SECRET}\n").as_bytes(), 0o600);
tracing::subscriber::with_default(sub, || {
load_token_at(&peer(private), None).unwrap();
});
let text = buf.lock().expect("log lock").join("\n");
text
};
let private = dir.write("logged", format!("{SECRET}\n").as_bytes(), 0o600);
let logs = logged(|| {
load_token_at(&peer(private), None).unwrap();
});
assert!(!logs.contains("SHOULD_NOT_LEAK"), "{logs}");
}
+41
View File
@@ -21,6 +21,47 @@ use crate::state::AppState;
const DEFAULT_PING_BODY: &str = r#"{"status":"ok","version":"0.0.0-fake"}"#;
/// Capture of `tracing` events for tests that assert nothing leaks into logs.
#[cfg(test)]
pub(crate) mod capture {
use std::sync::{Arc, Mutex};
use tracing_subscriber::layer::SubscriberExt;
struct Layer(Arc<Mutex<Vec<String>>>);
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Layer {
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut msg = String::new();
event.record(&mut FieldVisit(&mut msg));
self.0.lock().expect("log lock").push(msg);
}
}
struct FieldVisit<'a>(&'a mut String);
impl tracing::field::Visit for FieldVisit<'_> {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
use std::fmt::Write;
let _ = write!(self.0, "{}={value:?} ", field.name());
}
}
/// Run `f` under a subscriber that records every event, and return the
/// rendered fields joined by newlines.
pub(crate) fn logged(f: impl FnOnce()) -> String {
let buf = Arc::new(Mutex::new(Vec::new()));
let sub = tracing_subscriber::registry().with(Layer(buf.clone()));
tracing::subscriber::with_default(sub, f);
let text = buf.lock().expect("log lock").join("\n");
text
}
}
#[derive(Clone)]
enum Scripted {
Response {
+56 -68
View File
@@ -86,32 +86,56 @@ fn slinuxm(config: &Path, args: &[&str]) -> std::process::Output {
.expect("run slinuxm")
}
/// One `beta` peer with a private token file, plus the config that names it.
///
/// `scalars` goes into the `[peers]` table ahead of the entry (timeouts and
/// the like); pass `""` for the defaults.
struct PeerFixture {
dir: TempDir,
token: PathBuf,
config: PathBuf,
}
impl PeerFixture {
fn new(scalars: &str) -> Self {
let dir = TempDir::new();
let token = dir.path().join("peer.token");
write_private_token(&token, SECRET);
let config = dir.path().join("config.toml");
std::fs::write(
&config,
format!(
"[peers]\nenabled = true\n{scalars}\n\
[[peers.peer]]\n\
name = \"beta\"\n\
url = \"http://127.0.0.1:1984\"\n\
token_file = \"{}\"\n",
token.display()
),
)
.unwrap();
Self { dir, token, config }
}
fn dir(&self) -> &Path {
self.dir.path()
}
fn token(&self) -> &Path {
&self.token
}
fn config(&self) -> &Path {
&self.config
}
}
#[test]
fn print_config_shows_peer_paths_and_not_token_contents() {
let dir = TempDir::new();
let token = dir.path().join("peer.token");
write_private_token(&token, SECRET);
let cfg = dir.path().join("config.toml");
std::fs::write(
&cfg,
format!(
"\
[peers]\n\
enabled = true\n\
tcp_interval_secs = 20\n\
tcp_timeout_secs = 4\n\
\n\
[[peers.peer]]\n\
name = \"beta\"\n\
url = \"http://127.0.0.1:1984\"\n\
token_file = \"{}\"\n\
",
token.display()
),
)
.unwrap();
let fixture = PeerFixture::new("tcp_interval_secs = 20\ntcp_timeout_secs = 4");
let (dir, token, cfg) = (fixture.dir(), fixture.token(), fixture.config());
let out = slinuxm(&cfg, &["--print-config"]);
let out = slinuxm(cfg, &["--print-config"]);
let stdout = String::from_utf8(out.stdout).unwrap();
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(
@@ -124,7 +148,7 @@ fn print_config_shows_peer_paths_and_not_token_contents() {
assert!(!stdout.contains("SHOULD_NOT_LEAK"), "{stdout}");
assert!(!stderr.contains("SHOULD_NOT_LEAK"), "{stderr}");
let bare = dir.path().join("empty.toml");
let bare = dir.join("empty.toml");
std::fs::write(&bare, "").unwrap();
let out = slinuxm(&bare, &["--print-config"]);
let stdout = String::from_utf8(out.stdout).unwrap();
@@ -142,28 +166,10 @@ fn print_config_shows_peer_paths_and_not_token_contents() {
#[test]
fn peer_list_prints_config_and_never_the_token() {
let dir = TempDir::new();
let token = dir.path().join("peer.token");
write_private_token(&token, SECRET);
let cfg = dir.path().join("config.toml");
std::fs::write(
&cfg,
format!(
"\
[peers]\n\
enabled = true\n\
\n\
[[peers.peer]]\n\
name = \"beta\"\n\
url = \"http://127.0.0.1:1984\"\n\
token_file = \"{}\"\n\
",
token.display()
),
)
.unwrap();
let fixture = PeerFixture::new("");
let (dir, token, cfg) = (fixture.dir(), fixture.token(), fixture.config());
let out = slinuxm(&cfg, &["peer", "list"]);
let out = slinuxm(cfg, &["peer", "list"]);
let stdout = String::from_utf8(out.stdout).unwrap();
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(out.status.success(), "peer list failed: {stderr}");
@@ -173,7 +179,7 @@ fn peer_list_prints_config_and_never_the_token() {
assert!(!stdout.contains(SECRET), "{stdout}");
assert!(!stderr.contains(SECRET), "{stderr}");
let empty = dir.path().join("empty.toml");
let empty = dir.join("empty.toml");
std::fs::write(&empty, "").unwrap();
let out = slinuxm(&empty, &["peer", "list"]);
let stdout = String::from_utf8(out.stdout).unwrap();
@@ -204,28 +210,10 @@ async fn peer_check_reports_a_probe_through_the_fake_transport() {
#[test]
fn peer_check_binary_reports_the_missing_transport_without_the_token() {
let dir = TempDir::new();
let token = dir.path().join("peer.token");
write_private_token(&token, SECRET);
let cfg = dir.path().join("config.toml");
std::fs::write(
&cfg,
format!(
"\
[peers]\n\
enabled = true\n\
\n\
[[peers.peer]]\n\
name = \"beta\"\n\
url = \"http://127.0.0.1:1984\"\n\
token_file = \"{}\"\n\
",
token.display()
),
)
.unwrap();
let fixture = PeerFixture::new("");
let cfg = fixture.config();
let out = slinuxm(&cfg, &["peer", "check", "beta"]);
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(), "no transport yet: {stdout}");
@@ -233,7 +221,7 @@ fn peer_check_binary_reports_the_missing_transport_without_the_token() {
assert!(!stdout.contains(SECRET), "{stdout}");
assert!(!stderr.contains(SECRET), "{stderr}");
let out = slinuxm(&cfg, &["peer", "check", "nope"]);
let out = slinuxm(cfg, &["peer", "check", "nope"]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(!out.status.success());
assert!(stderr.contains("unknown peer"), "{stderr}");