Skip to main content

isothrum_runner/
console.rs

1//! The way into a machine as the embedder runs it: [`ShellCommand`], the command that opens a
2//! console there, and the one line a POSIX shell runs it from, its words quoted as a POSIX shell
3//! reads them back ([`sh_quote`], which every script the runner writes for a shell uses); the
4//! account a console may be asked to open as ([`check_user`]).
5
6use std::path::PathBuf;
7
8use isoloom_manifest::Machine;
9use serde::Serialize;
10
11use crate::error::{Error, Result};
12
13/// The command that opens an interactive console into a machine (a shell in a container, `vagrant
14/// ssh`, an SSH login): the runner builds it (it alone knows the runtime: the Compose project and
15/// files, the Vagrant define, the address and user a module gives), the embedder runs it in its
16/// own terminal. Addresses the machine by service or define name, or by the address the run gives
17/// it, never a guessed container.
18#[derive(Debug, Clone, Serialize)]
19#[non_exhaustive]
20pub struct ShellCommand {
21    /// The program to run (`docker`, `vagrant`, `ssh`).
22    pub program: String,
23    /// Its arguments.
24    pub args: Vec<String>,
25    /// The folder to run it in (the run's folder).
26    pub cwd: PathBuf,
27    /// Variables to run it with, besides the embedder's own (a Vagrant run's state folder,
28    /// `VAGRANT_DOTFILE_PATH`, without which Vagrant doesn't find the VM; its forwarded ports).
29    /// Empty for a Compose service on this computer and for an SSH login.
30    pub env: Vec<(String, String)>,
31}
32
33impl ShellCommand {
34    /// `program` with `args`, run in `cwd`, with no variable of its own.
35    #[must_use]
36    pub fn new(program: impl Into<String>, args: impl IntoIterator<Item = impl Into<String>>, cwd: impl Into<PathBuf>) -> ShellCommand {
37        ShellCommand {
38            program: program.into(),
39            args: args.into_iter().map(Into::into).collect(),
40            cwd: cwd.into(),
41            env: Vec::new(),
42        }
43    }
44
45    /// The same, run with `env` besides the embedder's own variables.
46    #[must_use]
47    pub fn with_env(mut self, env: Vec<(String, String)>) -> ShellCommand {
48        self.env = env;
49        self
50    }
51
52    /// The command as one line a POSIX shell runs as it is, to paste in a terminal:
53    /// `cd <cwd> && VAR=value… program args…`, each word that needs it single-quoted (a `sh -c`
54    /// script with `;` or `>`, a JSON value), so the shell splits it back into this argv.
55    #[must_use]
56    pub fn sh_line(&self) -> String {
57        let cwd = sh_word(&self.cwd.display().to_string());
58        let env = self.env.iter().map(|(k, v)| format!("{k}={}", sh_word(v)));
59        let argv = std::iter::once(&self.program).chain(&self.args).map(|w| sh_word(w));
60        let words: Vec<String> = env.chain(argv).collect();
61        format!("cd {cwd} && {}", words.join(" "))
62    }
63}
64
65/// Checks `user`, the account a console into `machine` is asked to open as: a name a Unix account
66/// has (1 to 32 lowercase letters, digits, `_` or `-`, starting with a letter or `_`), so it goes
67/// into a shell script, a `docker exec --user` or a `sudo -u` as it is; on a machine that isn't
68/// Windows, whose consoles have no such account switch.
69///
70/// # Errors
71///
72/// `unsupported` for a name no account has, or a Windows machine.
73pub(crate) fn check_user<'u>(user: &'u str, machine: &Machine) -> Result<&'u str> {
74    let first = |c: char| c.is_ascii_lowercase() || c == '_';
75    let rest = |c: char| first(c) || c.is_ascii_digit() || c == '-';
76    let named = user.len() <= 32 && user.chars().next().is_some_and(first) && user.chars().all(rest);
77    if !named {
78        return Err(Error::Unsupported {
79            what: format!("a console as `{user}`, which names no account (1 to 32 lowercase letters, digits, `_` or `-`, starting with a letter or `_`),"),
80        });
81    }
82    if machine.windows {
83        return Err(Error::Unsupported {
84            what: format!("a console as `{user}` into `{}`, which runs Windows,", machine.name),
85        });
86    }
87    Ok(user)
88}
89
90/// `word` as a POSIX shell reads it back: as it is when nothing in it is special, else
91/// single-quoted.
92fn sh_word(word: &str) -> String {
93    let plain = |c: char| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c);
94    if !word.is_empty() && word.chars().all(plain) {
95        word.to_owned()
96    } else {
97        sh_quote(word)
98    }
99}
100
101/// `s` single-quoted for a POSIX shell (`'` written `'\''`): a local terminal's line, a remote
102/// shell's command, a script's argument.
103pub(crate) fn sh_quote(s: &str) -> String {
104    format!("'{}'", s.replace('\'', r"'\''"))
105}
106
107#[cfg(test)]
108mod tests {
109    use proptest::prelude::*;
110
111    use super::*;
112
113    proptest! {
114        #[test]
115        fn a_quoted_word_reads_back_as_itself(s in ".{0,40}") {
116            // `'…'` with each `'` as `'\''`: undo it the way sh reads it.
117            let q = sh_quote(&s);
118            let inner = q.strip_prefix('\'').and_then(|q| q.strip_suffix('\'')).unwrap();
119            prop_assert_eq!(inner.replace(r"'\''", "'"), s);
120        }
121    }
122
123    /// The line a shell is given splits back into the command: its folder, its variables, and
124    /// each argument whole, whatever it holds.
125    #[cfg(unix)]
126    #[test]
127    fn a_shell_line_splits_back_into_the_command() {
128        let dir = tempfile::tempdir().unwrap();
129        let cwd = dir.path().join("a run's folder");
130        std::fs::create_dir(&cwd).unwrap();
131        let args = [
132            "-c",
133            r#"printf '%s\n' "$(pwd -P)" "$J" "$@""#,
134            "argv0",
135            "a b",
136            "x; echo no > /dev/null",
137            "it's",
138            "",
139            "$HOME",
140        ];
141        let cmd = ShellCommand::new("sh", args, cwd.clone()).with_env(vec![("J".into(), r#"{"a": [1, "b c"]}"#.into())]);
142        let line = cmd.sh_line();
143        assert!(line.starts_with("cd '"), "{line}");
144        let out = std::process::Command::new("sh").args(["-c", &line]).output().unwrap();
145        let said = String::from_utf8(out.stdout).unwrap();
146        let pwd = cwd.canonicalize().unwrap().display().to_string();
147        let expected = [pwd.as_str(), r#"{"a": [1, "b c"]}"#, "a b", "x; echo no > /dev/null", "it's", "", "$HOME"];
148        assert_eq!(said.lines().collect::<Vec<_>>(), expected, "{line}");
149    }
150
151    #[test]
152    fn a_plain_word_stays_as_it_is() {
153        let cmd = ShellCommand::new("vagrant", ["ssh", "web"], "/work/web-vm")
154            .with_env(vec![("VAGRANT_DOTFILE_PATH".into(), "/home/u/.isothrum/runs/web-vm/vagrant".into())]);
155        assert_eq!(
156            (cmd.program.as_str(), cmd.args.as_slice(), cmd.cwd.as_path()),
157            ("vagrant", &["ssh".to_owned(), "web".to_owned()][..], std::path::Path::new("/work/web-vm"))
158        );
159        assert_eq!(ShellCommand::new("docker", ["ps"], "/w").env, [], "no variable of its own until given");
160        assert_eq!(
161            cmd.sh_line(),
162            "cd /work/web-vm && VAGRANT_DOTFILE_PATH=/home/u/.isothrum/runs/web-vm/vagrant vagrant ssh web"
163        );
164    }
165}