rcom/tests/ssh_process.rs

101 lines
3.1 KiB
Rust
Raw Permalink Normal View History

#![cfg(unix)]
use std::env;
use std::ffi::OsString;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use rcom::domain::HostAlias;
use rcom::ssh::OpenSshConnector;
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
struct PathGuard {
previous: Option<OsString>,
}
impl PathGuard {
fn replace(path: OsString) -> Self {
let previous = env::var_os("PATH");
// SAFETY: every environment-changing test in this binary holds ENV_LOCK.
unsafe { env::set_var("PATH", path) };
Self { previous }
}
}
impl Drop for PathGuard {
fn drop(&mut self) {
// SAFETY: every environment-changing test in this binary holds ENV_LOCK until the guard
// is dropped, so no other test in this process can concurrently access the environment.
unsafe {
if let Some(path) = self.previous.take() {
env::set_var("PATH", path);
} else {
env::remove_var("PATH");
}
}
}
}
fn shell_quote(path: &Path) -> String {
let path = path.to_str().expect("temporary path should be valid UTF-8");
format!("'{}'", path.replace('\'', "'\"'\"'"))
}
#[tokio::test]
async fn openssh_process_receives_security_and_keepalive_options() {
let _env_guard = ENV_LOCK.lock().await;
let tempdir = tempfile::tempdir().expect("create fake ssh directory");
let fake_ssh = tempdir.path().join("ssh");
let argv_log = tempdir.path().join("argv");
let script = format!(
"#!/bin/sh\n\
printf '%s\\n' \"$@\" > {argv_log}\n\
while [ \"$#\" -ge 2 ]; do\n\
if [ \"$1\" = \"-E\" ]; then\n\
printf '%s\\n' 'fake ssh: intentional failure' > \"$2\"\n\
exit 1\n\
fi\n\
shift\n\
done\n\
exit 1\n",
argv_log = shell_quote(&argv_log),
);
fs::write(&fake_ssh, script).expect("write fake ssh");
fs::set_permissions(&fake_ssh, fs::Permissions::from_mode(0o755))
.expect("make fake ssh executable");
let original_path = env::var_os("PATH");
let mut paths = vec![tempdir.path().to_path_buf()];
if let Some(path) = &original_path {
paths.extend(env::split_paths(path));
}
let path = env::join_paths(paths).expect("construct test PATH");
let path_guard = PathGuard::replace(path);
let result = OpenSshConnector::default()
.connect(&HostAlias::new("fake.invalid"))
.await;
drop(path_guard);
assert_eq!(env::var_os("PATH"), original_path);
assert!(result.is_err(), "fake ssh must terminate with failure");
let logged = fs::read_to_string(argv_log).expect("read fake ssh argv");
let argv = logged.lines().collect::<Vec<_>>();
for option in [
"StrictHostKeyChecking=yes",
"BatchMode=yes",
"ConnectTimeout=10",
"ServerAliveInterval=15",
"ControlPersist=300s",
] {
assert!(
argv.windows(2)
.any(|pair| pair[0] == "-o" && pair[1] == option),
"missing -o {option}; actual argv: {argv:#?}"
);
}
}