use std::process::Stdio;
use crate::ssh::SshClient;
use crate::{PreparedSsh, SshPlatform, SshProbeError, SshServer};
use super::*;
#[derive(Clone, Default)]
struct RecordStarts(Arc<Mutex<Vec<Start>>>);
type Start = (Option<String>, ScriptDir);
impl RecordStarts {
fn seen(&self) -> Vec<Start> {
self.0.lock().unwrap().clone()
}
}
impl crate::ScriptPolicy for RecordStarts {
type State = ();
fn check(
&self,
script: &crate::ScriptCheck<'_>,
(): &(),
) -> impl Future<Output = ScriptDecision> + Send {
self.0
.lock()
.unwrap()
.push((script.location.map(str::to_string), script.start.clone()));
std::future::ready(ScriptDecision::Pass)
}
}
type Terminal = Shell<executor_core::tokio::TokioGlobal>;
#[derive(Template)]
#[template(path = "test_sshd_config.txt", escape = "none")]
struct SshdConfig<'a> {
port: u16,
host_key: &'a str,
authorized_keys: &'a str,
pid_file: &'a str,
home: &'a str,
login_shell: Option<&'a str>,
}
#[derive(Template)]
#[template(path = "test_ssh_config.txt", escape = "none")]
struct ClientConfig<'a> {
alias: &'a str,
port: u16,
user: &'a str,
identity: &'a str,
}
const ALIAS: &str = "fixture";
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port()
}
fn text(path: &Path) -> &str {
path.to_str().expect("a temporary path is UTF-8")
}
fn stdout_of(program: &str, args: &[&str]) -> String {
let output = std::process::Command::new(program)
.args(args)
.output()
.unwrap_or_else(|error| panic!("{program} runs: {error}"));
assert!(output.status.success(), "{program} {args:?} failed");
String::from_utf8(output.stdout).unwrap().trim().to_string()
}
fn keygen(path: &Path) {
stdout_of(
"ssh-keygen",
&["-q", "-t", "ed25519", "-N", "", "-f", text(path)],
);
}
fn client_config(dir: &Path, port: u16, identity: &Path) -> SshClient {
let path = dir.join("ssh_config");
let user = stdout_of("id", &["-un"]);
let config = ClientConfig {
alias: ALIAS,
port,
user: &user,
identity: text(identity),
}
.render()
.unwrap();
std::fs::write(&path, config).unwrap();
SshClient::with_config(path)
}
fn refusing_client(dir: &Path) -> SshClient {
client_config(dir, free_port(), &dir.join("no_key"))
}
struct Sshd {
dir: tempfile::TempDir,
child: std::process::Child,
client: SshClient,
}
impl Sshd {
async fn start() -> Self {
Self::start_with_heel(true).await
}
async fn start_with_heel(has_heel: bool) -> Self {
Self::start_with(has_heel, None).await
}
async fn start_with_login_shell(login_shell: &str) -> Self {
Self::start_with(false, Some(login_shell)).await
}
async fn start_with(has_heel: bool, login_shell: Option<&str>) -> Self {
let sshd = Path::new("/usr/sbin/sshd");
assert!(
sshd.is_file(),
"the SSH tests run a private OpenSSH server from /usr/sbin/sshd"
);
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
keygen(&root.join("host_key"));
keygen(&root.join("client_key"));
std::fs::copy(root.join("client_key.pub"), root.join("authorized_keys")).unwrap();
let home = root.join("home");
std::fs::create_dir_all(home.join(".local/bin")).unwrap();
if has_heel {
let heel = crate::test_heel::binary().await.unwrap();
std::os::unix::fs::symlink(heel.as_path(), home.join(".local/bin/heel")).unwrap();
}
let port = free_port();
let config = SshdConfig {
port,
host_key: text(&root.join("host_key")),
authorized_keys: text(&root.join("authorized_keys")),
pid_file: text(&root.join("sshd.pid")),
home: text(&home),
login_shell,
}
.render()
.unwrap();
std::fs::write(root.join("sshd_config"), config).unwrap();
let log = std::fs::File::create(root.join("sshd.log")).unwrap();
let child = std::process::Command::new(sshd)
.arg("-f")
.arg(root.join("sshd_config"))
.args(["-D", "-e"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(log)
.spawn()
.unwrap();
let client = client_config(&root, port, &root.join("client_key"));
let fixture = Self { dir, child, client };
for _ in 0..200 {
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
return fixture;
}
async_io::Timer::after(Duration::from_millis(25)).await;
}
panic!(
"sshd did not listen: {}",
std::fs::read_to_string(root.join("sshd.log")).unwrap_or_default()
);
}
fn home(&self) -> PathBuf {
std::fs::canonicalize(self.dir.path()).unwrap().join("home")
}
fn server() -> SshServer {
SshServer {
name: "fixture".to_string(),
target: ALIAS.to_string(),
}
}
fn accepted_connections(&self) -> usize {
std::fs::read_to_string(self.dir.path().join("sshd.log"))
.unwrap()
.lines()
.filter(|line| line.contains("Accepted publickey"))
.count()
}
}
impl Drop for Sshd {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn prepared(sshd: &Sshd, has_heel: bool) -> PreparedSsh {
let heel = has_heel.then(|| text(&sshd.home().join(".local/bin/heel")).to_string());
PreparedSsh::new(heel, remote_launch())
}
fn remote_launch() -> crate::RemoteLaunch {
crate::RemoteLaunch::new("/usr/bin", "/bin/bash")
}
fn home_registry(client: SshClient) -> ShellSessionRegistry {
ShellSessionRegistry::default().with_ssh_client(client)
}
async fn terminal(dir: &Path, registry: ShellSessionRegistry, approver: &Approvals) -> Terminal {
terminal_with(dir, registry, approver, RecordStarts::default()).await
}
async fn terminal_with(
dir: &Path,
registry: ShellSessionRegistry,
approver: &Approvals,
policy: RecordStarts,
) -> Terminal {
fresh_terminal(dir)
.await
.with_approver(approver.clone())
.with_shell_sessions(registry)
.with_test_policies(vec![crate::AnyScriptPolicy::new(policy)])
}
fn args(script: &str, mode: SandboxMode, location: &str) -> ShellArgs {
ShellArgs {
description: "run on the server".to_string(),
script: script.to_string(),
interpreter: Interpreter::Shell,
sandbox: mode,
location: Some(location.to_string()),
resolution: MediaResolution::Auto,
max_lines: Some(50),
raw: true,
timeout: 60,
background: false,
}
}
#[tokio::test(flavor = "multi_thread")]
async fn the_probe_reports_the_servers_platform_without_preparing_it() {
let sshd = Sshd::start().await;
let platform = sshd.client.probe_os(&Sshd::server()).await.unwrap();
assert_eq!(
platform,
SshPlatform {
os: stdout_of("uname", &["-s"]),
arch: stdout_of("uname", &["-m"]),
}
);
assert!(
!sshd.home().join(".cache/aither").exists(),
"the probe installs nothing"
);
let unreachable = tempfile::tempdir().unwrap();
assert!(matches!(
refusing_client(unreachable.path())
.probe_os(&Sshd::server())
.await,
Err(SshProbeError::Upload(_))
));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_added_live_is_asked_and_runs_both_modes() {
let sshd = Sshd::start().await;
let registry = home_registry(sshd.client.clone());
let dir = tempfile::tempdir().unwrap();
let approvals = Approvals::default();
let starts = RecordStarts::default();
let terminal = terminal_with(dir.path(), registry, &approvals, starts.clone()).await;
terminal
.shell_sessions()
.add_ssh_server(Sshd::server(), prepared(&sshd, true))
.unwrap();
let script = "echo remote=ok";
let sandboxed = terminal
.call(
args(script, SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect("a default-mode command runs on the server");
let sandboxed = render_terminal_result(&sandboxed);
assert!(!sandboxed.contains("Exit code:"), "{sandboxed}");
assert!(sandboxed.contains("remote=ok"), "{sandboxed}");
let asked = approvals.asked();
assert_eq!(asked.len(), 1);
assert_eq!(asked[0].kind().as_str(), "remote");
assert_eq!(asked[0].subject(), script);
assert_eq!(
starts.seen(),
[(
Some("fixture".to_string()),
ScriptDir::Remote {
server: "fixture".to_string()
}
)]
);
let direct = terminal
.call(
args(
"echo \"direct=ok home=$HOME\"",
SandboxMode::Unsandboxed,
" fixture ",
),
ToolContext::new(),
)
.await
.expect("an unsafe command runs on the server");
let direct = render_terminal_result(&direct);
assert!(
direct.contains(&format!("direct=ok home={}", sshd.home().display())),
"{direct}"
);
let asked = approvals.asked();
assert_eq!(asked.len(), 2, "no approval is remembered between scripts");
assert_eq!(asked[1].kind().as_str(), "unsandboxed");
terminal
.run_background(args("echo remote-job", SandboxMode::Sandboxed, "fixture"))
.await
.expect("a background command starts on the server");
let places = terminal
.job_registry()
.list()
.await
.into_iter()
.filter(|job| job.script == "echo remote-job")
.map(|job| job.place)
.collect::<Vec<_>>();
assert_eq!(places, [crate::JobPlace::Remote]);
assert_eq!(terminal.job_memory().snapshot().await.unwrap().jobs, []);
assert!(terminal.container_probe().is_none());
terminal.job_registry().kill_running().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_denied_script_on_a_server_carries_the_reason() {
let unreachable = tempfile::tempdir().unwrap();
let registry = home_registry(refusing_client(unreachable.path()));
registry
.add_ssh_server(
Sshd::server(),
PreparedSsh::new(Some("/opt/heel".into()), remote_launch()),
)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let approvals = Approvals::denying("fixture is off limits");
let terminal = terminal(dir.path(), registry, &approvals).await;
for _ in 0..2 {
let denied = terminal
.call(
args("true", SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect_err("a denied script runs nothing");
assert!(
denied.to_string().contains("fixture is off limits"),
"{denied}"
);
}
assert_eq!(approvals.asked().len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_remote_script_with_only_passes_needs_an_approver_and_an_allow_asks_nobody() {
let unreachable = tempfile::tempdir().unwrap();
let registry = home_registry(refusing_client(unreachable.path()));
registry
.add_ssh_server(
Sshd::server(),
PreparedSsh::new(Some("/opt/heel".into()), remote_launch()),
)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let tool = fresh_terminal(dir.path())
.await
.with_shell_sessions(registry.clone());
let error = tool
.call(
args("true", SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect_err("a remote script with only passes needs an approver");
assert!(error.to_string().contains("no approver"), "{error}");
let tool = fresh_terminal(dir.path())
.await
.with_shell_sessions(registry)
.with_test_policies(vec![crate::AnyScriptPolicy::new(Decide(
ScriptDecision::Allow,
))]);
let result = tool
.call(
args("true", SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await;
assert!(
result
.as_ref()
.err()
.is_none_or(|error| !error.to_string().contains("no approver")),
"{result:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_policy_sees_the_location_of_an_unsafe_command() {
let unreachable = tempfile::tempdir().unwrap();
let registry = home_registry(refusing_client(unreachable.path()));
registry
.add_ssh_server(Sshd::server(), PreparedSsh::new(None, remote_launch()))
.unwrap();
let dir = tempfile::tempdir().unwrap();
let starts = RecordStarts::default();
let terminal = terminal_with(dir.path(), registry, &Approvals::default(), starts.clone()).await;
let _ = terminal
.call(
args("true", SandboxMode::Unsandboxed, "fixture"),
ToolContext::new(),
)
.await;
terminal
.call(
args("true", SandboxMode::Unsandboxed, ""),
ToolContext::new(),
)
.await
.expect("an unsafe command runs at home");
let locations = starts
.seen()
.into_iter()
.map(|(location, _)| location)
.collect::<Vec<_>>();
assert_eq!(locations, [Some("fixture".to_string()), None]);
}
#[tokio::test(flavor = "multi_thread")]
async fn default_mode_needs_the_servers_heel() {
let unreachable = tempfile::tempdir().unwrap();
let registry = home_registry(refusing_client(unreachable.path()));
registry
.add_ssh_server(Sshd::server(), PreparedSsh::new(None, remote_launch()))
.unwrap();
let dir = tempfile::tempdir().unwrap();
let terminal = terminal(dir.path(), registry, &Approvals::default()).await;
let refused = terminal
.call(
args("true", SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect_err("no sandbox there");
assert_eq!(refused.to_string(), "no remote sandbox: fixture");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_removed_or_unknown_location_is_refused_and_an_empty_one_is_home() {
let registry = ShellSessionRegistry::default();
registry
.add_ssh_server(
Sshd::server(),
PreparedSsh::new(Some("/opt/heel".into()), remote_launch()),
)
.unwrap();
let dir = tempfile::tempdir().unwrap();
let approvals = Approvals::default();
let terminal = terminal(dir.path(), registry, &approvals).await;
assert_eq!(
terminal.shell_sessions().remove_ssh_server("fixture"),
Some(Sshd::server())
);
for name in ["fixture", "staging"] {
let refused = terminal
.call(
args("true", SandboxMode::Sandboxed, name),
ToolContext::new(),
)
.await
.expect_err("no such server");
assert_eq!(refused.to_string(), format!("unknown location: {name}"));
}
let home = terminal
.call(
args("echo home", SandboxMode::Sandboxed, ""),
ToolContext::new(),
)
.await
.expect("an empty location is the home environment");
assert!(render_terminal_result(&home).contains("home"));
assert_eq!(
approvals.asked(),
[],
"the home environment needs no approval"
);
}
#[tokio::test]
async fn the_public_probe_reports_an_unreachable_server() {
let error = crate::probe_ssh_os(&SshServer {
name: "nowhere".to_string(),
target: "ssh://nobody@127.0.0.1:1".to_string(),
})
.await
.expect_err("nothing answers");
assert!(matches!(error, SshProbeError::Upload(_)), "{error}");
}
#[cfg(feature = "jobserver")]
#[tokio::test(flavor = "multi_thread")]
async fn a_servers_command_runs_outside_the_job_pool_and_a_local_one_inside() {
let sshd = Sshd::start().await;
let registry = home_registry(sshd.client.clone());
let dir = tempfile::tempdir().unwrap();
let pool_dir = tempfile::tempdir().unwrap();
let pool = crate::jobserver::JobPool::create_fifo(pool_dir.path().join("pool.fifo"), 2)
.expect("a pool");
let terminal = terminal(dir.path(), registry, &Approvals::default())
.await
.with_jobserver_pool(pool, pool_dir.path().join("commands"))
.expect("the pool attaches");
terminal
.shell_sessions()
.add_ssh_server(Sshd::server(), prepared(&sshd, true))
.unwrap();
let script = "printenv MAKEFLAGS || echo jobs=none";
let remote = terminal
.call(
args(script, SandboxMode::Sandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect("a server's command runs while a pool is configured");
let remote = render_terminal_result(&remote);
assert!(remote.contains("jobs=none"), "{remote}");
let mut local = args(script, SandboxMode::Sandboxed, "fixture");
local.location = None;
let local = terminal
.call(local, ToolContext::new())
.await
.expect("a local command runs");
let local = render_terminal_result(&local);
assert!(local.contains("--jobserver-auth=fifo:"), "{local}");
}
#[tokio::test(flavor = "multi_thread")]
async fn spawn_on_a_server_streams_output_and_kill_ends_the_remote_tree() {
use crate::SpawnSpec;
let sshd = Sshd::start().await;
let dir = tempfile::tempdir().unwrap();
let heel = sshd.home().join(".local/bin/heel");
let sandbox = Sandbox::new(
crate::Backend::Ssh {
server: Sshd::server(),
heel: Some(text(&heel).to_string()),
launch: remote_launch(),
},
executor_core::tokio::TokioGlobal,
dir.path(),
)
.with_ssh_client(sshd.client.clone());
let mut child = sandbox
.spawn(SpawnSpec::new("/bin/echo").args(["from-the-server"]))
.await
.expect("the process starts under the server's heel");
let stdout = child.take_stdout().unwrap();
let stderr = child.take_stderr().unwrap();
let mut printed = Vec::new();
while let Ok(chunk) = stdout.recv().await {
printed.extend(chunk);
}
let mut failed = Vec::new();
while let Ok(chunk) = stderr.recv().await {
failed.extend(chunk);
}
let exit = child.wait().await;
assert_eq!(
String::from_utf8_lossy(&printed),
"from-the-server\n",
"{exit:?}: {}",
String::from_utf8_lossy(&failed)
);
assert!(exit.success());
let job = sshd.home().join("job.sh");
std::fs::write(&job, "sleep 300 &\necho $!\nwait\n").unwrap();
let unconfined = sandbox.unconfined();
let mut child = unconfined
.spawn(SpawnSpec::new("/bin/sh").args([text(&job)]))
.await
.expect("the process starts");
let stdout = child.take_stdout().unwrap();
let remote = tokio::time::timeout(Duration::from_secs(60), stdout.recv())
.await
.expect("the descendant reports its id")
.expect("stdout is open");
let remote = String::from_utf8(remote).unwrap().trim().to_string();
let alive = |pid: &str| {
std::process::Command::new("kill")
.args(["-0", pid])
.stderr(Stdio::null())
.status()
.unwrap()
.success()
};
assert!(alive(&remote), "the remote descendant runs");
child.kill().await.expect("the tree is killed");
tokio::time::timeout(Duration::from_secs(60), child.wait())
.await
.expect("the killed process is waited for");
tokio::time::timeout(Duration::from_secs(60), async {
while alive(&remote) {
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.expect("the remote descendant ends with the client");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_script_spawned_on_a_server_runs_in_the_managed_shell() {
use crate::SpawnSpec;
let sshd = Sshd::start().await;
let dir = tempfile::tempdir().unwrap();
let heel = sshd.home().join(".local/bin/heel");
let sandbox = Sandbox::new(
crate::Backend::Ssh {
server: Sshd::server(),
heel: Some(text(&heel).to_string()),
launch: remote_launch(),
},
executor_core::tokio::TokioGlobal,
dir.path(),
)
.with_ssh_client(sshd.client.clone());
let mut child = sandbox
.spawn(SpawnSpec::script("echo \"from-the-script\""))
.await
.expect("the script starts under the server's heel");
let stdout = child.take_stdout().unwrap();
let stderr = child.take_stderr().unwrap();
let mut printed = Vec::new();
while let Ok(chunk) = stdout.recv().await {
printed.extend(chunk);
}
let mut failed = Vec::new();
while let Ok(chunk) = stderr.recv().await {
failed.extend(chunk);
}
let exit = child.wait().await;
assert_eq!(
String::from_utf8_lossy(&printed),
"from-the-script\n",
"{exit:?}: {}",
String::from_utf8_lossy(&failed)
);
assert!(exit.success());
assert_eq!(
child.descendants_killed().await,
crate::Descendants::Unobserved
);
assert!(child.take_stdin_blocked().is_none());
}
const AWKWARD: &str = "a b 'single' \"double\" \\back\\\\slash \\' $HOME ${x} $(id) `id` !! ;|&<>\n\
\tindented\n\n中文:你好,世界\n日本語:こんにちは、世界\n한국어: 안녕하세요, 세계";
async fn assert_script_arrives_unchanged(login_shell: &str) {
let sshd = Sshd::start_with_login_shell(login_shell).await;
let script = format!("printf '%s\\n' \"$0\"\ncat <<'AITHER_END'\n{AWKWARD}\nAITHER_END\n");
let command = sshd.client.command(&Sshd::server(), &script).await.unwrap();
let output = async_process::Command::from(command)
.stdin(Stdio::null())
.output()
.await
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{login_shell}: {stderr}");
let stdout = String::from_utf8(output.stdout).unwrap();
let (path, body) = stdout.split_once('\n').unwrap();
assert_eq!(body, format!("{AWKWARD}\n"), "{login_shell}");
assert!(
!Path::new(path).exists(),
"{login_shell}: the script deletes its own file {path}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_script_reaches_sh_unchanged_under_a_posix_login_shell() {
assert_script_arrives_unchanged("/bin/sh").await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_script_reaches_sh_unchanged_under_a_fish_login_shell() {
let fish = [
"/opt/homebrew/bin/fish",
"/usr/local/bin/fish",
"/usr/bin/fish",
]
.into_iter()
.find(|path| Path::new(path).is_file());
let Some(fish) = fish else {
eprintln!("SKIPPED: fish is not installed, so the fish login shell case did not run");
return;
};
assert_script_arrives_unchanged(fish).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn the_commands_stdin_is_free_for_the_scripts_input() {
let sshd = Sshd::start().await;
let command = sshd.client.command(&Sshd::server(), "cat").await.unwrap();
let mut child = async_process::Command::from(command)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
futures_lite::io::AsyncWriteExt::write_all(&mut stdin, "输入 'x'\n".as_bytes())
.await
.unwrap();
drop(stdin);
let output = child.output().await.unwrap();
assert_eq!(output.stdout, "输入 'x'\n".as_bytes());
}
async fn run_script(client: &SshClient, script: &str) -> String {
let command = client.command(&Sshd::server(), script).await.unwrap();
let output = async_process::Command::from(command)
.stdin(Stdio::null())
.output()
.await
.unwrap();
assert!(output.status.success());
String::from_utf8(output.stdout).unwrap()
}
#[tokio::test(flavor = "multi_thread")]
async fn every_command_to_a_server_shares_one_connection() {
let sshd = Sshd::start().await;
assert_eq!(run_script(&sshd.client, "echo one").await, "one\n");
assert_eq!(
sshd.accepted_connections(),
1,
"the upload and the run of one script share a connection"
);
assert_eq!(run_script(&sshd.client, "echo two").await, "two\n");
assert_eq!(sshd.accepted_connections(), 1);
let fresh = Sshd::start().await;
let scripts = ["echo a", "echo b", "echo c", "echo d", "echo e", "echo f"];
let outputs = futures::future::join_all(
scripts
.iter()
.map(|script| run_script(&fresh.client, script)),
)
.await;
assert_eq!(outputs, ["a\n", "b\n", "c\n", "d\n", "e\n", "f\n"]);
assert_eq!(
fresh.accepted_connections(),
1,
"concurrent first uses start one master"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_master_still_opening_holds_up_no_other_server() {
let sshd = Sshd::start().await;
let stalled = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let config = sshd.dir.path().join("two_servers_config");
let fixture = std::fs::read_to_string(sshd.dir.path().join("ssh_config")).unwrap();
let port = stalled.local_addr().unwrap().port();
std::fs::write(
&config,
format!("Host stalled\n HostName 127.0.0.1\n Port {port}\n\n{fixture}"),
)
.unwrap();
let client = SshClient::with_config(config);
let stalled_server = SshServer {
name: "stalled".to_string(),
target: "stalled".to_string(),
};
let opening = {
let client = client.clone();
tokio::spawn(async move {
client
.command(&stalled_server, "echo never")
.await
.map(drop)
})
};
async_io::Timer::after(Duration::from_millis(500)).await;
assert!(!opening.is_finished(), "the stalled opening is in flight");
let started = std::time::Instant::now();
assert_eq!(run_script(&client, "echo other").await, "other\n");
assert!(
started.elapsed() < Duration::from_secs(5),
"the other server's command did not wait for the stalled opening"
);
assert!(
!opening.is_finished(),
"the stalled opening is still in flight"
);
opening.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn dropping_the_client_ends_its_master_and_removes_its_sockets() {
let sshd = Sshd::start().await;
let command = sshd
.client
.command(&Sshd::server(), "echo up")
.await
.unwrap();
drop(command);
let socket_dir = {
let ssh = sshd.client.ssh(&Sshd::server(), "true");
let path = ssh
.get_args()
.find_map(|arg| arg.to_str()?.strip_prefix("ControlPath="))
.unwrap()
.to_string();
PathBuf::from(path).parent().unwrap().to_path_buf()
};
assert!(socket_dir.is_dir());
let Sshd { client, .. } = &sshd;
let client = client.clone();
drop(sshd);
drop(client);
assert!(!socket_dir.exists(), "the socket directory is removed");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_script_that_cannot_be_uploaded_runs_nothing_and_says_why() {
let unreachable = tempfile::tempdir().unwrap();
let error = refusing_client(unreachable.path())
.command(&Sshd::server(), "echo ran")
.await
.unwrap_err();
assert!(
matches!(error, crate::ssh::SshUploadError::Failed { .. }),
"{error}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_command_reads_a_stdin_pipe_only_in_the_background() {
let sshd = Sshd::start_with_heel(false).await;
let dir = tempfile::tempdir().unwrap();
let terminal = terminal(
dir.path(),
home_registry(sshd.client.clone()),
&Approvals::default(),
)
.await;
terminal
.shell_sessions()
.add_ssh_server(Sshd::server(), prepared(&sshd, false))
.unwrap();
let foreground = terminal
.call(
args("cat", SandboxMode::Unsandboxed, "fixture"),
ToolContext::new(),
)
.await
.expect("a foreground cat runs on the server");
let command = foreground.command().expect("a command result");
assert_eq!(command.outcome, CommandOutcome::Exited { code: 0 });
assert!(
output_text(&command.stdout).is_some_and(str::is_empty),
"{command:?}"
);
let job = terminal
.run_background(ShellArgs {
background: true,
..args(
"read name; printf 'hello %s\\n' \"$name\"",
SandboxMode::Unsandboxed,
"fixture",
)
})
.await
.expect("a background reader starts on the server");
input_tool(terminal.jobs())
.call(
JobInputArgs {
task_id: job.task_id().to_owned(),
input: "lexo".to_string(),
append_newline: true,
},
ToolContext::new(),
)
.await
.expect("a background job on a server takes input");
let result = job.wait().await.expect("the fed job ends");
assert_eq!(
output_text(&result.stdout).map(str::trim),
Some("hello lexo")
);
}