Skip to main content

jubarte_cli/
update.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! `jubarte self-update`: replace this binary with a GitHub release when the
6//! user runs `jubarte self-update` (docs/SELF_UPDATE.md).
7//!
8//! The release lookup, SHA-256 check against `SHA256SUMS.txt`, archive
9//! extraction and binary swap are the
10//! [`self_update`](https://docs.rs/self_update) crate's; the zipsign
11//! signature check is [`verify_signature`](crate::update::verify_signature)
12//! (`zipsign.rs`), which `self_update`
13//! runs on the downloaded archive before extracting it. This module builds
14//! the call the binary makes: it picks the release archive for this platform
15//! (`asset_target`), decides whether the target is newer
16//! (`plan`) and refuses to ask on a non-interactive stdin
17//! (`preflight`). The signature rule lives in `signature_required`,
18//! split out so it is unit-tested without I/O.
19//!
20//! Entry points: `run` for the command itself, `plan` / `step` /
21//! `preflight` / `signature_required` for the decisions.
22
23use std::io::{BufRead, IsTerminal, Write};
24
25use self_update::backends::github;
26use self_update::version::cmp_versions;
27
28mod zipsign;
29pub use zipsign::{ReleaseKey, verify_signature};
30
31const REPO_OWNER: &str = "jandira-tech";
32const REPO_NAME: &str = "jubarte";
33const SUMS_ASSET: &str = "SHA256SUMS.txt";
34
35/// The ed25519 public keys trusted to sign release archives (zipsign), any
36/// one of which must have signed a release from [`FIRST_SIGNED_RELEASE`] on.
37///
38/// Empty until the owner commits a key, and with no key the updater checks
39/// `SHA256SUMS.txt` alone, as before. To trust a key, commit the 32-byte file
40/// `zipsign gen-key` writes and list it here:
41///
42/// ```text
43/// const RELEASE_KEYS: &[ReleaseKey] =
44///     &[*include_bytes!("../../../keys/release-signing.pub")];
45/// ```
46///
47/// A file that is not exactly 32 bytes fails the build. Set
48/// [`FIRST_SIGNED_RELEASE`] in the same commit; docs/SELF_UPDATE.md has the
49/// steps, including key rotation.
50const RELEASE_KEYS: &[ReleaseKey] = &[];
51
52/// The first release whose archives `release.yml` signed, without a leading
53/// `v` (`Some("0.11.0")`). `None` until [`RELEASE_KEYS`] holds a key.
54const FIRST_SIGNED_RELEASE: Option<&str> = None;
55
56/// Bytes `jubarte self-update` will download, or inflate from the one
57/// expected member of a release zip, before it refuses and leaves the
58/// installed binary in place.
59///
60/// Published archives are about 18 MiB (`v0.17.0`). This is several times
61/// that size. The tar.gz member's own inflation cap is a separate check.
62const UPDATE_ARCHIVE_BYTE_BUDGET: u64 = 128 * 1024 * 1024;
63
64/// The flags `jubarte self-update` accepts, resolved from the CLI before
65/// [`run`] sees them.
66#[derive(Clone, Debug, Default, PartialEq, Eq)]
67pub struct Options {
68    /// Print the installed and the latest version and install nothing
69    /// (`--check`).
70    pub check: bool,
71    /// Install without the interactive prompt (`--yes`).
72    pub yes: bool,
73    /// Install this release (`0.10.0` or `v0.10.0`; `--version`). A
74    /// request may downgrade; the installed version itself is up to date
75    /// and is not installed again.
76    pub version: Option<String>,
77}
78
79/// The decision [`plan`] returns, once the target release is known.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub enum Plan {
82    /// The installed version is the target (or already newer, when no
83    /// `--version` was asked for): nothing to do.
84    UpToDate {
85        /// The installed version.
86        current: String,
87    },
88    /// Replace the installed version with `to`.
89    Install {
90        /// The installed version.
91        from: String,
92        /// The release to install.
93        to: String,
94    },
95}
96
97/// The release archive suffix this binary will look up (`macos-aarch64`,
98/// `linux-x86_64`, `linux-musl-x86_64`, …), matching the names
99/// `release.yml` publishes. `None`
100/// for an OS / arch pair no archive is built for.
101#[must_use]
102pub fn asset_target() -> Option<&'static str> {
103    asset_target_for(
104        std::env::consts::OS,
105        std::env::consts::ARCH,
106        cfg!(target_env = "musl"),
107    )
108}
109
110/// `musl` picks the static archive: a musl build must not replace itself
111/// with the glibc one, which needs a loader Alpine lacks. No archive name
112/// holds another, because `self_update` matches assets by substring.
113fn asset_target_for(os: &str, arch: &str, musl: bool) -> Option<&'static str> {
114    Some(match (os, arch, musl) {
115        ("macos", "aarch64", false) => "macos-aarch64",
116        ("macos", "x86_64", false) => "macos-x86_64",
117        ("linux", "aarch64", false) => "linux-aarch64",
118        ("linux", "x86_64", false) => "linux-x86_64",
119        ("linux", "aarch64", true) => "linux-musl-aarch64",
120        ("linux", "x86_64", true) => "linux-musl-x86_64",
121        ("windows", "x86_64", false) => "windows-x86_64",
122        _ => return None,
123    })
124}
125
126/// Path of the binary inside the release archive, as `self_update` expects
127/// it (`{{ version }}` is filled in by the crate).
128fn bin_path_in_archive(target: &str) -> String {
129    format!(
130        "jubarte-{{{{ version }}}}-{target}/jubarte{}",
131        std::env::consts::EXE_SUFFIX
132    )
133}
134
135/// Refuse to start when the command would have to prompt and the stdin
136/// channel is not a terminal. None of the operation is touched, not even a
137/// network lookup.
138///
139/// # Errors
140///
141/// A message when neither [`Options::check`] nor [`Options::yes`] is set
142/// and `interactive` is `false`: passing `--check` or `--yes`, or being on a
143/// terminal, lets the run continue.
144pub fn preflight(opts: &Options, interactive: bool) -> Result<(), String> {
145    if opts.check || opts.yes || interactive {
146        Ok(())
147    } else {
148        Err("no terminal to confirm on; pass --yes to install or --check to only look".into())
149    }
150}
151
152/// Strip one leading `v` so `v0.10.0` and `0.10.0` name the same release.
153fn bare(version: &str) -> &str {
154    version.strip_prefix('v').unwrap_or(version)
155}
156
157/// Decide between staying and installing for a given installed version and
158/// the version `self_update` resolved on GitHub.
159///
160/// Without a requested version only a strictly newer release installs; a
161/// requested version installs whenever it differs from the installed one
162/// (downgrades included); the installed version is [`Plan::UpToDate`]. A leading `v` is stripped, so
163/// `v0.10.0` and `0.10.0` name the same release.
164///
165/// # Errors
166///
167/// A message when either version is not semver.
168pub fn plan(current: &str, target: &str, requested: bool) -> Result<Plan, String> {
169    let (current, target) = (bare(current), bare(target));
170    let order = cmp_versions(target, current).map_err(|e| format!("version {target}: {e}"))?;
171    let install = if requested {
172        order.is_ne()
173    } else {
174        order.is_gt()
175    };
176    Ok(if install {
177        Plan::Install {
178            from: current.to_string(),
179            to: target.to_string(),
180        }
181    } else {
182        Plan::UpToDate {
183            current: current.to_string(),
184        }
185    })
186}
187
188/// What `run` does once the release is resolved: report and stop, or ask
189/// (unless `--yes`) and install. Pure, so the "`--check` never installs"
190/// rule is unit-tested without the network.
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub enum Step {
193    /// Print `text` and stop. Nothing is downloaded or replaced.
194    Report {
195        /// The line to print.
196        text: String,
197    },
198    /// Confirm unless `opts.yes`, then replace the running binary.
199    Install {
200        /// The installed version.
201        from: String,
202        /// The release to install.
203        to: String,
204    },
205}
206
207/// `decision` is [`plan`]'s answer; `resolved` is the bare release version
208/// the lookup returned (the up-to-date message quotes it).
209#[must_use]
210pub fn step(opts: &Options, decision: &Plan, resolved: &str) -> Step {
211    match decision {
212        Plan::UpToDate { current } => Step::Report {
213            text: format!("jubarte {current} is up to date (latest release {resolved})."),
214        },
215        Plan::Install { from, to } if opts.check => Step::Report {
216            text: format!(
217                "jubarte {from} is installed; {to} is available. Run `jubarte self-update` to install it."
218            ),
219        },
220        Plan::Install { from, to } => Step::Install {
221            from: from.clone(),
222            to: to.clone(),
223        },
224    }
225}
226
227/// `jubarte self-update`. `Ok` means the run finished without error: the
228/// binary is replaced only when an install completes, and `--check`, an
229/// up-to-date release or a declined prompt leave it as it was. On failure
230/// the installed binary is unchanged. Writes progress to
231/// stdout, the prompt to stderr, and reads the answer from stdin.
232///
233/// The flow is: [`preflight`] → resolve the release for this platform
234/// ([`asset_target`]) → decide ([`plan`]) → act ([`step`]) → optional prompt
235/// → optional signature rule ([`signature_required`]) → `self_update`
236/// install. A prompt `y` / `Y` / `yes` confirms; anything else is "no".
237///
238/// # Errors
239///
240/// A message for one of:
241/// - the platform has no published archive ([`asset_target`] is `None`);
242/// - the [`preflight`] check refused the run;
243/// - the GitHub release lookup failed or returned no release;
244/// - the network or GitHub error inside the `self_update` installer;
245/// - the checksum download or verification did not match;
246/// - a signature was required but missing or did not verify against
247///   [`signature_required`];
248/// - the archive is over `UPDATE_ARCHIVE_BYTE_BUDGET`, lists the expected
249///   binary more than once, or inflates that binary past the budget;
250/// - the binary swap step failed.
251pub fn run(opts: &Options) -> Result<(), String> {
252    let interactive = std::io::stdin().is_terminal();
253    preflight(opts, interactive)?;
254    let target = asset_target().ok_or_else(|| {
255        format!(
256            "no release archive is built for {}-{}; build from source",
257            std::env::consts::OS,
258            std::env::consts::ARCH
259        )
260    })?;
261    let current = env!("CARGO_PKG_VERSION");
262
263    let mut builder = github::Update::configure();
264    builder
265        .repo_owner(REPO_OWNER)
266        .repo_name(REPO_NAME)
267        .bin_name("jubarte")
268        .target(target)
269        .current_version(current)
270        .bin_path_in_archive(bin_path_in_archive(target))
271        .verify_binary(extracted_binary_is_regular_file)
272        .checksum_from_asset(SUMS_ASSET)
273        .show_output(false)
274        .show_download_progress(interactive)
275        .no_confirm(true);
276    let lookup = builder.build().map_err(|e| e.to_string())?;
277    let release = match &opts.version {
278        Some(v) => lookup
279            .get_release_version(&format!("v{}", bare(v)))
280            .map(Some),
281        None => lookup
282            .get_latest_release()
283            .map(|releases| releases.into_vec().into_iter().next()),
284    }
285    .map_err(|e| format!("GitHub release lookup failed: {e}"))?
286    .ok_or("GitHub lists no release")?;
287
288    let decision = plan(current, release.version(), opts.version.is_some())?;
289    let (from, to) = match step(opts, &decision, bare(release.version())) {
290        Step::Report { text } => {
291            println!("{text}");
292            return Ok(());
293        }
294        Step::Install { from, to } => (from, to),
295    };
296    if !opts.yes && !confirm(&from, &to)? {
297        println!("Nothing changed.");
298        return Ok(());
299    }
300
301    let signed = signature_required(&to, FIRST_SIGNED_RELEASE, !RELEASE_KEYS.is_empty())?;
302    let member = resolved_bin_path(target, &to);
303    // Before extraction: cap the download and the inflated member, and refuse
304    // an archive that lists that member twice. The signature decision above
305    // is unchanged: this hook runs it only when that decision already said to.
306    builder.verify_archive(move |archive| {
307        confine_update_zip(archive, &member, UPDATE_ARCHIVE_BYTE_BUDGET)
308            .map_err(self_update::Error::archive_verification_rejected)?;
309        if signed {
310            verify_signature(archive, RELEASE_KEYS)
311                .map_err(self_update::Error::archive_verification_rejected)?;
312        }
313        Ok(())
314    });
315    if !signed && !RELEASE_KEYS.is_empty() {
316        eprintln!("note: {to} predates signed releases; only its SHA-256 is checked.");
317    }
318    let installer = builder
319        .release_tag(format!("v{to}"))
320        .build()
321        .map_err(|e| e.to_string())?;
322    installer
323        .update()
324        .map_err(|e| format!("update to {to} failed; the installed binary is unchanged: {e}"))?;
325    println!("jubarte {from} -> {to} installed.");
326    Ok(())
327}
328
329/// Whether installing `target_version` must pass a zipsign signature check.
330///
331/// True only when `keys_present` and the release sorts at or after
332/// `first_signed`: releases published before signing began carry no
333/// signature, so a `--version` downgrade to one of them is checked by its
334/// SHA-256 alone. A `v` prefix on either version is stripped before the
335/// comparison.
336///
337/// # Errors
338///
339/// A message when `keys_present` and `first_signed` are both set but either
340/// side is not semver.
341pub fn signature_required(
342    target_version: &str,
343    first_signed: Option<&str>,
344    keys_present: bool,
345) -> Result<bool, String> {
346    let Some(first) = first_signed.filter(|_| keys_present) else {
347        return Ok(false);
348    };
349    let (target, first) = (bare(target_version), bare(first));
350    let order = cmp_versions(target, first)
351        .map_err(|e| format!("version {target} against first signed release {first}: {e}"))?;
352    Ok(order.is_ge())
353}
354
355fn confirm(from: &str, to: &str) -> Result<bool, String> {
356    eprint!("Replace jubarte {from} with {to}? [y/N] ");
357    std::io::stderr().flush().map_err(|e| e.to_string())?;
358    let mut answer = String::new();
359    std::io::stdin()
360        .lock()
361        .read_line(&mut answer)
362        .map_err(|e| e.to_string())?;
363    Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes" | "YES"))
364}
365
366/// The `verify_binary` hook `run` registers (ZIP-16/#639): refuse the
367/// extracted binary when it is anything but a regular file. `self_update`
368/// already refuses a symlink *zip* entry in its single-file path, but its
369/// tar path delegates to `tar`'s `unpack_in`, which restores a symlink
370/// entry as a real link whose target is not confined to the staging
371/// directory — a crafted release archive could then install any path's
372/// contents as the new binary. `symlink_metadata`, not `metadata`, sees
373/// the entry itself rather than its target.
374fn extracted_binary_is_regular_file(path: &std::path::Path) -> self_update::Result<()> {
375    let metadata = std::fs::symlink_metadata(path).map_err(|e| {
376        self_update::Error::verification_rejected(format!(
377            "the extracted binary {} cannot be inspected: {e}",
378            path.display()
379        ))
380    })?;
381    if metadata.is_file() {
382        Ok(())
383    } else {
384        Err(self_update::Error::verification_rejected(format!(
385            "the extracted binary {} is not a regular file",
386            path.display()
387        )))
388    }
389}
390
391/// Path of the binary inside a release archive once `{{ version }}` is the
392/// release being installed. `self_update` fills that token itself; the
393/// pre-extract check has to use the same path.
394fn resolved_bin_path(target: &str, version: &str) -> String {
395    bin_path_in_archive(target).replace("{{ version }}", version)
396}
397
398/// Gate the downloaded release archive before `self_update` extracts it.
399///
400/// `run` registers this as the `verify_archive` hook, which runs after the
401/// checksum and before a byte of the archive is unpacked. `member` is the
402/// binary path inside the archive (`jubarte-<version>-<target>/jubarte` or
403/// `.exe`). A file larger than `budget` is refused. A zip whose expected
404/// member appears more than once, or whose expected member inflates past
405/// `budget`, is refused. A gzipped tar is refused when its expected member
406/// is a symlink or a hardlink, when that member's mode carries setuid,
407/// setgid or sticky bits, when any entry climbs out of the extract
408/// directory, or when the tar inflates past `budget`. Any other bytes are
409/// left alone once the download itself fits.
410fn confine_update_zip(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
411    let len = std::fs::metadata(archive)
412        .map_err(|e| {
413            format!(
414                "update archive {} cannot be inspected: {e}",
415                archive.display()
416            )
417        })?
418        .len();
419    if len > budget {
420        return Err(format!(
421            "update archive is {len} bytes, over the {budget}-byte download budget"
422        ));
423    }
424    let mut file = std::fs::File::open(archive)
425        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
426    // A zip is told by its end record, not by a leading `PK`: a zipsign
427    // signature sits before the zip and zip/self_update still read it
428    // (#2084 review). No end record and no `PK`: a gzip is the tar.gz the
429    // tar gate reads; anything else is not an archive this gate knows.
430    let Some(copies) = zip_member_copies(&mut file, len, member)? else {
431        if zip_magic(&mut file)? {
432            return Err("update archive has no zip end record".into());
433        }
434        if gzip_magic(&mut file)? {
435            return confine_update_tar(archive, member, budget);
436        }
437        return Ok(());
438    };
439    if copies > 1 {
440        return Err(format!("update archive lists {member} more than once"));
441    }
442    if copies == 0 {
443        return Err(format!("update archive has no member {member}"));
444    }
445    inflate_member_within_budget(archive, member, budget)
446}
447
448fn zip_magic(file: &mut std::fs::File) -> Result<bool, String> {
449    use std::io::{Read, Seek, SeekFrom};
450    file.seek(SeekFrom::Start(0))
451        .map_err(|e| format!("update archive cannot be rewound: {e}"))?;
452    let mut magic = [0u8; 2];
453    let read = file
454        .read(&mut magic)
455        .map_err(|e| format!("update archive cannot be read: {e}"))?;
456    Ok(read == 2 && magic == [0x50, 0x4b])
457}
458
459/// How many central-directory entries name `member`, or `None` when the
460/// file has no zip end record.
461///
462/// `zip`'s reader keeps one entry per name, so a repeated member is invisible
463/// there and the first copy would be the one installed. The count comes from
464/// the central directory itself. Each name is the one `zip` resolves (an
465/// adopted 0x7075 Unicode Path included), and a directory that a leading
466/// prefix moved past its recorded offset is found where `zip` finds it.
467fn zip_member_copies(
468    file: &mut std::fs::File,
469    len: u64,
470    member: &str,
471) -> Result<Option<u32>, String> {
472    const EOCD_LEN: u64 = 22;
473    const MAX_COMMENT: u64 = 65_535;
474    if len < EOCD_LEN {
475        return Ok(None);
476    }
477    let tail_len = len.min(EOCD_LEN.saturating_add(MAX_COMMENT));
478    let tail_at = len.saturating_sub(tail_len);
479    let tail_bytes = usize::try_from(tail_len)
480        .map_err(|_| "update archive is too large to inspect".to_string())?;
481    let mut tail = vec![0u8; tail_bytes];
482    read_exact_at(file, tail_at, &mut tail)?;
483    let Some(eocd) = find_eocd(&tail) else {
484        return Ok(None);
485    };
486    let entries = le_u16(&tail, eocd.saturating_add(10))?;
487    let cd_size = u64::from(le_u32(&tail, eocd.saturating_add(12))?);
488    let cd_offset = u64::from(le_u32(&tail, eocd.saturating_add(16))?);
489    if entries == u16::MAX || cd_size == u64::from(u32::MAX) || cd_offset == u64::from(u32::MAX) {
490        return Err("update archive uses ZIP64, which this check refuses".into());
491    }
492    // Bytes before the zip (a zipsign signature) shift the directory by
493    // the gap between where it ends and where the end record sits; zip
494    // reads it at the recorded offset first, then shifted.
495    let eocd_at = tail_at.saturating_add(eocd as u64);
496    let recorded_end = cd_offset
497        .checked_add(cd_size)
498        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
499    let shift = eocd_at
500        .checked_sub(recorded_end)
501        .ok_or_else(|| "update archive central directory runs past its end record".to_string())?;
502    let mut signature = [0u8; 4];
503    let at_recorded = cd_size == 0
504        || (read_exact_at(file, cd_offset, &mut signature).is_ok()
505            && signature == [0x50, 0x4b, 0x01, 0x02]);
506    let base = if at_recorded { 0 } else { shift };
507    let cd_start = cd_offset
508        .checked_add(base)
509        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
510    let cd_end = recorded_end
511        .checked_add(base)
512        .ok_or_else(|| "update archive central directory is out of range".to_string())?;
513    if cd_end > len {
514        return Err("update archive central directory runs past the file".into());
515    }
516    let mut at = cd_start;
517    let mut copies = 0u32;
518    let mut seen = 0u16;
519    let mut name_and_extra = Vec::new();
520    while at < cd_end {
521        let mut header = [0u8; 46];
522        read_exact_at(file, at, &mut header)?;
523        if header.get(..4) != Some(&[0x50, 0x4b, 0x01, 0x02]) {
524            return Err("update archive central directory is truncated".into());
525        }
526        let name_len = u64::from(le_u16(&header, 28)?);
527        let extra_len = u64::from(le_u16(&header, 30)?);
528        let comment_len = u64::from(le_u16(&header, 32)?);
529        let step = 46u64
530            .checked_add(name_len)
531            .and_then(|n| n.checked_add(extra_len))
532            .and_then(|n| n.checked_add(comment_len))
533            .ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
534        let next = at
535            .checked_add(step)
536            .ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
537        if next > cd_end {
538            return Err("update archive central directory entry runs past the directory".into());
539        }
540        let name_at = at
541            .checked_add(46)
542            .ok_or_else(|| "update archive member name is out of range".to_string())?;
543        let name_bytes = usize::try_from(name_len)
544            .map_err(|_| "update archive member name is too long".to_string())?;
545        let extra_bytes = usize::try_from(extra_len)
546            .map_err(|_| "update archive extra field is too long".to_string())?;
547        // One buffer for every entry: name then extra field, each at most
548        // 64 KiB, as the header records them.
549        name_and_extra.resize(name_bytes.saturating_add(extra_bytes), 0);
550        if !name_and_extra.is_empty() {
551            read_exact_at(file, name_at, &mut name_and_extra)?;
552        }
553        let (raw_name, extra) = name_and_extra.split_at(name_bytes);
554        let flags = le_u16(&header, 8)?;
555        let name = crate::admission::zip_entry_name_raw(raw_name, flags, extra)
556            .map_err(|e| format!("update archive member name cannot be read: {e}"))?;
557        if member_names_match(name.as_bytes(), member) {
558            copies = copies.saturating_add(1);
559        }
560        seen = seen
561            .checked_add(1)
562            .ok_or_else(|| "update archive has too many entries".to_string())?;
563        at = next;
564    }
565    if seen != entries {
566        return Err("update archive central directory does not match its end record".into());
567    }
568    Ok(Some(copies))
569}
570
571fn find_eocd(tail: &[u8]) -> Option<usize> {
572    let last = tail.len().checked_sub(22)?;
573    let mut at = last;
574    loop {
575        if tail.get(at..at.checked_add(4)?) == Some(&[0x50, 0x4b, 0x05, 0x06][..]) {
576            let comment = usize::from(le_u16(tail, at.saturating_add(20)).ok()?);
577            let end = at.checked_add(22)?.checked_add(comment)?;
578            if end == tail.len() {
579                return Some(at);
580            }
581        }
582        if at == 0 {
583            return None;
584        }
585        at = at.saturating_sub(1);
586    }
587}
588
589fn le_u16(bytes: &[u8], at: usize) -> Result<u16, String> {
590    let mut buf = [0u8; 2];
591    buf.copy_from_slice(
592        bytes
593            .get(
594                at..at
595                    .checked_add(2)
596                    .ok_or_else(|| "update archive field is out of range".to_string())?,
597            )
598            .ok_or_else(|| "update archive field is out of range".to_string())?,
599    );
600    Ok(u16::from_le_bytes(buf))
601}
602
603fn le_u32(bytes: &[u8], at: usize) -> Result<u32, String> {
604    let mut buf = [0u8; 4];
605    buf.copy_from_slice(
606        bytes
607            .get(
608                at..at
609                    .checked_add(4)
610                    .ok_or_else(|| "update archive field is out of range".to_string())?,
611            )
612            .ok_or_else(|| "update archive field is out of range".to_string())?,
613    );
614    Ok(u32::from_le_bytes(buf))
615}
616
617fn member_names_match(entry: &[u8], member: &str) -> bool {
618    let entry = entry.strip_prefix(b"./").unwrap_or(entry);
619    if entry.ends_with(b"/") {
620        return false;
621    }
622    let member = member.strip_prefix("./").unwrap_or(member).as_bytes();
623    entry.len() == member.len()
624        && entry
625            .iter()
626            .zip(member)
627            .all(|(got, want)| *got == *want || (*got == b'\\' && *want == b'/'))
628}
629
630fn read_exact_at(file: &mut std::fs::File, at: u64, buf: &mut [u8]) -> Result<(), String> {
631    use std::io::{Read, Seek, SeekFrom};
632    file.seek(SeekFrom::Start(at))
633        .map_err(|e| format!("update archive seek failed: {e}"))?;
634    file.read_exact(buf)
635        .map_err(|e| format!("update archive read failed: {e}"))
636}
637
638/// Count the bytes the expected member actually inflates to, and stop one
639/// byte past `budget`. The declared uncompressed size is not the limit:
640/// `self_update` copies the stream with no cap of its own.
641fn inflate_member_within_budget(
642    archive: &std::path::Path,
643    member: &str,
644    budget: u64,
645) -> Result<(), String> {
646    use std::io::{Read, copy, sink};
647    let file = std::fs::File::open(archive)
648        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
649    let mut zip = zip::ZipArchive::new(file)
650        .map_err(|e| format!("update archive is not a readable zip: {e}"))?;
651    let mut matched = None;
652    for index in 0..zip.len() {
653        let entry = zip
654            .by_index(index)
655            .map_err(|e| format!("update archive entry {index} cannot be read: {e}"))?;
656        let name = entry
657            .name()
658            .map_err(|e| format!("update archive entry {index} has no name: {e}"))?;
659        if member_names_match(name.as_bytes(), member) {
660            matched = Some(index);
661            break;
662        }
663    }
664    let Some(index) = matched else {
665        return Err(format!("update archive has no member {member}"));
666    };
667    let mut entry = zip
668        .by_index(index)
669        .map_err(|e| format!("update member {member} cannot be read: {e}"))?;
670    let inflated = copy(
671        &mut (&mut entry).take(budget.saturating_add(1)),
672        &mut sink(),
673    )
674    .map_err(|e| format!("update member {member} could not be inflated: {e}"))?;
675    if inflated > budget {
676        Err(format!(
677            "update member {member} inflates past the {budget}-byte budget"
678        ))
679    } else {
680        Ok(())
681    }
682}
683
684fn gzip_magic(file: &mut std::fs::File) -> Result<bool, String> {
685    use std::io::{Read, Seek, SeekFrom};
686    file.seek(SeekFrom::Start(0))
687        .map_err(|e| format!("update archive cannot be rewound: {e}"))?;
688    let mut magic = [0u8; 2];
689    let read = file
690        .read(&mut magic)
691        .map_err(|e| format!("update archive cannot be read: {e}"))?;
692    Ok(read == 2 && magic == [0x1f, 0x8b])
693}
694
695/// Walk a gzipped tar the way a Unix release archive is packed. `self_update`
696/// then asks `tar` to unpack the one member, which restores a symlink or a
697/// hardlink as a real link and keeps setuid bits. Refuse those before that
698/// unpack. The decompressed byte count stops at `budget`.
699fn confine_update_tar(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
700    let file = std::fs::File::open(archive)
701        .map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
702    let mut decoder = flate2::read::GzDecoder::new(file);
703    let mut inflated = 0u64;
704    let mut zero_blocks = 0u8;
705    let mut copies = 0u32;
706    // The tar crate's extension entries: a GNU `L` long name, a GNU `K`
707    // long link and a PAX `x` record set each describe the next member.
708    let mut long_name: Option<Vec<u8>> = None;
709    let mut long_link = false;
710    let mut pax: Option<Vec<u8>> = None;
711    loop {
712        let mut header = [0u8; 512];
713        if !read_tar_block(&mut decoder, &mut header, &mut inflated, budget)? {
714            break;
715        }
716        if header.iter().all(|byte| *byte == 0) {
717            zero_blocks = zero_blocks.saturating_add(1);
718            if zero_blocks == 2 {
719                break;
720            }
721            continue;
722        }
723        zero_blocks = 0;
724        if !tar_checksum_ok(&header) {
725            return Err("update archive is not a tar".into());
726        }
727        let typeflag = *header.get(156).unwrap_or(&0);
728        let extension = matches!(typeflag, b'L' | b'K' | b'x' | b'g');
729        let mut size = tar_octal(header.get(124..136).unwrap_or(&[]))?;
730        if !extension
731            && let Some(records) = pax.as_deref()
732            && let Some(pax_size) = pax_value(records, b"size")?
733        {
734            size = std::str::from_utf8(pax_size)
735                .ok()
736                .and_then(|text| text.parse::<u64>().ok())
737                .ok_or_else(|| "update archive PAX size is not a number".to_string())?;
738        }
739        if tar_magic_recognized(&header) && matches!(typeflag, b'L' | b'K' | b'x') {
740            let twice = match typeflag {
741                b'L' => long_name.is_some(),
742                b'K' => long_link,
743                _ => pax.is_some(),
744            };
745            if twice {
746                return Err("update archive describes one member twice".into());
747            }
748            let body = read_tar_extension(&mut decoder, size, &mut inflated, budget)?;
749            match typeflag {
750                b'L' => long_name = Some(body),
751                b'K' => long_link = true,
752                _ => pax = Some(body),
753            }
754            continue;
755        }
756        let name_bytes = match long_name.take() {
757            Some(mut bytes) => {
758                if bytes.last() == Some(&0) {
759                    bytes.pop();
760                }
761                bytes
762            }
763            None => match pax.as_deref().map(|records| pax_value(records, b"path")) {
764                Some(Ok(Some(path))) => path.to_vec(),
765                Some(Err(e)) => return Err(e),
766                _ => tar_entry_name(&header)?.into_bytes(),
767            },
768        };
769        pax = None;
770        long_link = false;
771        let name = String::from_utf8(name_bytes)
772            .map_err(|_| "update archive tar name is not UTF-8".to_string())?;
773        if tar_name_escapes(&name) {
774            return Err(format!(
775                "update archive entry {name} escapes the extraction directory"
776            ));
777        }
778        let mode = tar_octal(header.get(100..108).unwrap_or(&[]))?;
779        if member_names_match(name.as_bytes(), member) {
780            match typeflag {
781                b'2' => return Err(format!("update member {member} is a symlink")),
782                b'1' => return Err(format!("update member {member} is a hardlink")),
783                b'0' | 0 => {}
784                _ => {
785                    return Err(format!("update member {member} is not a regular file"));
786                }
787            }
788            if mode & 0o7000 != 0 {
789                return Err(format!(
790                    "update member {member} mode {mode:o} carries setuid, setgid, or sticky bits"
791                ));
792            }
793            copies = copies.saturating_add(1);
794        }
795        skip_tar_body(&mut decoder, size, &mut inflated, budget)?;
796    }
797    if long_name.is_some() || long_link || pax.is_some() {
798        return Err("update archive describes a member that never follows".into());
799    }
800    if copies > 1 {
801        return Err(format!("update archive lists {member} more than once"));
802    }
803    if copies == 0 {
804        return Err(format!("update archive has no member {member}"));
805    }
806    Ok(())
807}
808
809/// The tar crate honours `L`, `K` and `x` entries only under a ustar
810/// (`"ustar\0"`, `"00"`) or GNU (`"ustar "`, `" \0"`) magic.
811fn tar_magic_recognized(header: &[u8; 512]) -> bool {
812    let magic = header.get(257..263).unwrap_or(&[]);
813    let version = header.get(263..265).unwrap_or(&[]);
814    (magic == b"ustar\0" && version == b"00") || (magic == b"ustar " && version == b" \0")
815}
816
817/// Largest GNU long name or PAX record set the gate reads into memory.
818const TAR_EXTENSION_LIMIT: u64 = 1 << 20;
819
820fn read_tar_extension(
821    reader: &mut impl std::io::Read,
822    size: u64,
823    inflated: &mut u64,
824    budget: u64,
825) -> Result<Vec<u8>, String> {
826    if size > TAR_EXTENSION_LIMIT {
827        return Err(format!(
828            "update archive extension header of {size} bytes exceeds {TAR_EXTENSION_LIMIT}"
829        ));
830    }
831    let len = usize::try_from(size)
832        .map_err(|_| "update archive extension header is too large".to_string())?;
833    let mut body = vec![0u8; len];
834    read_exact_capped(reader, &mut body, inflated, budget)?;
835    let pad = (512 - size % 512) % 512;
836    let mut padding = [0u8; 512];
837    let pad_len = usize::try_from(pad).unwrap_or(0);
838    read_exact_capped(
839        reader,
840        padding
841            .get_mut(..pad_len)
842            .ok_or_else(|| "update archive tar padding is out of range".to_string())?,
843        inflated,
844        budget,
845    )?;
846    Ok(body)
847}
848
849/// The first value for `key` among PAX records `"<len> <key>=<value>\n"`.
850/// A malformed record set is a refusal: the extractor and the gate must
851/// not read it two ways.
852fn pax_value<'a>(records: &'a [u8], key: &[u8]) -> Result<Option<&'a [u8]>, String> {
853    let malformed = || "update archive PAX header is malformed".to_string();
854    let mut rest = records;
855    while !rest.is_empty() {
856        let space = rest
857            .iter()
858            .position(|byte| *byte == b' ')
859            .ok_or_else(malformed)?;
860        let len = std::str::from_utf8(rest.get(..space).ok_or_else(malformed)?)
861            .ok()
862            .and_then(|text| text.parse::<usize>().ok())
863            .ok_or_else(malformed)?;
864        let record = rest.get(..len).ok_or_else(malformed)?;
865        let body = record
866            .get(space.saturating_add(1)..)
867            .and_then(|body| body.strip_suffix(b"\n"))
868            .ok_or_else(malformed)?;
869        let equals = body
870            .iter()
871            .position(|byte| *byte == b'=')
872            .ok_or_else(malformed)?;
873        if body.get(..equals) == Some(key) {
874            return Ok(body.get(equals.saturating_add(1)..));
875        }
876        rest = rest.get(len..).ok_or_else(malformed)?;
877    }
878    Ok(None)
879}
880
881/// `Ok(false)` is a clean end of the gzip member. A short read in the middle
882/// of a header is a refusal.
883fn read_tar_block(
884    reader: &mut impl std::io::Read,
885    header: &mut [u8; 512],
886    inflated: &mut u64,
887    budget: u64,
888) -> Result<bool, String> {
889    let mut filled = 0usize;
890    while filled < header.len() {
891        if *inflated >= budget {
892            return Err(format!(
893                "update archive inflates past the {budget}-byte budget"
894            ));
895        }
896        let room = budget.saturating_sub(*inflated);
897        let want = u64::try_from(header.len().saturating_sub(filled)).unwrap_or(u64::MAX);
898        let take = usize::try_from(room.min(want)).unwrap_or(0);
899        if take == 0 {
900            return Err(format!(
901                "update archive inflates past the {budget}-byte budget"
902            ));
903        }
904        let end = filled.saturating_add(take);
905        let read = reader
906            .read(
907                header
908                    .get_mut(filled..end)
909                    .ok_or_else(|| "update archive tar header is out of range".to_string())?,
910            )
911            .map_err(|e| format!("update archive could not be inflated: {e}"))?;
912        if read == 0 {
913            if filled == 0 {
914                return Ok(false);
915            }
916            return Err("update archive ended inside a tar header".into());
917        }
918        filled = filled.saturating_add(read);
919        *inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
920    }
921    Ok(true)
922}
923
924fn skip_tar_body(
925    reader: &mut impl std::io::Read,
926    size: u64,
927    inflated: &mut u64,
928    budget: u64,
929) -> Result<(), String> {
930    let padded = size
931        .checked_add(511)
932        .ok_or_else(|| "update archive tar member is too large".to_string())?
933        / 512
934        * 512;
935    let mut left = padded;
936    let mut buf = [0u8; 8192];
937    while left > 0 {
938        let take = usize::try_from(left.min(8192)).unwrap_or(8192);
939        let dest = buf
940            .get_mut(..take)
941            .ok_or_else(|| "update archive tar member is out of range".to_string())?;
942        read_exact_capped(reader, dest, inflated, budget)?;
943        left = left.saturating_sub(u64::try_from(take).unwrap_or(left));
944    }
945    Ok(())
946}
947
948fn read_exact_capped(
949    reader: &mut impl std::io::Read,
950    buf: &mut [u8],
951    inflated: &mut u64,
952    budget: u64,
953) -> Result<(), String> {
954    let mut filled = 0usize;
955    while filled < buf.len() {
956        if *inflated >= budget {
957            return Err(format!(
958                "update archive inflates past the {budget}-byte budget"
959            ));
960        }
961        let room = budget.saturating_sub(*inflated);
962        let want = u64::try_from(buf.len().saturating_sub(filled)).unwrap_or(u64::MAX);
963        let take = usize::try_from(room.min(want)).unwrap_or(0);
964        if take == 0 {
965            return Err(format!(
966                "update archive inflates past the {budget}-byte budget"
967            ));
968        }
969        let end = filled.saturating_add(take);
970        let read = reader
971            .read(
972                buf.get_mut(filled..end)
973                    .ok_or_else(|| "update archive tar body is out of range".to_string())?,
974            )
975            .map_err(|e| format!("update archive could not be inflated: {e}"))?;
976        if read == 0 {
977            return Err("update archive ended inside a tar member".into());
978        }
979        filled = filled.saturating_add(read);
980        *inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
981    }
982    Ok(())
983}
984
985fn tar_checksum_ok(header: &[u8; 512]) -> bool {
986    let mut sum = 0u32;
987    for (index, byte) in header.iter().enumerate() {
988        if (148..156).contains(&index) {
989            sum += u32::from(b' ');
990        } else {
991            sum += u32::from(*byte);
992        }
993    }
994    tar_octal(header.get(148..156).unwrap_or(&[])).ok() == Some(u64::from(sum))
995}
996
997fn tar_entry_name(header: &[u8; 512]) -> Result<String, String> {
998    let name = tar_c_string(header.get(..100).unwrap_or(&[]))?;
999    // Only a ustar header carries a prefix field; a GNU header keeps
1000    // other data at those bytes, and the tar crate ignores them there.
1001    let ustar = header.get(257..263) == Some(b"ustar\0") && header.get(263..265) == Some(b"00");
1002    if !ustar {
1003        return Ok(name);
1004    }
1005    let prefix = tar_c_string(header.get(345..500).unwrap_or(&[]))?;
1006    if prefix.is_empty() {
1007        Ok(name)
1008    } else {
1009        Ok(format!("{prefix}/{name}"))
1010    }
1011}
1012
1013fn tar_c_string(bytes: &[u8]) -> Result<String, String> {
1014    let end = bytes
1015        .iter()
1016        .position(|byte| *byte == 0)
1017        .unwrap_or(bytes.len());
1018    let text = bytes.get(..end).unwrap_or(&[]);
1019    String::from_utf8(text.to_vec()).map_err(|_| "update archive tar name is not UTF-8".to_string())
1020}
1021
1022/// Parsed as the tar crate does: cut at the first NUL, trim blanks on both
1023/// sides, then read octal digits (an optional leading `+`, as
1024/// `u64::from_str_radix` allows). An empty field is refused there too.
1025fn tar_octal(bytes: &[u8]) -> Result<u64, String> {
1026    let end = bytes
1027        .iter()
1028        .position(|byte| *byte == 0)
1029        .unwrap_or(bytes.len());
1030    let text = bytes.get(..end).unwrap_or(&[]).trim_ascii();
1031    let text = text.strip_prefix(b"+").unwrap_or(text);
1032    if text.is_empty() {
1033        return Err("update archive tar field is not octal".into());
1034    }
1035    let mut value = 0u64;
1036    for byte in text {
1037        let digit = byte
1038            .checked_sub(b'0')
1039            .filter(|digit| *digit < 8)
1040            .ok_or_else(|| "update archive tar field is not octal".to_string())?;
1041        value = value
1042            .checked_mul(8)
1043            .and_then(|next| next.checked_add(u64::from(digit)))
1044            .ok_or_else(|| "update archive tar field is out of range".to_string())?;
1045    }
1046    Ok(value)
1047}
1048
1049fn tar_name_escapes(name: &str) -> bool {
1050    use std::path::{Component, Path};
1051    if name.starts_with('/') || name.starts_with('\\') {
1052        return true;
1053    }
1054    if name.split(['/', '\\']).any(|part| part == "..") {
1055        return true;
1056    }
1057    Path::new(name).components().any(|component| {
1058        matches!(
1059            component,
1060            Component::ParentDir | Component::RootDir | Component::Prefix(_)
1061        )
1062    })
1063}
1064
1065#[cfg(test)]
1066#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1067mod tests {
1068    use super::*;
1069
1070    #[test]
1071    fn asset_targets_match_the_release_workflow_archives() {
1072        let glibc = |os, arch| asset_target_for(os, arch, false);
1073        assert_eq!(glibc("macos", "aarch64"), Some("macos-aarch64"));
1074        assert_eq!(glibc("macos", "x86_64"), Some("macos-x86_64"));
1075        assert_eq!(glibc("linux", "aarch64"), Some("linux-aarch64"));
1076        assert_eq!(glibc("linux", "x86_64"), Some("linux-x86_64"));
1077        assert_eq!(glibc("windows", "x86_64"), Some("windows-x86_64"));
1078        // No archive is published for these: refuse rather than pick a wrong one.
1079        assert_eq!(glibc("windows", "aarch64"), None);
1080        assert_eq!(glibc("freebsd", "x86_64"), None);
1081        assert!(asset_target().is_some(), "every CI host has an archive");
1082    }
1083
1084    /// #2112: a static musl build updates to the musl archive. The glibc
1085    /// archive needs a loader Alpine does not have.
1086    #[test]
1087    fn a_musl_build_looks_up_the_musl_archive() {
1088        assert_eq!(
1089            asset_target_for("linux", "x86_64", true),
1090            Some("linux-musl-x86_64")
1091        );
1092        assert_eq!(
1093            asset_target_for("linux", "aarch64", true),
1094            Some("linux-musl-aarch64")
1095        );
1096        assert_eq!(asset_target_for("macos", "aarch64", true), None);
1097    }
1098
1099    /// Every archive `release.yml` publishes (its `binaries` matrix).
1100    const PUBLISHED_ARCHIVES: [&str; 7] = [
1101        "linux-x86_64",
1102        "linux-aarch64",
1103        "linux-musl-x86_64",
1104        "linux-musl-aarch64",
1105        "macos-x86_64",
1106        "macos-aarch64",
1107        "windows-x86_64",
1108    ];
1109
1110    /// `self_update` takes the first asset whose name *contains* the
1111    /// target, so no archive name may hold another: each lookup, through
1112    /// the crate's own matcher, lands on its own archive whatever the order.
1113    #[test]
1114    fn each_target_selects_its_own_archive_among_the_published_ones() {
1115        for order in [
1116            PUBLISHED_ARCHIVES.to_vec(),
1117            PUBLISHED_ARCHIVES.iter().rev().copied().collect(),
1118        ] {
1119            let release = self_update::update::Release::builder()
1120                .version("9.9.9")
1121                .assets(order.iter().map(|name| {
1122                    self_update::update::ReleaseAsset::new(
1123                        format!("jubarte-9.9.9-{name}.zip"),
1124                        format!("https://example.invalid/{name}"),
1125                    )
1126                }))
1127                .build()
1128                .expect("release");
1129            for name in PUBLISHED_ARCHIVES {
1130                let asset = release.asset_for(name, None).expect(name);
1131                assert_eq!(asset.name(), format!("jubarte-9.9.9-{name}.zip"));
1132            }
1133        }
1134    }
1135
1136    /// The overlap the test above guards against: a `-musl` suffix makes
1137    /// the glibc lookup match the musl archive when it is listed first.
1138    #[test]
1139    fn a_suffixed_musl_name_would_steal_the_glibc_lookup() {
1140        let release = self_update::update::Release::builder()
1141            .version("9.9.9")
1142            .assets(["linux-x86_64-musl", "linux-x86_64"].map(|name| {
1143                self_update::update::ReleaseAsset::new(
1144                    format!("jubarte-9.9.9-{name}.zip"),
1145                    format!("https://example.invalid/{name}"),
1146                )
1147            }))
1148            .build()
1149            .expect("release");
1150        let asset = release.asset_for("linux-x86_64", None).expect("asset");
1151        assert_eq!(asset.name(), "jubarte-9.9.9-linux-x86_64-musl.zip");
1152    }
1153
1154    #[test]
1155    fn archive_binary_path_names_the_staged_folder() {
1156        let path = bin_path_in_archive("macos-aarch64");
1157        assert_eq!(
1158            path,
1159            format!(
1160                "jubarte-{{{{ version }}}}-macos-aarch64/jubarte{}",
1161                std::env::consts::EXE_SUFFIX
1162            )
1163        );
1164        assert!(path.contains("{{ version }}"));
1165    }
1166
1167    #[test]
1168    fn without_a_terminal_only_check_or_yes_proceed() {
1169        let ask = Options::default();
1170        assert!(preflight(&ask, false).is_err());
1171        assert!(preflight(&ask, true).is_ok());
1172        let check = Options {
1173            check: true,
1174            ..Options::default()
1175        };
1176        assert!(preflight(&check, false).is_ok());
1177        let yes = Options {
1178            yes: true,
1179            ..Options::default()
1180        };
1181        assert!(preflight(&yes, false).is_ok());
1182        // Naming a version still needs an answer.
1183        let pinned = Options {
1184            version: Some("0.9.3".into()),
1185            ..Options::default()
1186        };
1187        assert!(preflight(&pinned, false).is_err());
1188    }
1189
1190    #[test]
1191    fn check_reports_and_never_installs() {
1192        let install = Plan::Install {
1193            from: "0.10.0".into(),
1194            to: "0.11.0".into(),
1195        };
1196        // --check turns an install decision into a report: Step::Install is
1197        // unreachable with check set, so nothing is ever downloaded or replaced.
1198        let look = Options {
1199            check: true,
1200            ..Options::default()
1201        };
1202        assert_eq!(
1203            step(&look, &install, "0.11.0"),
1204            Step::Report {
1205                text: "jubarte 0.10.0 is installed; 0.11.0 is available. Run `jubarte self-update` to install it.".into()
1206            }
1207        );
1208        // --check wins over --yes too: an explicit look never installs.
1209        let look_yes = Options {
1210            check: true,
1211            yes: true,
1212            ..Options::default()
1213        };
1214        assert!(matches!(
1215            step(&look_yes, &install, "0.11.0"),
1216            Step::Report { .. }
1217        ));
1218        // Without --check the same decision installs.
1219        assert_eq!(
1220            step(&Options::default(), &install, "0.11.0"),
1221            Step::Install {
1222                from: "0.10.0".into(),
1223                to: "0.11.0".into()
1224            }
1225        );
1226        // An up-to-date binary reports and stops whatever the flags say.
1227        let up_to_date = Plan::UpToDate {
1228            current: "0.11.0".into(),
1229        };
1230        for opts in [
1231            look,
1232            look_yes,
1233            Options {
1234                yes: true,
1235                ..Options::default()
1236            },
1237            Options::default(),
1238        ] {
1239            assert!(matches!(
1240                step(&opts, &up_to_date, "0.11.0"),
1241                Step::Report { .. }
1242            ));
1243        }
1244    }
1245
1246    #[test]
1247    fn latest_installs_only_when_newer() {
1248        assert_eq!(
1249            plan("0.9.3", "v0.10.0", false),
1250            Ok(Plan::Install {
1251                from: "0.9.3".into(),
1252                to: "0.10.0".into()
1253            })
1254        );
1255        assert_eq!(
1256            plan("0.10.0", "0.10.0", false),
1257            Ok(Plan::UpToDate {
1258                current: "0.10.0".into()
1259            })
1260        );
1261        // A newer local build never downgrades to the latest release.
1262        assert_eq!(
1263            plan("0.11.0", "0.10.0", false),
1264            Ok(Plan::UpToDate {
1265                current: "0.11.0".into()
1266            })
1267        );
1268    }
1269
1270    #[test]
1271    fn a_requested_version_installs_even_when_older() {
1272        assert_eq!(
1273            plan("0.10.0", "0.9.3", true),
1274            Ok(Plan::Install {
1275                from: "0.10.0".into(),
1276                to: "0.9.3".into()
1277            })
1278        );
1279        assert_eq!(
1280            plan("0.9.3", "v0.9.3", true),
1281            Ok(Plan::UpToDate {
1282                current: "0.9.3".into()
1283            })
1284        );
1285    }
1286
1287    #[test]
1288    fn a_non_semver_tag_is_an_error() {
1289        assert!(plan("0.10.0", "nightly", false).is_err());
1290    }
1291
1292    #[test]
1293    fn without_keys_no_signature_is_required() {
1294        for (target, first) in [
1295            ("0.12.0", Some("0.11.0")),
1296            ("0.11.0", Some("0.11.0")),
1297            ("0.9.0", Some("0.11.0")),
1298            ("0.12.0", None),
1299        ] {
1300            assert_eq!(
1301                signature_required(target, first, false),
1302                Ok(false),
1303                "{target} with first signed {first:?}"
1304            );
1305        }
1306    }
1307
1308    #[test]
1309    fn keys_without_a_first_signed_release_require_nothing() {
1310        assert_eq!(signature_required("0.12.0", None, true), Ok(false));
1311        assert_eq!(signature_required("v0.12.0", None, true), Ok(false));
1312    }
1313
1314    #[test]
1315    fn the_first_signed_release_and_later_ones_require_a_signature() {
1316        let first = Some("0.11.0");
1317        assert_eq!(signature_required("0.11.0", first, true), Ok(true));
1318        assert_eq!(signature_required("v0.11.0", first, true), Ok(true));
1319        assert_eq!(signature_required("0.11.1", first, true), Ok(true));
1320        assert_eq!(signature_required("v1.0.0", first, true), Ok(true));
1321        // A `v` on the threshold is the same release.
1322        assert_eq!(
1323            signature_required("0.11.0", Some("v0.11.0"), true),
1324            Ok(true)
1325        );
1326    }
1327
1328    #[test]
1329    fn releases_before_the_first_signed_one_are_checksum_only() {
1330        let first = Some("0.11.0");
1331        assert_eq!(signature_required("0.10.1", first, true), Ok(false));
1332        assert_eq!(signature_required("v0.10.1", first, true), Ok(false));
1333        // A pre-release of the first signed version sorts before it.
1334        assert_eq!(signature_required("0.11.0-rc.1", first, true), Ok(false));
1335    }
1336
1337    #[test]
1338    fn a_non_semver_version_is_an_error_when_signing_is_on() {
1339        assert!(signature_required("nightly", Some("0.11.0"), true).is_err());
1340        assert!(signature_required("0.11.0", Some("next"), true).is_err());
1341    }
1342
1343    #[test]
1344    fn the_shipped_key_set_and_threshold_agree() {
1345        // Both are set in the same commit (docs/SELF_UPDATE.md): a threshold
1346        // with no key would never check a signature, and a key with no
1347        // threshold would never be used.
1348        assert_eq!(
1349            FIRST_SIGNED_RELEASE.is_some(),
1350            !RELEASE_KEYS.is_empty(),
1351            "set FIRST_SIGNED_RELEASE and RELEASE_KEYS together"
1352        );
1353        if let Some(first) = FIRST_SIGNED_RELEASE {
1354            // The threshold is semver and carries no `v`. It is set to the
1355            // next release, before `Cargo.toml` is bumped, so it is not
1356            // compared with this build's version.
1357            assert!(!first.starts_with('v'), "write {first} without the v");
1358            assert_eq!(signature_required(first, Some(first), true), Ok(true));
1359        }
1360    }
1361
1362    /// ZIP-16 (#639): the binary swap must never install a link or a
1363    /// special file. `self_update`'s zip path refuses a symlink entry, but
1364    /// its tar path hands the entry to `tar`'s `unpack_in`, which restores
1365    /// a symlink as a real link whose target the crate does not confine to
1366    /// the staging dir — a crafted release could install any path as the
1367    /// new binary. The extracted path is checked with `symlink_metadata`
1368    /// (not `metadata`, which follows the link).
1369    #[test]
1370    fn a_special_extracted_binary_is_refused_before_the_swap() {
1371        let dir = tempfile::tempdir().unwrap();
1372        let regular = dir.path().join("jubarte");
1373        std::fs::write(&regular, b"binary").unwrap();
1374        extracted_binary_is_regular_file(&regular).expect("a regular file installs");
1375        extracted_binary_is_regular_file(dir.path())
1376            .expect_err("a directory at the extracted path must be refused");
1377        #[cfg(unix)]
1378        {
1379            let link = dir.path().join("linked");
1380            std::os::unix::fs::symlink(&regular, &link).unwrap();
1381            extracted_binary_is_regular_file(&link)
1382                .expect_err("a symlink at the extracted path must be refused");
1383            let dangling = dir.path().join("dangling");
1384            std::os::unix::fs::symlink(dir.path().join("no-such-target"), &dangling).unwrap();
1385            extracted_binary_is_regular_file(&dangling)
1386                .expect_err("a dangling symlink must be refused too");
1387        }
1388    }
1389
1390    const UPDATE_MEMBER: &str = "jubarte-9.9.9-windows-x86_64/jubarte.exe";
1391
1392    fn write_update_archive(dir: &std::path::Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
1393        let path = dir.join(name);
1394        std::fs::write(&path, bytes).unwrap();
1395        path
1396    }
1397
1398    fn deflated_update_zip(member: &str, payload: &[u8]) -> Vec<u8> {
1399        use std::io::Write;
1400        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
1401        let options: zip::write::FullFileOptions<'_, '_> =
1402            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
1403        writer.start_file(member, options).expect("start member");
1404        writer.write_all(payload).expect("write member");
1405        writer.finish().expect("finish zip").into_inner()
1406    }
1407
1408    /// ZIP-28 (#656): the downloaded file itself has a byte budget, before
1409    /// any member is inflated.
1410    #[test]
1411    fn update_archive_over_the_download_budget_is_refused() {
1412        let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
1413        let dir = tempfile::tempdir().unwrap();
1414        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1415        let budget = (bytes.len() as u64).saturating_sub(1);
1416        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
1417            .expect_err("an archive larger than the download budget was accepted");
1418        assert!(
1419            err.contains("download budget"),
1420            "the refusal must name the download budget, got {err}"
1421        );
1422    }
1423
1424    /// ZIP-28 (#656): the expected member can inflate far past the archive
1425    /// that carried it. The download fits; the unpacked member must not.
1426    #[test]
1427    fn update_archive_inflation_is_capped() {
1428        let payload = vec![0u8; 8_000];
1429        let bytes = deflated_update_zip(UPDATE_MEMBER, &payload);
1430        assert!(
1431            bytes.len() < payload.len(),
1432            "the fixture must be smaller on disk than the member it inflates to, got {} bytes",
1433            bytes.len()
1434        );
1435        let dir = tempfile::tempdir().unwrap();
1436        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1437        let budget = bytes.len() as u64;
1438        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
1439            .expect_err("an inflated member past the budget was extracted with no cap");
1440        assert!(
1441            err.contains("inflates past"),
1442            "the refusal must name the inflation cap, got {err}"
1443        );
1444        assert_eq!(
1445            std::fs::read_dir(dir.path()).unwrap().count(),
1446            1,
1447            "a refused archive must stay the only file in the directory"
1448        );
1449    }
1450
1451    /// ZIP-28 (#656): two central-directory entries with the expected name
1452    /// are ambiguous. The first match must not be installed.
1453    #[test]
1454    fn update_archive_duplicate_member_is_refused() {
1455        let name = UPDATE_MEMBER.as_bytes();
1456        let bytes = crate::admission::zip_names::zip(&[
1457            crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
1458            crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
1459        ]);
1460        let dir = tempfile::tempdir().unwrap();
1461        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1462        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1463            .expect_err("an archive that lists the expected member twice was accepted");
1464        assert!(
1465            err.contains("more than once"),
1466            "the refusal must name the repeated member, got {err}"
1467        );
1468    }
1469
1470    /// #2084 review: a zipsign-signed zip starts with its
1471    /// signature block, not `PK`, and its offsets are not rewritten; zip and
1472    /// self_update still read it. The checks must run on it too.
1473    fn prefixed(prefix_len: usize, zip: &[u8]) -> Vec<u8> {
1474        let mut out = vec![0xA5u8; prefix_len];
1475        out.extend_from_slice(zip);
1476        out
1477    }
1478
1479    #[test]
1480    fn update_archive_with_a_prefix_still_refuses_a_repeated_member() {
1481        let name = UPDATE_MEMBER.as_bytes();
1482        let bytes = prefixed(
1483            64,
1484            &crate::admission::zip_names::zip(&[
1485                crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
1486                crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
1487            ]),
1488        );
1489        let dir = tempfile::tempdir().unwrap();
1490        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1491        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1492            .expect_err("a prefixed archive skipped the repeated-member check");
1493        assert!(err.contains("more than once"), "{err}");
1494    }
1495
1496    #[test]
1497    fn update_archive_with_a_prefix_still_caps_inflation() {
1498        let payload = vec![0u8; 8_000];
1499        let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, &payload));
1500        let dir = tempfile::tempdir().unwrap();
1501        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1502        let budget = bytes.len() as u64;
1503        let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
1504            .expect_err("a prefixed archive skipped the inflation cap");
1505        assert!(err.contains("inflates past"), "{err}");
1506    }
1507
1508    #[test]
1509    fn update_archive_with_a_prefix_and_one_member_is_allowed() {
1510        let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte"));
1511        let dir = tempfile::tempdir().unwrap();
1512        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1513        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1514            .expect("a signed (prefixed) release zip with one member");
1515    }
1516
1517    /// #2084 review: zip names an entry by its adopted 0x7075
1518    /// Unicode Path, so a second entry whose raw name differs but whose
1519    /// Unicode Path is the member is the same installed file.
1520    #[test]
1521    fn update_archive_unicode_path_copy_is_a_repeated_member() {
1522        let name = UPDATE_MEMBER.as_bytes();
1523        let bytes = crate::admission::zip_names::zip(&[
1524            crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
1525            crate::admission::zip_names::RawEntry::raw(b"decoy.bin", b"SECOND").unicode_path(name),
1526        ]);
1527        let dir = tempfile::tempdir().unwrap();
1528        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1529        let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1530            .expect_err("a Unicode Path copy of the member was not counted");
1531        assert!(err.contains("more than once"), "{err}");
1532    }
1533
1534    #[test]
1535    fn update_archive_single_member_is_allowed() {
1536        let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
1537        let dir = tempfile::tempdir().unwrap();
1538        let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
1539        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1540            .expect("one member inside the budget is the release zip");
1541    }
1542
1543    #[test]
1544    fn update_archive_non_zip_inside_budget_is_allowed() {
1545        let dir = tempfile::tempdir().unwrap();
1546        let archive = write_update_archive(dir.path(), "jubarte.tar.gz", b"not a zip");
1547        confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1548            .expect("a tar.gz inside the download budget is not a zip refusal");
1549    }
1550
1551    const TAR_MEMBER: &str = "jubarte-9.9.9-linux-x86_64/jubarte";
1552
1553    /// A ustar header. `size` is the entry payload. Symlinks and hardlinks
1554    /// use a zero size and carry the target in the link field.
1555    fn tar_header(name: &str, typeflag: u8, mode: u32, size: u64, link: &str) -> [u8; 512] {
1556        let mut header = [0u8; 512];
1557        let name_bytes = name.as_bytes();
1558        assert!(name_bytes.len() < 100, "tar name fits the ustar field");
1559        header[..name_bytes.len()].copy_from_slice(name_bytes);
1560        let mode_text = format!("{mode:07o}");
1561        header[100..100 + mode_text.len()].copy_from_slice(mode_text.as_bytes());
1562        let size_text = format!("{size:011o}");
1563        header[124..124 + size_text.len()].copy_from_slice(size_text.as_bytes());
1564        header[136..147].copy_from_slice(b"00000000000");
1565        header[156] = typeflag;
1566        let link_bytes = link.as_bytes();
1567        assert!(
1568            link_bytes.len() < 100,
1569            "tar link target fits the ustar field"
1570        );
1571        header[157..157 + link_bytes.len()].copy_from_slice(link_bytes);
1572        header[257..263].copy_from_slice(b"ustar\0");
1573        header[263..265].copy_from_slice(b"00");
1574        tar_reseal(&mut header);
1575        header
1576    }
1577
1578    /// Rewrite the header checksum after a test edits a field.
1579    fn tar_reseal(header: &mut [u8; 512]) {
1580        let mut sum = 0u32;
1581        for (index, byte) in header.iter().enumerate() {
1582            if (148..156).contains(&index) {
1583                sum += u32::from(b' ');
1584            } else {
1585                sum += u32::from(*byte);
1586            }
1587        }
1588        let checksum = format!("{sum:06o}\0 ");
1589        header[148..156].copy_from_slice(checksum.as_bytes());
1590    }
1591
1592    /// One PAX extended-header record, `"<len> <key>=<value>\n"`, where
1593    /// `<len>` counts the whole record including its own digits.
1594    fn pax_record(key: &str, value: &str) -> Vec<u8> {
1595        let body = format!(" {key}={value}\n");
1596        let mut len = body.len() + 1;
1597        while format!("{len}").len() + body.len() != len {
1598            len += 1;
1599        }
1600        format!("{len}{body}").into_bytes()
1601    }
1602
1603    fn gzip_tar(entries: &[([u8; 512], &[u8])]) -> Vec<u8> {
1604        use std::io::Write;
1605        let mut raw = Vec::new();
1606        for (header, body) in entries {
1607            raw.extend_from_slice(header);
1608            raw.extend_from_slice(body);
1609            let pad = (512 - (body.len() % 512)) % 512;
1610            raw.extend(std::iter::repeat_n(0u8, pad));
1611        }
1612        raw.extend_from_slice(&[0u8; 1024]);
1613        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1614        encoder.write_all(&raw).expect("gzip");
1615        encoder.finish().expect("finish gzip")
1616    }
1617
1618    fn tar_archive(dir: &std::path::Path, entries: &[([u8; 512], &[u8])]) -> std::path::PathBuf {
1619        write_update_archive(dir, "jubarte.tar.gz", &gzip_tar(entries))
1620    }
1621
1622    /// R06a (#1305): macOS and Linux extract a tar.gz. A symlink at the
1623    /// binary's path must not be unpacked and installed.
1624    #[test]
1625    fn update_tar_symlink_member_is_refused() {
1626        let header = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
1627        let dir = tempfile::tempdir().unwrap();
1628        let archive = tar_archive(dir.path(), &[(header, &[][..])]);
1629        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1630            .expect_err("a tar.gz symlink member was accepted");
1631        assert!(
1632            err.contains("symlink"),
1633            "the refusal must name the symlink, got {err}"
1634        );
1635    }
1636
1637    /// R06a (#1305): a hardlink is not a regular file either.
1638    #[test]
1639    fn update_tar_hardlink_member_is_refused() {
1640        let header = tar_header(TAR_MEMBER, b'1', 0o644, 0, "other");
1641        let dir = tempfile::tempdir().unwrap();
1642        let archive = tar_archive(dir.path(), &[(header, &[][..])]);
1643        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1644            .expect_err("a tar.gz hardlink member was accepted");
1645        assert!(
1646            err.contains("hardlink"),
1647            "the refusal must name the hardlink, got {err}"
1648        );
1649    }
1650
1651    /// R06a (#1305): the zip arm masks mode to `0o777`. A setuid tar member
1652    /// must not be installed with those bits.
1653    #[test]
1654    fn update_tar_setuid_member_is_refused() {
1655        let body = b"#!/jubarte";
1656        let header = tar_header(TAR_MEMBER, b'0', 0o4755, body.len() as u64, "");
1657        let dir = tempfile::tempdir().unwrap();
1658        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
1659        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1660            .expect_err("a setuid tar member was accepted");
1661        assert!(
1662            err.contains("setuid"),
1663            "the refusal must name the setuid bit, got {err}"
1664        );
1665    }
1666
1667    /// R06a (#1305): an entry name that climbs out of the extract directory
1668    /// is refused even when the expected binary is also present.
1669    #[test]
1670    fn update_tar_escaping_entry_is_refused() {
1671        let body = b"#!/jubarte";
1672        let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1673        let escape = tar_header("../outside", b'0', 0o644, 1, "");
1674        let dir = tempfile::tempdir().unwrap();
1675        let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
1676        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1677            .expect_err("a tar entry that climbs out of the extract directory was accepted");
1678        assert!(
1679            err.contains("escapes"),
1680            "the refusal must name the escaping path, got {err}"
1681        );
1682    }
1683
1684    /// #2085 review: the tar crate takes a member's path from a PAX `path`
1685    /// record before the ustar name. A symlink whose ustar name is harmless
1686    /// but whose PAX path is the binary must be refused.
1687    #[test]
1688    fn update_tar_pax_path_symlink_is_refused() {
1689        let body = b"#!/jubarte";
1690        let pax = pax_record("path", TAR_MEMBER);
1691        let pax_header = tar_header("PaxHeaders/other", b'x', 0o644, pax.len() as u64, "");
1692        let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
1693        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1694        let dir = tempfile::tempdir().unwrap();
1695        let archive = tar_archive(
1696            dir.path(),
1697            &[(pax_header, &pax[..]), (link, &[][..]), (decoy, &body[..])],
1698        );
1699        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1700            .expect_err("a symlink named by a PAX path record was accepted");
1701        assert!(err.contains("symlink"), "got {err}");
1702    }
1703
1704    /// #2085 review: a GNU `L` long-name entry renames the member after it.
1705    #[test]
1706    fn update_tar_gnu_long_name_symlink_is_refused() {
1707        let body = b"#!/jubarte";
1708        let mut long = TAR_MEMBER.as_bytes().to_vec();
1709        long.push(0);
1710        let long_header = tar_header("././@LongLink", b'L', 0o644, long.len() as u64, "");
1711        let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
1712        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1713        let dir = tempfile::tempdir().unwrap();
1714        let archive = tar_archive(
1715            dir.path(),
1716            &[
1717                (long_header, &long[..]),
1718                (link, &[][..]),
1719                (decoy, &body[..]),
1720            ],
1721        );
1722        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1723            .expect_err("a symlink named by a GNU long name was accepted");
1724        assert!(err.contains("symlink"), "got {err}");
1725    }
1726
1727    /// #2085 review: a PAX `size` record overrides the ustar size. A gate
1728    /// that skips the ustar size steps over a header the extractor reads.
1729    #[test]
1730    fn update_tar_pax_size_cannot_hide_a_member() {
1731        let body = b"#!/jubarte";
1732        let pax = pax_record("size", "0");
1733        let pax_header = tar_header("PaxHeaders/pad", b'x', 0o644, pax.len() as u64, "");
1734        let hidden = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
1735        let pad = tar_header("pad", b'0', 0o644, 512, "");
1736        let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1737        let dir = tempfile::tempdir().unwrap();
1738        let archive = tar_archive(
1739            dir.path(),
1740            &[
1741                (pax_header, &pax[..]),
1742                (pad, &hidden[..]),
1743                (decoy, &body[..]),
1744            ],
1745        );
1746        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1747            .expect_err("a member hidden behind a PAX size was accepted");
1748        assert!(err.contains("symlink"), "got {err}");
1749    }
1750
1751    /// #2085 review: the tar crate trims blanks around an octal field, so a
1752    /// mode of `" 4755"` is setuid there and must be setuid here.
1753    #[test]
1754    fn update_tar_space_led_setuid_mode_is_refused() {
1755        let body = b"#!/jubarte";
1756        let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1757        header[100..108].copy_from_slice(b"  4755\0\0");
1758        tar_reseal(&mut header);
1759        let dir = tempfile::tempdir().unwrap();
1760        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
1761        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1762            .expect_err("a blank-led setuid mode was accepted");
1763        assert!(err.contains("setuid"), "got {err}");
1764    }
1765
1766    /// #2093 review: the tar crate cuts a numeric field at its first NUL
1767    /// and refuses what is left when it is empty. A NUL-led size must not
1768    /// read as zero here, or the gate and the extractor walk different
1769    /// entries.
1770    #[test]
1771    fn update_tar_nul_led_size_is_refused() {
1772        let body = b"#!/jubarte";
1773        let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1774        header[124..136].copy_from_slice(b"\x0000000000012");
1775        tar_reseal(&mut header);
1776        let dir = tempfile::tempdir().unwrap();
1777        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
1778        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1779            .expect_err("a NUL-led size field was accepted");
1780        assert!(err.contains("octal"), "got {err}");
1781    }
1782
1783    /// #2085 review: a `..` between backslashes is refused like one
1784    /// between slashes, matching how member names are compared.
1785    #[test]
1786    fn update_tar_backslash_parent_entry_is_refused() {
1787        let body = b"#!/jubarte";
1788        let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1789        let escape = tar_header("jubarte-9.9.9\\..\\..\\outside", b'0', 0o644, 1, "");
1790        let dir = tempfile::tempdir().unwrap();
1791        let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
1792        let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1793            .expect_err("a backslash .. entry was accepted");
1794        assert!(err.contains("escapes"), "got {err}");
1795    }
1796
1797    /// A long binary path carried by a PAX record (as GNU tar and bsdtar
1798    /// write it) is still the release archive.
1799    #[test]
1800    fn update_tar_pax_path_regular_member_is_allowed() {
1801        let body = b"#!/jubarte";
1802        let mut pax = pax_record("mtime", "1700000000.5");
1803        pax.extend(pax_record("path", TAR_MEMBER));
1804        let pax_header = tar_header("PaxHeaders/jubarte", b'x', 0o644, pax.len() as u64, "");
1805        let binary = tar_header("short-name", b'0', 0o755, body.len() as u64, "");
1806        let dir = tempfile::tempdir().unwrap();
1807        let archive = tar_archive(dir.path(), &[(pax_header, &pax[..]), (binary, &body[..])]);
1808        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1809            .expect("a regular member named by a PAX path is the release archive");
1810    }
1811
1812    #[test]
1813    fn update_tar_regular_member_is_allowed() {
1814        let body = b"#!/jubarte";
1815        let header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
1816        let dir = tempfile::tempdir().unwrap();
1817        let archive = tar_archive(dir.path(), &[(header, &body[..])]);
1818        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1819            .expect("a regular tar member inside the budget is the release archive");
1820        let fixture = dir.path().join("unsigned.tar.gz");
1821        std::fs::write(
1822            &fixture,
1823            include_bytes!("../../../tests/data/self_update/unsigned.tar.gz"),
1824        )
1825        .unwrap();
1826        confine_update_zip(&fixture, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1827            .expect("the signed-update fixture tar is a regular member");
1828    }
1829
1830    fn gzip_raw(raw: &[u8]) -> Vec<u8> {
1831        use std::io::Write;
1832        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1833        encoder.write_all(raw).expect("gzip");
1834        encoder.finish().expect("finish gzip")
1835    }
1836
1837    fn confine_tar(entries: &[([u8; 512], &[u8])], budget: u64) -> Result<(), String> {
1838        let dir = tempfile::tempdir().unwrap();
1839        let archive = tar_archive(dir.path(), entries);
1840        confine_update_zip(&archive, TAR_MEMBER, budget)
1841    }
1842
1843    fn confine_raw(raw: &[u8]) -> Result<(), String> {
1844        let dir = tempfile::tempdir().unwrap();
1845        let archive = write_update_archive(dir.path(), "jubarte.tar.gz", &gzip_raw(raw));
1846        confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
1847    }
1848
1849    fn gnu(mut header: [u8; 512]) -> [u8; 512] {
1850        header[257..263].copy_from_slice(b"ustar ");
1851        header[263..265].copy_from_slice(b" \0");
1852        tar_reseal(&mut header);
1853        header
1854    }
1855
1856    #[test]
1857    fn update_tar_header_damage_is_refused() {
1858        let mut bad = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
1859        bad[148] ^= 1;
1860        let err = confine_tar(&[(bad, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
1861        assert_eq!(err, "update archive is not a tar");
1862        let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
1863        let err = confine_raw(&header[..100]).unwrap_err();
1864        assert_eq!(err, "update archive ended inside a tar header");
1865        let big = tar_header(TAR_MEMBER, b'0', 0o755, 600, "");
1866        let mut raw = big.to_vec();
1867        raw.extend_from_slice(&[7u8; 100]);
1868        assert_eq!(
1869            confine_raw(&raw).unwrap_err(),
1870            "update archive ended inside a tar member"
1871        );
1872        // The budget runs out inside the header, then inside the body.
1873        for budget in [200, 520] {
1874            let err = confine_tar(&[(header, &b"x"[..])], budget).unwrap_err();
1875            assert!(
1876                err.contains(&format!("inflates past the {budget}-byte budget")),
1877                "{err}"
1878            );
1879        }
1880    }
1881
1882    #[test]
1883    fn update_tar_member_count_must_be_one() {
1884        let member = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
1885        let err = confine_tar(
1886            &[(member, &b"x"[..]), (member, &b"x"[..])],
1887            UPDATE_ARCHIVE_BYTE_BUDGET,
1888        )
1889        .unwrap_err();
1890        assert!(err.contains("more than once"), "{err}");
1891        let other = tar_header("README", b'0', 0o644, 1, "");
1892        let err = confine_tar(&[(other, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
1893        assert!(err.contains("has no member"), "{err}");
1894    }
1895
1896    #[test]
1897    fn update_tar_long_names_name_the_next_member_once() {
1898        let long_body = format!("{TAR_MEMBER}\0");
1899        let long = gnu(tar_header(
1900            "././@LongLink",
1901            b'L',
1902            0o644,
1903            long_body.len() as u64,
1904            "",
1905        ));
1906        let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
1907        confine_tar(
1908            &[(long, long_body.as_bytes()), (plain, &b"x"[..])],
1909            UPDATE_ARCHIVE_BYTE_BUDGET,
1910        )
1911        .expect("a GNU long name naming the member is the member");
1912        let err = confine_tar(
1913            &[
1914                (long, long_body.as_bytes()),
1915                (long, long_body.as_bytes()),
1916                (plain, &b"x"[..]),
1917            ],
1918            UPDATE_ARCHIVE_BYTE_BUDGET,
1919        )
1920        .unwrap_err();
1921        assert!(err.contains("one member twice"), "{err}");
1922        let err =
1923            confine_tar(&[(long, long_body.as_bytes())], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
1924        assert!(err.contains("never follows"), "{err}");
1925        let huge = tar_header("././@LongLink", b'L', 0o644, TAR_EXTENSION_LIMIT + 1, "");
1926        let err = confine_tar(&[(huge, &b""[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
1927        assert!(err.contains("exceeds"), "{err}");
1928        // Without a recognised magic an `L` entry is an ordinary member.
1929        let mut unmarked = tar_header("././@LongLink", b'L', 0o644, long_body.len() as u64, "");
1930        unmarked[257..265].fill(0);
1931        tar_reseal(&mut unmarked);
1932        let err = confine_tar(
1933            &[(unmarked, long_body.as_bytes())],
1934            UPDATE_ARCHIVE_BYTE_BUDGET,
1935        )
1936        .unwrap_err();
1937        assert!(err.contains("has no member"), "{err}");
1938    }
1939
1940    #[test]
1941    fn update_tar_ustar_prefix_joins_the_name() {
1942        let (prefix, name) = TAR_MEMBER.split_once('/').unwrap();
1943        let mut header = tar_header(name, b'0', 0o755, 1, "");
1944        header[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes());
1945        tar_reseal(&mut header);
1946        confine_tar(&[(header, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET)
1947            .expect("prefix/name is the member");
1948        let absolute = tar_header("/etc/jubarte", b'0', 0o755, 1, "");
1949        let err = confine_tar(&[(absolute, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
1950        assert!(err.contains("escapes"), "{err}");
1951        assert!(tar_name_escapes("\\jubarte"));
1952        assert!(!tar_name_escapes("dir/jubarte"));
1953    }
1954
1955    #[test]
1956    fn tar_fields_parse_as_the_tar_crate_reads_them() {
1957        assert_eq!(tar_octal(b" +17 \0junk"), Ok(15));
1958        assert!(tar_octal(b"   \0").is_err());
1959        assert!(tar_octal(b"9").is_err());
1960        assert!(tar_octal(b"7777777777777777777777777").is_err());
1961        assert_eq!(pax_value(&pax_record("path", "a"), b"size"), Ok(None));
1962        assert_eq!(
1963            pax_value(b"x", b"path").unwrap_err(),
1964            "update archive PAX header is malformed"
1965        );
1966        assert!(pax_value(b"9 path\n", b"path").is_err());
1967    }
1968
1969    fn stored_zip(members: &[&str], comment: &str) -> Vec<u8> {
1970        use std::io::Write;
1971        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
1972        let options: zip::write::FullFileOptions<'_, '_> =
1973            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
1974        for member in members {
1975            if let Some(dir) = member.strip_suffix('/') {
1976                writer
1977                    .add_directory(dir, options.clone())
1978                    .expect("directory");
1979            } else {
1980                writer
1981                    .start_file(*member, options.clone())
1982                    .expect("start member");
1983                writer.write_all(b"binary").expect("write member");
1984            }
1985        }
1986        writer.set_comment(comment).unwrap();
1987        writer.finish().expect("finish zip").into_inner()
1988    }
1989
1990    fn confine_bytes(bytes: &[u8]) -> Result<(), String> {
1991        let dir = tempfile::tempdir().unwrap();
1992        let archive = write_update_archive(dir.path(), "jubarte.zip", bytes);
1993        confine_update_zip(&archive, "jubarte.exe", UPDATE_ARCHIVE_BYTE_BUDGET)
1994    }
1995
1996    /// Offset of the end record in a zip written without a comment.
1997    fn eocd(bytes: &[u8]) -> usize {
1998        bytes.len() - 22
1999    }
2000
2001    fn central(bytes: &[u8]) -> usize {
2002        let at = eocd(bytes);
2003        u32::from_le_bytes(bytes[at + 16..at + 20].try_into().unwrap()) as usize
2004    }
2005
2006    #[test]
2007    fn update_zip_directory_damage_is_refused() {
2008        let good = stored_zip(&["bin/", "jubarte.exe"], "");
2009        confine_bytes(&good).expect("one regular member");
2010        // A comment after the end record still finds it.
2011        confine_bytes(&stored_zip(&["jubarte.exe"], "signed by nobody")).expect("commented zip");
2012
2013        let mut zip64 = good.clone();
2014        let at = eocd(&zip64);
2015        zip64[at + 10..at + 12].copy_from_slice(&u16::MAX.to_le_bytes());
2016        assert!(confine_bytes(&zip64).unwrap_err().contains("ZIP64"));
2017
2018        let mut count = good.clone();
2019        let at = eocd(&count);
2020        count[at + 10..at + 12].copy_from_slice(&3u16.to_le_bytes());
2021        assert!(
2022            confine_bytes(&count)
2023                .unwrap_err()
2024                .contains("does not match its end record")
2025        );
2026
2027        let mut torn = good.clone();
2028        let cd = central(&torn);
2029        torn[cd] = b'X';
2030        assert!(
2031            confine_bytes(&torn)
2032                .unwrap_err()
2033                .contains("central directory is truncated")
2034        );
2035
2036        let mut long = good.clone();
2037        let cd = central(&long);
2038        long[cd + 28..cd + 30].copy_from_slice(&u16::MAX.to_le_bytes());
2039        assert!(
2040            confine_bytes(&long)
2041                .unwrap_err()
2042                .contains("runs past the directory")
2043        );
2044
2045        let mut empty = vec![0x50, 0x4b, 0x05, 0x06];
2046        empty.extend_from_slice(&[0u8; 18]);
2047        assert!(confine_bytes(&empty).unwrap_err().contains("has no member"));
2048    }
2049
2050    #[test]
2051    fn update_files_that_are_not_zips_are_told_apart() {
2052        let err = confine_bytes(b"PK\x03\x04 not really a zip").unwrap_err();
2053        assert_eq!(err, "update archive has no zip end record");
2054        confine_bytes(b"P").expect("a one-byte file is no archive this gate knows");
2055        assert!(member_names_match(b"./bin\\jubarte", "bin/jubarte"));
2056        assert!(!member_names_match(b"bin/", "bin/"));
2057        assert!(!member_names_match(b"bin/jubartf", "bin/jubarte"));
2058    }
2059
2060    #[test]
2061    fn update_tar_extensions_left_dangling_or_unterminated() {
2062        let long = gnu(tar_header(
2063            "././@LongLink",
2064            b'L',
2065            0o644,
2066            TAR_MEMBER.len() as u64,
2067            "",
2068        ));
2069        let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
2070        confine_tar(
2071            &[(long, TAR_MEMBER.as_bytes()), (plain, &b"x"[..])],
2072            UPDATE_ARCHIVE_BYTE_BUDGET,
2073        )
2074        .expect("a long name without its NUL still names the member");
2075        let link = gnu(tar_header("././@LongLink", b'K', 0o644, 4, ""));
2076        let err = confine_tar(&[(link, &b"dest"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
2077        assert!(err.contains("never follows"), "{err}");
2078        let records = pax_record("comment", "x");
2079        let pax = tar_header("pax", b'x', 0o644, records.len() as u64, "");
2080        let err = confine_tar(&[(pax, &records[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
2081        assert!(err.contains("never follows"), "{err}");
2082        // An archive that stops at a block boundary, with no end blocks.
2083        let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
2084        let mut raw = header.to_vec();
2085        raw.extend_from_slice(&[b'x'; 512]);
2086        confine_raw(&raw).expect("a clean end after a whole member");
2087    }
2088
2089    #[test]
2090    fn update_zip_end_records_hidden_or_impossible() {
2091        // A comment holding an end-record signature is skipped over.
2092        let fake = format!("PK\u{5}\u{6}{}", "z".repeat(30));
2093        confine_bytes(&stored_zip(&["jubarte.exe"], &fake)).expect("the real end record is found");
2094        let good = stored_zip(&["jubarte.exe"], "");
2095        for field in [12, 16] {
2096            let mut zip64 = good.clone();
2097            let at = eocd(&zip64);
2098            zip64[at + field..at + field + 4].copy_from_slice(&u32::MAX.to_le_bytes());
2099            assert!(
2100                confine_bytes(&zip64).unwrap_err().contains("ZIP64"),
2101                "{field}"
2102            );
2103        }
2104        // A nameless entry whose comment holds the old name's bytes.
2105        let mut nameless = good.clone();
2106        let cd = central(&nameless);
2107        let name_len = nameless[cd + 28..cd + 30].to_vec();
2108        nameless[cd + 28..cd + 30].copy_from_slice(&[0, 0]);
2109        nameless[cd + 30..cd + 32].copy_from_slice(&[0, 0]);
2110        nameless[cd + 32..cd + 34].copy_from_slice(&name_len);
2111        assert!(
2112            confine_bytes(&nameless)
2113                .unwrap_err()
2114                .contains("has no member")
2115        );
2116    }
2117}