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.
828 lines
27 KiB
Rust
828 lines
27 KiB
Rust
//! Peer seams exercised end to end against the fake transport and fake
|
|
//! sources: the peer-less default, the ping route, and registry reads.
|
|
|
|
use std::net::{IpAddr, Ipv4Addr};
|
|
use std::os::unix::fs::PermissionsExt;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::time::Duration;
|
|
|
|
use axum::body::{to_bytes, Body};
|
|
use axum::http::{Request, StatusCode};
|
|
use figment::Jail;
|
|
use skyg_linux_tracker::api;
|
|
use skyg_linux_tracker::config::{CliOverrides, Config};
|
|
use skyg_linux_tracker::peers::testing::{
|
|
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::{cli, PeerError, ProxyOpts};
|
|
use tower::ServiceExt;
|
|
|
|
async fn get(app: &axum::Router, uri: &str) -> (StatusCode, String) {
|
|
let resp = app
|
|
.clone()
|
|
.oneshot(Request::get(uri).body(Body::empty()).unwrap())
|
|
.await
|
|
.unwrap();
|
|
let status = resp.status();
|
|
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
|
(status, String::from_utf8(body.to_vec()).unwrap())
|
|
}
|
|
|
|
fn status(name: &str, up: bool) -> PeerStatus {
|
|
PeerStatus {
|
|
name: PeerName::parse(name).unwrap(),
|
|
enabled: true,
|
|
url: format!("http://{name}:1984"),
|
|
server: ServerStatus {
|
|
up,
|
|
..ServerStatus::default()
|
|
},
|
|
api: ApiStatus::default(),
|
|
}
|
|
}
|
|
|
|
const SECRET: &str = "slinuxm_PEER_TOKEN_SHOULD_NOT_LEAK";
|
|
|
|
fn slinuxm(config: &Path, args: &[&str]) -> std::process::Output {
|
|
Command::new(env!("CARGO_BIN_EXE_slinuxm"))
|
|
.arg("--config")
|
|
.arg(config)
|
|
.args(args)
|
|
.env_clear()
|
|
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
|
|
.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("peers");
|
|
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{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
|
|
}
|
|
}
|
|
|
|
/// 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]
|
|
fn print_config_shows_peer_paths_and_not_token_contents() {
|
|
let fixture = PeerFixture::new("tcp_interval_secs = 20\ntcp_timeout_secs = 4");
|
|
let (token, cfg) = (fixture.token(), fixture.config());
|
|
|
|
let out = slinuxm(cfg, &["--print-config"]);
|
|
let stdout = String::from_utf8(out.stdout).unwrap();
|
|
let stderr = String::from_utf8(out.stderr).unwrap();
|
|
assert!(
|
|
out.status.success(),
|
|
"print-config failed: {stderr}\n{stdout}"
|
|
);
|
|
assert!(!stderr.contains("SHOULD_NOT_LEAK"), "{stderr}");
|
|
assert!(!stdout.contains("SHOULD_NOT_LEAK"), "{stdout}");
|
|
|
|
let (head, peers) = split_peers(&stdout);
|
|
// Adding a peer entry changes nothing outside the peers table.
|
|
assert_eq!(head, PRE_PEERS_DEFAULT);
|
|
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!(
|
|
peers.contains(&format!("token_file = {:?}\n", token.display().to_string())),
|
|
"{peers}"
|
|
);
|
|
assert!(peers.contains("name = \"beta\"\n"), "{peers}");
|
|
}
|
|
|
|
#[test]
|
|
fn peer_list_prints_config_and_never_the_token() {
|
|
let fixture = PeerFixture::new("");
|
|
let (dir, token, cfg) = (fixture.dir(), fixture.token(), fixture.config());
|
|
|
|
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}");
|
|
assert!(stdout.contains("beta"), "{stdout}");
|
|
assert!(stdout.contains("http://127.0.0.1:1984"), "{stdout}");
|
|
assert!(stdout.contains(&token.display().to_string()), "{stdout}");
|
|
assert!(!stdout.contains(SECRET), "{stdout}");
|
|
assert!(!stderr.contains(SECRET), "{stderr}");
|
|
|
|
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();
|
|
assert!(out.status.success(), "{stdout}");
|
|
assert_eq!(stdout, "no peers configured\n");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn peer_check_reports_a_probe_through_the_fake_transport() {
|
|
let fake = FakeTransport::new();
|
|
fake.peer("beta").tcp(Ok(Duration::from_millis(4)));
|
|
fake.peer("beta").respond(
|
|
"/api/v1/ping",
|
|
200,
|
|
"application/json",
|
|
r#"{"status":"ok"}"#,
|
|
);
|
|
let cfg = fake_peers_config(&["beta"]);
|
|
|
|
let report = cli::check_report(fake.as_ref(), &cfg, "beta")
|
|
.await
|
|
.unwrap();
|
|
assert!(report.contains("peer beta"), "{report}");
|
|
assert!(report.contains("server up (4 ms)"), "{report}");
|
|
assert!(report.contains("api up, auth ok"), "{report}");
|
|
assert!(!report.contains(SECRET), "{report}");
|
|
}
|
|
|
|
#[test]
|
|
fn peer_check_binary_reports_the_missing_transport_without_the_token() {
|
|
let fixture = PeerFixture::new("");
|
|
let cfg = fixture.config();
|
|
|
|
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}");
|
|
assert!(stderr.contains("transport not available"), "{stderr}");
|
|
assert!(!stdout.contains(SECRET), "{stdout}");
|
|
assert!(!stderr.contains(SECRET), "{stderr}");
|
|
|
|
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}");
|
|
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]
|
|
async fn peerless_default_is_off_and_unchanged() {
|
|
let config = Config::default();
|
|
assert!(!config.peers.enabled);
|
|
assert!(config.peers.peer.is_empty());
|
|
|
|
let state = skyg_linux_tracker::sources::fake::fake_state(config);
|
|
assert!(state.peers.is_none());
|
|
let (s, b) = get(&api::router(state), "/systemd/units").await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
assert!(!b.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error
|
|
fn vm_peer_entries_load_when_enabled_and_ca_file_are_omitted() {
|
|
Jail::expect_with(|jail| {
|
|
let beta_token = jail.directory().join("peer-beta");
|
|
let gamma_token = jail.directory().join("peer-gamma");
|
|
let delta_token = jail.directory().join("peer-delta");
|
|
for path in [&beta_token, &gamma_token, &delta_token] {
|
|
std::fs::write(path, "pending\n").unwrap();
|
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
|
}
|
|
jail.create_file(
|
|
"peers.toml",
|
|
&format!(
|
|
r#"
|
|
[server]
|
|
bind = "0.0.0.0"
|
|
|
|
[peers]
|
|
enabled = true
|
|
tcp_interval_secs = 2
|
|
tcp_timeout_secs = 1
|
|
api_interval_secs = 3
|
|
api_timeout_secs = 2
|
|
fail_threshold = 2
|
|
request_timeout_secs = 4
|
|
|
|
[[peers.peer]]
|
|
name = "beta"
|
|
url = "http://beta:1984"
|
|
token_file = "{beta}"
|
|
allow_plain_http = true
|
|
|
|
[[peers.peer]]
|
|
name = "gamma"
|
|
url = "https://gamma:1984"
|
|
token_file = "{gamma}"
|
|
ca_file = "/etc/ssl/private-ca.pem"
|
|
allow_plain_http = false
|
|
|
|
[[peers.peer]]
|
|
name = "delta"
|
|
url = "https://delta:1984"
|
|
token_file = "{delta}"
|
|
enabled = false
|
|
"#,
|
|
beta = beta_token.display(),
|
|
gamma = gamma_token.display(),
|
|
delta = delta_token.display(),
|
|
),
|
|
)?;
|
|
let cfg = Config::load(Some(Path::new("peers.toml")), &CliOverrides::default())
|
|
.expect("peer entries must deserialize");
|
|
assert!(cfg.auth.enabled);
|
|
assert_eq!(cfg.server.bind, IpAddr::V4(Ipv4Addr::UNSPECIFIED));
|
|
assert!(cfg.peers.enabled);
|
|
assert_eq!(cfg.peers.tcp_interval_secs, 2);
|
|
assert_eq!(cfg.peers.api_timeout_secs, 2);
|
|
assert_eq!(cfg.peers.request_timeout_secs, 4);
|
|
assert_eq!(cfg.peers.max_response_bytes, 8 * 1024 * 1024);
|
|
|
|
let peer = |name: &str| {
|
|
cfg.peers
|
|
.peer
|
|
.iter()
|
|
.find(|p| p.name.as_str() == name)
|
|
.unwrap()
|
|
};
|
|
let beta = peer("beta");
|
|
assert!(beta.enabled);
|
|
assert!(beta.allow_plain_http);
|
|
assert!(beta.ca_file.is_none());
|
|
assert_eq!(beta.token_file, beta_token);
|
|
let gamma = peer("gamma");
|
|
assert!(gamma.enabled);
|
|
assert!(!gamma.allow_plain_http);
|
|
assert_eq!(
|
|
gamma.ca_file.as_deref(),
|
|
Some(Path::new("/etc/ssl/private-ca.pem"))
|
|
);
|
|
let delta = peer("delta");
|
|
assert!(!delta.enabled);
|
|
assert!(!delta.allow_plain_http);
|
|
assert!(delta.ca_file.is_none());
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error
|
|
fn load_rejects_invalid_peers_and_accepts_a_placeholder_token() {
|
|
Jail::expect_with(|jail| {
|
|
jail.create_file("empty-peers.toml", "[peers]\nenabled = true\n")?;
|
|
Config::load(
|
|
Some(Path::new("empty-peers.toml")),
|
|
&CliOverrides::default(),
|
|
)
|
|
.expect("enabled with zero peers is a warning, not an error");
|
|
|
|
jail.create_file(
|
|
"bad-name.toml",
|
|
"\
|
|
[peers]\n\
|
|
[[peers.peer]]\n\
|
|
name = \"Beta\"\n\
|
|
url = \"https://beta:1984\"\n\
|
|
token_file = \"/run/peers/beta\"\n\
|
|
",
|
|
)?;
|
|
let err = Config::load(Some(Path::new("bad-name.toml")), &CliOverrides::default())
|
|
.expect_err("peer name regex");
|
|
let text = err.to_string();
|
|
assert!(
|
|
text.contains("must match ^[a-z0-9][a-z0-9_-]{0,31}$"),
|
|
"{text}"
|
|
);
|
|
|
|
jail.create_file(
|
|
"timeout.toml",
|
|
"[peers]\ntcp_interval_secs = 10\ntcp_timeout_secs = 10\n",
|
|
)?;
|
|
let err = Config::load(Some(Path::new("timeout.toml")), &CliOverrides::default())
|
|
.expect_err("timeout below interval");
|
|
assert!(err.to_string().contains("tcp_timeout_secs"), "{err}");
|
|
|
|
jail.create_file(
|
|
"userinfo.toml",
|
|
"\
|
|
[peers]\n\
|
|
[[peers.peer]]\n\
|
|
name = \"beta\"\n\
|
|
url = \"http://user:s3cret@127.0.0.1:1984\"\n\
|
|
token_file = \"/run/peers/beta\"\n\
|
|
",
|
|
)?;
|
|
let err = Config::load(Some(Path::new("userinfo.toml")), &CliOverrides::default())
|
|
.expect_err("userinfo");
|
|
let text = err.to_string();
|
|
assert!(text.contains("userinfo"), "{text}");
|
|
assert!(!text.contains("s3cret"), "{text}");
|
|
|
|
let missing = jail.directory().join("not-there");
|
|
jail.create_file(
|
|
"missing.toml",
|
|
&format!(
|
|
"\
|
|
[peers]\n\
|
|
enabled = true\n\
|
|
[[peers.peer]]\n\
|
|
name = \"beta\"\n\
|
|
url = \"https://beta:1984\"\n\
|
|
token_file = \"{}\"\n\
|
|
",
|
|
missing.display()
|
|
),
|
|
)?;
|
|
// 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");
|
|
let text = err.to_string();
|
|
assert!(text.contains("peer beta"), "{text}");
|
|
assert!(text.contains("not readable"), "{text}");
|
|
|
|
let placeholder = jail.directory().join("placeholder");
|
|
std::fs::write(&placeholder, "pending\n").unwrap();
|
|
std::fs::set_permissions(&placeholder, std::fs::Permissions::from_mode(0o600)).unwrap();
|
|
jail.create_file(
|
|
"ok.toml",
|
|
&format!(
|
|
"\
|
|
[peers]\n\
|
|
enabled = true\n\
|
|
tcp_interval_secs = 2\n\
|
|
tcp_timeout_secs = 1\n\
|
|
api_interval_secs = 3\n\
|
|
api_timeout_secs = 2\n\
|
|
[[peers.peer]]\n\
|
|
name = \"beta\"\n\
|
|
url = \"http://127.0.0.1:1984\"\n\
|
|
token_file = \"{}\"\n\
|
|
",
|
|
placeholder.display()
|
|
),
|
|
)?;
|
|
let cfg = Config::load(Some(Path::new("ok.toml")), &CliOverrides::default())
|
|
.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!(!format!("{cfg:?}").contains("pending"));
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error
|
|
fn config_load_uses_the_token_loader_and_rereads_a_rotated_file() {
|
|
Jail::expect_with(|jail| {
|
|
let creds = jail.directory().join("credentials");
|
|
jail.create_dir("credentials")?;
|
|
jail.set_env("CREDENTIALS_DIRECTORY", creds.display());
|
|
let token = creds.join("peer-beta");
|
|
std::fs::write(&token, "pending\n").unwrap();
|
|
std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o644)).unwrap();
|
|
jail.create_file(
|
|
"creds.toml",
|
|
&format!(
|
|
"\
|
|
[peers]\n\
|
|
enabled = true\n\
|
|
[[peers.peer]]\n\
|
|
name = \"beta\"\n\
|
|
url = \"http://127.0.0.1:1984\"\n\
|
|
token_file = \"{}\"\n\
|
|
",
|
|
token.display()
|
|
),
|
|
)?;
|
|
// systemd's credential directory protects the file, not its mode.
|
|
let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default())
|
|
.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");
|
|
|
|
let outside = jail.directory().join("outside");
|
|
jail.create_dir("outside")?;
|
|
let loose = outside.join("peer-beta");
|
|
std::fs::write(&loose, "pending\n").unwrap();
|
|
std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o644)).unwrap();
|
|
jail.create_file(
|
|
"loose.toml",
|
|
&format!(
|
|
"\
|
|
[peers]\n\
|
|
enabled = true\n\
|
|
[[peers.peer]]\n\
|
|
name = \"beta\"\n\
|
|
url = \"http://127.0.0.1:1984\"\n\
|
|
token_file = \"{}\"\n\
|
|
",
|
|
loose.display()
|
|
),
|
|
)?;
|
|
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");
|
|
let text = err.to_string();
|
|
assert!(text.contains("peer beta"), "{text}");
|
|
assert!(text.contains("group or world readable"), "{text}");
|
|
assert!(!text.contains("pending"), "{text}");
|
|
|
|
// The loader keeps no copy: a replacement file is read on the next call.
|
|
std::fs::write(&token, "rotated\n").unwrap();
|
|
let cfg = Config::load(Some(Path::new("creds.toml")), &CliOverrides::default())
|
|
.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();
|
|
assert_eq!(secret.expose(), "rotated");
|
|
assert!(!format!("{secret:?}").contains("rotated"));
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn ping_without_a_token_is_unauthorized() {
|
|
let pool = sqlx::sqlite::SqlitePoolOptions::new()
|
|
.max_connections(1)
|
|
.connect("sqlite::memory:")
|
|
.await
|
|
.unwrap();
|
|
skyg_linux_tracker::db::migrate(&pool).await.unwrap();
|
|
let token = skyg_linux_tracker::auth::tokens::create(&pool, "ping")
|
|
.await
|
|
.unwrap();
|
|
|
|
let mut config = Config::default();
|
|
config.auth.enabled = true;
|
|
let mut state = skyg_linux_tracker::sources::fake::fake_state(config);
|
|
state.db = Some(pool);
|
|
let app = skyg_linux_tracker::server::build_router(state);
|
|
|
|
let (status, body, www) = request(&app, "/api/v1/ping", None).await;
|
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
|
assert_eq!(www.as_deref(), Some("Bearer"));
|
|
assert!(body.contains("unauthorized"));
|
|
|
|
let (status, body, _) = request(&app, "/api/v1/ping", Some(&format!("Bearer {token}"))).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
|
|
assert_eq!(v["status"], "ok");
|
|
assert!(v["version"].as_str().is_some_and(|s| !s.is_empty()));
|
|
}
|
|
|
|
async fn request(
|
|
app: &axum::Router,
|
|
uri: &str,
|
|
authorization: Option<&str>,
|
|
) -> (StatusCode, String, Option<String>) {
|
|
let mut builder = Request::builder().uri(uri);
|
|
if let Some(auth) = authorization {
|
|
builder = builder.header("authorization", auth);
|
|
}
|
|
let resp = app
|
|
.clone()
|
|
.oneshot(builder.body(Body::empty()).unwrap())
|
|
.await
|
|
.unwrap();
|
|
let status = resp.status();
|
|
let www = resp
|
|
.headers()
|
|
.get(axum::http::header::WWW_AUTHENTICATE)
|
|
.and_then(|v| v.to_str().ok())
|
|
.map(str::to_owned);
|
|
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
|
|
(status, String::from_utf8(body.to_vec()).unwrap(), www)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn fake_state_carries_the_registry() {
|
|
let fake = FakeTransport::new();
|
|
let reg = registry_with(fake, fake_peers_config(&["beta", "gamma"]));
|
|
let state = fake_state_with_peers(Config::default(), reg);
|
|
let peers = state.peers.as_ref().expect("registry present");
|
|
let names: Vec<_> = peers
|
|
.snapshot()
|
|
.into_iter()
|
|
.map(|p| p.name.as_str().to_owned())
|
|
.collect();
|
|
assert_eq!(names, ["beta", "gamma"]);
|
|
assert_eq!(peers.status("beta").unwrap().api.auth, AuthState::Unknown);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn registry_proxies_through_the_fake_and_records_the_request() {
|
|
let fake = FakeTransport::new();
|
|
fake.peer("beta")
|
|
.respond("/systemd/units", 200, "application/json", r#"{"units":[]}"#);
|
|
let reg = registry_with(fake.clone(), fake_peers_config(&["beta"]));
|
|
|
|
let resp = reg
|
|
.get(
|
|
"beta",
|
|
"/systemd/units",
|
|
&[("state".into(), "failed".into())],
|
|
ProxyOpts::default(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status, 200);
|
|
|
|
let calls = fake.calls();
|
|
assert_eq!(calls.len(), 1);
|
|
assert_eq!(
|
|
calls[0].1.query,
|
|
vec![("state".to_owned(), "failed".to_owned())]
|
|
);
|
|
assert!(calls[0]
|
|
.1
|
|
.headers
|
|
.iter()
|
|
.any(|(k, v)| k.as_str() == "x-slinuxm-hop" && v == "1"));
|
|
assert!(!calls[0]
|
|
.1
|
|
.headers
|
|
.iter()
|
|
.any(|(k, _)| k.as_str() == "authorization"));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn unknown_peer_and_peer_failures_use_the_shared_mapping() {
|
|
let fake = FakeTransport::new();
|
|
fake.peer("beta")
|
|
.respond_err("/systemd/units", PeerError::Rejected);
|
|
let reg = registry_with(fake, fake_peers_config(&["beta"]));
|
|
|
|
let err = reg
|
|
.get("nope", "/systemd/units", &[], ProxyOpts::default())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(err.code(), "not_found");
|
|
assert_eq!(err.message(), "peer nope: unknown peer");
|
|
|
|
let err = reg
|
|
.get("beta", "/systemd/units", &[], ProxyOpts::default())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(err.code(), "unavailable");
|
|
assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
|
|
assert!(err.message().contains("beta"));
|
|
assert_eq!(err.message(), "peer beta: peer rejected credentials");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn static_registry_is_sorted_and_serves_rendering() {
|
|
let reg = static_registry(vec![status("gamma", false), status("beta", true)]);
|
|
let snap = reg.snapshot();
|
|
assert_eq!(snap[0].name.as_str(), "beta");
|
|
assert_eq!(snap[1].name.as_str(), "gamma");
|
|
assert!(reg.status("beta").unwrap().server.up);
|
|
assert_eq!(reg.status("nope").unwrap_err().code(), "not_found");
|
|
|
|
// Static snapshots do not script the transport; unscripted GETs still use
|
|
// the fake defaults, so a proxy call is bounded and never touches a socket.
|
|
let resp = tokio::time::timeout(
|
|
Duration::from_secs(1),
|
|
reg.get("beta", "/systemd/units", &[], ProxyOpts::default()),
|
|
)
|
|
.await
|
|
.expect("fake transport must not block")
|
|
.unwrap();
|
|
assert_eq!(resp.status, 404);
|
|
}
|