use std::io::{BufRead, IsTerminal, Write};
use self_update::backends::github;
use self_update::version::cmp_versions;
mod zipsign;
pub use zipsign::{ReleaseKey, verify_signature};
const REPO_OWNER: &str = "jandira-tech";
const REPO_NAME: &str = "jubarte";
const SUMS_ASSET: &str = "SHA256SUMS.txt";
const RELEASE_KEYS: &[ReleaseKey] = &[];
const FIRST_SIGNED_RELEASE: Option<&str> = None;
const UPDATE_ARCHIVE_BYTE_BUDGET: u64 = 128 * 1024 * 1024;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Options {
pub check: bool,
pub yes: bool,
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Plan {
UpToDate {
current: String,
},
Install {
from: String,
to: String,
},
}
#[must_use]
pub fn asset_target() -> Option<&'static str> {
asset_target_for(
std::env::consts::OS,
std::env::consts::ARCH,
cfg!(target_env = "musl"),
)
}
fn asset_target_for(os: &str, arch: &str, musl: bool) -> Option<&'static str> {
Some(match (os, arch, musl) {
("macos", "aarch64", false) => "macos-aarch64",
("macos", "x86_64", false) => "macos-x86_64",
("linux", "aarch64", false) => "linux-aarch64",
("linux", "x86_64", false) => "linux-x86_64",
("linux", "aarch64", true) => "linux-musl-aarch64",
("linux", "x86_64", true) => "linux-musl-x86_64",
("windows", "x86_64", false) => "windows-x86_64",
_ => return None,
})
}
fn bin_path_in_archive(target: &str) -> String {
format!(
"jubarte-{{{{ version }}}}-{target}/jubarte{}",
std::env::consts::EXE_SUFFIX
)
}
pub fn preflight(opts: &Options, interactive: bool) -> Result<(), String> {
if opts.check || opts.yes || interactive {
Ok(())
} else {
Err("no terminal to confirm on; pass --yes to install or --check to only look".into())
}
}
fn bare(version: &str) -> &str {
version.strip_prefix('v').unwrap_or(version)
}
pub fn plan(current: &str, target: &str, requested: bool) -> Result<Plan, String> {
let (current, target) = (bare(current), bare(target));
let order = cmp_versions(target, current).map_err(|e| format!("version {target}: {e}"))?;
let install = if requested {
order.is_ne()
} else {
order.is_gt()
};
Ok(if install {
Plan::Install {
from: current.to_string(),
to: target.to_string(),
}
} else {
Plan::UpToDate {
current: current.to_string(),
}
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Step {
Report {
text: String,
},
Install {
from: String,
to: String,
},
}
#[must_use]
pub fn step(opts: &Options, decision: &Plan, resolved: &str) -> Step {
match decision {
Plan::UpToDate { current } => Step::Report {
text: format!("jubarte {current} is up to date (latest release {resolved})."),
},
Plan::Install { from, to } if opts.check => Step::Report {
text: format!(
"jubarte {from} is installed; {to} is available. Run `jubarte self-update` to install it."
),
},
Plan::Install { from, to } => Step::Install {
from: from.clone(),
to: to.clone(),
},
}
}
pub fn run(opts: &Options) -> Result<(), String> {
let interactive = std::io::stdin().is_terminal();
preflight(opts, interactive)?;
let target = asset_target().ok_or_else(|| {
format!(
"no release archive is built for {}-{}; build from source",
std::env::consts::OS,
std::env::consts::ARCH
)
})?;
let current = env!("CARGO_PKG_VERSION");
let mut builder = github::Update::configure();
builder
.repo_owner(REPO_OWNER)
.repo_name(REPO_NAME)
.bin_name("jubarte")
.target(target)
.current_version(current)
.bin_path_in_archive(bin_path_in_archive(target))
.verify_binary(extracted_binary_is_regular_file)
.checksum_from_asset(SUMS_ASSET)
.show_output(false)
.show_download_progress(interactive)
.no_confirm(true);
let lookup = builder.build().map_err(|e| e.to_string())?;
let release = match &opts.version {
Some(v) => lookup
.get_release_version(&format!("v{}", bare(v)))
.map(Some),
None => lookup
.get_latest_release()
.map(|releases| releases.into_vec().into_iter().next()),
}
.map_err(|e| format!("GitHub release lookup failed: {e}"))?
.ok_or("GitHub lists no release")?;
let decision = plan(current, release.version(), opts.version.is_some())?;
let (from, to) = match step(opts, &decision, bare(release.version())) {
Step::Report { text } => {
println!("{text}");
return Ok(());
}
Step::Install { from, to } => (from, to),
};
if !opts.yes && !confirm(&from, &to)? {
println!("Nothing changed.");
return Ok(());
}
let signed = signature_required(&to, FIRST_SIGNED_RELEASE, !RELEASE_KEYS.is_empty())?;
let member = resolved_bin_path(target, &to);
builder.verify_archive(move |archive| {
confine_update_zip(archive, &member, UPDATE_ARCHIVE_BYTE_BUDGET)
.map_err(self_update::Error::archive_verification_rejected)?;
if signed {
verify_signature(archive, RELEASE_KEYS)
.map_err(self_update::Error::archive_verification_rejected)?;
}
Ok(())
});
if !signed && !RELEASE_KEYS.is_empty() {
eprintln!("note: {to} predates signed releases; only its SHA-256 is checked.");
}
let installer = builder
.release_tag(format!("v{to}"))
.build()
.map_err(|e| e.to_string())?;
installer
.update()
.map_err(|e| format!("update to {to} failed; the installed binary is unchanged: {e}"))?;
println!("jubarte {from} -> {to} installed.");
Ok(())
}
pub fn signature_required(
target_version: &str,
first_signed: Option<&str>,
keys_present: bool,
) -> Result<bool, String> {
let Some(first) = first_signed.filter(|_| keys_present) else {
return Ok(false);
};
let (target, first) = (bare(target_version), bare(first));
let order = cmp_versions(target, first)
.map_err(|e| format!("version {target} against first signed release {first}: {e}"))?;
Ok(order.is_ge())
}
fn confirm(from: &str, to: &str) -> Result<bool, String> {
eprint!("Replace jubarte {from} with {to}? [y/N] ");
std::io::stderr().flush().map_err(|e| e.to_string())?;
let mut answer = String::new();
std::io::stdin()
.lock()
.read_line(&mut answer)
.map_err(|e| e.to_string())?;
Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes" | "YES"))
}
fn extracted_binary_is_regular_file(path: &std::path::Path) -> self_update::Result<()> {
let metadata = std::fs::symlink_metadata(path).map_err(|e| {
self_update::Error::verification_rejected(format!(
"the extracted binary {} cannot be inspected: {e}",
path.display()
))
})?;
if metadata.is_file() {
Ok(())
} else {
Err(self_update::Error::verification_rejected(format!(
"the extracted binary {} is not a regular file",
path.display()
)))
}
}
fn resolved_bin_path(target: &str, version: &str) -> String {
bin_path_in_archive(target).replace("{{ version }}", version)
}
fn confine_update_zip(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
let len = std::fs::metadata(archive)
.map_err(|e| {
format!(
"update archive {} cannot be inspected: {e}",
archive.display()
)
})?
.len();
if len > budget {
return Err(format!(
"update archive is {len} bytes, over the {budget}-byte download budget"
));
}
let mut file = std::fs::File::open(archive)
.map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
let Some(copies) = zip_member_copies(&mut file, len, member)? else {
if zip_magic(&mut file)? {
return Err("update archive has no zip end record".into());
}
if gzip_magic(&mut file)? {
return confine_update_tar(archive, member, budget);
}
return Ok(());
};
if copies > 1 {
return Err(format!("update archive lists {member} more than once"));
}
if copies == 0 {
return Err(format!("update archive has no member {member}"));
}
inflate_member_within_budget(archive, member, budget)
}
fn zip_magic(file: &mut std::fs::File) -> Result<bool, String> {
use std::io::{Read, Seek, SeekFrom};
file.seek(SeekFrom::Start(0))
.map_err(|e| format!("update archive cannot be rewound: {e}"))?;
let mut magic = [0u8; 2];
let read = file
.read(&mut magic)
.map_err(|e| format!("update archive cannot be read: {e}"))?;
Ok(read == 2 && magic == [0x50, 0x4b])
}
fn zip_member_copies(
file: &mut std::fs::File,
len: u64,
member: &str,
) -> Result<Option<u32>, String> {
const EOCD_LEN: u64 = 22;
const MAX_COMMENT: u64 = 65_535;
if len < EOCD_LEN {
return Ok(None);
}
let tail_len = len.min(EOCD_LEN.saturating_add(MAX_COMMENT));
let tail_at = len.saturating_sub(tail_len);
let tail_bytes = usize::try_from(tail_len)
.map_err(|_| "update archive is too large to inspect".to_string())?;
let mut tail = vec![0u8; tail_bytes];
read_exact_at(file, tail_at, &mut tail)?;
let Some(eocd) = find_eocd(&tail) else {
return Ok(None);
};
let entries = le_u16(&tail, eocd.saturating_add(10))?;
let cd_size = u64::from(le_u32(&tail, eocd.saturating_add(12))?);
let cd_offset = u64::from(le_u32(&tail, eocd.saturating_add(16))?);
if entries == u16::MAX || cd_size == u64::from(u32::MAX) || cd_offset == u64::from(u32::MAX) {
return Err("update archive uses ZIP64, which this check refuses".into());
}
let eocd_at = tail_at.saturating_add(eocd as u64);
let recorded_end = cd_offset
.checked_add(cd_size)
.ok_or_else(|| "update archive central directory is out of range".to_string())?;
let shift = eocd_at
.checked_sub(recorded_end)
.ok_or_else(|| "update archive central directory runs past its end record".to_string())?;
let mut signature = [0u8; 4];
let at_recorded = cd_size == 0
|| (read_exact_at(file, cd_offset, &mut signature).is_ok()
&& signature == [0x50, 0x4b, 0x01, 0x02]);
let base = if at_recorded { 0 } else { shift };
let cd_start = cd_offset
.checked_add(base)
.ok_or_else(|| "update archive central directory is out of range".to_string())?;
let cd_end = recorded_end
.checked_add(base)
.ok_or_else(|| "update archive central directory is out of range".to_string())?;
if cd_end > len {
return Err("update archive central directory runs past the file".into());
}
let mut at = cd_start;
let mut copies = 0u32;
let mut seen = 0u16;
let mut name_and_extra = Vec::new();
while at < cd_end {
let mut header = [0u8; 46];
read_exact_at(file, at, &mut header)?;
if header.get(..4) != Some(&[0x50, 0x4b, 0x01, 0x02]) {
return Err("update archive central directory is truncated".into());
}
let name_len = u64::from(le_u16(&header, 28)?);
let extra_len = u64::from(le_u16(&header, 30)?);
let comment_len = u64::from(le_u16(&header, 32)?);
let step = 46u64
.checked_add(name_len)
.and_then(|n| n.checked_add(extra_len))
.and_then(|n| n.checked_add(comment_len))
.ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
let next = at
.checked_add(step)
.ok_or_else(|| "update archive central directory entry is out of range".to_string())?;
if next > cd_end {
return Err("update archive central directory entry runs past the directory".into());
}
let name_at = at
.checked_add(46)
.ok_or_else(|| "update archive member name is out of range".to_string())?;
let name_bytes = usize::try_from(name_len)
.map_err(|_| "update archive member name is too long".to_string())?;
let extra_bytes = usize::try_from(extra_len)
.map_err(|_| "update archive extra field is too long".to_string())?;
name_and_extra.resize(name_bytes.saturating_add(extra_bytes), 0);
if !name_and_extra.is_empty() {
read_exact_at(file, name_at, &mut name_and_extra)?;
}
let (raw_name, extra) = name_and_extra.split_at(name_bytes);
let flags = le_u16(&header, 8)?;
let name = crate::admission::zip_entry_name_raw(raw_name, flags, extra)
.map_err(|e| format!("update archive member name cannot be read: {e}"))?;
if member_names_match(name.as_bytes(), member) {
copies = copies.saturating_add(1);
}
seen = seen
.checked_add(1)
.ok_or_else(|| "update archive has too many entries".to_string())?;
at = next;
}
if seen != entries {
return Err("update archive central directory does not match its end record".into());
}
Ok(Some(copies))
}
fn find_eocd(tail: &[u8]) -> Option<usize> {
let last = tail.len().checked_sub(22)?;
let mut at = last;
loop {
if tail.get(at..at.checked_add(4)?) == Some(&[0x50, 0x4b, 0x05, 0x06][..]) {
let comment = usize::from(le_u16(tail, at.saturating_add(20)).ok()?);
let end = at.checked_add(22)?.checked_add(comment)?;
if end == tail.len() {
return Some(at);
}
}
if at == 0 {
return None;
}
at = at.saturating_sub(1);
}
}
fn le_u16(bytes: &[u8], at: usize) -> Result<u16, String> {
let mut buf = [0u8; 2];
buf.copy_from_slice(
bytes
.get(
at..at
.checked_add(2)
.ok_or_else(|| "update archive field is out of range".to_string())?,
)
.ok_or_else(|| "update archive field is out of range".to_string())?,
);
Ok(u16::from_le_bytes(buf))
}
fn le_u32(bytes: &[u8], at: usize) -> Result<u32, String> {
let mut buf = [0u8; 4];
buf.copy_from_slice(
bytes
.get(
at..at
.checked_add(4)
.ok_or_else(|| "update archive field is out of range".to_string())?,
)
.ok_or_else(|| "update archive field is out of range".to_string())?,
);
Ok(u32::from_le_bytes(buf))
}
fn member_names_match(entry: &[u8], member: &str) -> bool {
let entry = entry.strip_prefix(b"./").unwrap_or(entry);
if entry.ends_with(b"/") {
return false;
}
let member = member.strip_prefix("./").unwrap_or(member).as_bytes();
entry.len() == member.len()
&& entry
.iter()
.zip(member)
.all(|(got, want)| *got == *want || (*got == b'\\' && *want == b'/'))
}
fn read_exact_at(file: &mut std::fs::File, at: u64, buf: &mut [u8]) -> Result<(), String> {
use std::io::{Read, Seek, SeekFrom};
file.seek(SeekFrom::Start(at))
.map_err(|e| format!("update archive seek failed: {e}"))?;
file.read_exact(buf)
.map_err(|e| format!("update archive read failed: {e}"))
}
fn inflate_member_within_budget(
archive: &std::path::Path,
member: &str,
budget: u64,
) -> Result<(), String> {
use std::io::{Read, copy, sink};
let file = std::fs::File::open(archive)
.map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
let mut zip = zip::ZipArchive::new(file)
.map_err(|e| format!("update archive is not a readable zip: {e}"))?;
let mut matched = None;
for index in 0..zip.len() {
let entry = zip
.by_index(index)
.map_err(|e| format!("update archive entry {index} cannot be read: {e}"))?;
let name = entry
.name()
.map_err(|e| format!("update archive entry {index} has no name: {e}"))?;
if member_names_match(name.as_bytes(), member) {
matched = Some(index);
break;
}
}
let Some(index) = matched else {
return Err(format!("update archive has no member {member}"));
};
let mut entry = zip
.by_index(index)
.map_err(|e| format!("update member {member} cannot be read: {e}"))?;
let inflated = copy(
&mut (&mut entry).take(budget.saturating_add(1)),
&mut sink(),
)
.map_err(|e| format!("update member {member} could not be inflated: {e}"))?;
if inflated > budget {
Err(format!(
"update member {member} inflates past the {budget}-byte budget"
))
} else {
Ok(())
}
}
fn gzip_magic(file: &mut std::fs::File) -> Result<bool, String> {
use std::io::{Read, Seek, SeekFrom};
file.seek(SeekFrom::Start(0))
.map_err(|e| format!("update archive cannot be rewound: {e}"))?;
let mut magic = [0u8; 2];
let read = file
.read(&mut magic)
.map_err(|e| format!("update archive cannot be read: {e}"))?;
Ok(read == 2 && magic == [0x1f, 0x8b])
}
fn confine_update_tar(archive: &std::path::Path, member: &str, budget: u64) -> Result<(), String> {
let file = std::fs::File::open(archive)
.map_err(|e| format!("update archive {} cannot be opened: {e}", archive.display()))?;
let mut decoder = flate2::read::GzDecoder::new(file);
let mut inflated = 0u64;
let mut zero_blocks = 0u8;
let mut copies = 0u32;
let mut long_name: Option<Vec<u8>> = None;
let mut long_link = false;
let mut pax: Option<Vec<u8>> = None;
loop {
let mut header = [0u8; 512];
if !read_tar_block(&mut decoder, &mut header, &mut inflated, budget)? {
break;
}
if header.iter().all(|byte| *byte == 0) {
zero_blocks = zero_blocks.saturating_add(1);
if zero_blocks == 2 {
break;
}
continue;
}
zero_blocks = 0;
if !tar_checksum_ok(&header) {
return Err("update archive is not a tar".into());
}
let typeflag = *header.get(156).unwrap_or(&0);
let extension = matches!(typeflag, b'L' | b'K' | b'x' | b'g');
let mut size = tar_octal(header.get(124..136).unwrap_or(&[]))?;
if !extension
&& let Some(records) = pax.as_deref()
&& let Some(pax_size) = pax_value(records, b"size")?
{
size = std::str::from_utf8(pax_size)
.ok()
.and_then(|text| text.parse::<u64>().ok())
.ok_or_else(|| "update archive PAX size is not a number".to_string())?;
}
if tar_magic_recognized(&header) && matches!(typeflag, b'L' | b'K' | b'x') {
let twice = match typeflag {
b'L' => long_name.is_some(),
b'K' => long_link,
_ => pax.is_some(),
};
if twice {
return Err("update archive describes one member twice".into());
}
let body = read_tar_extension(&mut decoder, size, &mut inflated, budget)?;
match typeflag {
b'L' => long_name = Some(body),
b'K' => long_link = true,
_ => pax = Some(body),
}
continue;
}
let name_bytes = match long_name.take() {
Some(mut bytes) => {
if bytes.last() == Some(&0) {
bytes.pop();
}
bytes
}
None => match pax.as_deref().map(|records| pax_value(records, b"path")) {
Some(Ok(Some(path))) => path.to_vec(),
Some(Err(e)) => return Err(e),
_ => tar_entry_name(&header)?.into_bytes(),
},
};
pax = None;
long_link = false;
let name = String::from_utf8(name_bytes)
.map_err(|_| "update archive tar name is not UTF-8".to_string())?;
if tar_name_escapes(&name) {
return Err(format!(
"update archive entry {name} escapes the extraction directory"
));
}
let mode = tar_octal(header.get(100..108).unwrap_or(&[]))?;
if member_names_match(name.as_bytes(), member) {
match typeflag {
b'2' => return Err(format!("update member {member} is a symlink")),
b'1' => return Err(format!("update member {member} is a hardlink")),
b'0' | 0 => {}
_ => {
return Err(format!("update member {member} is not a regular file"));
}
}
if mode & 0o7000 != 0 {
return Err(format!(
"update member {member} mode {mode:o} carries setuid, setgid, or sticky bits"
));
}
copies = copies.saturating_add(1);
}
skip_tar_body(&mut decoder, size, &mut inflated, budget)?;
}
if long_name.is_some() || long_link || pax.is_some() {
return Err("update archive describes a member that never follows".into());
}
if copies > 1 {
return Err(format!("update archive lists {member} more than once"));
}
if copies == 0 {
return Err(format!("update archive has no member {member}"));
}
Ok(())
}
fn tar_magic_recognized(header: &[u8; 512]) -> bool {
let magic = header.get(257..263).unwrap_or(&[]);
let version = header.get(263..265).unwrap_or(&[]);
(magic == b"ustar\0" && version == b"00") || (magic == b"ustar " && version == b" \0")
}
const TAR_EXTENSION_LIMIT: u64 = 1 << 20;
fn read_tar_extension(
reader: &mut impl std::io::Read,
size: u64,
inflated: &mut u64,
budget: u64,
) -> Result<Vec<u8>, String> {
if size > TAR_EXTENSION_LIMIT {
return Err(format!(
"update archive extension header of {size} bytes exceeds {TAR_EXTENSION_LIMIT}"
));
}
let len = usize::try_from(size)
.map_err(|_| "update archive extension header is too large".to_string())?;
let mut body = vec![0u8; len];
read_exact_capped(reader, &mut body, inflated, budget)?;
let pad = (512 - size % 512) % 512;
let mut padding = [0u8; 512];
let pad_len = usize::try_from(pad).unwrap_or(0);
read_exact_capped(
reader,
padding
.get_mut(..pad_len)
.ok_or_else(|| "update archive tar padding is out of range".to_string())?,
inflated,
budget,
)?;
Ok(body)
}
fn pax_value<'a>(records: &'a [u8], key: &[u8]) -> Result<Option<&'a [u8]>, String> {
let malformed = || "update archive PAX header is malformed".to_string();
let mut rest = records;
while !rest.is_empty() {
let space = rest
.iter()
.position(|byte| *byte == b' ')
.ok_or_else(malformed)?;
let len = std::str::from_utf8(rest.get(..space).ok_or_else(malformed)?)
.ok()
.and_then(|text| text.parse::<usize>().ok())
.ok_or_else(malformed)?;
let record = rest.get(..len).ok_or_else(malformed)?;
let body = record
.get(space.saturating_add(1)..)
.and_then(|body| body.strip_suffix(b"\n"))
.ok_or_else(malformed)?;
let equals = body
.iter()
.position(|byte| *byte == b'=')
.ok_or_else(malformed)?;
if body.get(..equals) == Some(key) {
return Ok(body.get(equals.saturating_add(1)..));
}
rest = rest.get(len..).ok_or_else(malformed)?;
}
Ok(None)
}
fn read_tar_block(
reader: &mut impl std::io::Read,
header: &mut [u8; 512],
inflated: &mut u64,
budget: u64,
) -> Result<bool, String> {
let mut filled = 0usize;
while filled < header.len() {
if *inflated >= budget {
return Err(format!(
"update archive inflates past the {budget}-byte budget"
));
}
let room = budget.saturating_sub(*inflated);
let want = u64::try_from(header.len().saturating_sub(filled)).unwrap_or(u64::MAX);
let take = usize::try_from(room.min(want)).unwrap_or(0);
if take == 0 {
return Err(format!(
"update archive inflates past the {budget}-byte budget"
));
}
let end = filled.saturating_add(take);
let read = reader
.read(
header
.get_mut(filled..end)
.ok_or_else(|| "update archive tar header is out of range".to_string())?,
)
.map_err(|e| format!("update archive could not be inflated: {e}"))?;
if read == 0 {
if filled == 0 {
return Ok(false);
}
return Err("update archive ended inside a tar header".into());
}
filled = filled.saturating_add(read);
*inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
}
Ok(true)
}
fn skip_tar_body(
reader: &mut impl std::io::Read,
size: u64,
inflated: &mut u64,
budget: u64,
) -> Result<(), String> {
let padded = size
.checked_add(511)
.ok_or_else(|| "update archive tar member is too large".to_string())?
/ 512
* 512;
let mut left = padded;
let mut buf = [0u8; 8192];
while left > 0 {
let take = usize::try_from(left.min(8192)).unwrap_or(8192);
let dest = buf
.get_mut(..take)
.ok_or_else(|| "update archive tar member is out of range".to_string())?;
read_exact_capped(reader, dest, inflated, budget)?;
left = left.saturating_sub(u64::try_from(take).unwrap_or(left));
}
Ok(())
}
fn read_exact_capped(
reader: &mut impl std::io::Read,
buf: &mut [u8],
inflated: &mut u64,
budget: u64,
) -> Result<(), String> {
let mut filled = 0usize;
while filled < buf.len() {
if *inflated >= budget {
return Err(format!(
"update archive inflates past the {budget}-byte budget"
));
}
let room = budget.saturating_sub(*inflated);
let want = u64::try_from(buf.len().saturating_sub(filled)).unwrap_or(u64::MAX);
let take = usize::try_from(room.min(want)).unwrap_or(0);
if take == 0 {
return Err(format!(
"update archive inflates past the {budget}-byte budget"
));
}
let end = filled.saturating_add(take);
let read = reader
.read(
buf.get_mut(filled..end)
.ok_or_else(|| "update archive tar body is out of range".to_string())?,
)
.map_err(|e| format!("update archive could not be inflated: {e}"))?;
if read == 0 {
return Err("update archive ended inside a tar member".into());
}
filled = filled.saturating_add(read);
*inflated = inflated.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
}
Ok(())
}
fn tar_checksum_ok(header: &[u8; 512]) -> bool {
let mut sum = 0u32;
for (index, byte) in header.iter().enumerate() {
if (148..156).contains(&index) {
sum += u32::from(b' ');
} else {
sum += u32::from(*byte);
}
}
tar_octal(header.get(148..156).unwrap_or(&[])).ok() == Some(u64::from(sum))
}
fn tar_entry_name(header: &[u8; 512]) -> Result<String, String> {
let name = tar_c_string(header.get(..100).unwrap_or(&[]))?;
let ustar = header.get(257..263) == Some(b"ustar\0") && header.get(263..265) == Some(b"00");
if !ustar {
return Ok(name);
}
let prefix = tar_c_string(header.get(345..500).unwrap_or(&[]))?;
if prefix.is_empty() {
Ok(name)
} else {
Ok(format!("{prefix}/{name}"))
}
}
fn tar_c_string(bytes: &[u8]) -> Result<String, String> {
let end = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
let text = bytes.get(..end).unwrap_or(&[]);
String::from_utf8(text.to_vec()).map_err(|_| "update archive tar name is not UTF-8".to_string())
}
fn tar_octal(bytes: &[u8]) -> Result<u64, String> {
let end = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
let text = bytes.get(..end).unwrap_or(&[]).trim_ascii();
let text = text.strip_prefix(b"+").unwrap_or(text);
if text.is_empty() {
return Err("update archive tar field is not octal".into());
}
let mut value = 0u64;
for byte in text {
let digit = byte
.checked_sub(b'0')
.filter(|digit| *digit < 8)
.ok_or_else(|| "update archive tar field is not octal".to_string())?;
value = value
.checked_mul(8)
.and_then(|next| next.checked_add(u64::from(digit)))
.ok_or_else(|| "update archive tar field is out of range".to_string())?;
}
Ok(value)
}
fn tar_name_escapes(name: &str) -> bool {
use std::path::{Component, Path};
if name.starts_with('/') || name.starts_with('\\') {
return true;
}
if name.split(['/', '\\']).any(|part| part == "..") {
return true;
}
Path::new(name).components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
})
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn asset_targets_match_the_release_workflow_archives() {
let glibc = |os, arch| asset_target_for(os, arch, false);
assert_eq!(glibc("macos", "aarch64"), Some("macos-aarch64"));
assert_eq!(glibc("macos", "x86_64"), Some("macos-x86_64"));
assert_eq!(glibc("linux", "aarch64"), Some("linux-aarch64"));
assert_eq!(glibc("linux", "x86_64"), Some("linux-x86_64"));
assert_eq!(glibc("windows", "x86_64"), Some("windows-x86_64"));
assert_eq!(glibc("windows", "aarch64"), None);
assert_eq!(glibc("freebsd", "x86_64"), None);
assert!(asset_target().is_some(), "every CI host has an archive");
}
#[test]
fn a_musl_build_looks_up_the_musl_archive() {
assert_eq!(
asset_target_for("linux", "x86_64", true),
Some("linux-musl-x86_64")
);
assert_eq!(
asset_target_for("linux", "aarch64", true),
Some("linux-musl-aarch64")
);
assert_eq!(asset_target_for("macos", "aarch64", true), None);
}
const PUBLISHED_ARCHIVES: [&str; 7] = [
"linux-x86_64",
"linux-aarch64",
"linux-musl-x86_64",
"linux-musl-aarch64",
"macos-x86_64",
"macos-aarch64",
"windows-x86_64",
];
#[test]
fn each_target_selects_its_own_archive_among_the_published_ones() {
for order in [
PUBLISHED_ARCHIVES.to_vec(),
PUBLISHED_ARCHIVES.iter().rev().copied().collect(),
] {
let release = self_update::update::Release::builder()
.version("9.9.9")
.assets(order.iter().map(|name| {
self_update::update::ReleaseAsset::new(
format!("jubarte-9.9.9-{name}.zip"),
format!("https://example.invalid/{name}"),
)
}))
.build()
.expect("release");
for name in PUBLISHED_ARCHIVES {
let asset = release.asset_for(name, None).expect(name);
assert_eq!(asset.name(), format!("jubarte-9.9.9-{name}.zip"));
}
}
}
#[test]
fn a_suffixed_musl_name_would_steal_the_glibc_lookup() {
let release = self_update::update::Release::builder()
.version("9.9.9")
.assets(["linux-x86_64-musl", "linux-x86_64"].map(|name| {
self_update::update::ReleaseAsset::new(
format!("jubarte-9.9.9-{name}.zip"),
format!("https://example.invalid/{name}"),
)
}))
.build()
.expect("release");
let asset = release.asset_for("linux-x86_64", None).expect("asset");
assert_eq!(asset.name(), "jubarte-9.9.9-linux-x86_64-musl.zip");
}
#[test]
fn archive_binary_path_names_the_staged_folder() {
let path = bin_path_in_archive("macos-aarch64");
assert_eq!(
path,
format!(
"jubarte-{{{{ version }}}}-macos-aarch64/jubarte{}",
std::env::consts::EXE_SUFFIX
)
);
assert!(path.contains("{{ version }}"));
}
#[test]
fn without_a_terminal_only_check_or_yes_proceed() {
let ask = Options::default();
assert!(preflight(&ask, false).is_err());
assert!(preflight(&ask, true).is_ok());
let check = Options {
check: true,
..Options::default()
};
assert!(preflight(&check, false).is_ok());
let yes = Options {
yes: true,
..Options::default()
};
assert!(preflight(&yes, false).is_ok());
let pinned = Options {
version: Some("0.9.3".into()),
..Options::default()
};
assert!(preflight(&pinned, false).is_err());
}
#[test]
fn check_reports_and_never_installs() {
let install = Plan::Install {
from: "0.10.0".into(),
to: "0.11.0".into(),
};
let look = Options {
check: true,
..Options::default()
};
assert_eq!(
step(&look, &install, "0.11.0"),
Step::Report {
text: "jubarte 0.10.0 is installed; 0.11.0 is available. Run `jubarte self-update` to install it.".into()
}
);
let look_yes = Options {
check: true,
yes: true,
..Options::default()
};
assert!(matches!(
step(&look_yes, &install, "0.11.0"),
Step::Report { .. }
));
assert_eq!(
step(&Options::default(), &install, "0.11.0"),
Step::Install {
from: "0.10.0".into(),
to: "0.11.0".into()
}
);
let up_to_date = Plan::UpToDate {
current: "0.11.0".into(),
};
for opts in [
look,
look_yes,
Options {
yes: true,
..Options::default()
},
Options::default(),
] {
assert!(matches!(
step(&opts, &up_to_date, "0.11.0"),
Step::Report { .. }
));
}
}
#[test]
fn latest_installs_only_when_newer() {
assert_eq!(
plan("0.9.3", "v0.10.0", false),
Ok(Plan::Install {
from: "0.9.3".into(),
to: "0.10.0".into()
})
);
assert_eq!(
plan("0.10.0", "0.10.0", false),
Ok(Plan::UpToDate {
current: "0.10.0".into()
})
);
assert_eq!(
plan("0.11.0", "0.10.0", false),
Ok(Plan::UpToDate {
current: "0.11.0".into()
})
);
}
#[test]
fn a_requested_version_installs_even_when_older() {
assert_eq!(
plan("0.10.0", "0.9.3", true),
Ok(Plan::Install {
from: "0.10.0".into(),
to: "0.9.3".into()
})
);
assert_eq!(
plan("0.9.3", "v0.9.3", true),
Ok(Plan::UpToDate {
current: "0.9.3".into()
})
);
}
#[test]
fn a_non_semver_tag_is_an_error() {
assert!(plan("0.10.0", "nightly", false).is_err());
}
#[test]
fn without_keys_no_signature_is_required() {
for (target, first) in [
("0.12.0", Some("0.11.0")),
("0.11.0", Some("0.11.0")),
("0.9.0", Some("0.11.0")),
("0.12.0", None),
] {
assert_eq!(
signature_required(target, first, false),
Ok(false),
"{target} with first signed {first:?}"
);
}
}
#[test]
fn keys_without_a_first_signed_release_require_nothing() {
assert_eq!(signature_required("0.12.0", None, true), Ok(false));
assert_eq!(signature_required("v0.12.0", None, true), Ok(false));
}
#[test]
fn the_first_signed_release_and_later_ones_require_a_signature() {
let first = Some("0.11.0");
assert_eq!(signature_required("0.11.0", first, true), Ok(true));
assert_eq!(signature_required("v0.11.0", first, true), Ok(true));
assert_eq!(signature_required("0.11.1", first, true), Ok(true));
assert_eq!(signature_required("v1.0.0", first, true), Ok(true));
assert_eq!(
signature_required("0.11.0", Some("v0.11.0"), true),
Ok(true)
);
}
#[test]
fn releases_before_the_first_signed_one_are_checksum_only() {
let first = Some("0.11.0");
assert_eq!(signature_required("0.10.1", first, true), Ok(false));
assert_eq!(signature_required("v0.10.1", first, true), Ok(false));
assert_eq!(signature_required("0.11.0-rc.1", first, true), Ok(false));
}
#[test]
fn a_non_semver_version_is_an_error_when_signing_is_on() {
assert!(signature_required("nightly", Some("0.11.0"), true).is_err());
assert!(signature_required("0.11.0", Some("next"), true).is_err());
}
#[test]
fn the_shipped_key_set_and_threshold_agree() {
assert_eq!(
FIRST_SIGNED_RELEASE.is_some(),
!RELEASE_KEYS.is_empty(),
"set FIRST_SIGNED_RELEASE and RELEASE_KEYS together"
);
if let Some(first) = FIRST_SIGNED_RELEASE {
assert!(!first.starts_with('v'), "write {first} without the v");
assert_eq!(signature_required(first, Some(first), true), Ok(true));
}
}
#[test]
fn a_special_extracted_binary_is_refused_before_the_swap() {
let dir = tempfile::tempdir().unwrap();
let regular = dir.path().join("jubarte");
std::fs::write(®ular, b"binary").unwrap();
extracted_binary_is_regular_file(®ular).expect("a regular file installs");
extracted_binary_is_regular_file(dir.path())
.expect_err("a directory at the extracted path must be refused");
#[cfg(unix)]
{
let link = dir.path().join("linked");
std::os::unix::fs::symlink(®ular, &link).unwrap();
extracted_binary_is_regular_file(&link)
.expect_err("a symlink at the extracted path must be refused");
let dangling = dir.path().join("dangling");
std::os::unix::fs::symlink(dir.path().join("no-such-target"), &dangling).unwrap();
extracted_binary_is_regular_file(&dangling)
.expect_err("a dangling symlink must be refused too");
}
}
const UPDATE_MEMBER: &str = "jubarte-9.9.9-windows-x86_64/jubarte.exe";
fn write_update_archive(dir: &std::path::Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
path
}
fn deflated_update_zip(member: &str, payload: &[u8]) -> Vec<u8> {
use std::io::Write;
let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let options: zip::write::FullFileOptions<'_, '_> =
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
writer.start_file(member, options).expect("start member");
writer.write_all(payload).expect("write member");
writer.finish().expect("finish zip").into_inner()
}
#[test]
fn update_archive_over_the_download_budget_is_refused() {
let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let budget = (bytes.len() as u64).saturating_sub(1);
let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
.expect_err("an archive larger than the download budget was accepted");
assert!(
err.contains("download budget"),
"the refusal must name the download budget, got {err}"
);
}
#[test]
fn update_archive_inflation_is_capped() {
let payload = vec![0u8; 8_000];
let bytes = deflated_update_zip(UPDATE_MEMBER, &payload);
assert!(
bytes.len() < payload.len(),
"the fixture must be smaller on disk than the member it inflates to, got {} bytes",
bytes.len()
);
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let budget = bytes.len() as u64;
let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
.expect_err("an inflated member past the budget was extracted with no cap");
assert!(
err.contains("inflates past"),
"the refusal must name the inflation cap, got {err}"
);
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
1,
"a refused archive must stay the only file in the directory"
);
}
#[test]
fn update_archive_duplicate_member_is_refused() {
let name = UPDATE_MEMBER.as_bytes();
let bytes = crate::admission::zip_names::zip(&[
crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
]);
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("an archive that lists the expected member twice was accepted");
assert!(
err.contains("more than once"),
"the refusal must name the repeated member, got {err}"
);
}
fn prefixed(prefix_len: usize, zip: &[u8]) -> Vec<u8> {
let mut out = vec![0xA5u8; prefix_len];
out.extend_from_slice(zip);
out
}
#[test]
fn update_archive_with_a_prefix_still_refuses_a_repeated_member() {
let name = UPDATE_MEMBER.as_bytes();
let bytes = prefixed(
64,
&crate::admission::zip_names::zip(&[
crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
crate::admission::zip_names::RawEntry::raw(name, b"SECOND"),
]),
);
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a prefixed archive skipped the repeated-member check");
assert!(err.contains("more than once"), "{err}");
}
#[test]
fn update_archive_with_a_prefix_still_caps_inflation() {
let payload = vec![0u8; 8_000];
let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, &payload));
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let budget = bytes.len() as u64;
let err = confine_update_zip(&archive, UPDATE_MEMBER, budget)
.expect_err("a prefixed archive skipped the inflation cap");
assert!(err.contains("inflates past"), "{err}");
}
#[test]
fn update_archive_with_a_prefix_and_one_member_is_allowed() {
let bytes = prefixed(64, &deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte"));
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("a signed (prefixed) release zip with one member");
}
#[test]
fn update_archive_unicode_path_copy_is_a_repeated_member() {
let name = UPDATE_MEMBER.as_bytes();
let bytes = crate::admission::zip_names::zip(&[
crate::admission::zip_names::RawEntry::raw(name, b"FIRST"),
crate::admission::zip_names::RawEntry::raw(b"decoy.bin", b"SECOND").unicode_path(name),
]);
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
let err = confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a Unicode Path copy of the member was not counted");
assert!(err.contains("more than once"), "{err}");
}
#[test]
fn update_archive_single_member_is_allowed() {
let bytes = deflated_update_zip(UPDATE_MEMBER, b"#!/jubarte");
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", &bytes);
confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("one member inside the budget is the release zip");
}
#[test]
fn update_archive_non_zip_inside_budget_is_allowed() {
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.tar.gz", b"not a zip");
confine_update_zip(&archive, UPDATE_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("a tar.gz inside the download budget is not a zip refusal");
}
const TAR_MEMBER: &str = "jubarte-9.9.9-linux-x86_64/jubarte";
fn tar_header(name: &str, typeflag: u8, mode: u32, size: u64, link: &str) -> [u8; 512] {
let mut header = [0u8; 512];
let name_bytes = name.as_bytes();
assert!(name_bytes.len() < 100, "tar name fits the ustar field");
header[..name_bytes.len()].copy_from_slice(name_bytes);
let mode_text = format!("{mode:07o}");
header[100..100 + mode_text.len()].copy_from_slice(mode_text.as_bytes());
let size_text = format!("{size:011o}");
header[124..124 + size_text.len()].copy_from_slice(size_text.as_bytes());
header[136..147].copy_from_slice(b"00000000000");
header[156] = typeflag;
let link_bytes = link.as_bytes();
assert!(
link_bytes.len() < 100,
"tar link target fits the ustar field"
);
header[157..157 + link_bytes.len()].copy_from_slice(link_bytes);
header[257..263].copy_from_slice(b"ustar\0");
header[263..265].copy_from_slice(b"00");
tar_reseal(&mut header);
header
}
fn tar_reseal(header: &mut [u8; 512]) {
let mut sum = 0u32;
for (index, byte) in header.iter().enumerate() {
if (148..156).contains(&index) {
sum += u32::from(b' ');
} else {
sum += u32::from(*byte);
}
}
let checksum = format!("{sum:06o}\0 ");
header[148..156].copy_from_slice(checksum.as_bytes());
}
fn pax_record(key: &str, value: &str) -> Vec<u8> {
let body = format!(" {key}={value}\n");
let mut len = body.len() + 1;
while format!("{len}").len() + body.len() != len {
len += 1;
}
format!("{len}{body}").into_bytes()
}
fn gzip_tar(entries: &[([u8; 512], &[u8])]) -> Vec<u8> {
use std::io::Write;
let mut raw = Vec::new();
for (header, body) in entries {
raw.extend_from_slice(header);
raw.extend_from_slice(body);
let pad = (512 - (body.len() % 512)) % 512;
raw.extend(std::iter::repeat_n(0u8, pad));
}
raw.extend_from_slice(&[0u8; 1024]);
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(&raw).expect("gzip");
encoder.finish().expect("finish gzip")
}
fn tar_archive(dir: &std::path::Path, entries: &[([u8; 512], &[u8])]) -> std::path::PathBuf {
write_update_archive(dir, "jubarte.tar.gz", &gzip_tar(entries))
}
#[test]
fn update_tar_symlink_member_is_refused() {
let header = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &[][..])]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a tar.gz symlink member was accepted");
assert!(
err.contains("symlink"),
"the refusal must name the symlink, got {err}"
);
}
#[test]
fn update_tar_hardlink_member_is_refused() {
let header = tar_header(TAR_MEMBER, b'1', 0o644, 0, "other");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &[][..])]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a tar.gz hardlink member was accepted");
assert!(
err.contains("hardlink"),
"the refusal must name the hardlink, got {err}"
);
}
#[test]
fn update_tar_setuid_member_is_refused() {
let body = b"#!/jubarte";
let header = tar_header(TAR_MEMBER, b'0', 0o4755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &body[..])]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a setuid tar member was accepted");
assert!(
err.contains("setuid"),
"the refusal must name the setuid bit, got {err}"
);
}
#[test]
fn update_tar_escaping_entry_is_refused() {
let body = b"#!/jubarte";
let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let escape = tar_header("../outside", b'0', 0o644, 1, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a tar entry that climbs out of the extract directory was accepted");
assert!(
err.contains("escapes"),
"the refusal must name the escaping path, got {err}"
);
}
#[test]
fn update_tar_pax_path_symlink_is_refused() {
let body = b"#!/jubarte";
let pax = pax_record("path", TAR_MEMBER);
let pax_header = tar_header("PaxHeaders/other", b'x', 0o644, pax.len() as u64, "");
let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(
dir.path(),
&[(pax_header, &pax[..]), (link, &[][..]), (decoy, &body[..])],
);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a symlink named by a PAX path record was accepted");
assert!(err.contains("symlink"), "got {err}");
}
#[test]
fn update_tar_gnu_long_name_symlink_is_refused() {
let body = b"#!/jubarte";
let mut long = TAR_MEMBER.as_bytes().to_vec();
long.push(0);
let long_header = tar_header("././@LongLink", b'L', 0o644, long.len() as u64, "");
let link = tar_header("other", b'2', 0o777, 0, "/tmp/outside");
let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(
dir.path(),
&[
(long_header, &long[..]),
(link, &[][..]),
(decoy, &body[..]),
],
);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a symlink named by a GNU long name was accepted");
assert!(err.contains("symlink"), "got {err}");
}
#[test]
fn update_tar_pax_size_cannot_hide_a_member() {
let body = b"#!/jubarte";
let pax = pax_record("size", "0");
let pax_header = tar_header("PaxHeaders/pad", b'x', 0o644, pax.len() as u64, "");
let hidden = tar_header(TAR_MEMBER, b'2', 0o777, 0, "/tmp/outside");
let pad = tar_header("pad", b'0', 0o644, 512, "");
let decoy = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(
dir.path(),
&[
(pax_header, &pax[..]),
(pad, &hidden[..]),
(decoy, &body[..]),
],
);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a member hidden behind a PAX size was accepted");
assert!(err.contains("symlink"), "got {err}");
}
#[test]
fn update_tar_space_led_setuid_mode_is_refused() {
let body = b"#!/jubarte";
let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
header[100..108].copy_from_slice(b" 4755\0\0");
tar_reseal(&mut header);
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &body[..])]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a blank-led setuid mode was accepted");
assert!(err.contains("setuid"), "got {err}");
}
#[test]
fn update_tar_nul_led_size_is_refused() {
let body = b"#!/jubarte";
let mut header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
header[124..136].copy_from_slice(b"\x0000000000012");
tar_reseal(&mut header);
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &body[..])]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a NUL-led size field was accepted");
assert!(err.contains("octal"), "got {err}");
}
#[test]
fn update_tar_backslash_parent_entry_is_refused() {
let body = b"#!/jubarte";
let binary = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let escape = tar_header("jubarte-9.9.9\\..\\..\\outside", b'0', 0o644, 1, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(binary, &body[..]), (escape, b"x")]);
let err = confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect_err("a backslash .. entry was accepted");
assert!(err.contains("escapes"), "got {err}");
}
#[test]
fn update_tar_pax_path_regular_member_is_allowed() {
let body = b"#!/jubarte";
let mut pax = pax_record("mtime", "1700000000.5");
pax.extend(pax_record("path", TAR_MEMBER));
let pax_header = tar_header("PaxHeaders/jubarte", b'x', 0o644, pax.len() as u64, "");
let binary = tar_header("short-name", b'0', 0o755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(pax_header, &pax[..]), (binary, &body[..])]);
confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("a regular member named by a PAX path is the release archive");
}
#[test]
fn update_tar_regular_member_is_allowed() {
let body = b"#!/jubarte";
let header = tar_header(TAR_MEMBER, b'0', 0o755, body.len() as u64, "");
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), &[(header, &body[..])]);
confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("a regular tar member inside the budget is the release archive");
let fixture = dir.path().join("unsigned.tar.gz");
std::fs::write(
&fixture,
include_bytes!("../../../tests/data/self_update/unsigned.tar.gz"),
)
.unwrap();
confine_update_zip(&fixture, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("the signed-update fixture tar is a regular member");
}
fn gzip_raw(raw: &[u8]) -> Vec<u8> {
use std::io::Write;
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(raw).expect("gzip");
encoder.finish().expect("finish gzip")
}
fn confine_tar(entries: &[([u8; 512], &[u8])], budget: u64) -> Result<(), String> {
let dir = tempfile::tempdir().unwrap();
let archive = tar_archive(dir.path(), entries);
confine_update_zip(&archive, TAR_MEMBER, budget)
}
fn confine_raw(raw: &[u8]) -> Result<(), String> {
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.tar.gz", &gzip_raw(raw));
confine_update_zip(&archive, TAR_MEMBER, UPDATE_ARCHIVE_BYTE_BUDGET)
}
fn gnu(mut header: [u8; 512]) -> [u8; 512] {
header[257..263].copy_from_slice(b"ustar ");
header[263..265].copy_from_slice(b" \0");
tar_reseal(&mut header);
header
}
#[test]
fn update_tar_header_damage_is_refused() {
let mut bad = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
bad[148] ^= 1;
let err = confine_tar(&[(bad, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert_eq!(err, "update archive is not a tar");
let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
let err = confine_raw(&header[..100]).unwrap_err();
assert_eq!(err, "update archive ended inside a tar header");
let big = tar_header(TAR_MEMBER, b'0', 0o755, 600, "");
let mut raw = big.to_vec();
raw.extend_from_slice(&[7u8; 100]);
assert_eq!(
confine_raw(&raw).unwrap_err(),
"update archive ended inside a tar member"
);
for budget in [200, 520] {
let err = confine_tar(&[(header, &b"x"[..])], budget).unwrap_err();
assert!(
err.contains(&format!("inflates past the {budget}-byte budget")),
"{err}"
);
}
}
#[test]
fn update_tar_member_count_must_be_one() {
let member = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
let err = confine_tar(
&[(member, &b"x"[..]), (member, &b"x"[..])],
UPDATE_ARCHIVE_BYTE_BUDGET,
)
.unwrap_err();
assert!(err.contains("more than once"), "{err}");
let other = tar_header("README", b'0', 0o644, 1, "");
let err = confine_tar(&[(other, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("has no member"), "{err}");
}
#[test]
fn update_tar_long_names_name_the_next_member_once() {
let long_body = format!("{TAR_MEMBER}\0");
let long = gnu(tar_header(
"././@LongLink",
b'L',
0o644,
long_body.len() as u64,
"",
));
let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
confine_tar(
&[(long, long_body.as_bytes()), (plain, &b"x"[..])],
UPDATE_ARCHIVE_BYTE_BUDGET,
)
.expect("a GNU long name naming the member is the member");
let err = confine_tar(
&[
(long, long_body.as_bytes()),
(long, long_body.as_bytes()),
(plain, &b"x"[..]),
],
UPDATE_ARCHIVE_BYTE_BUDGET,
)
.unwrap_err();
assert!(err.contains("one member twice"), "{err}");
let err =
confine_tar(&[(long, long_body.as_bytes())], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("never follows"), "{err}");
let huge = tar_header("././@LongLink", b'L', 0o644, TAR_EXTENSION_LIMIT + 1, "");
let err = confine_tar(&[(huge, &b""[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("exceeds"), "{err}");
let mut unmarked = tar_header("././@LongLink", b'L', 0o644, long_body.len() as u64, "");
unmarked[257..265].fill(0);
tar_reseal(&mut unmarked);
let err = confine_tar(
&[(unmarked, long_body.as_bytes())],
UPDATE_ARCHIVE_BYTE_BUDGET,
)
.unwrap_err();
assert!(err.contains("has no member"), "{err}");
}
#[test]
fn update_tar_ustar_prefix_joins_the_name() {
let (prefix, name) = TAR_MEMBER.split_once('/').unwrap();
let mut header = tar_header(name, b'0', 0o755, 1, "");
header[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes());
tar_reseal(&mut header);
confine_tar(&[(header, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET)
.expect("prefix/name is the member");
let absolute = tar_header("/etc/jubarte", b'0', 0o755, 1, "");
let err = confine_tar(&[(absolute, &b"x"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("escapes"), "{err}");
assert!(tar_name_escapes("\\jubarte"));
assert!(!tar_name_escapes("dir/jubarte"));
}
#[test]
fn tar_fields_parse_as_the_tar_crate_reads_them() {
assert_eq!(tar_octal(b" +17 \0junk"), Ok(15));
assert!(tar_octal(b" \0").is_err());
assert!(tar_octal(b"9").is_err());
assert!(tar_octal(b"7777777777777777777777777").is_err());
assert_eq!(pax_value(&pax_record("path", "a"), b"size"), Ok(None));
assert_eq!(
pax_value(b"x", b"path").unwrap_err(),
"update archive PAX header is malformed"
);
assert!(pax_value(b"9 path\n", b"path").is_err());
}
fn stored_zip(members: &[&str], comment: &str) -> Vec<u8> {
use std::io::Write;
let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let options: zip::write::FullFileOptions<'_, '_> =
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
for member in members {
if let Some(dir) = member.strip_suffix('/') {
writer
.add_directory(dir, options.clone())
.expect("directory");
} else {
writer
.start_file(*member, options.clone())
.expect("start member");
writer.write_all(b"binary").expect("write member");
}
}
writer.set_comment(comment).unwrap();
writer.finish().expect("finish zip").into_inner()
}
fn confine_bytes(bytes: &[u8]) -> Result<(), String> {
let dir = tempfile::tempdir().unwrap();
let archive = write_update_archive(dir.path(), "jubarte.zip", bytes);
confine_update_zip(&archive, "jubarte.exe", UPDATE_ARCHIVE_BYTE_BUDGET)
}
fn eocd(bytes: &[u8]) -> usize {
bytes.len() - 22
}
fn central(bytes: &[u8]) -> usize {
let at = eocd(bytes);
u32::from_le_bytes(bytes[at + 16..at + 20].try_into().unwrap()) as usize
}
#[test]
fn update_zip_directory_damage_is_refused() {
let good = stored_zip(&["bin/", "jubarte.exe"], "");
confine_bytes(&good).expect("one regular member");
confine_bytes(&stored_zip(&["jubarte.exe"], "signed by nobody")).expect("commented zip");
let mut zip64 = good.clone();
let at = eocd(&zip64);
zip64[at + 10..at + 12].copy_from_slice(&u16::MAX.to_le_bytes());
assert!(confine_bytes(&zip64).unwrap_err().contains("ZIP64"));
let mut count = good.clone();
let at = eocd(&count);
count[at + 10..at + 12].copy_from_slice(&3u16.to_le_bytes());
assert!(
confine_bytes(&count)
.unwrap_err()
.contains("does not match its end record")
);
let mut torn = good.clone();
let cd = central(&torn);
torn[cd] = b'X';
assert!(
confine_bytes(&torn)
.unwrap_err()
.contains("central directory is truncated")
);
let mut long = good.clone();
let cd = central(&long);
long[cd + 28..cd + 30].copy_from_slice(&u16::MAX.to_le_bytes());
assert!(
confine_bytes(&long)
.unwrap_err()
.contains("runs past the directory")
);
let mut empty = vec![0x50, 0x4b, 0x05, 0x06];
empty.extend_from_slice(&[0u8; 18]);
assert!(confine_bytes(&empty).unwrap_err().contains("has no member"));
}
#[test]
fn update_files_that_are_not_zips_are_told_apart() {
let err = confine_bytes(b"PK\x03\x04 not really a zip").unwrap_err();
assert_eq!(err, "update archive has no zip end record");
confine_bytes(b"P").expect("a one-byte file is no archive this gate knows");
assert!(member_names_match(b"./bin\\jubarte", "bin/jubarte"));
assert!(!member_names_match(b"bin/", "bin/"));
assert!(!member_names_match(b"bin/jubartf", "bin/jubarte"));
}
#[test]
fn update_tar_extensions_left_dangling_or_unterminated() {
let long = gnu(tar_header(
"././@LongLink",
b'L',
0o644,
TAR_MEMBER.len() as u64,
"",
));
let plain = gnu(tar_header("short", b'0', 0o755, 1, ""));
confine_tar(
&[(long, TAR_MEMBER.as_bytes()), (plain, &b"x"[..])],
UPDATE_ARCHIVE_BYTE_BUDGET,
)
.expect("a long name without its NUL still names the member");
let link = gnu(tar_header("././@LongLink", b'K', 0o644, 4, ""));
let err = confine_tar(&[(link, &b"dest"[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("never follows"), "{err}");
let records = pax_record("comment", "x");
let pax = tar_header("pax", b'x', 0o644, records.len() as u64, "");
let err = confine_tar(&[(pax, &records[..])], UPDATE_ARCHIVE_BYTE_BUDGET).unwrap_err();
assert!(err.contains("never follows"), "{err}");
let header = tar_header(TAR_MEMBER, b'0', 0o755, 1, "");
let mut raw = header.to_vec();
raw.extend_from_slice(&[b'x'; 512]);
confine_raw(&raw).expect("a clean end after a whole member");
}
#[test]
fn update_zip_end_records_hidden_or_impossible() {
let fake = format!("PK\u{5}\u{6}{}", "z".repeat(30));
confine_bytes(&stored_zip(&["jubarte.exe"], &fake)).expect("the real end record is found");
let good = stored_zip(&["jubarte.exe"], "");
for field in [12, 16] {
let mut zip64 = good.clone();
let at = eocd(&zip64);
zip64[at + field..at + field + 4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(
confine_bytes(&zip64).unwrap_err().contains("ZIP64"),
"{field}"
);
}
let mut nameless = good.clone();
let cd = central(&nameless);
let name_len = nameless[cd + 28..cd + 30].to_vec();
nameless[cd + 28..cd + 30].copy_from_slice(&[0, 0]);
nameless[cd + 30..cd + 32].copy_from_slice(&[0, 0]);
nameless[cd + 32..cd + 34].copy_from_slice(&name_len);
assert!(
confine_bytes(&nameless)
.unwrap_err()
.contains("has no member")
);
}
}