Skip to main content

mira/
update.rs

1//! `mira update` — replace this binary with a release from GitHub.
2//!
3//! It does that by re-running the installer, not by re-implementing it.
4//! `scripts/get-mira.sh` already resolves the latest tag, picks the Rust target
5//! triple, verifies `SHA256SUMS`, verifies the build attestation when `gh` is
6//! present, and elevates only for the final move. Doing any of that from Rust
7//! needs an HTTPS client, and the smallest one worth trusting costs `rustls`
8//! plus `ring` plus their trees — against a dependency count the README
9//! publishes as a product property. Shelling out keeps that number where it is
10//! and keeps the installer singular: the same bytes that installed mira update
11//! it, so there is no second code path to be wrong by the next release.
12//!
13//! There is no `--check`. The installer prints `mira vX is already installed`
14//! and stops when the version matches, so running it *is* the check, and a
15//! second network path that only prints would be a second thing to keep true.
16//!
17//! The one thing this adds on top of the script is `MIRA_INSTALL_DIR`. The
18//! script defaults to `/usr/local/bin`; someone who put mira in `~/.local/bin`
19//! and typed `mira update` means *this* mira, not a second copy that then
20//! shadows it depending on `PATH` order.
21
22use std::path::{Path, PathBuf};
23
24/// Where the installer is published. `docs/install.sh` is a symlink to
25/// `scripts/get-mira.sh`, so this URL and the one in the install docs are the
26/// same file.
27const INSTALLER: &str = "https://miradb.dev/install.sh";
28
29/// Where to go when there is no shell to run the installer with.
30const RELEASES: &str = "https://github.com/TrianaLab/mira/releases";
31
32/// This verb's own place in the tree `main::cli` builds.
33///
34/// It declares its own `--version`, which is why the root's `-V` is not
35/// propagated: `mira update --version v0.1.0` has to install that tag rather
36/// than print this binary's own.
37pub fn cli() -> clap::Command {
38    clap::Command::new("update")
39        .about("replace this binary with a release from GitHub")
40        .after_help(
41            "Runs the same installer as\n  \
42             curl -fsSL https://miradb.dev/install.sh | bash\n\n\
43             Installs over this binary's own directory, not /usr/local/bin, unless\n\
44             MIRA_INSTALL_DIR says otherwise. Nothing happens if the running version\n\
45             is already the one that would be installed.\n\n\
46             Needs bash and either curl or wget, because it runs the installer rather\n\
47             than carrying an HTTPS client. The container image has none of them;\n\
48             upgrade that by pulling a newer tag.",
49        )
50        .arg(
51            clap::Arg::new("version")
52                .long("version")
53                .short('v')
54                .value_name("VERSION")
55                .value_parser(tag)
56                .help("install this tag instead of the latest (e.g. v0.1.0)"),
57        )
58        .arg(
59            clap::Arg::new("dry-run")
60                .long("dry-run")
61                .action(clap::ArgAction::SetTrue)
62                .help("print the command that would run, and stop"),
63        )
64}
65
66/// A release tag, checked against a charset rather than quoted.
67///
68/// It goes into a shell command, and quoting is a thing to get subtly wrong
69/// once: no real Git tag needs a character outside this set. Unknown flags are
70/// refused rather than forwarded — that is clap's job now — because the
71/// installer's own flag set is not this one's, and silently passing `--no-sudo`
72/// through would make its behaviour depend on a flag this usage does not
73/// document.
74pub fn tag(v: &str) -> Result<String, String> {
75    if v.is_empty()
76        || !v
77            .chars()
78            .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
79    {
80        return Err(format!("{v:?} is not a release tag"));
81    }
82    Ok(v.to_owned())
83}
84
85/// The shell line that does the update.
86///
87/// `curl` or `wget` is chosen inside the shell rather than out here: the script
88/// itself already has to make that choice for every download it does, and one
89/// `command -v` in a string is smaller than a probe, an enum and a match.
90pub fn command(version: Option<&str>) -> String {
91    let tag = match version {
92        Some(v) => format!(" --version {v}"),
93        None => String::new(),
94    };
95    format!(
96        "if command -v curl >/dev/null 2>&1; then curl -fsSL {INSTALLER}; \
97         elif command -v wget >/dev/null 2>&1; then wget -qO- {INSTALLER}; \
98         else echo 'mira update needs curl or wget' >&2; exit 1; fi \
99         | bash -s --{tag}"
100    )
101}
102
103/// The directory to install into, given this process's own executable path.
104///
105/// `None` when it cannot be resolved or has no parent, which leaves
106/// `MIRA_INSTALL_DIR` unset and the script on its `/usr/local/bin` default —
107/// the right fallback, because a mira that cannot find itself is more likely to
108/// be a test harness than a real install.
109pub fn install_dir(exe: Option<&Path>) -> Option<PathBuf> {
110    let real = std::fs::canonicalize(exe?).ok()?;
111    real.parent().map(Path::to_path_buf)
112}
113
114/// Run it.
115///
116/// The child inherits stdio, so the installer's own progress and its `sudo`
117/// prompt reach the terminal directly. Its exit status becomes this command's:
118/// a failed download must not look like a successful update to whatever ran
119/// `mira update` in a script.
120pub fn run(m: &clap::ArgMatches) -> Result<(), String> {
121    let line = command(m.get_one::<String>("version").map(String::as_str));
122    if m.get_flag("dry-run") {
123        println!("{line}");
124        return Ok(());
125    }
126
127    spawn(&mut installer(&line))
128}
129
130/// The child, configured but not started.
131///
132/// Separate from [`spawn`] so a test can assert what would run — the program,
133/// the shell line, the install directory — without a test run downloading a
134/// release over the binary that is running the test.
135fn installer(line: &str) -> std::process::Command {
136    let mut cmd = std::process::Command::new("bash");
137    cmd.arg("-c").arg(line);
138    if std::env::var_os("MIRA_INSTALL_DIR").is_none()
139        && let Some(dir) = install_dir(std::env::current_exe().ok().as_deref())
140    {
141        cmd.env("MIRA_INSTALL_DIR", dir);
142    }
143    cmd
144}
145
146/// Start it and turn its exit into this command's.
147///
148/// Taking a `Command` rather than the line means both failure arms — the child
149/// that never started and the child that started and failed — are reachable
150/// from a test with `true`, `false` and a path that does not exist.
151fn spawn(cmd: &mut std::process::Command) -> Result<(), String> {
152    let status = cmd
153        .status()
154        .map_err(|e| start_failed(&cmd.get_program().to_string_lossy(), &e))?;
155    if !status.success() {
156        return Err(format!("installer exited with {status}"));
157    }
158    Ok(())
159}
160
161/// What to say about a child that never started.
162///
163/// `NotFound` is not an unusual system here, it is the shipped one: the image
164/// is distroless, so it has no bash, no curl and no writable install directory,
165/// and the raw "No such file or directory (os error 2)" names the symptom while
166/// hiding the answer — a container upgrades by pulling a newer tag, not by
167/// rewriting its own rootfs. Every other tool the installer needs already
168/// refuses by name (curl-or-wget in [`command`], sha256sum in the script), so
169/// this is the last case that did not.
170fn start_failed(program: &str, e: &std::io::Error) -> String {
171    if e.kind() == std::io::ErrorKind::NotFound {
172        return format!(
173            "`{program}` is not on PATH, so there is nothing here to run the \
174             installer with. In a container, upgrade by pulling a newer image \
175             tag. Otherwise install {program}, or take the tarball for this \
176             platform straight from {RELEASES}."
177        );
178    }
179    format!("could not run the installer: {e}")
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    /// This verb's own arguments, through the tree it is a part of.
187    fn parse(a: &[&str]) -> Result<clap::ArgMatches, String> {
188        cli()
189            .try_get_matches_from(std::iter::once("update").chain(a.iter().copied()))
190            .map_err(|e| e.to_string())
191    }
192
193    #[test]
194    fn no_flags_installs_the_latest_release() {
195        let m = parse(&[]).unwrap();
196        assert_eq!(m.get_one::<String>("version"), None);
197        assert!(!m.get_flag("dry-run"));
198        let line = command(None);
199        assert!(line.ends_with("| bash -s --"), "{line}");
200        assert!(line.contains(INSTALLER), "{line}");
201    }
202
203    #[test]
204    fn a_tag_is_forwarded_to_the_installer() {
205        let m = parse(&["--version", "v0.1.0"]).unwrap();
206        let v = m.get_one::<String>("version").map(String::as_str);
207        assert_eq!(v, Some("v0.1.0"));
208        assert!(!m.get_flag("dry-run"));
209        assert!(command(v).ends_with("--version v0.1.0"));
210    }
211
212    #[test]
213    fn a_tag_that_could_be_a_shell_command_is_refused_rather_than_quoted() {
214        for bad in ["v1; rm -rf /", "$(id)", "`id`", "v1 --no-sudo", ""] {
215            // Through the parser, because the charset check is only a guarantee
216            // if it is the value parser the flag actually carries.
217            let e = parse(&["--version", bad]).unwrap_err();
218            assert!(e.contains("is not a release tag"), "{bad:?}: {e}");
219            assert!(tag(bad).is_err(), "{bad:?} passed the charset check");
220        }
221        assert!(tag("v0.1.0-rc.1").is_ok(), "a real tag was refused");
222        let e = parse(&["--version"]).unwrap_err();
223        assert!(e.contains("a value is required"), "{e}");
224    }
225
226    #[test]
227    fn an_installer_flag_this_command_does_not_document_is_refused() {
228        let e = parse(&["--no-sudo"]).unwrap_err();
229        assert!(e.contains("--no-sudo"), "{e}");
230        assert!(e.contains("Usage: update"), "the usage is part of it: {e}");
231    }
232
233    #[test]
234    fn the_downloader_is_chosen_by_the_shell_and_not_assumed() {
235        let line = command(None);
236        assert!(line.contains("command -v curl"), "{line}");
237        assert!(line.contains("command -v wget"), "{line}");
238        assert!(line.contains("needs curl or wget"), "{line}");
239    }
240
241    #[test]
242    fn the_install_directory_is_this_binarys_own() {
243        let exe = std::env::current_exe().unwrap();
244        assert_eq!(
245            install_dir(Some(&exe)).unwrap(),
246            std::fs::canonicalize(&exe).unwrap().parent().unwrap()
247        );
248        assert_eq!(install_dir(None), None);
249        assert_eq!(install_dir(Some(Path::new("/no/such/mira"))), None);
250    }
251
252    #[test]
253    fn dry_run_prints_the_command_instead_of_running_it() {
254        run(&parse(&["--dry-run", "--version", "v9.9.9"]).unwrap()).unwrap();
255        // `--help` and `--nope` never reach `run` any more: clap answers both
256        // before the matches exist, which is the whole reason this verb no
257        // longer hand-parses its own argv.
258        assert!(parse(&["--help"]).is_err(), "--help produced matches");
259        assert!(parse(&["--nope"]).is_err());
260    }
261
262    /// Asserts the child rather than running it: the real one would replace the
263    /// binary under test with a download.
264    #[test]
265    fn the_child_is_the_installer_pointed_at_this_binarys_directory() {
266        let line = command(None);
267        let cmd = installer(&line);
268        assert_eq!(cmd.get_program(), "bash");
269        let argv: Vec<_> = cmd.get_args().collect();
270        assert_eq!(argv, ["-c", line.as_str()]);
271        // The harness runs with `MIRA_INSTALL_DIR` unset, so the override is the
272        // one this command adds, and it points at wherever the test binary is.
273        let dir = cmd
274            .get_envs()
275            .find(|(k, _)| *k == "MIRA_INSTALL_DIR")
276            .and_then(|(_, v)| v)
277            .expect("an install directory");
278        let exe = std::env::current_exe().unwrap();
279        assert_eq!(Path::new(dir), install_dir(Some(&exe)).unwrap());
280    }
281
282    #[test]
283    fn a_failed_installer_is_a_failed_update() {
284        spawn(&mut std::process::Command::new("true")).unwrap();
285
286        let e = spawn(&mut std::process::Command::new("false")).unwrap_err();
287        assert!(e.starts_with("installer exited with"), "{e}");
288
289        let e = spawn(&mut std::process::Command::new("/no/such/installer")).unwrap_err();
290        assert!(e.starts_with("`/no/such/installer` is not on PATH"), "{e}");
291    }
292
293    /// The distroless image has no bash, and that has to read as an answer
294    /// rather than as an errno.
295    #[test]
296    fn no_shell_says_so_and_says_what_to_do_instead() {
297        let e = start_failed("bash", &std::io::ErrorKind::NotFound.into());
298        assert!(e.starts_with("`bash` is not on PATH"), "{e}");
299        assert!(e.contains("pulling a newer image tag"), "{e}");
300        assert!(e.contains(RELEASES), "{e}");
301
302        // Anything else is a real error and is reported as one, rather than
303        // being explained away as a missing shell.
304        let e = start_failed("bash", &std::io::ErrorKind::PermissionDenied.into());
305        assert!(e.starts_with("could not run the installer:"), "{e}");
306    }
307
308    /// The host requirement is only discoverable from `--help`, so it is the
309    /// one line of that text worth asserting on: [`start_failed`] above can say
310    /// `bash` is missing, but only after the user has already run the verb.
311    #[test]
312    fn the_help_names_what_it_needs_on_the_host() {
313        let help = cli().render_long_help().to_string();
314        assert!(
315            help.contains("Needs bash and either curl or wget"),
316            "{help}"
317        );
318    }
319}