Skip to main content

nextest_runner/
update.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Self-updates for nextest.
5
6use crate::{
7    errors::{UpdateError, UpdateVersionParseError},
8    helpers::{ThemeCharacters, progress::progress_bar_style},
9};
10use byte_wrapper::HexArray;
11use camino::{Utf8Path, Utf8PathBuf};
12use indicatif::{ProgressBar, ProgressStyle};
13use mukti_metadata::{
14    DigestAlgorithm, MuktiProject, MuktiReleasesJson, ReleaseLocation, ReleaseStatus,
15};
16use owo_colors::{OwoColorize, Style};
17use self_update::{ArchiveKind, Compression, Extract};
18use semver::{Version, VersionReq};
19use serde::Deserialize;
20use sha2::{Digest, Sha256};
21#[cfg(not(target_arch = "riscv32"))]
22use std::sync::OnceLock;
23use std::{
24    fs,
25    io::{self, BufRead, BufReader, BufWriter, Write as _},
26    str::FromStr,
27    time::Duration,
28};
29use target_spec::Platform;
30use tracing::{debug, info, warn};
31
32/// Update backend using mukti
33#[derive(Clone, Debug)]
34pub struct MuktiBackend {
35    /// The URL to download releases from
36    pub url: String,
37
38    /// The package name.
39    pub package_name: String,
40}
41
42impl MuktiBackend {
43    /// Fetch releases.
44    pub fn fetch_releases(&self, current_version: Version) -> Result<NextestReleases, UpdateError> {
45        info!(target: "nextest-runner::update", "checking for self-updates");
46        // Is the URL a file that exists on disk? If so, use that.
47        let as_path = Utf8Path::new(&self.url);
48        let releases_buf = if as_path.exists() {
49            fs::read(as_path).map_err(|error| UpdateError::ReadLocalMetadata {
50                path: as_path.to_owned(),
51                error,
52            })?
53        } else {
54            let agent = ureq_agent();
55            agent
56                .get(&self.url)
57                .call()
58                .map_err(UpdateError::Http)?
59                .into_body()
60                // The default read_to_vec() limit is 10 MiB, which the
61                // releases JSON could plausibly exceed as releases
62                // accumulate. Use a 64 MiB limit instead.
63                .into_with_config()
64                .limit(64 * 1024 * 1024)
65                .read_to_vec()
66                .map_err(UpdateError::Http)?
67        };
68
69        let mut releases_json: MuktiReleasesJson =
70            serde_json::from_slice(&releases_buf).map_err(UpdateError::ReleaseMetadataDe)?;
71
72        let project = match releases_json.projects.remove(&self.package_name) {
73            Some(project) => project,
74            None => {
75                return Err(UpdateError::MuktiProjectNotFound {
76                    not_found: self.package_name.clone(),
77                    known: releases_json.projects.keys().cloned().collect(),
78                });
79            }
80        };
81
82        NextestReleases::new(&self.package_name, project, current_version)
83    }
84}
85
86/// Release info for nextest.
87///
88/// Returned by [`MuktiBackend::fetch_releases`].
89#[derive(Clone, Debug)]
90#[non_exhaustive]
91pub struct NextestReleases {
92    /// The package name.
93    pub package_name: String,
94
95    /// The mukti project.
96    pub project: MuktiProject,
97
98    /// The currently running version.
99    pub current_version: Version,
100
101    /// The install path.
102    pub bin_install_path: Utf8PathBuf,
103}
104
105impl NextestReleases {
106    fn new(
107        package_name: &str,
108        project: MuktiProject,
109        current_version: Version,
110    ) -> Result<Self, UpdateError> {
111        let bin_install_path = std::env::current_exe()
112            .and_then(|exe| {
113                Utf8PathBuf::try_from(exe)
114                    .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
115            })
116            .map_err(UpdateError::CurrentExe)?;
117
118        Ok(Self {
119            package_name: package_name.to_owned(),
120            project,
121            current_version,
122            bin_install_path,
123        })
124    }
125
126    /// Checks for whether an update should be performed.
127    pub fn check<'a>(
128        &'a self,
129        version_req: &UpdateVersionReq,
130        force: bool,
131        bin_path_in_archive: &'a Utf8Path,
132        perform_setup_fn: impl FnOnce(&Version) -> bool,
133    ) -> Result<CheckStatus<'a>, UpdateError> {
134        let (version, version_data) = self.resolve_version(version_req)?;
135        debug!(
136            target: "nextest-runner::update",
137            "current version is {}, update version is {version}",
138            self.current_version,
139        );
140
141        if &self.current_version == version && !force {
142            return Ok(CheckStatus::AlreadyOnRequested(version.clone()));
143        }
144        if &self.current_version > version && !force {
145            return Ok(CheckStatus::DowngradeNotAllowed {
146                current_version: self.current_version.clone(),
147                requested: version.clone(),
148            });
149        }
150
151        // Look for data for this platform.
152        let triple = self.target_triple();
153        debug!(target: "nextest-runner::update", "target triple: {triple}");
154
155        let location = version_data
156            .locations
157            .iter()
158            .find(|&data| data.format == TAR_GZ_SUFFIX && data.target == triple)
159            .ok_or_else(|| {
160                let known_triples = version_data
161                    .locations
162                    .iter()
163                    .filter(|data| data.format == TAR_GZ_SUFFIX)
164                    .map(|data| data.target.clone())
165                    .collect();
166                UpdateError::NoTargetData {
167                    version: version.clone(),
168                    triple,
169                    known_triples,
170                }
171            })?;
172
173        let force_disable_setup = version_data
174            .metadata
175            .is_some_and(|metadata| metadata.force_disable_setup);
176        let perform_setup = !force_disable_setup && perform_setup_fn(version);
177
178        Ok(CheckStatus::Success(MuktiUpdateContext {
179            context: self,
180            version: version.clone(),
181            location: location.clone(),
182            bin_path_in_archive,
183            perform_setup,
184        }))
185    }
186
187    // ---
188    // Helper methods
189    // ---
190
191    fn resolve_version(
192        &self,
193        version_req: &UpdateVersionReq,
194    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
195        match version_req {
196            UpdateVersionReq::Latest => {
197                // Get the latest stable (non-prerelease) version.
198                let (version, release_data) = self
199                    .project
200                    .get_latest_matching(&VersionReq::STAR)
201                    .ok_or(UpdateError::NoStableVersion)?;
202                Ok((version, self.parse_release_data(release_data)))
203            }
204            UpdateVersionReq::Version(update_version) => self.get_version_data(update_version),
205            UpdateVersionReq::LatestPrerelease(kind) => self.get_latest_prerelease(*kind),
206        }
207    }
208
209    fn get_version_data(
210        &self,
211        version: &UpdateVersion,
212    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
213        let (version, release_data) = match version {
214            UpdateVersion::Exact(version) => {
215                self.project.get_version_data(version).ok_or_else(|| {
216                    let known = self
217                        .project
218                        .all_versions()
219                        .map(|(v, release_data)| (v.clone(), release_data.status))
220                        .collect();
221                    UpdateError::VersionNotFound {
222                        version: version.clone(),
223                        known,
224                    }
225                })?
226            }
227            UpdateVersion::Req(req) => self
228                .project
229                .get_latest_matching(req)
230                .ok_or_else(|| UpdateError::NoMatchForVersionReq { req: req.clone() })?,
231        };
232
233        Ok((version, self.parse_release_data(release_data)))
234    }
235
236    fn get_latest_prerelease(
237        &self,
238        kind: PrereleaseKind,
239    ) -> Result<(&Version, ReleaseVersionData), UpdateError> {
240        // all_versions() returns versions in descending order (most recent first).
241        for (version, release_data) in self.project.all_versions() {
242            if release_data.status == ReleaseStatus::Active && kind.matches(version) {
243                return Ok((version, self.parse_release_data(release_data)));
244            }
245        }
246
247        Err(UpdateError::NoVersionForPrereleaseKind { kind })
248    }
249
250    fn parse_release_data(
251        &self,
252        release_data: &mukti_metadata::ReleaseVersionData,
253    ) -> ReleaseVersionData {
254        // Parse the metadata into our custom format.
255        let metadata = if release_data.metadata.is_null() {
256            None
257        } else {
258            // Attempt to parse the metadata.
259            match serde_json::from_value::<NextestReleaseMetadata>(release_data.metadata.clone()) {
260                Ok(metadata) => Some(metadata),
261                Err(error) => {
262                    warn!(
263                        target: "nextest-runner::update",
264                        "failed to parse custom release metadata: {error}",
265                    );
266                    None
267                }
268            }
269        };
270
271        ReleaseVersionData {
272            release_url: release_data.release_url.clone(),
273            status: release_data.status,
274            locations: release_data.locations.clone(),
275            metadata,
276        }
277    }
278
279    fn target_triple(&self) -> String {
280        // In this case, use the build target, *not* `rustc -vV` output. This
281        // ensures that e.g. musl binary updates continue to use the musl
282        // target.
283        let current = Platform::build_target().expect("build target could not be detected");
284        let triple_str = current.triple_str();
285        if triple_str.ends_with("-apple-darwin") {
286            // Nextest builds a universal binary for Mac.
287            "universal-apple-darwin".to_owned()
288        } else {
289            triple_str.to_owned()
290        }
291    }
292}
293
294/// Like `mukti-metadata`'s `ReleaseVersionData`, except with parsed metadata.
295#[derive(Clone, Debug)]
296pub struct ReleaseVersionData {
297    /// Canonical URL for this release
298    pub release_url: String,
299
300    /// The status of a release
301    pub status: ReleaseStatus,
302
303    /// Release locations
304    pub locations: Vec<ReleaseLocation>,
305
306    /// Custom domain-specific information stored about this release.
307    pub metadata: Option<NextestReleaseMetadata>,
308}
309
310/// Nextest-specific release metadata.
311#[derive(Clone, Debug, Deserialize)]
312pub struct NextestReleaseMetadata {
313    /// Whether to force disable `cargo nextest self setup` for this version.
314    #[serde(default)]
315    pub force_disable_setup: bool,
316}
317
318/// The result of [`NextestReleases::check`].
319#[derive(Clone, Debug)]
320pub enum CheckStatus<'a> {
321    /// The current version is the same as the requested version.
322    AlreadyOnRequested(Version),
323
324    /// A downgrade was requested but wasn't allowed.
325    DowngradeNotAllowed {
326        /// The currently running version.
327        current_version: Version,
328
329        /// The requested version.
330        requested: Version,
331    },
332
333    /// All checks were performed successfully and we are ready to update.
334    Success(MuktiUpdateContext<'a>),
335}
336
337/// Display styles for update progress output.
338#[derive(Clone, Debug, Default)]
339pub struct UpdateDisplayStyles {
340    /// Style for the progress bar prefix (e.g. "Downloading").
341    pub progress_prefix: Style,
342
343    /// Theme characters for the progress bar (ASCII or Unicode).
344    pub theme_characters: ThemeCharacters,
345}
346
347impl UpdateDisplayStyles {
348    /// Creates colorized styles.
349    pub fn colorize(&mut self) {
350        self.progress_prefix = Style::new().green().bold();
351    }
352}
353
354/// Context for an update.
355///
356/// Returned as part of the `Success` variant of [`CheckStatus`].
357#[derive(Clone, Debug)]
358#[non_exhaustive]
359pub struct MuktiUpdateContext<'a> {
360    /// The `MuktiReleases` context.
361    pub context: &'a NextestReleases,
362
363    /// The version being updated to.
364    pub version: Version,
365
366    /// The target-specific release location from which the package will be downloaded.
367    pub location: ReleaseLocation,
368
369    /// The path to the binary within the archive.
370    pub bin_path_in_archive: &'a Utf8Path,
371
372    /// Whether to run `cargo nextest self setup` as part of the update.
373    pub perform_setup: bool,
374}
375
376impl MuktiUpdateContext<'_> {
377    /// Performs the update.
378    pub fn do_update(&self, styles: &UpdateDisplayStyles) -> Result<(), UpdateError> {
379        // This method is adapted from self_update's update_extended.
380
381        let tmp_dir_parent = self.context.bin_install_path.parent().ok_or_else(|| {
382            UpdateError::CurrentExe(io::Error::new(
383                io::ErrorKind::InvalidData,
384                format!(
385                    "parent directory of current exe `{}` could not be determined",
386                    self.context.bin_install_path
387                ),
388            ))
389        })?;
390        let tmp_backup_dir_prefix = format!("__{}_backup", self.context.package_name);
391        let tmp_backup_filename = tmp_backup_dir_prefix.clone();
392
393        if cfg!(windows) {
394            // Windows executables can not be removed while they are running, which prevents clean up
395            // of the temporary directory by the `tempfile` crate after we move the running executable
396            // into it during an update. We clean up any previously created temporary directories here.
397            // Ignore errors during cleanup since this is not critical for completing the update.
398            let _ = cleanup_backup_temp_directories(
399                tmp_dir_parent,
400                &tmp_backup_dir_prefix,
401                &tmp_backup_filename,
402            );
403        }
404
405        let tmp_archive_dir_prefix = format!("{}_download", self.context.package_name);
406        let tmp_archive_dir = camino_tempfile::Builder::new()
407            .prefix(&tmp_archive_dir_prefix)
408            .tempdir_in(tmp_dir_parent)
409            .map_err(|error| UpdateError::TempDirCreate {
410                location: tmp_dir_parent.to_owned(),
411                error,
412            })?;
413        let tmp_dir_path: &Utf8Path = tmp_archive_dir.path();
414        let tmp_archive_path =
415            tmp_dir_path.join(format!("{}.{TAR_GZ_SUFFIX}", self.context.package_name));
416        let tmp_archive = fs::File::create(&tmp_archive_path).map_err(|error| {
417            UpdateError::TempArchiveCreate {
418                archive_path: tmp_archive_path.clone(),
419                error,
420            }
421        })?;
422        let mut tmp_archive_buf = BufWriter::new(tmp_archive);
423
424        let agent = ureq_agent();
425        let resp = agent
426            .get(&self.location.url)
427            .header(http::header::ACCEPT.as_str(), "application/octet-stream")
428            .call()
429            .map_err(UpdateError::Http)?;
430
431        let content_length: Option<u64> =
432            match resp.headers().get(http::header::CONTENT_LENGTH.as_str()) {
433                Some(v) => {
434                    let s = v.to_str().map_err(|_| UpdateError::ContentLengthInvalid {
435                        value: format!("{v:?}"),
436                    })?;
437                    let len = s
438                        .parse::<u64>()
439                        .map_err(|_| UpdateError::ContentLengthInvalid {
440                            value: s.to_owned(),
441                        })?;
442                    Some(len)
443                }
444                None => None,
445            };
446
447        // Stream the response body to the archive file with a progress bar.
448        // into_reader() has no size limit, unlike read_to_vec(). This is
449        // intentional: release archives are ~10 MiB as of March 2026 and
450        // are streamed to a temporary file via tmp_archive_buf above,
451        // not buffered entirely in memory. The SHA-256 checksum verified
452        // later guards against corruption or truncation.
453        let mut src = BufReader::new(resp.into_body().into_reader());
454        let prefix = format!("{}", "Downloading".style(styles.progress_prefix));
455        let progress_bar = match content_length {
456            Some(size) => {
457                let pb = ProgressBar::new(size);
458                pb.set_style(progress_bar_style(
459                    styles.theme_characters.progress_chars(),
460                    "{bytes:>9}/{total_bytes:>9}",
461                ));
462                pb
463            }
464            None => {
465                let pb = ProgressBar::new_spinner();
466                pb.set_style(
467                    ProgressStyle::default_spinner()
468                        .template("{prefix:>12} [{elapsed_precise:>9}] {bytes}")
469                        .expect("valid progress spinner template"),
470                );
471                pb
472            }
473        };
474        progress_bar.set_prefix(prefix);
475
476        let mut downloaded: u64 = 0;
477        loop {
478            let n = {
479                let buf = src.fill_buf().map_err(UpdateError::HttpBody)?;
480                tmp_archive_buf
481                    .write_all(buf)
482                    .map_err(|error| UpdateError::TempArchiveWrite {
483                        archive_path: tmp_archive_path.clone(),
484                        error,
485                    })?;
486                buf.len()
487            };
488            if n == 0 {
489                break;
490            }
491            src.consume(n);
492            downloaded += n as u64;
493            progress_bar.set_position(downloaded);
494        }
495        progress_bar.finish();
496
497        // Verify that we received the expected number of bytes.
498        if let Some(expected) = content_length
499            && downloaded != expected
500        {
501            return Err(UpdateError::ContentLengthMismatch {
502                expected,
503                actual: downloaded,
504            });
505        }
506
507        debug!(target: "nextest-runner::update", "downloaded to {tmp_archive_path}");
508
509        let tmp_archive =
510            tmp_archive_buf
511                .into_inner()
512                .map_err(|error| UpdateError::TempArchiveWrite {
513                    archive_path: tmp_archive_path.clone(),
514                    error: error.into_error(),
515                })?;
516        tmp_archive
517            .sync_all()
518            .map_err(|error| UpdateError::TempArchiveWrite {
519                archive_path: tmp_archive_path.clone(),
520                error,
521            })?;
522        std::mem::drop(tmp_archive);
523
524        // Verify the checksum of the downloaded file if available.
525        let mut hasher = Sha256::default();
526        // Just read the file into memory for now -- it would be nice to have an
527        // incremental hasher that updates the hash as it's being downloaded,
528        // but it's not critical since our archives are quite small.
529        let mut tmp_archive =
530            fs::File::open(&tmp_archive_path).map_err(|error| UpdateError::TempArchiveRead {
531                archive_path: tmp_archive_path.clone(),
532                error,
533            })?;
534        io::copy(&mut tmp_archive, &mut hasher).map_err(|error| UpdateError::TempArchiveRead {
535            archive_path: tmp_archive_path.clone(),
536            error,
537        })?;
538        let hash = hasher.finalize();
539        verify_sha256(
540            self.location.checksums.get(&DigestAlgorithm::SHA256),
541            HexArray::new(hash.into()),
542        )?;
543
544        // Now extract data from this archive.
545        Extract::from_source(tmp_archive_path.as_std_path())
546            .archive(ArchiveKind::Tar(Some(Compression::Gz)))
547            .extract_file(
548                tmp_archive_dir.path().as_std_path(),
549                self.bin_path_in_archive,
550            )
551            .map_err(UpdateError::SelfUpdate)?;
552
553        // Since we're currently restricted to .tar.gz which carries metadata with it, there's no
554        // need to make this file executable.
555
556        let new_exe = tmp_dir_path.join(self.bin_path_in_archive);
557        debug!(target: "nextest-runner::update", "extracted to {new_exe}, replacing existing binary");
558
559        let tmp_backup_dir = camino_tempfile::Builder::new()
560            .prefix(&tmp_backup_dir_prefix)
561            .tempdir_in(tmp_dir_parent)
562            .map_err(|error| UpdateError::TempDirCreate {
563                location: tmp_dir_parent.to_owned(),
564                error,
565            })?;
566
567        let tmp_backup_dir_path: &Utf8Path = tmp_backup_dir.path();
568        let tmp_file_path = tmp_backup_dir_path.join(&tmp_backup_filename);
569
570        Move::from_source(&new_exe)
571            .replace_using_temp(&tmp_file_path)
572            .to_dest(&self.context.bin_install_path)?;
573
574        // Finally, run `cargo nextest self setup` if requested.
575        if self.perform_setup {
576            info!(target: "nextest-runner::update", "running `cargo nextest self setup`");
577            let mut cmd = std::process::Command::new(&self.context.bin_install_path);
578            cmd.args(["nextest", "self", "setup", "--source", "self-update"]);
579            let status = cmd.status().map_err(UpdateError::SelfSetup)?;
580            if !status.success() {
581                return Err(UpdateError::SelfSetup(io::Error::other(format!(
582                    "`cargo nextest self setup` failed with exit code {}",
583                    status
584                        .code()
585                        .map_or("(unknown)".to_owned(), |c| c.to_string())
586                ))));
587            }
588        }
589
590        Ok(())
591    }
592}
593
594fn verify_sha256(
595    expected: Option<&mukti_metadata::Digest>,
596    actual: HexArray<32>,
597) -> Result<(), UpdateError> {
598    match expected {
599        Some(expected) => {
600            if expected.as_bytes() != actual.as_slice() {
601                return Err(UpdateError::ChecksumMismatch {
602                    expected: expected.clone(),
603                    actual,
604                });
605            }
606            debug!(target: "nextest-runner::update", "SHA-256 checksum verified: {actual}");
607        }
608        None => {
609            warn!(target: "nextest-runner::update", "unable to verify SHA-256 checksum of downloaded archive ({actual})");
610        }
611    }
612    Ok(())
613}
614
615/// Moves a file from the given path to the specified destination.
616///
617/// `source` and `dest` must be on the same filesystem.
618/// If `replace_using_temp` is specified, the destination file will be
619/// replaced using the given temporary path.
620/// If the existing `dest` file is a currently running long running program,
621/// `replace_using_temp` may run into errors cleaning up the temp dir.
622/// If that's the case for your use-case, consider not specifying a temp dir to use.
623///
624/// * Errors:
625///     * Io - copying / renaming
626#[derive(Debug)]
627struct Move<'a> {
628    source: &'a Utf8Path,
629    temp: Option<&'a Utf8Path>,
630}
631impl<'a> Move<'a> {
632    /// Specify source file
633    pub fn from_source(source: &'a Utf8Path) -> Move<'a> {
634        Self { source, temp: None }
635    }
636
637    /// If specified and the destination file already exists, the "destination"
638    /// file will be moved to the given temporary location before the "source"
639    /// file is moved to the "destination" file.
640    ///
641    /// In the event of an `io` error while renaming "source" to "destination",
642    /// the temporary file will be moved back to "destination".
643    ///
644    /// The `temp` dir must be explicitly provided since `rename` operations require
645    /// files to live on the same filesystem.
646    pub fn replace_using_temp(&mut self, temp: &'a Utf8Path) -> &mut Self {
647        self.temp = Some(temp);
648        self
649    }
650
651    /// Move source file to specified destination
652    pub fn to_dest(&self, dest: &Utf8Path) -> Result<(), UpdateError> {
653        match self.temp {
654            None => Self::fs_rename(self.source, dest),
655            Some(temp) => {
656                if dest.exists() {
657                    // Move the existing dest to a temp location so we can move it
658                    // back it there's an error. If the existing `dest` file is a
659                    // long running program, this may prevent the temp dir from
660                    // being cleaned up.
661                    Self::fs_rename(dest, temp)?;
662                    if let Err(e) = Self::fs_rename(self.source, dest) {
663                        Self::fs_rename(temp, dest)?;
664                        return Err(e);
665                    }
666                } else {
667                    Self::fs_rename(self.source, dest)?;
668                }
669                Ok(())
670            }
671        }
672    }
673
674    // ---
675    // Helper methods
676    // ---
677
678    fn fs_rename(source: &Utf8Path, dest: &Utf8Path) -> Result<(), UpdateError> {
679        fs::rename(source, dest).map_err(|error| UpdateError::FsRename {
680            source: source.to_owned(),
681            dest: dest.to_owned(),
682            error,
683        })
684    }
685}
686
687fn cleanup_backup_temp_directories(
688    tmp_dir_parent: &Utf8Path,
689    tmp_dir_prefix: &str,
690    expected_tmp_filename: &str,
691) -> io::Result<()> {
692    for entry in fs::read_dir(tmp_dir_parent)? {
693        let entry = entry?;
694        let tmp_dir_name = if let Ok(tmp_dir_name) = entry.file_name().into_string() {
695            tmp_dir_name
696        } else {
697            continue;
698        };
699
700        // For safety, check that the temporary directory contains only the expected backup
701        // binary file before removing. If subdirectories or other files exist then the user
702        // is using the temp directory for something else. This is unlikely, but we should
703        // be careful with `fs::remove_dir_all`.
704        let is_expected_tmp_file = |tmp_file_entry: std::io::Result<fs::DirEntry>| {
705            tmp_file_entry
706                .ok()
707                .filter(|e| e.file_name() == expected_tmp_filename)
708                .is_some()
709        };
710
711        if tmp_dir_name.starts_with(tmp_dir_prefix)
712            && fs::read_dir(entry.path())?.all(is_expected_tmp_file)
713        {
714            fs::remove_dir_all(entry.path())?;
715        }
716    }
717    Ok(())
718}
719
720/// Returns a ureq agent configured with rustls and the aws-lc-rs crypto
721/// provider.
722///
723/// On 32-bit RISC-V, rustls/aws-lc-rs aren't available; see the RISC-V variant
724/// below.
725#[cfg(not(target_arch = "riscv32"))]
726fn ureq_agent() -> ureq::Agent {
727    // Install aws-lc-rs as the default rustls crypto provider. The OnceLock
728    // ensures we only attempt this once; if it's already set (by us or someone
729    // else), we log and move on.
730    static PROVIDER_INSTALLED: OnceLock<()> = OnceLock::new();
731    PROVIDER_INSTALLED.get_or_init(|| {
732        if rustls::crypto::CryptoProvider::install_default(
733            rustls::crypto::aws_lc_rs::default_provider(),
734        )
735        .is_err()
736        {
737            warn!(
738                target: "nextest-runner::update",
739                "a rustls crypto provider was already installed; \
740                 using the existing provider",
741            );
742        }
743    });
744
745    ureq::Agent::new_with_config(
746        ureq::Agent::config_builder()
747            // Set a connect timeout to avoid hanging on unreachable hosts.
748            // No global timeout: binary downloads can be large on slow
749            // connections, and the progress bar keeps the user informed.
750            .timeout_connect(Some(CONNECT_TIMEOUT))
751            .tls_config(
752                ureq::tls::TlsConfig::builder()
753                    .provider(ureq::tls::TlsProvider::Rustls)
754                    .build(),
755            )
756            .build(),
757    )
758}
759
760/// Returns a ureq agent configured with native-tls.
761///
762/// On 32-bit RISC-V, rustls/aws-lc-rs aren't available (see
763/// <https://github.com/nextest-rs/nextest/issues/820>), so native-tls is used
764/// instead.
765#[cfg(target_arch = "riscv32")]
766fn ureq_agent() -> ureq::Agent {
767    ureq::Agent::new_with_config(
768        ureq::Agent::config_builder()
769            .timeout_connect(Some(CONNECT_TIMEOUT))
770            .tls_config(
771                ureq::tls::TlsConfig::builder()
772                    .provider(ureq::tls::TlsProvider::NativeTls)
773                    .build(),
774            )
775            .build(),
776    )
777}
778
779/// Connect timeout for HTTP requests. Matches reqwest's old default of 30
780/// seconds, which self_update 0.42.0 relied on implicitly.
781const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
782
783const TAR_GZ_SUFFIX: &str = "tar.gz";
784
785/// Represents the user's requested version for an update.
786#[derive(Clone, Debug, Eq, PartialEq)]
787pub enum UpdateVersionReq {
788    /// Update to the latest stable (non-prerelease) version.
789    Latest,
790
791    /// Update to a specific version or version requirement.
792    Version(UpdateVersion),
793
794    /// Update to the latest prerelease of the given kind.
795    LatestPrerelease(PrereleaseKind),
796}
797
798/// The kind of prerelease to look for.
799#[derive(Clone, Copy, Debug, Eq, PartialEq)]
800pub enum PrereleaseKind {
801    /// Beta channel (includes beta `-b.N`, RC `-rc.N`, and stable versions).
802    Beta,
803
804    /// Release candidate channel (`-rc.N` and stable versions).
805    Rc,
806}
807
808impl PrereleaseKind {
809    /// Returns true if this version is acceptable for this prerelease kind.
810    ///
811    /// `Beta` accepts stable, RC, or beta versions.
812    ///
813    /// `Rc` accepts stable or RC versions (not beta).
814    pub fn matches(&self, version: &Version) -> bool {
815        // Stable versions are always acceptable.
816        if version.pre.is_empty() {
817            return true;
818        }
819        let pre_str = version.pre.as_str();
820        match self {
821            // Beta accepts everything: stable, -b.N, or -rc.N.
822            PrereleaseKind::Beta => pre_str.starts_with("b.") || pre_str.starts_with("rc."),
823            // RC accepts stable or -rc.N (not -b.N).
824            PrereleaseKind::Rc => pre_str.starts_with("rc."),
825        }
826    }
827
828    /// Returns a description of this prerelease kind for user-facing messages.
829    pub fn description(&self) -> &'static str {
830        match self {
831            PrereleaseKind::Beta => "beta or RC",
832            PrereleaseKind::Rc => "RC",
833        }
834    }
835}
836
837/// Represents the version this project is being updated to.
838#[derive(Clone, Debug, Eq, PartialEq)]
839pub enum UpdateVersion {
840    /// Update to this exact version.
841    Exact(Version),
842
843    /// Update to the latest non-pre-release, non-yanked version matching this [`VersionReq`].
844    Req(VersionReq),
845}
846
847/// Parses x.y.z as if it were =x.y.z, and provides error messages in the case of invalid
848/// values.
849impl FromStr for UpdateVersion {
850    type Err = UpdateVersionParseError;
851
852    fn from_str(input: &str) -> Result<Self, Self::Err> {
853        // Adapted from Cargo's source:
854        // https://github.com/rust-lang/cargo/blob/6b8e1922261bbed1894bf40069fb2d5dc8d62fb0/src/cargo/ops/cargo_install.rs#L760-L806
855
856        // If the version begins with character <, >, =, ^, ~ parse it as a
857        // version range, otherwise parse it as a specific version
858
859        if input == "latest" {
860            return Ok(UpdateVersion::Req(VersionReq::STAR));
861        }
862
863        let first = input
864            .chars()
865            .next()
866            .ok_or(UpdateVersionParseError::EmptyString)?;
867
868        let is_req = "<>=^~".contains(first) || input.contains('*');
869        if is_req {
870            match input.parse::<VersionReq>() {
871                Ok(v) => Ok(Self::Req(v)),
872                Err(error) => Err(UpdateVersionParseError::InvalidVersionReq {
873                    input: input.to_owned(),
874                    error,
875                }),
876            }
877        } else {
878            match input.parse::<Version>() {
879                Ok(v) => Ok(Self::Exact(v)),
880                Err(error) => Err(UpdateVersionParseError::InvalidVersion {
881                    input: input.to_owned(),
882                    error,
883                }),
884            }
885        }
886    }
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892    use std::{net::TcpListener, thread};
893
894    #[test]
895    fn verify_sha256_compares_bytes() {
896        const ACTUAL: HexArray<32> = HexArray::new([
897            0x1d, 0x4c, 0xe3, 0x02, 0xb8, 0x20, 0xc0, 0xf0, 0xc9, 0x48, 0x82, 0xc1, 0xcf, 0x08,
898            0xfc, 0x36, 0x0c, 0xaf, 0x08, 0xbe, 0x6e, 0x7d, 0xf4, 0xb8, 0x9b, 0xfb, 0xa9, 0x13,
899            0x51, 0xc4, 0x7b, 0x02,
900        ]);
901        const ACTUAL_LOWER: &str =
902            "1d4ce302b820c0f0c94882c1cf08fc360caf08be6e7df4b89bfba91351c47b02";
903        const ACTUAL_UPPER: &str =
904            "1D4CE302B820C0F0C94882C1CF08FC360CAF08BE6E7DF4B89BFBA91351C47B02";
905        const OTHER_LOWER: &str =
906            "6b284d6fde9670dfb6ee10ea9d9abbc85f95643d3f592472d420d82e257b3a6c";
907
908        let parse = |hex: &str| -> mukti_metadata::Digest {
909            serde_json::from_value(serde_json::Value::String(hex.to_owned()))
910                .expect("deserialized a hex digest")
911        };
912
913        verify_sha256(Some(&parse(ACTUAL_LOWER)), ACTUAL).expect("lowercase digest matches");
914        verify_sha256(Some(&parse(ACTUAL_UPPER)), ACTUAL).expect("uppercase digest matches");
915        verify_sha256(None, ACTUAL).expect("a missing digest only warns");
916
917        let error = verify_sha256(Some(&parse(OTHER_LOWER)), ACTUAL)
918            .expect_err("a different digest is a mismatch");
919        let error_message = error.to_string();
920        match error {
921            UpdateError::ChecksumMismatch { expected, actual } => {
922                assert_eq!(expected, parse(OTHER_LOWER), "expected digest is reported");
923                assert_eq!(actual, ACTUAL, "actual digest is reported");
924                assert_eq!(
925                    error_message,
926                    format!(
927                        "SHA-256 checksum mismatch: expected: {OTHER_LOWER}, actual: {ACTUAL_LOWER}"
928                    ),
929                    "message shows both digests as lowercase hex",
930                );
931            }
932            other => panic!("expected ChecksumMismatch, got {other:?}"),
933        }
934    }
935
936    // ureq panics on the first https request if the selected TLS provider's
937    // Cargo feature is off -- this catches a cfg mismatch between ureq_agent
938    // and Cargo.toml on the test's target platform.
939    #[test]
940    fn ureq_agent_tls_provider_is_enabled() {
941        let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bound a loopback listener");
942        let addr = listener.local_addr().expect("listener has a local address");
943
944        // Accept one connection and hang up so the handshake fails promptly. We
945        // don't wait on the thread to exit, because if the request never
946        // connects, a join would hang rather than fail.
947        thread::spawn(move || {
948            let (stream, _) = listener.accept().expect("accepted a connection");
949            drop(stream);
950        });
951
952        // Call .proxy(None) so proxy environment variables can't redirect the
953        // request away from the listener.
954        let result = ureq_agent()
955            .get(format!("https://{addr}/"))
956            .config()
957            .proxy(None)
958            .build()
959            .call();
960
961        result.expect_err("TLS handshake fails against a peer that hangs up");
962    }
963}