A: test the token-free commands, snapshot print-config and tighten assertions

The peer-less `--print-config` output is now compared against the committed
pre-peers text plus the default `[peers]` block, and a config with a peer
must leave everything before that block byte-identical. New binary tests
cover `--print-config`, `peer list`, `token create|list` with an unreadable
token file, and `serve` refusing to start while naming the peer.
This commit is contained in:
ari committed 2026-10-19 22:31:29 -04:00
1 parent de7a47d040
commit e2ff40beae
1 file changed
+235 -55
+235 -55
View File
@@ -14,6 +14,7 @@ use skyg_linux_tracker::api;
use skyg_linux_tracker::config::{CliOverrides, Config}; use skyg_linux_tracker::config::{CliOverrides, Config};
use skyg_linux_tracker::peers::testing::{ use skyg_linux_tracker::peers::testing::{
fake_peers_config, fake_state_with_peers, registry_with, static_registry, FakeTransport, fake_peers_config, fake_state_with_peers, registry_with, static_registry, FakeTransport,
TempDir,
}; };
use skyg_linux_tracker::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus}; use skyg_linux_tracker::peers::types::{ApiStatus, AuthState, PeerName, PeerStatus, ServerStatus};
use skyg_linux_tracker::peers::{cli, PeerError, ProxyOpts}; use skyg_linux_tracker::peers::{cli, PeerError, ProxyOpts};
@@ -45,36 +46,6 @@ fn status(name: &str, up: bool) -> PeerStatus {
const SECRET: &str = "slinuxm_PEER_TOKEN_SHOULD_NOT_LEAK"; const SECRET: &str = "slinuxm_PEER_TOKEN_SHOULD_NOT_LEAK";
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Self {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.subsec_nanos();
let dir =
std::env::temp_dir().join(format!("slinuxm-peers-{}-{nanos}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
Self(dir)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn write_private_token(path: &Path, contents: &str) {
std::fs::write(path, contents).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
}
fn slinuxm(config: &Path, args: &[&str]) -> std::process::Output { fn slinuxm(config: &Path, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_slinuxm")) Command::new(env!("CARGO_BIN_EXE_slinuxm"))
.arg("--config") .arg("--config")
@@ -98,9 +69,8 @@ struct PeerFixture {
impl PeerFixture { impl PeerFixture {
fn new(scalars: &str) -> Self { fn new(scalars: &str) -> Self {
let dir = TempDir::new(); let dir = TempDir::new("peers");
let token = dir.path().join("peer.token"); let token = dir.write("peer.token", SECRET.as_bytes(), 0o600);
write_private_token(&token, SECRET);
let config = dir.path().join("config.toml"); let config = dir.path().join("config.toml");
std::fs::write( std::fs::write(
&config, &config,
@@ -130,10 +100,102 @@ impl PeerFixture {
} }
} }
/// The default `--print-config` output before the `[peers]` table existed.
/// Committed so that adding peers cannot perturb any other section: if this
/// breaks, the diff has to be explained, not adjusted.
const PRE_PEERS_DEFAULT: &str = r#"[server]
bind = "127.0.0.1"
port = 1984
allowed_hosts = []
allowed_origins = []
[server.tls]
enabled = false
cert_file = ""
key_file = ""
[auth]
enabled = true
db_path = "/var/lib/skyg-linux-tracker/db.sqlite"
[otel]
enabled = false
endpoint = "http://localhost:4317"
protocol = "grpc"
service_name = "skyg-linux-tracker"
export_unit_metrics = true
export_logs = false
metrics_interval_secs = 30
[otel.headers]
[otel.logs]
journal_units = []
docker_containers = []
[otel.metrics]
units = []
containers = []
[sources]
docker_socket = "/var/run/docker.sock"
journal_namespace = ""
[limits]
max_lines = 1000
max_tail = 1000
max_follow_secs = 60
"#;
/// Peer-less defaults of the `[peers]` table: the only addition to
/// [`PRE_PEERS_DEFAULT`].
const PEERS_DEFAULT: &str = r#"[peers]
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 = 8388608
max_concurrent_per_peer = 4
max_concurrent_total = 16
deny_cidrs = [
"169.254.0.0/16",
"0.0.0.0/8",
]
peer = []
"#;
/// Everything before the `[peers]` table.
fn split_peers(text: &str) -> (&str, &str) {
let idx = text
.find("[peers]\n")
.unwrap_or_else(|| panic!("no peers table in:\n{text}"));
(&text[..idx], &text[idx..])
}
#[test]
fn print_config_default_is_the_old_output_plus_only_the_peers_block() {
let fixture = PeerFixture::new("");
let empty = fixture.dir().join("empty.toml");
std::fs::write(&empty, "").unwrap();
let out = slinuxm(&empty, &["--print-config"]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8(out.stdout).unwrap();
assert_eq!(stdout, format!("{PRE_PEERS_DEFAULT}{PEERS_DEFAULT}"));
assert_eq!(split_peers(&stdout).0, PRE_PEERS_DEFAULT);
}
#[test] #[test]
fn print_config_shows_peer_paths_and_not_token_contents() { fn print_config_shows_peer_paths_and_not_token_contents() {
let fixture = PeerFixture::new("tcp_interval_secs = 20\ntcp_timeout_secs = 4"); let fixture = PeerFixture::new("tcp_interval_secs = 20\ntcp_timeout_secs = 4");
let (dir, token, cfg) = (fixture.dir(), fixture.token(), fixture.config()); let (token, cfg) = (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 stdout = String::from_utf8(out.stdout).unwrap();
@@ -142,26 +204,20 @@ fn print_config_shows_peer_paths_and_not_token_contents() {
out.status.success(), out.status.success(),
"print-config failed: {stderr}\n{stdout}" "print-config failed: {stderr}\n{stdout}"
); );
assert!(stdout.contains("[peers]"));
assert!(stdout.contains("enabled = true"));
assert!(stdout.contains(&token.display().to_string()));
assert!(!stdout.contains("SHOULD_NOT_LEAK"), "{stdout}");
assert!(!stderr.contains("SHOULD_NOT_LEAK"), "{stderr}"); assert!(!stderr.contains("SHOULD_NOT_LEAK"), "{stderr}");
assert!(!stdout.contains("SHOULD_NOT_LEAK"), "{stdout}");
let bare = dir.join("empty.toml"); let (head, peers) = split_peers(&stdout);
std::fs::write(&bare, "").unwrap(); // Adding a peer entry changes nothing outside the peers table.
let out = slinuxm(&bare, &["--print-config"]); assert_eq!(head, PRE_PEERS_DEFAULT);
let stdout = String::from_utf8(out.stdout).unwrap(); assert!(peers.contains("enabled = true\n"), "{peers}");
assert!(peers.contains("tcp_interval_secs = 20\n"), "{peers}");
assert!(peers.contains("tcp_timeout_secs = 4\n"), "{peers}");
assert!( assert!(
out.status.success(), peers.contains(&format!("token_file = {:?}\n", token.display().to_string())),
"{}", "{peers}"
String::from_utf8_lossy(&out.stderr)
); );
assert!(stdout.contains("[peers]\n")); assert!(peers.contains("name = \"beta\"\n"), "{peers}");
assert!(stdout.contains("enabled = false\n"));
assert!(stdout.contains("port = 1984\n"));
assert!(stdout.contains("peer = []\n"));
assert!(!stdout.contains("SHOULD_NOT_LEAK"));
} }
#[test] #[test]
@@ -228,6 +284,114 @@ fn peer_check_binary_reports_the_missing_transport_without_the_token() {
assert!(!stderr.contains(SECRET), "{stderr}"); assert!(!stderr.contains(SECRET), "{stderr}");
} }
/// A peer whose token file does not exist: the state outside the unit, before
/// credentials are installed, and in a shell that cannot see them.
struct MissingTokenFixture {
dir: TempDir,
config: PathBuf,
}
impl MissingTokenFixture {
fn new() -> Self {
let dir = TempDir::new("peers-missing");
let token = dir.path().join("peer-beta-missing");
assert!(!token.exists());
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:1984\"\n\
token_file = \"{}\"\n",
token.display()
),
)
.unwrap();
Self { dir, config }
}
fn config(&self) -> &Path {
&self.config
}
fn db_path(&self) -> PathBuf {
self.dir.path().join("db.sqlite")
}
}
#[test]
fn commands_that_do_not_contact_a_peer_work_without_the_token_file() {
let fixture = MissingTokenFixture::new();
let cfg = fixture.config();
let db = fixture.db_path();
let db = db.to_str().unwrap();
let out = slinuxm(cfg, &["--print-config"]);
assert!(
out.status.success(),
"--print-config: {}",
String::from_utf8_lossy(&out.stderr)
);
let out = slinuxm(cfg, &["peer", "list"]);
let stdout = String::from_utf8(out.stdout).unwrap();
assert!(
out.status.success(),
"peer list: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(stdout.contains("beta"), "{stdout}");
// Token management runs as the service user against the service database,
// usually from a shell that cannot read the credential directory.
let out = slinuxm(cfg, &["--db-path", db, "token", "create", "ci"]);
assert!(
out.status.success(),
"token create: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(!String::from_utf8_lossy(&out.stdout).contains(SECRET));
let out = slinuxm(cfg, &["--db-path", db, "token", "list"]);
let stdout = String::from_utf8(out.stdout).unwrap();
assert!(
out.status.success(),
"token list: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(stdout.contains("ci"), "{stdout}");
}
#[test]
fn peer_check_reports_the_missing_token_before_the_missing_transport() {
let fixture = MissingTokenFixture::new();
let out = slinuxm(fixture.config(), &["peer", "check", "beta"]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(!out.status.success());
assert!(stderr.contains("peer beta"), "{stderr}");
assert!(stderr.contains("not readable"), "{stderr}");
assert!(!stderr.contains("transport not available"), "{stderr}");
}
#[test]
fn serve_refuses_to_start_and_names_the_peer_with_the_unreadable_token() {
let fixture = MissingTokenFixture::new();
let db = fixture.db_path();
// The token check runs before anything binds, so a regression here would
// show up as a started server rather than as a flaky assertion.
let out = slinuxm(
fixture.config(),
&["--db-path", db.to_str().unwrap(), "--port", "1984"],
);
let stdout = String::from_utf8(out.stdout).unwrap();
let stderr = String::from_utf8(out.stderr).unwrap();
assert!(!out.status.success(), "serve started: {stdout}");
assert!(stderr.contains("peer beta"), "{stderr}");
assert!(stderr.contains("not readable"), "{stderr}");
}
#[tokio::test] #[tokio::test]
async fn peerless_default_is_off_and_unchanged() { async fn peerless_default_is_off_and_unchanged() {
let config = Config::default(); let config = Config::default();
@@ -249,7 +413,8 @@ fn vm_peer_entries_load_when_enabled_and_ca_file_are_omitted() {
let gamma_token = jail.directory().join("peer-gamma"); let gamma_token = jail.directory().join("peer-gamma");
let delta_token = jail.directory().join("peer-delta"); let delta_token = jail.directory().join("peer-delta");
for path in [&beta_token, &gamma_token, &delta_token] { for path in [&beta_token, &gamma_token, &delta_token] {
write_private_token(path, "pending\n"); std::fs::write(path, "pending\n").unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
} }
jail.create_file( jail.create_file(
"peers.toml", "peers.toml",
@@ -353,7 +518,7 @@ fn load_rejects_invalid_peers_and_accepts_a_placeholder_token() {
.expect_err("peer name regex"); .expect_err("peer name regex");
let text = err.to_string(); let text = err.to_string();
assert!( assert!(
text.contains("must match") || text.contains("Beta"), text.contains("must match ^[a-z0-9][a-z0-9_-]{0,31}$"),
"{text}" "{text}"
); );
@@ -396,14 +561,20 @@ fn load_rejects_invalid_peers_and_accepts_a_placeholder_token() {
missing.display() missing.display()
), ),
)?; )?;
let err = Config::load(Some(Path::new("missing.toml")), &CliOverrides::default()) // Loading only checks the config text; the credential is checked by
// `serve` (and `peer check`) so token commands work without it.
let cfg = Config::load(Some(Path::new("missing.toml")), &CliOverrides::default())
.expect("a missing token file is not a config error");
let err = cfg
.validate_token_readiness()
.expect_err("missing token file"); .expect_err("missing token file");
let text = err.to_string(); let text = err.to_string();
assert!(text.contains("peer beta"), "{text}"); assert!(text.contains("peer beta"), "{text}");
assert!(text.contains("not readable"), "{text}"); assert!(text.contains("not readable"), "{text}");
let placeholder = jail.directory().join("placeholder"); let placeholder = jail.directory().join("placeholder");
write_private_token(&placeholder, "pending\n"); std::fs::write(&placeholder, "pending\n").unwrap();
std::fs::set_permissions(&placeholder, std::fs::Permissions::from_mode(0o600)).unwrap();
jail.create_file( jail.create_file(
"ok.toml", "ok.toml",
&format!( &format!(
@@ -424,6 +595,8 @@ fn load_rejects_invalid_peers_and_accepts_a_placeholder_token() {
)?; )?;
let cfg = Config::load(Some(Path::new("ok.toml")), &CliOverrides::default()) let cfg = Config::load(Some(Path::new("ok.toml")), &CliOverrides::default())
.expect("placeholder token file must load"); .expect("placeholder token file must load");
cfg.validate_token_readiness()
.expect("placeholder token is readable");
assert_eq!(cfg.peers.peer[0].name.as_str(), "beta"); assert_eq!(cfg.peers.peer[0].name.as_str(), "beta");
assert!(!format!("{cfg:?}").contains("pending")); assert!(!format!("{cfg:?}").contains("pending"));
Ok(()) Ok(())
@@ -457,6 +630,8 @@ fn config_load_uses_the_token_loader_and_rereads_a_rotated_file() {
// systemd's credential directory protects the file, not its mode. // systemd's credential directory protects the file, not its mode.
let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default()) let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default())
.expect("credential-directory token must load"); .expect("credential-directory token must load");
cfg.validate_token_readiness()
.expect("credential-directory token must be ready");
assert_eq!(cfg.peers.peer[0].name.as_str(), "beta"); assert_eq!(cfg.peers.peer[0].name.as_str(), "beta");
let outside = jail.directory().join("outside"); let outside = jail.directory().join("outside");
@@ -478,7 +653,10 @@ fn config_load_uses_the_token_loader_and_rereads_a_rotated_file() {
loose.display() loose.display()
), ),
)?; )?;
let err = Config::load(Some(Path::new("loose.toml")), &CliOverrides::default()) let cfg = Config::load(Some(Path::new("loose.toml")), &CliOverrides::default())
.expect("the token mode is a startup check, not a parse error");
let err = cfg
.validate_token_readiness()
.expect_err("group/world readable token outside the credential dir"); .expect_err("group/world readable token outside the credential dir");
let text = err.to_string(); let text = err.to_string();
assert!(text.contains("peer beta"), "{text}"); assert!(text.contains("peer beta"), "{text}");
@@ -489,6 +667,8 @@ fn config_load_uses_the_token_loader_and_rereads_a_rotated_file() {
std::fs::write(&token, "rotated\n").unwrap(); std::fs::write(&token, "rotated\n").unwrap();
let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default()) let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default())
.expect("rotated token must load"); .expect("rotated token must load");
cfg.validate_token_readiness()
.expect("rotated token must be ready");
let secret = skyg_linux_tracker::peers::load_token(&cfg.peers.peer[0]).unwrap(); let secret = skyg_linux_tracker::peers::load_token(&cfg.peers.peer[0]).unwrap();
assert_eq!(secret.expose(), "rotated"); assert_eq!(secret.expose(), "rotated");
assert!(!format!("{secret:?}").contains("rotated")); assert!(!format!("{secret:?}").contains("rotated"));