#![allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_used,
clippy::unused_result_ok,
reason = "a test reports by panicking; its helpers and stand-in servers live as long as the test"
)]
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::Duration;
#[path = "../../test-support/processes.rs"]
mod processes;
#[path = "../../test-support/machine.rs"]
mod machine;
struct Sockets(std::path::PathBuf);
impl Sockets {
fn new(tag: &str) -> Self {
Self(std::env::temp_dir().join(format!("tc{}-{tag}", std::process::id())))
}
fn arg(&self) -> &std::ffi::OsStr {
self.0.as_os_str()
}
fn state(&self) -> std::path::PathBuf {
self.0.with_extension("state")
}
}
impl Drop for Sockets {
fn drop(&mut self) {
processes::kill_naming(&self.0.to_string_lossy());
std::fs::remove_dir_all(&self.0).ok();
std::fs::remove_dir_all(self.state()).ok();
}
}
async fn local_relay() -> std::net::SocketAddr {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
machine::serve(listener, teter_relay::Config::new());
addr
}
async fn status_of(sockets: &Sockets) -> String {
let status = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("status")
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.output()
.await
.unwrap();
assert!(status.status.success(), "{status:?}");
String::from_utf8(status.stdout).unwrap()
}
type Lines = tokio::io::Lines<tokio::io::BufReader<tokio::process::ChildStdout>>;
fn link_logging_all(
addr: std::net::SocketAddr,
sockets: &Sockets,
stderr_path: &std::path::Path,
) -> (tokio::process::Child, Lines) {
use tokio::io::AsyncBufReadExt;
let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("link")
.args([
"--relay",
&format!("ws://{addr}/backend"),
"--shell",
"/bin/sh",
])
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.env(
"XDG_CONFIG_HOME",
machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
)
.env("RUST_LOG", "trace,tungstenite=debug")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(std::fs::File::create(stderr_path).unwrap())
.kill_on_drop(true)
.spawn()
.unwrap();
let stdout = tokio::io::BufReader::new(child.stdout.take().unwrap()).lines();
(child, stdout)
}
#[tokio::test]
async fn the_link_prints_the_session_and_status_alone_the_token_and_secret() {
let addr = local_relay().await;
let sockets = Sockets::new("prints");
let stderr_path = sockets.0.with_extension("stderr");
let (mut child, mut stdout) = link_logging_all(addr, &sockets, &stderr_path);
let mut lines = Vec::new();
while lines.len() < 2 {
let line = tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
.await
.expect("the backend printed nothing")
.unwrap()
.expect("the backend ended");
lines.push(line);
}
let line = |prefix: &str| {
lines
.iter()
.find_map(|line| line.strip_prefix(prefix))
.unwrap_or_else(|| panic!("no {prefix:?} in {lines:?}"))
.to_owned()
};
let id = line("session: ");
assert!(uuid_like(&id), "{id}");
let shown = status_of(&sockets).await;
assert!(shown.starts_with("main\n"), "{shown}");
assert!(shown.contains(&format!(" session: {id}\n")), "{shown}");
let token = status_value(&shown, "token");
assert_eq!(token.len(), 64, "{token}");
let secret = status_value(&shown, "secret");
assert!(
teter_client::e2e::Secret::parse(&secret).is_ok(),
"{secret}"
);
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(child.try_wait().unwrap().is_none(), "the link ended");
child.kill().await.ok();
while let Ok(Some(line)) = stdout.next_line().await {
lines.push(line);
}
let logs = std::fs::read_to_string(&stderr_path).unwrap();
std::fs::remove_file(&stderr_path).ok();
assert!(
logs.contains("serving the session"),
"the link logged nothing"
);
let session_log = std::fs::read_to_string(sockets.0.join("main.log")).unwrap();
for (what, text) in [
("output", lines.join("\n")),
("logs", logs),
("session log", session_log),
] {
assert!(!text.contains(&secret), "the link's {what} hold the secret");
assert!(!text.contains(&token), "the link's {what} hold the token");
}
}
fn status_value(shown: &str, key: &str) -> String {
shown
.lines()
.find_map(|line| line.strip_prefix(&format!(" {key}: ")))
.unwrap_or_else(|| panic!("no {key} in {shown}"))
.to_owned()
}
#[test]
fn status_without_sessions_says_so() {
let sockets = Sockets::new("none");
let out = Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("status")
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.output()
.unwrap();
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("no session runs"), "{stderr}");
}
#[test]
fn an_unregistered_machine_s_link_exits_with_the_in_use_status() {
let sockets = Sockets::new("unregistered");
for (args, status) in [(&[][..], 3), (&["--in-use-status", "0"][..], 0)] {
let out = Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("link")
.args(args)
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.env("XDG_CONFIG_HOME", sockets.state().join("config"))
.env_remove("TETER_RELAY")
.stdin(Stdio::null())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(status), "{args:?}: {stderr}");
assert!(stderr.contains("not registered"), "{stderr}");
}
}
fn status_in(sockets: &Sockets) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("status")
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.output()
.unwrap()
}
#[test]
fn status_fails_when_no_session_process_answers() {
use std::os::unix::fs::DirBuilderExt;
let sockets = Sockets::new("silent");
std::fs::DirBuilder::new()
.mode(0o700)
.create(&sockets.0)
.unwrap();
drop(std::os::unix::net::UnixListener::bind(sockets.0.join("gone.sock")).unwrap());
let out = status_in(&sockets);
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("gone:"), "{stderr}");
assert!(stderr.contains("answered"), "{stderr}");
}
#[test]
fn status_refuses_a_directory_open_to_others() {
use std::os::unix::fs::DirBuilderExt;
let sockets = Sockets::new("open");
std::fs::DirBuilder::new()
.mode(0o755)
.create(&sockets.0)
.unwrap();
std::fs::set_permissions(
&sockets.0,
std::os::unix::fs::PermissionsExt::from_mode(0o777),
)
.unwrap();
let out = status_in(&sockets);
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("closed to others"), "{stderr}");
}
#[test]
fn an_unreachable_relay_exits_with_an_error() {
let held = tokio::net::TcpSocket::new_v4().unwrap();
held.bind("127.0.0.1:0".parse().unwrap()).unwrap();
let port = held.local_addr().unwrap().port();
let sockets = Sockets::new("unreachable");
let out = Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("link")
.args(["--relay", &format!("ws://127.0.0.1:{port}/backend")])
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.env(
"XDG_CONFIG_HOME",
machine::fixed_host_config(&sockets.state(), &format!("ws://127.0.0.1:{port}")),
)
.stdin(Stdio::null())
.output()
.unwrap();
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.starts_with("teter: "), "{stderr}");
}
fn uuid_like(s: &str) -> bool {
s.len() == 36 && s.chars().filter(|&c| c == '-').count() == 4
}
#[test]
fn a_missing_ca_file_is_refused_with_its_path() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let sockets = Sockets::new("ca");
let mut child = Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("link")
.args(["--relay", &format!("wss://localhost:{port}/backend")])
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.args(["--ca-cert", "/nonexistent/ca.crt"])
.env(
"XDG_CONFIG_HOME",
machine::fixed_host_config(&sockets.state(), &format!("wss://localhost:{port}")),
)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let start = std::time::Instant::now();
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if start.elapsed() > Duration::from_secs(5) {
child.kill().ok();
child.wait().ok();
panic!("the backend did not refuse the missing CA file at once");
}
std::thread::sleep(Duration::from_millis(50));
};
assert!(!status.success());
let mut stderr = String::new();
std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut stderr).unwrap();
assert!(stderr.contains("/nonexistent/ca.crt"), "{stderr}");
}
#[cfg(target_os = "linux")]
fn session_processes(dir: &std::path::Path) -> Vec<i32> {
let dir = dir.to_string_lossy().into_owned();
std::fs::read_dir("/proc")
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let pid = entry.file_name().to_string_lossy().parse::<i32>().ok()?;
let cmdline = std::fs::read(entry.path().join("cmdline")).ok()?;
let args: Vec<_> = cmdline
.split(|&b| b == 0)
.map(String::from_utf8_lossy)
.collect();
(args.iter().any(|a| a == "session") && args.iter().any(|a| *a == dir)).then_some(pid)
})
.collect()
}
#[cfg(target_os = "linux")]
fn children(pid: i32) -> Vec<i32> {
std::fs::read_dir("/proc")
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let child = entry.file_name().to_string_lossy().parse::<i32>().ok()?;
let stat = std::fs::read_to_string(entry.path().join("stat")).ok()?;
let parent = stat.rsplit_once(')')?.1.split_whitespace().nth(1)?;
(parent.parse::<i32>().ok()? == pid).then_some(child)
})
.collect()
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn killing_the_links_process_group_leaves_the_session_and_its_shell() {
use std::os::unix::process::CommandExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
machine::serve(listener, teter_relay::Config::new());
let sockets = Sockets::new("group");
let mut link = Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("link")
.args([
"--relay",
&format!("ws://{addr}/backend"),
"--shell",
"/bin/sh",
])
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.env(
"XDG_CONFIG_HOME",
machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.process_group(0)
.spawn()
.unwrap();
let stdout = link.stdout.take().unwrap();
let lines = tokio::task::spawn_blocking(move || BufReader::new(stdout).lines().take(2).count());
let count = tokio::time::timeout(Duration::from_secs(10), lines)
.await
.expect("the backend printed nothing")
.unwrap();
assert_eq!(count, 2);
let sessions = session_processes(&sockets.0);
let [session] = sessions[..] else {
panic!("one session process expected: {sessions:?}");
};
let group = rustix::process::Pid::from_raw(i32::try_from(link.id()).unwrap()).unwrap();
rustix::process::kill_process_group(group, rustix::process::Signal::KILL).unwrap();
link.wait().unwrap();
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(
std::path::Path::new(&format!("/proc/{session}")).exists(),
"the session process died with the link's group"
);
assert!(
!children(session).is_empty(),
"its shell died with the link's group"
);
tokio::net::UnixStream::connect(sockets.0.join("main.sock"))
.await
.expect("the session process no longer listens");
}
#[cfg(target_os = "linux")]
fn env_names(pid: i32) -> Vec<String> {
std::fs::read(format!("/proc/{pid}/environ"))
.unwrap()
.split(|&b| b == 0)
.filter_map(|var| var.split(|&b| b == b'=').next())
.map(|name| String::from_utf8_lossy(name).into_owned())
.collect()
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_relay_url_reaches_neither_session_processes_nor_shells_and_a_second_link_exits_3() {
use tokio::io::AsyncBufReadExt;
let addr = local_relay().await;
let sockets = Sockets::new("creds");
let link = |sockets: &Sockets| {
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"));
command
.arg("link")
.arg("--sockets")
.arg(sockets.arg())
.env("XDG_STATE_HOME", sockets.state())
.args(["--shell", "/bin/sh"])
.env("TETER_RELAY", format!("ws://{addr}/backend"))
.env(
"XDG_CONFIG_HOME",
machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
)
.stdin(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
command
};
let mut first = link(&sockets).stdout(Stdio::piped()).spawn().unwrap();
let mut stdout = tokio::io::BufReader::new(first.stdout.take().unwrap()).lines();
for _ in 0..2 {
tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
.await
.expect("the backend printed nothing")
.unwrap();
}
let sessions = session_processes(&sockets.0);
let [session] = sessions[..] else {
panic!("one session process expected: {sessions:?}");
};
let shells = children(session);
assert!(!shells.is_empty(), "no shell");
for pid in std::iter::once(session).chain(shells) {
let names = env_names(pid);
assert!(
!names.iter().any(|name| name == "TETER_RELAY"),
"TETER_RELAY in the environment of {pid}"
);
}
let second = link(&sockets).stdout(Stdio::null()).status().await.unwrap();
assert_eq!(second.code(), Some(3), "{second:?}");
first.kill().await.ok();
}