Skip to main content

quickgui_system/
update.rs

1use std::{
2    collections::HashMap,
3    ffi::OsString,
4    fs::{self, File},
5    io::{Read, Write},
6    path::{Path, PathBuf},
7    sync::{
8        Arc,
9        atomic::{AtomicBool, Ordering},
10    },
11};
12
13#[cfg(any(target_os = "windows", target_os = "linux"))]
14use std::ffi::OsStr;
15#[cfg(target_os = "windows")]
16use std::process::{Command, Stdio};
17
18use base64::Engine;
19use minisign_verify::{PublicKey, Signature};
20use semver::Version;
21use serde::Deserialize;
22
23use crate::{Result, SystemIntegrationError, invalid};
24
25pub const MAX_UPDATE_MANIFEST_BYTES: usize = 1024 * 1024;
26pub const MAX_UPDATE_SIGNATURE_BYTES: usize = 64 * 1024;
27pub const DEFAULT_MAX_UPDATE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
28pub const DEFAULT_MAX_EXPANDED_UPDATE_BYTES: u64 = 8 * 1024 * 1024 * 1024;
29pub const MAX_UPDATE_ARCHIVE_ENTRIES: usize = 131_072;
30pub const MAX_UPDATE_INSTALLER_ARGUMENTS: usize = 128;
31pub const MAX_UPDATE_INSTALLER_ARGUMENT_BYTES: usize = 128 * 1024;
32
33/// Thread-safe cooperative cancellation for updater network, verification, and staging work.
34///
35/// Cancellation is observed between bounded I/O chunks and before any irreversible installer
36/// launch or atomic replacement. Once an atomic replacement has started, it finishes or rolls
37/// back instead of leaving a partially installed application.
38#[derive(Clone, Debug, Default)]
39pub struct UpdateCancellation(Arc<AtomicBool>);
40
41impl UpdateCancellation {
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    pub fn cancel(&self) {
47        self.0.store(true, Ordering::Release);
48    }
49
50    pub fn is_cancelled(&self) -> bool {
51        self.0.load(Ordering::Acquire)
52    }
53
54    fn check(&self) -> Result<()> {
55        if self.is_cancelled() {
56            Err(SystemIntegrationError::Cancelled)
57        } else {
58            Ok(())
59        }
60    }
61}
62
63/// One newer, target-specific artifact selected from signed updater metadata.
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub struct AvailableUpdate {
66    pub version: String,
67    pub current_version: String,
68    pub target: String,
69    pub url: String,
70    pub signature: String,
71    pub notes: Option<String>,
72    pub published_at: Option<String>,
73}
74
75/// Bounded milestones emitted by download, verification, and installation operations.
76#[derive(Clone, Debug, Eq, PartialEq)]
77pub enum UpdateProgress {
78    DownloadStarted {
79        total_bytes: Option<u64>,
80    },
81    Downloaded {
82        chunk_bytes: usize,
83        downloaded_bytes: u64,
84        total_bytes: Option<u64>,
85    },
86    DownloadFinished {
87        downloaded_bytes: u64,
88    },
89    VerificationStarted,
90    VerificationFinished,
91    Staged {
92        path: PathBuf,
93    },
94    InstallStarted {
95        artifact: PathBuf,
96    },
97    InstallFinished {
98        installation: InstalledUpdate,
99    },
100}
101
102/// Native Windows installer presentation policy.
103#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
104pub enum WindowsUpdateInstallMode {
105    BasicUi,
106    Quiet,
107    #[default]
108    Passive,
109}
110
111impl WindowsUpdateInstallMode {
112    pub const fn msi_arguments(self) -> &'static [&'static str] {
113        match self {
114            Self::BasicUi => &["/qb+"],
115            Self::Quiet => &["/quiet"],
116            Self::Passive => &["/passive"],
117        }
118    }
119
120    pub const fn executable_arguments(self) -> &'static [&'static str] {
121        match self {
122            Self::BasicUi => &[],
123            Self::Quiet => &["/S", "/R"],
124            Self::Passive => &["/P", "/R"],
125        }
126    }
127}
128
129/// Installation overrides for a verified staged artifact.
130#[derive(Clone, Debug, Eq, PartialEq)]
131pub struct UpdateInstallOptions {
132    target_executable: Option<PathBuf>,
133    retain_backup: bool,
134    windows_mode: WindowsUpdateInstallMode,
135    installer_arguments: Vec<OsString>,
136}
137
138impl Default for UpdateInstallOptions {
139    fn default() -> Self {
140        Self {
141            target_executable: None,
142            retain_backup: false,
143            windows_mode: WindowsUpdateInstallMode::Passive,
144            installer_arguments: Vec::new(),
145        }
146    }
147}
148
149impl UpdateInstallOptions {
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    /// Override the running executable used to locate the application bundle or replacement file.
155    pub fn target_executable(mut self, executable: impl Into<PathBuf>) -> Self {
156        self.target_executable = Some(executable.into());
157        self
158    }
159
160    /// Keep the previous bundle or executable beside the installed version for caller cleanup.
161    pub fn retain_backup(mut self, retain: bool) -> Self {
162        self.retain_backup = retain;
163        self
164    }
165
166    pub fn windows_mode(mut self, mode: WindowsUpdateInstallMode) -> Self {
167        self.windows_mode = mode;
168        self
169    }
170
171    /// Append native installer arguments without invoking a shell.
172    pub fn installer_arguments<I, S>(mut self, arguments: I) -> Self
173    where
174        I: IntoIterator<Item = S>,
175        S: Into<OsString>,
176    {
177        self.installer_arguments
178            .extend(arguments.into_iter().map(Into::into));
179        self
180    }
181
182    pub fn executable_override(&self) -> Option<&Path> {
183        self.target_executable.as_deref()
184    }
185
186    pub const fn retains_backup(&self) -> bool {
187        self.retain_backup
188    }
189
190    pub const fn windows_install_mode(&self) -> WindowsUpdateInstallMode {
191        self.windows_mode
192    }
193
194    pub fn extra_installer_arguments(&self) -> &[OsString] {
195        &self.installer_arguments
196    }
197}
198
199#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
200pub enum UpdateInstallDisposition {
201    Applied,
202    InstallerLaunched,
203}
204
205/// Result of applying or launching one re-verified staged update.
206#[derive(Clone, Debug, Eq, PartialEq)]
207pub struct InstalledUpdate {
208    version: String,
209    disposition: UpdateInstallDisposition,
210    installed_path: PathBuf,
211    backup_path: Option<PathBuf>,
212    installer_process_id: Option<u32>,
213}
214
215impl InstalledUpdate {
216    pub fn version(&self) -> &str {
217        &self.version
218    }
219
220    pub const fn disposition(&self) -> UpdateInstallDisposition {
221        self.disposition
222    }
223
224    pub fn installed_path(&self) -> &Path {
225        &self.installed_path
226    }
227
228    pub fn backup_path(&self) -> Option<&Path> {
229        self.backup_path.as_deref()
230    }
231
232    pub const fn installer_process_id(&self) -> Option<u32> {
233        self.installer_process_id
234    }
235
236    pub const fn requires_application_exit(&self) -> bool {
237        true
238    }
239
240    pub const fn relaunch_recommended(&self) -> bool {
241        matches!(self.disposition, UpdateInstallDisposition::Applied)
242    }
243}
244
245/// Checks Tauri-compatible updater JSON and stages only successfully verified artifacts.
246#[derive(Clone, Debug)]
247pub struct UpdateClient {
248    current_version: Version,
249    current_version_text: String,
250    public_key: String,
251    target: String,
252    maximum_download_bytes: u64,
253}
254
255impl UpdateClient {
256    pub fn new(current_version: &str, public_key: impl Into<String>) -> Result<Self> {
257        let version_text = current_version.trim_start_matches('v');
258        let current_version = Version::parse(version_text).map_err(|error| {
259            SystemIntegrationError::InvalidUpdate(Arc::from(format!(
260                "invalid current semantic version: {error}"
261            )))
262        })?;
263        let public_key = public_key.into();
264        parse_public_key(&public_key)?;
265        Ok(Self {
266            current_version,
267            current_version_text: version_text.to_owned(),
268            public_key,
269            target: default_update_target(),
270            maximum_download_bytes: DEFAULT_MAX_UPDATE_BYTES,
271        })
272    }
273
274    pub fn target(mut self, target: impl Into<String>) -> Result<Self> {
275        let target = target.into();
276        if target.is_empty()
277            || target.len() > 256
278            || target.contains('\0')
279            || target.contains(['\r', '\n'])
280        {
281            return Err(invalid(
282                "the update target must be nonempty, single-line, and at most 256 UTF-8 bytes",
283            ));
284        }
285        self.target = target;
286        Ok(self)
287    }
288
289    pub fn maximum_download_bytes(mut self, maximum: u64) -> Result<Self> {
290        if maximum == 0 || maximum > DEFAULT_MAX_UPDATE_BYTES {
291            return Err(invalid(
292                "the update download limit must be between 1 byte and 2 GiB",
293            ));
294        }
295        self.maximum_download_bytes = maximum;
296        Ok(self)
297    }
298
299    /// Fetch bounded update metadata and return `None` when the remote version is not newer.
300    pub fn check(&self, endpoint: &str) -> Result<Option<AvailableUpdate>> {
301        self.check_with_cancellation(endpoint, &UpdateCancellation::new())
302    }
303
304    /// Fetch update metadata while cooperatively observing cancellation between I/O reads.
305    pub fn check_with_cancellation(
306        &self,
307        endpoint: &str,
308        cancellation: &UpdateCancellation,
309    ) -> Result<Option<AvailableUpdate>> {
310        cancellation.check()?;
311        validate_https_url(endpoint, "update endpoint")?;
312        let endpoint = expand_endpoint(endpoint, &self.target, &self.current_version_text);
313        let agent = https_agent();
314        let mut response = agent
315            .get(&endpoint)
316            .call()
317            .map_err(|error| network(error.to_string()))?;
318        cancellation.check()?;
319        let mut bytes = Vec::with_capacity(16 * 1024);
320        CancellableReader::new(
321            response
322                .body_mut()
323                .as_reader()
324                .take(MAX_UPDATE_MANIFEST_BYTES as u64 + 1),
325            cancellation,
326        )
327        .read_to_end(&mut bytes)
328        .map_err(|error| cancelled_or(cancellation, || network(error.to_string())))?;
329        cancellation.check()?;
330        if bytes.len() > MAX_UPDATE_MANIFEST_BYTES {
331            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
332                "the update manifest exceeds 1 MiB",
333            )));
334        }
335        self.parse_manifest(&bytes)
336    }
337
338    /// Parse already-fetched metadata using the same bounded, target-aware rules as [`Self::check`].
339    pub fn parse_manifest(&self, bytes: &[u8]) -> Result<Option<AvailableUpdate>> {
340        if bytes.len() > MAX_UPDATE_MANIFEST_BYTES {
341            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
342                "the update manifest exceeds 1 MiB",
343            )));
344        }
345        let manifest: Manifest = serde_json::from_slice(bytes).map_err(|error| {
346            SystemIntegrationError::InvalidUpdate(Arc::from(format!(
347                "could not parse updater JSON: {error}"
348            )))
349        })?;
350        let version_text = manifest.version.trim_start_matches('v');
351        let remote = Version::parse(version_text).map_err(|error| {
352            SystemIntegrationError::InvalidUpdate(Arc::from(format!(
353                "invalid remote semantic version: {error}"
354            )))
355        })?;
356        if remote <= self.current_version {
357            return Ok(None);
358        }
359        let platform = match (manifest.url, manifest.signature) {
360            (Some(url), Some(signature)) => ManifestPlatform { url, signature },
361            (None, None) => manifest
362                .platforms
363                .get(&self.target)
364                .cloned()
365                .ok_or_else(|| {
366                    SystemIntegrationError::InvalidUpdate(Arc::from(format!(
367                        "the update manifest has no artifact for target {}",
368                        self.target
369                    )))
370                })?,
371            _ => {
372                return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
373                    "a dynamic update manifest requires both url and signature",
374                )));
375            }
376        };
377        validate_https_url(&platform.url, "update artifact URL")?;
378        validate_signature_metadata(&platform.signature)?;
379        Ok(Some(AvailableUpdate {
380            version: version_text.to_owned(),
381            current_version: self.current_version_text.clone(),
382            target: self.target.clone(),
383            url: platform.url,
384            signature: platform.signature,
385            notes: manifest.notes,
386            published_at: manifest.pub_date,
387        }))
388    }
389
390    /// Download, stream-verify, fsync, and atomically persist an update artifact.
391    pub fn download_and_stage(
392        &self,
393        update: &AvailableUpdate,
394        destination_directory: impl AsRef<Path>,
395    ) -> Result<PathBuf> {
396        self.download_and_stage_with_progress_and_cancellation(
397            update,
398            destination_directory,
399            |_| {},
400            &UpdateCancellation::new(),
401        )
402    }
403
404    /// Download and stage while reporting bounded byte progress on the calling thread.
405    pub fn download_and_stage_with_progress(
406        &self,
407        update: &AvailableUpdate,
408        destination_directory: impl AsRef<Path>,
409        on_progress: impl FnMut(UpdateProgress),
410    ) -> Result<PathBuf> {
411        self.download_and_stage_with_progress_and_cancellation(
412            update,
413            destination_directory,
414            on_progress,
415            &UpdateCancellation::new(),
416        )
417    }
418
419    /// Download and stage with progress plus cooperative cancellation between bounded chunks.
420    pub fn download_and_stage_with_progress_and_cancellation(
421        &self,
422        update: &AvailableUpdate,
423        destination_directory: impl AsRef<Path>,
424        mut on_progress: impl FnMut(UpdateProgress),
425        cancellation: &UpdateCancellation,
426    ) -> Result<PathBuf> {
427        cancellation.check()?;
428        self.validate_update(update)?;
429        let public_key = parse_public_key(&self.public_key)?;
430        let signature = parse_signature(&update.signature)?;
431        let mut verifier = public_key.verify_stream(&signature).map_err(|error| {
432            SystemIntegrationError::InvalidSignature(Arc::from(format!(
433                "streaming requires a modern prehashed Minisign signature: {error}"
434            )))
435        })?;
436        let directory = destination_directory.as_ref();
437        fs::create_dir_all(directory).map_err(io_error)?;
438        let mut temporary = tempfile::NamedTempFile::new_in(directory).map_err(io_error)?;
439        let agent = https_agent();
440        let mut response = agent
441            .get(&update.url)
442            .call()
443            .map_err(|error| network(error.to_string()))?;
444        cancellation.check()?;
445        let content_length = response
446            .headers()
447            .get("content-length")
448            .and_then(|value| value.to_str().ok())
449            .and_then(|value| value.parse::<u64>().ok());
450        if content_length.is_some_and(|length| length > self.maximum_download_bytes) {
451            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
452                "the update artifact exceeds the configured download limit",
453            )));
454        }
455        on_progress(UpdateProgress::DownloadStarted {
456            total_bytes: content_length,
457        });
458        let mut reader = response.body_mut().as_reader();
459        let mut buffer = [0_u8; 64 * 1024];
460        let mut total = 0_u64;
461        loop {
462            cancellation.check()?;
463            let read = reader.read(&mut buffer).map_err(io_error)?;
464            if read == 0 {
465                break;
466            }
467            total = total.saturating_add(read as u64);
468            if total > self.maximum_download_bytes {
469                return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
470                    "the update artifact exceeds the configured download limit",
471                )));
472            }
473            verifier.update(&buffer[..read]);
474            temporary.write_all(&buffer[..read]).map_err(io_error)?;
475            on_progress(UpdateProgress::Downloaded {
476                chunk_bytes: read,
477                downloaded_bytes: total,
478                total_bytes: content_length,
479            });
480        }
481        on_progress(UpdateProgress::DownloadFinished {
482            downloaded_bytes: total,
483        });
484        on_progress(UpdateProgress::VerificationStarted);
485        cancellation.check()?;
486        verifier.finalize().map_err(|error| {
487            SystemIntegrationError::InvalidSignature(Arc::from(error.to_string()))
488        })?;
489        on_progress(UpdateProgress::VerificationFinished);
490        cancellation.check()?;
491        temporary.as_file().sync_all().map_err(io_error)?;
492        let destination = directory.join(artifact_file_name(&update.url, &update.version));
493        cancellation.check()?;
494        temporary
495            .persist_noclobber(&destination)
496            .map_err(|error| io_error(error.error))?;
497        on_progress(UpdateProgress::Staged {
498            path: destination.clone(),
499        });
500        Ok(destination)
501    }
502
503    fn validate_update(&self, update: &AvailableUpdate) -> Result<()> {
504        if update.target != self.target {
505            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
506                "the update target does not match this client",
507            )));
508        }
509        if update.current_version != self.current_version_text {
510            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
511                "the update's current version does not match this client",
512            )));
513        }
514        let update_version =
515            Version::parse(update.version.trim_start_matches('v')).map_err(|error| {
516                SystemIntegrationError::InvalidUpdate(Arc::from(format!(
517                    "invalid update semantic version: {error}"
518                )))
519            })?;
520        if update_version <= self.current_version {
521            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
522                "the staged update must be newer than the current version",
523            )));
524        }
525        validate_https_url(&update.url, "update artifact URL")?;
526        validate_signature_metadata(&update.signature)
527    }
528
529    /// Verify an existing local artifact using the configured public key and bounded streaming.
530    pub fn verify_file(&self, path: impl AsRef<Path>, signature: &str) -> Result<()> {
531        self.verify_file_with_cancellation(path, signature, &UpdateCancellation::new())
532    }
533
534    pub fn verify_file_with_cancellation(
535        &self,
536        path: impl AsRef<Path>,
537        signature: &str,
538        cancellation: &UpdateCancellation,
539    ) -> Result<()> {
540        cancellation.check()?;
541        let metadata = fs::metadata(path.as_ref()).map_err(io_error)?;
542        if metadata.len() > self.maximum_download_bytes {
543            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
544                "the update artifact exceeds the configured download limit",
545            )));
546        }
547        let public_key = parse_public_key(&self.public_key)?;
548        let signature = parse_signature(signature)?;
549        let mut verifier = public_key.verify_stream(&signature).map_err(|error| {
550            SystemIntegrationError::InvalidSignature(Arc::from(format!(
551                "streaming requires a modern prehashed Minisign signature: {error}"
552            )))
553        })?;
554        let mut file = File::open(path.as_ref()).map_err(io_error)?;
555        let mut buffer = [0_u8; 64 * 1024];
556        loop {
557            cancellation.check()?;
558            let read = file.read(&mut buffer).map_err(io_error)?;
559            if read == 0 {
560                break;
561            }
562            verifier.update(&buffer[..read]);
563        }
564        cancellation.check()?;
565        verifier
566            .finalize()
567            .map_err(|error| SystemIntegrationError::InvalidSignature(Arc::from(error.to_string())))
568    }
569
570    /// Re-verify and install a staged artifact using the current platform's native strategy.
571    ///
572    /// macOS expects a gzip-compressed tar archive containing one `.app` bundle. Linux accepts a
573    /// raw executable or a gzip-compressed tar archive containing one AppImage. Windows launches
574    /// an `.exe` or `.msi` installer with the configured UI policy. The caller should request an
575    /// orderly application relaunch after an applied Unix update, or orderly exit after a Windows
576    /// installer is launched.
577    pub fn install_staged(
578        &self,
579        update: &AvailableUpdate,
580        artifact: impl AsRef<Path>,
581        options: UpdateInstallOptions,
582    ) -> Result<InstalledUpdate> {
583        self.install_staged_with_progress_and_cancellation(
584            update,
585            artifact,
586            options,
587            |_| {},
588            &UpdateCancellation::new(),
589        )
590    }
591
592    pub fn install_staged_with_progress(
593        &self,
594        update: &AvailableUpdate,
595        artifact: impl AsRef<Path>,
596        options: UpdateInstallOptions,
597        on_progress: impl FnMut(UpdateProgress),
598    ) -> Result<InstalledUpdate> {
599        self.install_staged_with_progress_and_cancellation(
600            update,
601            artifact,
602            options,
603            on_progress,
604            &UpdateCancellation::new(),
605        )
606    }
607
608    /// Re-verify and install while observing cancellation before every reversible phase.
609    pub fn install_staged_with_progress_and_cancellation(
610        &self,
611        update: &AvailableUpdate,
612        artifact: impl AsRef<Path>,
613        options: UpdateInstallOptions,
614        mut on_progress: impl FnMut(UpdateProgress),
615        cancellation: &UpdateCancellation,
616    ) -> Result<InstalledUpdate> {
617        cancellation.check()?;
618        self.validate_update(update)?;
619        validate_install_options(&options)?;
620        let artifact = artifact.as_ref();
621        let metadata = fs::metadata(artifact).map_err(io_error)?;
622        if !metadata.is_file() || metadata.len() > self.maximum_download_bytes {
623            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
624                "the staged update must be a regular file within the configured download limit",
625            )));
626        }
627        on_progress(UpdateProgress::VerificationStarted);
628        self.verify_file_with_cancellation(artifact, &update.signature, cancellation)?;
629        on_progress(UpdateProgress::VerificationFinished);
630        cancellation.check()?;
631        on_progress(UpdateProgress::InstallStarted {
632            artifact: artifact.to_path_buf(),
633        });
634        let installation =
635            install_current_application(artifact, &options, &update.version, cancellation)?;
636        on_progress(UpdateProgress::InstallFinished {
637            installation: installation.clone(),
638        });
639        Ok(installation)
640    }
641}
642
643fn validate_install_options(options: &UpdateInstallOptions) -> Result<()> {
644    if options.installer_arguments.len() > MAX_UPDATE_INSTALLER_ARGUMENTS {
645        return Err(invalid(format!(
646            "an update installer cannot receive more than {MAX_UPDATE_INSTALLER_ARGUMENTS} extra arguments"
647        )));
648    }
649    let mut total = 0_usize;
650    for argument in &options.installer_arguments {
651        let bytes = argument.as_os_str().as_encoded_bytes();
652        if bytes.contains(&0) {
653            return Err(invalid("update installer arguments must be NUL-free"));
654        }
655        total = total.saturating_add(bytes.len());
656        if total > MAX_UPDATE_INSTALLER_ARGUMENT_BYTES {
657            return Err(invalid(format!(
658                "update installer arguments cannot exceed {MAX_UPDATE_INSTALLER_ARGUMENT_BYTES} encoded bytes in aggregate"
659            )));
660        }
661    }
662    if let Some(executable) = &options.target_executable {
663        validate_install_path(executable, "the update target executable")?;
664    }
665    Ok(())
666}
667
668fn validate_install_path(path: &Path, name: &str) -> Result<()> {
669    let bytes = path.as_os_str().as_encoded_bytes();
670    if !path.is_absolute() || bytes.is_empty() || bytes.contains(&0) || bytes.len() > 32 * 1024 {
671        return Err(invalid(format!(
672            "{name} must be absolute, NUL-free, and at most 32768 encoded bytes"
673        )));
674    }
675    Ok(())
676}
677
678#[cfg(target_os = "macos")]
679fn install_current_application(
680    artifact: &Path,
681    options: &UpdateInstallOptions,
682    version: &str,
683    cancellation: &UpdateCancellation,
684) -> Result<InstalledUpdate> {
685    cancellation.check()?;
686    let executable = options
687        .target_executable
688        .clone()
689        .map_or_else(std::env::current_exe, Ok)
690        .map_err(io_error)?;
691    let bundle = macos_bundle_for_executable(&executable)?;
692    let parent = bundle
693        .parent()
694        .ok_or_else(|| invalid("the current macOS application bundle has no parent directory"))?;
695    let extraction = tempfile::Builder::new()
696        .prefix(".quickgui-update-")
697        .tempdir_in(parent)
698        .map_err(io_error)?;
699    let replacement = extract_macos_bundle_archive(artifact, extraction.path(), cancellation)?;
700    cancellation.check()?;
701    let backup =
702        replace_directory_atomically(&replacement, &bundle, options.retain_backup, cancellation)?;
703    Ok(InstalledUpdate {
704        version: version.to_owned(),
705        disposition: UpdateInstallDisposition::Applied,
706        installed_path: bundle,
707        backup_path: backup,
708        installer_process_id: None,
709    })
710}
711
712#[cfg(target_os = "linux")]
713fn install_current_application(
714    artifact: &Path,
715    options: &UpdateInstallOptions,
716    version: &str,
717    cancellation: &UpdateCancellation,
718) -> Result<InstalledUpdate> {
719    cancellation.check()?;
720    let target = match &options.target_executable {
721        Some(target) => target.clone(),
722        None => std::env::var_os("APPIMAGE")
723            .map(PathBuf::from)
724            .filter(|path| path.is_absolute())
725            .map_or_else(std::env::current_exe, Ok)
726            .map_err(io_error)?,
727    };
728    validate_install_path(&target, "the Linux update target")?;
729    let extraction;
730    let replacement = if is_gzip_file(artifact)? {
731        let parent = target
732            .parent()
733            .ok_or_else(|| invalid("the Linux update target has no parent directory"))?;
734        extraction = tempfile::Builder::new()
735            .prefix(".quickgui-update-")
736            .tempdir_in(parent)
737            .map_err(io_error)?;
738        extract_single_app_image(artifact, extraction.path(), cancellation)?
739    } else {
740        artifact.to_path_buf()
741    };
742    cancellation.check()?;
743    let backup =
744        replace_file_atomically(&replacement, &target, options.retain_backup, cancellation)?;
745    Ok(InstalledUpdate {
746        version: version.to_owned(),
747        disposition: UpdateInstallDisposition::Applied,
748        installed_path: target,
749        backup_path: backup,
750        installer_process_id: None,
751    })
752}
753
754#[cfg(target_os = "windows")]
755fn install_current_application(
756    artifact: &Path,
757    options: &UpdateInstallOptions,
758    version: &str,
759    cancellation: &UpdateCancellation,
760) -> Result<InstalledUpdate> {
761    cancellation.check()?;
762    let extension = artifact
763        .extension()
764        .and_then(OsStr::to_str)
765        .unwrap_or_default();
766    let mut command = if extension.eq_ignore_ascii_case("msi") {
767        let mut command = Command::new("msiexec.exe");
768        command.arg("/i").arg(artifact);
769        command.args(options.windows_mode.msi_arguments());
770        command
771    } else if extension.eq_ignore_ascii_case("exe") {
772        let mut command = Command::new(artifact);
773        command.args(options.windows_mode.executable_arguments());
774        command
775    } else {
776        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
777            "Windows updates must be staged as an .exe or .msi installer",
778        )));
779    };
780    cancellation.check()?;
781    let child = command
782        .args(&options.installer_arguments)
783        .stdin(Stdio::null())
784        .stdout(Stdio::null())
785        .stderr(Stdio::null())
786        .spawn()
787        .map_err(io_error)?;
788    Ok(InstalledUpdate {
789        version: version.to_owned(),
790        disposition: UpdateInstallDisposition::InstallerLaunched,
791        installed_path: artifact.to_path_buf(),
792        backup_path: None,
793        installer_process_id: Some(child.id()),
794    })
795}
796
797#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
798fn install_current_application(
799    _artifact: &Path,
800    _options: &UpdateInstallOptions,
801    _version: &str,
802    cancellation: &UpdateCancellation,
803) -> Result<InstalledUpdate> {
804    cancellation.check()?;
805    Err(SystemIntegrationError::Unsupported)
806}
807
808#[cfg(target_os = "macos")]
809fn macos_bundle_for_executable(executable: &Path) -> Result<PathBuf> {
810    if executable
811        .extension()
812        .is_some_and(|extension| extension == "app")
813    {
814        validate_install_path(executable, "the macOS application bundle")?;
815        return Ok(executable.to_path_buf());
816    }
817    let bundle = executable
818        .ancestors()
819        .find(|path| path.extension().is_some_and(|extension| extension == "app"))
820        .ok_or_else(|| {
821            SystemIntegrationError::InvalidUpdate(Arc::from(
822                "the running executable is not inside a macOS .app bundle",
823            ))
824        })?;
825    validate_install_path(bundle, "the macOS application bundle")?;
826    Ok(bundle.to_path_buf())
827}
828
829#[cfg(target_os = "macos")]
830fn extract_macos_bundle_archive(
831    archive: &Path,
832    directory: &Path,
833    cancellation: &UpdateCancellation,
834) -> Result<PathBuf> {
835    extract_single_archive_entry(
836        archive,
837        directory,
838        |root| root.extension().is_some_and(|extension| extension == "app"),
839        "a single top-level .app bundle",
840        cancellation,
841    )
842}
843
844#[cfg(target_os = "linux")]
845fn extract_single_app_image(
846    archive: &Path,
847    directory: &Path,
848    cancellation: &UpdateCancellation,
849) -> Result<PathBuf> {
850    extract_single_archive_entry(
851        archive,
852        directory,
853        |root| {
854            root.extension()
855                .and_then(OsStr::to_str)
856                .is_some_and(|extension| extension.eq_ignore_ascii_case("appimage"))
857        },
858        "a single top-level AppImage",
859        cancellation,
860    )
861}
862
863#[cfg(any(target_os = "macos", target_os = "linux", test))]
864fn extract_single_archive_entry(
865    archive_path: &Path,
866    directory: &Path,
867    accepts_root: impl Fn(&Path) -> bool,
868    expected: &str,
869    cancellation: &UpdateCancellation,
870) -> Result<PathBuf> {
871    use std::path::Component;
872
873    cancellation.check()?;
874    let file = File::open(archive_path).map_err(io_error)?;
875    let decoder = flate2::read::GzDecoder::new(CancellableReader::new(file, cancellation));
876    let mut archive = tar::Archive::new(decoder);
877    let mut root: Option<OsString> = None;
878    let mut entries = 0_usize;
879    let mut expanded = 0_u64;
880    for entry in archive
881        .entries()
882        .map_err(|error| cancelled_or(cancellation, || io_error(error)))?
883    {
884        cancellation.check()?;
885        let mut entry = entry.map_err(|error| cancelled_or(cancellation, || io_error(error)))?;
886        entries = entries.saturating_add(1);
887        if entries > MAX_UPDATE_ARCHIVE_ENTRIES {
888            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
889                "the update archive contains too many entries",
890            )));
891        }
892        expanded = expanded.saturating_add(
893            entry
894                .header()
895                .size()
896                .map_err(|error| cancelled_or(cancellation, || io_error(error)))?,
897        );
898        if expanded > DEFAULT_MAX_EXPANDED_UPDATE_BYTES {
899            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
900                "the expanded update archive exceeds 8 GiB",
901            )));
902        }
903        let path = entry
904            .path()
905            .map_err(|error| cancelled_or(cancellation, || io_error(error)))?;
906        let mut components = path
907            .components()
908            .filter(|component| !matches!(component, Component::CurDir));
909        let Some(Component::Normal(first)) = components.next() else {
910            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
911                "the update archive contains an unsafe path",
912            )));
913        };
914        if components.any(|component| !matches!(component, Component::Normal(_))) {
915            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
916                "the update archive contains an unsafe path",
917            )));
918        }
919        match &root {
920            Some(root) if root != first => {
921                return Err(SystemIntegrationError::InvalidUpdate(Arc::from(format!(
922                    "the update archive must contain {expected}"
923                ))));
924            }
925            None => root = Some(first.to_os_string()),
926            _ => {}
927        }
928        if let Some(link) = entry
929            .link_name()
930            .map_err(|error| cancelled_or(cancellation, || io_error(error)))?
931        {
932            validate_archive_link(&path, &link)?;
933        }
934        if !entry
935            .unpack_in(directory)
936            .map_err(|error| cancelled_or(cancellation, || io_error(error)))?
937        {
938            return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
939                "the update archive tried to write outside its extraction directory",
940            )));
941        }
942    }
943    cancellation.check()?;
944    let root = root.ok_or_else(|| {
945        SystemIntegrationError::InvalidUpdate(Arc::from("the update archive is empty"))
946    })?;
947    let extracted = directory.join(root);
948    if !accepts_root(&extracted) || !extracted.exists() {
949        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(format!(
950            "the update archive must contain {expected}"
951        ))));
952    }
953    Ok(extracted)
954}
955
956#[cfg(any(target_os = "macos", target_os = "linux", test))]
957fn validate_archive_link(entry: &Path, link: &Path) -> Result<()> {
958    use std::path::Component;
959
960    if link.is_absolute() {
961        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
962            "the update archive contains an absolute link",
963        )));
964    }
965    let combined = entry.parent().unwrap_or_else(|| Path::new("")).join(link);
966    let mut depth = 0_usize;
967    for component in combined.components() {
968        match component {
969            Component::CurDir => {}
970            Component::Normal(_) => depth = depth.saturating_add(1),
971            Component::ParentDir if depth > 1 => depth -= 1,
972            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
973                return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
974                    "the update archive contains a link outside its application root",
975                )));
976            }
977        }
978    }
979    Ok(())
980}
981
982#[cfg(target_os = "linux")]
983fn is_gzip_file(path: &Path) -> Result<bool> {
984    let mut file = File::open(path).map_err(io_error)?;
985    let mut magic = [0_u8; 2];
986    let read = file.read(&mut magic).map_err(io_error)?;
987    Ok(read == magic.len() && magic == [0x1f, 0x8b])
988}
989
990#[cfg(any(target_os = "linux", test))]
991fn replace_file_atomically(
992    source: &Path,
993    destination: &Path,
994    retain_backup: bool,
995    cancellation: &UpdateCancellation,
996) -> Result<Option<PathBuf>> {
997    cancellation.check()?;
998    validate_install_path(destination, "the update destination")?;
999    let metadata = fs::metadata(destination).map_err(io_error)?;
1000    if !metadata.is_file() {
1001        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
1002            "the update destination is not a regular file",
1003        )));
1004    }
1005    let parent = destination
1006        .parent()
1007        .ok_or_else(|| invalid("the update destination has no parent directory"))?;
1008    let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(io_error)?;
1009    let input = File::open(source).map_err(io_error)?;
1010    std::io::copy(
1011        &mut CancellableReader::new(input, cancellation),
1012        &mut temporary,
1013    )
1014    .map_err(|error| cancelled_or(cancellation, || io_error(error)))?;
1015    temporary
1016        .as_file()
1017        .set_permissions(metadata.permissions())
1018        .map_err(io_error)?;
1019    temporary.as_file().sync_all().map_err(io_error)?;
1020    cancellation.check()?;
1021    let backup = vacant_backup_path(destination)?;
1022    fs::rename(destination, &backup).map_err(io_error)?;
1023    if let Err(error) = temporary.persist_noclobber(destination) {
1024        return Err(rollback_replacement(&backup, destination, error.error));
1025    }
1026    sync_parent_directory(parent);
1027    Ok(cleanup_backup(backup, false, retain_backup))
1028}
1029
1030#[cfg(any(target_os = "macos", test))]
1031fn replace_directory_atomically(
1032    source: &Path,
1033    destination: &Path,
1034    retain_backup: bool,
1035    cancellation: &UpdateCancellation,
1036) -> Result<Option<PathBuf>> {
1037    cancellation.check()?;
1038    validate_install_path(destination, "the update destination")?;
1039    if !fs::metadata(destination).map_err(io_error)?.is_dir()
1040        || !fs::metadata(source).map_err(io_error)?.is_dir()
1041    {
1042        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
1043            "macOS update replacement paths must be application directories",
1044        )));
1045    }
1046    let parent = destination
1047        .parent()
1048        .ok_or_else(|| invalid("the update destination has no parent directory"))?;
1049    let backup = vacant_backup_path(destination)?;
1050    cancellation.check()?;
1051    fs::rename(destination, &backup).map_err(io_error)?;
1052    if let Err(error) = fs::rename(source, destination) {
1053        return Err(rollback_replacement(&backup, destination, error));
1054    }
1055    sync_parent_directory(parent);
1056    Ok(cleanup_backup(backup, true, retain_backup))
1057}
1058
1059#[cfg(any(target_os = "macos", target_os = "linux", test))]
1060fn vacant_backup_path(destination: &Path) -> Result<PathBuf> {
1061    let parent = destination
1062        .parent()
1063        .ok_or_else(|| invalid("the update destination has no parent directory"))?;
1064    let name = destination
1065        .file_name()
1066        .ok_or_else(|| invalid("the update destination has no file name"))?;
1067    for nonce in 0..1_024_u16 {
1068        let mut candidate = name.to_os_string();
1069        candidate.push(format!(".quickgui-backup-{}-{nonce}", std::process::id()));
1070        let candidate = parent.join(candidate);
1071        if !candidate.exists() {
1072            return Ok(candidate);
1073        }
1074    }
1075    Err(SystemIntegrationError::Platform(Arc::from(
1076        "could not reserve an update backup path",
1077    )))
1078}
1079
1080#[cfg(any(target_os = "macos", target_os = "linux", test))]
1081fn cleanup_backup(path: PathBuf, directory: bool, retain: bool) -> Option<PathBuf> {
1082    if retain {
1083        return Some(path);
1084    }
1085    let result = if directory {
1086        fs::remove_dir_all(&path)
1087    } else {
1088        fs::remove_file(&path)
1089    };
1090    result.err().map(|_| path)
1091}
1092
1093#[cfg(any(target_os = "macos", target_os = "linux", test))]
1094fn rollback_replacement(
1095    backup: &Path,
1096    destination: &Path,
1097    replacement_error: std::io::Error,
1098) -> SystemIntegrationError {
1099    match fs::rename(backup, destination) {
1100        Ok(()) => {
1101            if let Some(parent) = destination.parent() {
1102                sync_parent_directory(parent);
1103            }
1104            io_error(replacement_error)
1105        }
1106        Err(rollback_error) => SystemIntegrationError::Platform(Arc::from(format!(
1107            "update replacement failed ({replacement_error}); restoring '{}' to '{}' also failed ({rollback_error}); the previous application may remain at the backup path",
1108            backup.display(),
1109            destination.display(),
1110        ))),
1111    }
1112}
1113
1114#[cfg(any(target_os = "macos", target_os = "linux"))]
1115fn sync_parent_directory(parent: &Path) {
1116    if let Ok(directory) = File::open(parent) {
1117        let _ = directory.sync_all();
1118    }
1119}
1120
1121#[cfg(all(test, not(any(target_os = "macos", target_os = "linux"))))]
1122fn sync_parent_directory(_parent: &Path) {}
1123
1124#[derive(Deserialize)]
1125struct Manifest {
1126    version: String,
1127    #[serde(default)]
1128    notes: Option<String>,
1129    #[serde(default)]
1130    pub_date: Option<String>,
1131    #[serde(default)]
1132    url: Option<String>,
1133    #[serde(default)]
1134    signature: Option<String>,
1135    #[serde(default)]
1136    platforms: HashMap<String, ManifestPlatform>,
1137}
1138
1139#[derive(Clone, Deserialize)]
1140struct ManifestPlatform {
1141    url: String,
1142    signature: String,
1143}
1144
1145pub fn default_update_target() -> String {
1146    let system = match std::env::consts::OS {
1147        "macos" => "darwin",
1148        "windows" => "windows",
1149        "linux" => "linux",
1150        other => other,
1151    };
1152    format!("{system}-{}", std::env::consts::ARCH)
1153}
1154
1155fn expand_endpoint(endpoint: &str, target: &str, current_version: &str) -> String {
1156    let (system, architecture) = target.split_once('-').unwrap_or((target, target));
1157    endpoint
1158        .replace("{{target}}", system)
1159        .replace("{{arch}}", architecture)
1160        .replace("{{current_version}}", current_version)
1161}
1162
1163fn parse_public_key(value: &str) -> Result<PublicKey> {
1164    let decoded = decode_wrapped_text(value);
1165    PublicKey::decode(&decoded)
1166        .or_else(|_| PublicKey::from_base64(&decoded))
1167        .map_err(|error| {
1168            SystemIntegrationError::InvalidSignature(Arc::from(format!(
1169                "invalid Minisign public key: {error}"
1170            )))
1171        })
1172}
1173
1174fn parse_signature(value: &str) -> Result<Signature> {
1175    validate_signature_metadata(value)?;
1176    let decoded = decode_wrapped_text(value);
1177    Signature::decode(&decoded).map_err(|error| {
1178        SystemIntegrationError::InvalidSignature(Arc::from(format!(
1179            "invalid Minisign signature: {error}"
1180        )))
1181    })
1182}
1183
1184fn validate_signature_metadata(value: &str) -> Result<()> {
1185    if value.is_empty() || value.len() > MAX_UPDATE_SIGNATURE_BYTES || value.contains('\0') {
1186        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(
1187            "the update signature must be nonempty, NUL-free, and at most 64 KiB",
1188        )));
1189    }
1190    Ok(())
1191}
1192
1193fn decode_wrapped_text(value: &str) -> String {
1194    if value.contains('\n') {
1195        return value.to_owned();
1196    }
1197    base64::engine::general_purpose::STANDARD
1198        .decode(value)
1199        .ok()
1200        .and_then(|bytes| String::from_utf8(bytes).ok())
1201        .filter(|decoded| decoded.contains('\n'))
1202        .unwrap_or_else(|| value.to_owned())
1203}
1204
1205fn validate_https_url(value: &str, name: &str) -> Result<()> {
1206    if value.len() > 16 * 1024 || value.contains('\0') || !value.starts_with("https://") {
1207        return Err(SystemIntegrationError::InvalidUpdate(Arc::from(format!(
1208            "{name} must be a bounded HTTPS URL"
1209        ))));
1210    }
1211    Ok(())
1212}
1213
1214fn https_agent() -> ureq::Agent {
1215    let config = ureq::Agent::config_builder().https_only(true).build();
1216    ureq::Agent::new_with_config(config)
1217}
1218
1219fn artifact_file_name(url: &str, version: &str) -> String {
1220    let candidate = url
1221        .split('?')
1222        .next()
1223        .and_then(|value| value.rsplit('/').next())
1224        .filter(|value| {
1225            !value.is_empty()
1226                && value.len() <= 255
1227                && value
1228                    .bytes()
1229                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
1230        });
1231    candidate
1232        .map(str::to_owned)
1233        .unwrap_or_else(|| format!("quickgui-update-{version}.bin"))
1234}
1235
1236fn network(error: impl Into<Arc<str>>) -> SystemIntegrationError {
1237    SystemIntegrationError::Network(error.into())
1238}
1239
1240fn cancelled_or(
1241    cancellation: &UpdateCancellation,
1242    fallback: impl FnOnce() -> SystemIntegrationError,
1243) -> SystemIntegrationError {
1244    if cancellation.is_cancelled() {
1245        SystemIntegrationError::Cancelled
1246    } else {
1247        fallback()
1248    }
1249}
1250
1251struct CancellableReader<'a, R> {
1252    inner: R,
1253    cancellation: &'a UpdateCancellation,
1254}
1255
1256impl<'a, R> CancellableReader<'a, R> {
1257    fn new(inner: R, cancellation: &'a UpdateCancellation) -> Self {
1258        Self {
1259            inner,
1260            cancellation,
1261        }
1262    }
1263}
1264
1265impl<R: Read> Read for CancellableReader<'_, R> {
1266    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
1267        if self.cancellation.is_cancelled() {
1268            return Err(std::io::Error::new(
1269                std::io::ErrorKind::Interrupted,
1270                "update operation cancelled",
1271            ));
1272        }
1273        self.inner.read(buffer)
1274    }
1275}
1276
1277fn io_error(error: impl ToString) -> SystemIntegrationError {
1278    SystemIntegrationError::Platform(Arc::from(error.to_string()))
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284
1285    const KEY: &str = "RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3";
1286
1287    #[test]
1288    fn selects_newer_target_artifact() {
1289        let client = UpdateClient::new("1.0.0", KEY)
1290            .unwrap()
1291            .target("darwin-aarch64")
1292            .unwrap();
1293        let json = serde_json::json!({
1294            "version": "1.1.0",
1295            "platforms": {
1296                "darwin-aarch64": {
1297                    "url": "https://example.com/app.tar.gz",
1298                    "signature": "signed-metadata-is-verified-when-staged",
1299                }
1300            }
1301        });
1302        let update = client
1303            .parse_manifest(json.to_string().as_bytes())
1304            .unwrap()
1305            .unwrap();
1306        assert_eq!(update.version, "1.1.0");
1307    }
1308
1309    #[test]
1310    fn rejects_missing_signature_metadata() {
1311        let client = UpdateClient::new("1.0.0", KEY).unwrap();
1312        let json = br#"{"version":"1.1.0","url":"https://example.com/update","signature":""}"#;
1313        assert!(client.parse_manifest(json).is_err());
1314    }
1315
1316    #[test]
1317    fn ignores_same_or_older_versions() {
1318        let client = UpdateClient::new("1.2.0", KEY).unwrap();
1319        let json = br#"{"version":"1.2.0","url":"https://example.com/update","signature":"bad"}"#;
1320        assert!(client.parse_manifest(json).unwrap().is_none());
1321    }
1322
1323    #[test]
1324    fn sanitizes_artifact_file_names() {
1325        assert_eq!(
1326            artifact_file_name("https://example.com/App.tar.gz?token=x", "1.0.0"),
1327            "App.tar.gz"
1328        );
1329        assert_eq!(
1330            artifact_file_name("https://example.com/%2e%2e", "1.0.0"),
1331            "quickgui-update-1.0.0.bin"
1332        );
1333    }
1334
1335    #[test]
1336    fn rejects_staging_metadata_from_another_check() {
1337        let client = UpdateClient::new("1.0.0", KEY).unwrap();
1338        let directory = tempfile::tempdir().unwrap();
1339        let mut update = AvailableUpdate {
1340            version: "1.1.0".to_owned(),
1341            current_version: "0.9.0".to_owned(),
1342            target: client.target.clone(),
1343            url: "https://example.com/update".to_owned(),
1344            signature: "not-reached".to_owned(),
1345            notes: None,
1346            published_at: None,
1347        };
1348        assert!(
1349            client
1350                .download_and_stage(&update, directory.path())
1351                .is_err()
1352        );
1353
1354        update.current_version = "1.0.0".to_owned();
1355        update.version = "1.0.0".to_owned();
1356        assert!(
1357            client
1358                .download_and_stage(&update, directory.path())
1359                .is_err()
1360        );
1361    }
1362
1363    #[test]
1364    fn https_agent_rejects_downgrade_redirects() {
1365        assert!(https_agent().config().https_only());
1366    }
1367
1368    #[test]
1369    fn cancellation_is_cloneable_and_wins_before_updater_io_or_mutation() {
1370        let cancellation = UpdateCancellation::new();
1371        let observer = cancellation.clone();
1372        cancellation.cancel();
1373        assert!(observer.is_cancelled());
1374
1375        let client = UpdateClient::new("1.0.0", KEY).unwrap();
1376        assert_eq!(
1377            client.verify_file_with_cancellation(
1378                "/path/that/must/not/be-opened",
1379                "not-parsed",
1380                &observer,
1381            ),
1382            Err(SystemIntegrationError::Cancelled)
1383        );
1384
1385        let extraction = tempfile::tempdir().unwrap();
1386        assert_eq!(
1387            extract_single_archive_entry(
1388                Path::new("/path/that/must/not/be-opened"),
1389                extraction.path(),
1390                |_| true,
1391                "one root",
1392                &observer,
1393            ),
1394            Err(SystemIntegrationError::Cancelled)
1395        );
1396        assert!(extraction.path().read_dir().unwrap().next().is_none());
1397    }
1398
1399    #[test]
1400    fn install_options_bound_native_arguments_before_spawning() {
1401        let arguments = (0..=MAX_UPDATE_INSTALLER_ARGUMENTS).map(|_| OsString::from("argument"));
1402        let options = UpdateInstallOptions::new().installer_arguments(arguments);
1403        assert!(validate_install_options(&options).is_err());
1404        assert_eq!(
1405            WindowsUpdateInstallMode::Passive.msi_arguments(),
1406            ["/passive"]
1407        );
1408        assert_eq!(
1409            WindowsUpdateInstallMode::Quiet.executable_arguments(),
1410            ["/S", "/R"]
1411        );
1412    }
1413
1414    #[test]
1415    fn archive_extraction_requires_one_confined_application_root() {
1416        let directory = tempfile::tempdir().unwrap();
1417        let archive = directory.path().join("Demo.tar.gz");
1418        write_test_archive(&archive, &[("Demo.app/Contents/MacOS/Demo", b"binary")]);
1419        let extraction = tempfile::tempdir().unwrap();
1420        let bundle = extract_single_archive_entry(
1421            &archive,
1422            extraction.path(),
1423            |root| root.extension().is_some_and(|extension| extension == "app"),
1424            "a single top-level .app bundle",
1425            &UpdateCancellation::new(),
1426        )
1427        .unwrap();
1428        assert_eq!(bundle.file_name().unwrap(), "Demo.app");
1429        assert_eq!(
1430            fs::read(bundle.join("Contents/MacOS/Demo")).unwrap(),
1431            b"binary"
1432        );
1433
1434        let invalid = directory.path().join("Multiple.tar.gz");
1435        write_test_archive(
1436            &invalid,
1437            &[
1438                ("First.app/Contents/first", b"first"),
1439                ("Second.app/Contents/second", b"second"),
1440            ],
1441        );
1442        assert!(
1443            extract_single_archive_entry(
1444                &invalid,
1445                tempfile::tempdir().unwrap().path(),
1446                |_| true,
1447                "one root",
1448                &UpdateCancellation::new(),
1449            )
1450            .is_err()
1451        );
1452    }
1453
1454    #[test]
1455    fn file_replacement_is_rollback_capable_and_can_retain_its_backup() {
1456        let directory = tempfile::tempdir().unwrap();
1457        let destination = directory.path().join("application");
1458        let source = directory.path().join("update");
1459        fs::write(&destination, b"old").unwrap();
1460        fs::write(&source, b"new").unwrap();
1461
1462        let backup =
1463            replace_file_atomically(&source, &destination, true, &UpdateCancellation::new())
1464                .unwrap()
1465                .unwrap();
1466        assert_eq!(fs::read(&destination).unwrap(), b"new");
1467        assert_eq!(fs::read(backup).unwrap(), b"old");
1468    }
1469
1470    #[test]
1471    fn rollback_failure_preserves_the_backup_location_in_the_error() {
1472        let directory = tempfile::tempdir().unwrap();
1473        let backup = directory.path().join("missing-backup");
1474        let destination = directory.path().join("application");
1475        let error = rollback_replacement(
1476            &backup,
1477            &destination,
1478            std::io::Error::other("replacement failed"),
1479        );
1480
1481        let SystemIntegrationError::Platform(message) = error else {
1482            panic!("rollback failure should be a platform error");
1483        };
1484        assert!(message.contains("replacement failed"));
1485        assert!(message.contains(backup.to_string_lossy().as_ref()));
1486        assert!(message.contains(destination.to_string_lossy().as_ref()));
1487    }
1488
1489    fn write_test_archive(path: &Path, entries: &[(&str, &[u8])]) {
1490        let file = File::create(path).unwrap();
1491        let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
1492        let mut archive = tar::Builder::new(encoder);
1493        for (path, bytes) in entries {
1494            let mut header = tar::Header::new_gnu();
1495            header.set_mode(0o755);
1496            header.set_size(bytes.len() as u64);
1497            header.set_cksum();
1498            archive
1499                .append_data(&mut header, path, &mut &bytes[..])
1500                .unwrap();
1501        }
1502        archive.into_inner().unwrap().finish().unwrap();
1503    }
1504}