Skip to main content

aither_sandbox/
ssh.rs

1//! SSH servers as execution locations: the server set a registry holds while
2//! it lives, the client every connection goes through, the lazily prepared
3//! state of each server and the OS probe an embedder runs when a server is
4//! added.
5
6use std::collections::HashMap;
7use std::future::Future;
8use std::path::PathBuf;
9use std::pin::Pin;
10use std::process::Stdio;
11use std::sync::{Arc, OnceLock};
12
13use arc_swap::ArcSwap;
14use async_lock::OnceCell;
15use futures_lite::io::AsyncWriteExt;
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19
20use crate::RemoteLaunch;
21
22/// A named SSH destination commands may run on.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
24pub struct SshServer {
25    /// The name a command gives as its `location` to run on this server.
26    pub name: String,
27    /// SSH target, as passed to `ssh` (for example `user@host` or a host
28    /// alias of the user's SSH configuration).
29    pub target: String,
30}
31
32impl SshServer {
33    /// The name used to address this server.
34    #[must_use]
35    pub fn id(&self) -> &str {
36        &self.name
37    }
38}
39
40/// Why a server cannot join a registry's server set.
41#[derive(Debug, thiserror::Error)]
42pub enum SshServerError {
43    /// The name or the target is blank.
44    #[error("an SSH server needs a non-empty name and target")]
45    Blank,
46    /// Another server already has this name.
47    #[error("an SSH server named `{0}` is already configured")]
48    Duplicate(String),
49}
50
51/// Why a script could not be written to a server, so that nothing ran.
52#[derive(Debug, thiserror::Error)]
53pub enum SshUploadError {
54    /// `ssh` could not be started or waited for.
55    #[error("could not start ssh: {0}")]
56    Spawn(std::io::Error),
57    /// The script could not be sent to `ssh`.
58    #[error("could not send the script to ssh: {0}")]
59    Write(std::io::Error),
60    /// The connection failed or the server could not store the script.
61    #[error("writing the script to `{target}` failed ({status}): {stderr}")]
62    Failed {
63        /// The SSH target written to.
64        target: String,
65        /// The exit status `ssh` returned.
66        status: std::process::ExitStatus,
67        /// What it wrote to its standard error.
68        stderr: String,
69    },
70}
71
72/// The operating system and architecture a server reports, as `uname -s`
73/// and `uname -m` print them (for example `Linux` and `x86_64`).
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
75pub struct SshPlatform {
76    /// The kernel name, `uname -s`.
77    pub os: String,
78    /// The machine hardware name, `uname -m`.
79    pub arch: String,
80}
81
82/// Why [`probe_ssh_os`] could not tell a server's platform.
83#[derive(Debug, thiserror::Error)]
84pub enum SshProbeError {
85    /// `ssh` could not be started.
86    #[error("could not start ssh: {0}")]
87    Spawn(#[from] std::io::Error),
88    /// The probe script could not be written to the server.
89    #[error(transparent)]
90    Upload(#[from] SshUploadError),
91    /// The connection or the remote command failed.
92    #[error("the probe of `{target}` exited with {status}: {stderr}")]
93    Failed {
94        /// The SSH target probed.
95        target: String,
96        /// The exit status `ssh` returned.
97        status: std::process::ExitStatus,
98        /// What it wrote to its standard error.
99        stderr: String,
100    },
101    /// The server answered something other than `uname -s -m` output.
102    #[error("the probe answered `{0}`, which is not `uname -s -m` output")]
103    Unreadable(String),
104}
105
106/// The platform `server` runs: one `uname -s -m` over one SSH connection,
107/// installing nothing and asking no one. An embedder calls it when the user
108/// adds a server, to record what the server is.
109///
110/// # Errors
111///
112/// Fails when `ssh` cannot start, the connection or `uname` fails, or the
113/// answer is not two words.
114pub async fn probe_ssh_os(server: &SshServer) -> Result<SshPlatform, SshProbeError> {
115    SshClient::default().probe_os(server).await
116}
117
118/// The private directory holding the control sockets of the master
119/// connections a client owns, one per server. It exists from the client's
120/// first connection until its last clone drops, which ends every master.
121#[derive(Debug, Default)]
122struct Masters {
123    dir: OnceLock<tempfile::TempDir>,
124    /// Each target's once-only opening of its master; the map is locked only
125    /// to find the cell.
126    opened: std::sync::Mutex<HashMap<String, Arc<OnceCell<()>>>>,
127}
128
129impl Masters {
130    /// The control socket of the master to `target`. The name is a short
131    /// digest because a unix socket path is limited to about a hundred bytes
132    /// and `ssh` appends a suffix of its own while binding.
133    fn socket(&self, target: &str) -> PathBuf {
134        let dir = self.dir.get_or_init(|| {
135            tempfile::Builder::new()
136                .prefix("ssh-")
137                .tempdir()
138                .expect("the private directory of the SSH control sockets can be created")
139        });
140        let digest = Sha256::digest(target.as_bytes());
141        dir.path().join(hex::encode(&digest[..6]))
142    }
143}
144
145impl Drop for Masters {
146    fn drop(&mut self) {
147        let Some(dir) = self.dir.get() else { return };
148        let Ok(sockets) = std::fs::read_dir(dir.path()) else {
149            return;
150        };
151        for socket in sockets.flatten() {
152            let _ = std::process::Command::new("ssh")
153                .args(["-O", "exit", "-o"])
154                .arg(format!("ControlPath={}", socket.path().display()))
155                .args(["--", "master"])
156                .stdin(Stdio::null())
157                .stdout(Stdio::null())
158                .stderr(Stdio::null())
159                .status();
160        }
161    }
162}
163
164/// How every SSH connection is made: `ssh` in batch mode with a bounded
165/// connect time, the remote command run by `sh` whatever the login shell.
166/// Every command to a server shares one master connection the client opens on
167/// the first and ends when its last clone drops.
168#[derive(Debug, Clone, Default)]
169pub struct SshClient {
170    /// An `ssh_config(5)` file read instead of the user's; only tests set
171    /// one, to reach their own server.
172    config: Option<PathBuf>,
173    masters: Arc<Masters>,
174}
175
176impl SshClient {
177    #[cfg(test)]
178    pub(crate) fn with_config(config: PathBuf) -> Self {
179        Self {
180            config: Some(config),
181            masters: Arc::default(),
182        }
183    }
184
185    /// `ssh` to `server` with `line` as the remote command line.
186    ///
187    /// The remote login shell parses `line` before anything else runs, and
188    /// shells disagree on quoting, so every line this client sends is made
189    /// only of letters, digits and `-`, `.`, `/`, `;`, `>` and spaces.
190    pub(crate) fn ssh(&self, server: &SshServer, line: &str) -> std::process::Command {
191        let mut command = self.options(server);
192        command.arg("--").arg(&server.target).arg(line);
193        command
194    }
195
196    /// `ssh` with every option of this client, before the target.
197    fn options(&self, server: &SshServer) -> std::process::Command {
198        let mut command = std::process::Command::new("ssh");
199        command.args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]);
200        // `ControlPersist` keeps the master the first command starts alive
201        // for the next ones; the timeout only reaps a master whose client
202        // died without ending it.
203        command
204            .args(["-o", "ControlMaster=auto", "-o", "ControlPersist=10m"])
205            .arg("-o")
206            .arg(format!(
207                "ControlPath={}",
208                self.masters.socket(&server.target).display()
209            ));
210        if let Some(config) = &self.config {
211            command.arg("-F").arg(config);
212        }
213        command
214    }
215
216    /// Makes sure the master connection to `server` is up, opening it when
217    /// it is not. A server's master opens once, under that server's own cell:
218    /// `ControlMaster=auto` makes a second `ssh` that finds the socket still
219    /// being bound give up multiplexing and open a connection of its own, so
220    /// concurrent first commands to one server wait for the one opening and
221    /// commands to other servers wait for nothing. A failed opening is not
222    /// remembered. Once opened, a master that later dies is re-created by
223    /// the next command's `ControlMaster=auto`.
224    async fn ensure_master(&self, server: &SshServer) -> Result<(), SshUploadError> {
225        let opened = Arc::clone(
226            self.masters
227                .opened
228                .lock()
229                .expect("the map of opened masters is never held across a panic")
230                .entry(server.target.clone())
231                .or_default(),
232        );
233        opened
234            .get_or_try_init(|| async {
235                let output = async_process::Command::from(self.ssh(server, "true"))
236                    .stdin(Stdio::null())
237                    .stdout(Stdio::null())
238                    .stderr(Stdio::piped())
239                    .output()
240                    .await
241                    .map_err(SshUploadError::Spawn)?;
242                if output.status.success() {
243                    return Ok(());
244                }
245                Err(SshUploadError::Failed {
246                    target: server.target.clone(),
247                    status: output.status,
248                    stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
249                })
250            })
251            .await?;
252        Ok(())
253    }
254
255    /// `ssh` running `script` under `sh` on `server`, with the command's
256    /// standard input free for the script's own input.
257    ///
258    /// The script never appears on the remote command line: one `ssh` writes
259    /// it to a private file on the server through its standard input, and the
260    /// command returned runs that file with `sh`, which reads it byte for
261    /// byte. The script deletes its own file as its first action.
262    ///
263    /// # Errors
264    ///
265    /// Fails, running nothing, when the script cannot be written to the
266    /// server.
267    pub(crate) async fn command(
268        &self,
269        server: &SshServer,
270        script: &str,
271    ) -> Result<std::process::Command, SshUploadError> {
272        self.ensure_master(server).await?;
273        let path = format!("/tmp/aither-{}.sh", uuid::Uuid::new_v4().simple());
274        let upload = |error: std::io::Error| SshUploadError::Spawn(error);
275        let mut child =
276            async_process::Command::from(self.ssh(server, &format!("umask 077; cat > {path}")))
277                .stdin(Stdio::piped())
278                .stdout(Stdio::null())
279                .stderr(Stdio::piped())
280                .kill_on_drop(true)
281                .spawn()
282                .map_err(upload)?;
283        let mut stdin = child.stdin.take().expect("the upload's stdin is piped");
284        let body = format!("rm -f \"$0\"\n{script}");
285        let written = stdin.write_all(body.as_bytes()).await;
286        drop(stdin);
287        let output = child.output().await.map_err(upload)?;
288        if !output.status.success() {
289            return Err(SshUploadError::Failed {
290                target: server.target.clone(),
291                status: output.status,
292                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
293            });
294        }
295        written.map_err(SshUploadError::Write)?;
296        Ok(self.ssh(server, &format!("sh {path}")))
297    }
298
299    pub(crate) async fn probe_os(&self, server: &SshServer) -> Result<SshPlatform, SshProbeError> {
300        let output = async_process::Command::from(self.command(server, "uname -s -m").await?)
301            .stdin(Stdio::null())
302            .output()
303            .await?;
304        if !output.status.success() {
305            return Err(SshProbeError::Failed {
306                target: server.target.clone(),
307                status: output.status,
308                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
309            });
310        }
311        let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
312        let mut words = answer.split_whitespace();
313        match (words.next(), words.next(), words.next()) {
314            (Some(os), Some(arch), None) => Ok(SshPlatform {
315                os: os.to_string(),
316                arch: arch.to_string(),
317            }),
318            _ => Err(SshProbeError::Unreadable(answer)),
319        }
320    }
321}
322
323/// What the embedder prepared on a server: its `heel` and the programs its
324/// scripts run with.
325#[derive(Debug, Clone)]
326pub struct PreparedSsh {
327    /// The `heel` binary on the server, when it has one; a default-mode
328    /// command needs it, an `unsafe` one does not.
329    pub(crate) heel: Option<String>,
330    pub(crate) launch: RemoteLaunch,
331}
332
333impl PreparedSsh {
334    /// The preparation of a server whose `heel` is at the path `heel` on the
335    /// server, if it has one, and whose programs `launch` describes.
336    #[must_use]
337    pub const fn new(heel: Option<String>, launch: RemoteLaunch) -> Self {
338        Self { heel, launch }
339    }
340}
341
342/// Why a server could not be prepared. The server stays in the set, and the
343/// next command naming it prepares it again.
344#[derive(Debug, thiserror::Error)]
345#[error("preparing the SSH server `{server}` failed: {source}")]
346pub struct SshPrepareError {
347    /// The name of the server.
348    pub server: String,
349    /// What the embedder's [`PrepareSsh`] reported.
350    #[source]
351    pub source: Box<dyn std::error::Error + Send + Sync>,
352}
353
354/// Prepares a server for the shell's scripts: finds or installs its `heel`
355/// and the programs scripts run with.
356///
357/// It runs when the first command names the server, not when the server is
358/// added, so adding a server never waits on it and an unreachable server
359/// fails only the commands that name it. Commands that name the server
360/// together share the one preparation; a preparation that fails fails the
361/// commands waiting on it and is not remembered, so the next command
362/// prepares again. A [`PreparedSsh`] is a preparation already done.
363pub trait PrepareSsh: Send + Sync + 'static {
364    /// Why the preparation failed.
365    type Error: std::error::Error + Send + Sync + 'static;
366
367    /// Prepares `server`.
368    fn prepare(
369        &self,
370        server: &SshServer,
371    ) -> impl Future<Output = Result<PreparedSsh, Self::Error>> + Send;
372}
373
374impl PrepareSsh for PreparedSsh {
375    type Error = std::convert::Infallible;
376
377    fn prepare(
378        &self,
379        _server: &SshServer,
380    ) -> impl Future<Output = Result<Self, Self::Error>> + Send {
381        std::future::ready(Ok(self.clone()))
382    }
383}
384
385/// Object-safe twin of [`PrepareSsh`].
386trait PrepareSshImpl: Send + Sync {
387    fn prepare<'a>(
388        &'a self,
389        server: &'a SshServer,
390    ) -> Pin<Box<dyn Future<Output = Result<PreparedSsh, SshPrepareError>> + Send + 'a>>;
391}
392
393impl<T: PrepareSsh> PrepareSshImpl for T {
394    fn prepare<'a>(
395        &'a self,
396        server: &'a SshServer,
397    ) -> Pin<Box<dyn Future<Output = Result<PreparedSsh, SshPrepareError>> + Send + 'a>> {
398        Box::pin(async move {
399            PrepareSsh::prepare(self, server)
400                .await
401                .map_err(|error| SshPrepareError {
402                    server: server.name.clone(),
403                    source: Box::new(error),
404                })
405        })
406    }
407}
408
409/// A type-erased [`PrepareSsh`].
410#[derive(Clone)]
411pub struct AnyPrepareSsh(Arc<dyn PrepareSshImpl>);
412
413impl AnyPrepareSsh {
414    /// Erases `prepare`.
415    #[must_use]
416    pub fn new(prepare: impl PrepareSsh) -> Self {
417        Self(Arc::new(prepare))
418    }
419}
420
421impl std::fmt::Debug for AnyPrepareSsh {
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        f.write_str("AnyPrepareSsh")
424    }
425}
426
427/// One server of a registry's set and what the embedder prepared on it.
428/// Removing the server drops them.
429#[derive(Debug)]
430pub struct SshEnvironment {
431    server: SshServer,
432    prepare: AnyPrepareSsh,
433    prepared: OnceCell<PreparedSsh>,
434}
435
436impl SshEnvironment {
437    pub(crate) const fn server(&self) -> &SshServer {
438        &self.server
439    }
440
441    /// What the embedder prepared on the server, preparing it first when no
442    /// command has yet. Concurrent callers share one preparation.
443    ///
444    /// # Errors
445    /// Fails with what the preparation reported; the next call prepares
446    /// again.
447    pub(crate) async fn prepared(&self) -> Result<&PreparedSsh, SshPrepareError> {
448        self.prepared
449            .get_or_try_init(|| self.prepare.0.prepare(&self.server))
450            .await
451    }
452}
453
454/// The servers a registry offers, shared by every clone of it and changed
455/// while it lives.
456#[derive(Debug, Clone, Default)]
457pub struct SshEnvironments {
458    client: SshClient,
459    servers: Arc<ArcSwap<Vec<Arc<SshEnvironment>>>>,
460}
461
462impl SshEnvironments {
463    #[cfg(test)]
464    pub(crate) fn with_client(mut self, client: SshClient) -> Self {
465        self.client = client;
466        self
467    }
468
469    pub(crate) const fn client(&self) -> &SshClient {
470        &self.client
471    }
472
473    pub(crate) fn add(
474        &self,
475        server: SshServer,
476        prepare: impl PrepareSsh,
477    ) -> Result<(), SshServerError> {
478        let SshServer { name, target } = server;
479        let server = SshServer {
480            name: name.trim().to_string(),
481            target: target.trim().to_string(),
482        };
483        if server.name.is_empty() || server.target.is_empty() {
484            return Err(SshServerError::Blank);
485        }
486        let environment = Arc::new(SshEnvironment {
487            server,
488            prepare: AnyPrepareSsh::new(prepare),
489            prepared: OnceCell::new(),
490        });
491        let mut duplicate = false;
492        self.servers.rcu(|servers| {
493            duplicate = servers
494                .iter()
495                .any(|existing| existing.server.name == environment.server.name);
496            let mut next = Vec::clone(servers);
497            if !duplicate {
498                next.push(Arc::clone(&environment));
499            }
500            next
501        });
502        if duplicate {
503            return Err(SshServerError::Duplicate(environment.server.name.clone()));
504        }
505        Ok(())
506    }
507
508    pub(crate) fn remove(&self, name: &str) -> Option<SshServer> {
509        let mut removed = None;
510        self.servers.rcu(|servers| {
511            let (gone, kept): (Vec<_>, Vec<_>) = servers
512                .iter()
513                .cloned()
514                .partition(|environment| environment.server.name == name);
515            removed = gone.into_iter().next();
516            kept
517        });
518        removed.map(|environment| environment.server.clone())
519    }
520
521    pub(crate) fn list(&self) -> Vec<SshServer> {
522        self.servers
523            .load()
524            .iter()
525            .map(|environment| environment.server.clone())
526            .collect()
527    }
528
529    pub(crate) fn get(&self, name: &str) -> Option<Arc<SshEnvironment>> {
530        self.servers
531            .load()
532            .iter()
533            .find(|environment| environment.server.name == name)
534            .cloned()
535    }
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541
542    fn server(name: &str, target: &str) -> SshServer {
543        SshServer {
544            name: name.to_string(),
545            target: target.to_string(),
546        }
547    }
548
549    fn prepared() -> PreparedSsh {
550        PreparedSsh::new(
551            None,
552            RemoteLaunch::new("/opt/tools/bin", "/opt/tools/bin/bash"),
553        )
554    }
555
556    #[test]
557    fn servers_join_and_leave_a_live_set_every_clone_sees() {
558        let set = SshEnvironments::default();
559        let clone = set.clone();
560        set.add(server(" build ", " builder@build.internal "), prepared())
561            .unwrap();
562        assert_eq!(
563            clone.list(),
564            [server("build", "builder@build.internal")],
565            "names and targets are trimmed and the clone sees the addition"
566        );
567        assert!(matches!(
568            clone.add(server("build", "other@build.internal"), prepared()),
569            Err(SshServerError::Duplicate(name)) if name == "build"
570        ));
571        assert!(matches!(
572            set.add(server("staging", "  "), prepared()),
573            Err(SshServerError::Blank)
574        ));
575        assert_eq!(
576            clone.remove("build"),
577            Some(server("build", "builder@build.internal"))
578        );
579        assert_eq!(set.list(), []);
580        assert_eq!(set.remove("build"), None);
581    }
582
583    /// Counts its preparations, takes its time over each and fails the first
584    /// `failures` of them.
585    struct Counting {
586        runs: Arc<std::sync::atomic::AtomicUsize>,
587        failures: usize,
588    }
589
590    #[derive(Debug, thiserror::Error)]
591    #[error("the server is unreachable")]
592    struct Unreachable;
593
594    impl PrepareSsh for Counting {
595        type Error = Unreachable;
596
597        async fn prepare(&self, _server: &SshServer) -> Result<PreparedSsh, Unreachable> {
598            let run = self.runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
599            for _ in 0..10 {
600                tokio::task::yield_now().await;
601            }
602            if run < self.failures {
603                Err(Unreachable)
604            } else {
605                Ok(prepared())
606            }
607        }
608    }
609
610    fn environment(failures: usize) -> (Arc<SshEnvironment>, Arc<std::sync::atomic::AtomicUsize>) {
611        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
612        let set = SshEnvironments::default();
613        set.add(
614            server("build", "builder@build.internal"),
615            Counting {
616                runs: Arc::clone(&runs),
617                failures,
618            },
619        )
620        .unwrap();
621        (set.get("build").unwrap(), runs)
622    }
623
624    #[tokio::test]
625    async fn a_server_is_prepared_on_its_first_use_and_only_once() {
626        let (environment, runs) = environment(0);
627        assert_eq!(
628            runs.load(std::sync::atomic::Ordering::SeqCst),
629            0,
630            "adding the server prepares nothing"
631        );
632        let (first, second) = tokio::join!(environment.prepared(), environment.prepared());
633        first.unwrap();
634        second.unwrap();
635        environment.prepared().await.unwrap();
636        assert_eq!(
637            runs.load(std::sync::atomic::Ordering::SeqCst),
638            1,
639            "two concurrent first commands and a later one share one preparation"
640        );
641    }
642
643    #[tokio::test]
644    async fn a_failed_preparation_is_reported_and_retried_by_the_next_command() {
645        let (environment, runs) = environment(1);
646        let error = environment.prepared().await.unwrap_err();
647        assert_eq!(error.server, "build");
648        assert!(error.source.to_string().contains("unreachable"), "{error}");
649        environment
650            .prepared()
651            .await
652            .expect("the next command prepares again");
653        environment.prepared().await.unwrap();
654        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 2);
655    }
656}