fix: validate the portable launcher before committing its update

This commit is contained in:
skylartaylor committed 2026-10-22 15:58:28 +02:00
1 parent 51ab0ca09e
commit c868893f30
2 files changed
+109 -26

No files matched your search

+55 -13
View File
@@ -306,11 +306,11 @@ pub fn remove(app: &CraftApp, record: &Record) -> Result<(), String> {
/// Unpacks the launcher's own portable zip into `staging`, with the same checks as an app's, and
/// copies it over `folder` for a self-update. `check` must accept every unpacked file before
/// any is copied. When every file sits in one top-level folder, that folder's contents are the
/// program. A copy that fails puts the previous files back. When one of them can't be put back,
/// any is copied, and again before the backup is removed. The archive must include `executable`.
/// When every file sits in one top-level folder, that folder's contents are the program. A copy that fails puts the previous files back. When one of them can't be put back,
/// the previous files move to a `<staging>-recovery-<time>` folder beside `staging`, which no
/// later update removes, and the error names it. `staging` is removed afterwards.
pub fn unpack_over(zip: &Path, staging: &Path, folder: &Path, check: &dyn Fn(&Path) -> Result<(), String>) -> Result<(), String> {
pub fn unpack_over(zip: &Path, staging: &Path, folder: &Path, executable: &std::ffi::OsStr, check: &dyn Fn(&Path) -> Result<(), String>) -> Result<(), String> {
let backup = staging.join("backup");
// A failed update whose files couldn't be moved to a recovery folder: never clear them.
if backup.exists() {
@@ -318,30 +318,39 @@ pub fn unpack_over(zip: &Path, staging: &Path, folder: &Path, check: &dyn Fn(&Pa
}
let _ = std::fs::remove_dir_all(staging);
let mut keep = false;
let result = replace_with(zip, staging, folder, check, &mut keep);
let result = replace_with(zip, staging, folder, executable, check, &mut keep);
if !keep {
let _ = std::fs::remove_dir_all(staging);
}
result
}
fn replace_with(zip: &Path, staging: &Path, folder: &Path, check: &dyn Fn(&Path) -> Result<(), String>, keep: &mut bool) -> Result<(), String> {
fn replace_with(zip: &Path, staging: &Path, folder: &Path, executable: &std::ffi::OsStr, check: &dyn Fn(&Path) -> Result<(), String>, keep: &mut bool) -> Result<(), String> {
let unpacked = staging.join("unpacked");
let backup = staging.join("backup");
std::fs::create_dir_all(&unpacked).map_err(|e| e.to_string())?;
let files = extract(zip, &unpacked)?;
for relative in &files {
let top = single_top_folder(&files);
let files = files
.into_iter()
.map(|relative| {
let inside = match &top {
Some(top) => relative.strip_prefix(top).map_err(|e| e.to_string())?.to_path_buf(),
None => relative.clone(),
};
Ok((relative, inside))
})
.collect::<Result<Vec<_>, String>>()?;
if !files.iter().any(|(_, inside)| inside == Path::new(executable)) {
return Err(format!("the update doesn't contain {}", executable.to_string_lossy()));
}
for (relative, _) in &files {
check(&unpacked.join(relative))?;
}
let top = single_top_folder(&files);
let mut saved = Vec::new();
let mut created = Vec::new();
let copied = (|| {
for relative in &files {
let inside = match &top {
Some(top) => relative.strip_prefix(top).map_err(|e| e.to_string())?,
None => relative.as_path(),
};
for (relative, inside) in &files {
let target = folder.join(inside);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
@@ -356,6 +365,10 @@ fn replace_with(zip: &Path, staging: &Path, folder: &Path, check: &dyn Fn(&Path)
}
std::fs::copy(unpacked.join(relative), &target).map_err(|e| format!("couldn't replace {} ({e})", target.display()))?;
}
// Keep the previous files until the installed copies have passed the same checks.
for (_, inside) in &files {
check(&folder.join(inside))?;
}
Ok::<(), String>(())
})();
if let Err(error) = copied {
@@ -413,12 +426,41 @@ mod tests {
let zip = archive(dir.path(), "update.zip", &[("artcraft-launcher.exe", b"0.2.0")]);
let folder = dir.path().join("ArtCraft Launcher");
std::fs::create_dir_all(&folder).unwrap();
let error = unpack_over(&zip, &staging, &folder, &|_| Ok(())).unwrap_err();
let error = unpack_over(&zip, &staging, &folder, std::ffi::OsStr::new("artcraft-launcher.exe"), &|_| Ok(())).unwrap_err();
assert!(error.contains("previous files"), "{error}");
assert_eq!(std::fs::read_to_string(staging.join("backup").join("artcraft-launcher.exe")).unwrap(), "0.1.0");
assert!(!folder.join("artcraft-launcher.exe").exists());
}
/// Validation of the installed copy is part of the transaction, while a backup still exists.
#[test]
fn a_self_update_that_fails_validation_puts_the_previous_files_back() {
let dir = tempfile::tempdir().unwrap();
let staging = dir.path().join("launcher-update");
let folder = dir.path().join("ArtCraft Launcher");
std::fs::create_dir_all(&folder).unwrap();
let exe = folder.join("artcraft-launcher.exe");
std::fs::write(&exe, "old launcher").unwrap();
let zip = archive(dir.path(), "update.zip", &[("launcher/artcraft-launcher.exe", b"new launcher"), ("launcher/README.md", b"new readme")]);
let checked = std::cell::Cell::new(false);
let error = unpack_over(&zip, &staging, &folder, std::ffi::OsStr::new("artcraft-launcher.exe"), &|file| {
if file == exe {
assert_eq!(std::fs::read(file).unwrap(), b"new launcher");
assert!(folder.join("README.md").is_file());
checked.set(true);
Err("installed launcher failed validation".into())
} else {
Ok(())
}
})
.unwrap_err();
assert_eq!(error, "installed launcher failed validation");
assert!(checked.get());
assert_eq!(std::fs::read(&exe).unwrap(), b"old launcher");
assert!(!folder.join("README.md").exists());
assert!(!staging.exists());
}
fn archive(root: &Path, name: &str, files: &[(&str, &[u8])]) -> PathBuf {
let path = root.join(name);
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
+54 -13
View File
@@ -498,6 +498,9 @@ pub fn finish(args: &[OsString]) -> Option<Result<(), String>> {
// The new launcher, or the old one when the step failed.
let started = signed_like(&me, &exe)
.and_then(|()| process::spawn_detached(std::process::Command::new(&exe)).map_err(|e| format!("couldn't start {} ({e})", exe.display())));
if let Err(e) = &started {
record_failure(&paths, e);
}
Some(done.and(started))
}
@@ -598,11 +601,12 @@ fn run_step(reference: &Path, pid: u32, exe: &Path, step: &Finish, wait: std::ti
let result = if process::wait_for_exit(pid, wait) {
match step {
Finish::Msi(msi) => signed_like(reference, msi).and_then(|()| install::windows::reinstall(msi)),
Finish::Portable { zip, tmp } => match exe.parent() {
Some(dir) => {
crate::portable::unpack_over(zip, tmp, dir, &|file| if is_program(file) { signed_like(reference, file) } else { Ok(()) })
}
None => Err("the launcher isn't in a folder".into()),
Finish::Portable { zip, tmp } => match (exe.parent(), exe.file_name()) {
(Some(dir), Some(executable)) => crate::portable::unpack_over(zip, tmp, dir, executable, &|file| {
// The expected launcher must be signed even when its contents aren't a PE file.
if file.file_name() == Some(executable) || is_program(file) { signed_like(reference, file) } else { Ok(()) }
}),
_ => Err("the launcher isn't in a folder".into()),
},
}
} else {
@@ -693,12 +697,13 @@ mod tests {
std::fs::write(folder.join("ArtCraftLauncherData").join("settings.json"), "{}").unwrap();
let zip = dir.path().join("artcraft-launcher-0.2.0-windows-x64-portable.zip");
let mut writer = zip::ZipWriter::new(std::fs::File::create(&zip).unwrap());
let signed_exe = std::fs::read(system_program("cmd.exe")).unwrap();
for (name, body) in [
("artcraft-launcher-0.2.0-windows-x64-portable/artcraft-launcher.exe", "0.2.0"),
("artcraft-launcher-0.2.0-windows-x64-portable/portable.txt", ""),
("artcraft-launcher-0.2.0-windows-x64-portable/artcraft-launcher.exe", signed_exe.as_slice()),
("artcraft-launcher-0.2.0-windows-x64-portable/portable.txt", b"".as_slice()),
] {
writer.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(body.as_bytes()).unwrap();
writer.write_all(body).unwrap();
}
writer.finish().unwrap();
let tmp = dir.path().join("cache").join("launcher-update");
@@ -714,7 +719,7 @@ mod tests {
assert_eq!(std::fs::read_to_string(&exe).unwrap(), "0.1.0", "replaced while the old launcher was still running");
old.wait().unwrap();
helper.join().unwrap().unwrap();
assert_eq!(std::fs::read_to_string(&exe).unwrap(), "0.2.0");
assert_eq!(std::fs::read(&exe).unwrap(), signed_exe);
assert_eq!(std::fs::read_to_string(folder.join("ArtCraftLauncherData").join("settings.json")).unwrap(), "{}");
assert!(!folder.join("artcraft-launcher-0.2.0-windows-x64-portable").exists(), "the zip's folder must not be nested in the launcher's");
assert!(!zip.exists() && !tmp.exists(), "the download and the staging folder are removed");
@@ -899,6 +904,8 @@ mod tests {
let mut writer = zip::ZipWriter::new(std::fs::File::create(&zip).unwrap());
writer.start_file("artcraft-launcher-0.2.0-windows-x64-portable/README.md", zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(b"# ArtCraft Launcher").unwrap();
writer.start_file("artcraft-launcher-0.2.0-windows-x64-portable/artcraft-launcher.exe", zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(&std::fs::read(system_program("cmd.exe")).unwrap()).unwrap();
// An unsigned program under a harmless name.
writer.start_file("artcraft-launcher-0.2.0-windows-x64-portable/notes.txt", zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(&std::fs::read(std::env::current_exe().unwrap()).unwrap()).unwrap();
@@ -912,6 +919,39 @@ mod tests {
assert!(!zip.exists() && !tmp.exists());
}
/// A missing or malformed executable must be rejected before any installed file is changed.
#[cfg(windows)]
#[test]
fn a_portable_update_requires_a_signed_launcher_even_without_an_mz_header() {
use std::io::Write;
for launcher in [None, Some(b"not a Windows program".as_slice()), Some(b"".as_slice())] {
let dir = tempfile::tempdir().unwrap();
let folder = dir.path().join("ArtCraft Launcher");
std::fs::create_dir_all(folder.join("ArtCraftLauncherData")).unwrap();
let exe = folder.join("artcraft-launcher.exe");
std::fs::write(&exe, "old launcher").unwrap();
let settings = folder.join("ArtCraftLauncherData/settings.json");
std::fs::write(&settings, "settings").unwrap();
let zip = dir.path().join("update.zip");
let mut writer = zip::ZipWriter::new(std::fs::File::create(&zip).unwrap());
writer.start_file("launcher/README.md", zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(b"new readme").unwrap();
if let Some(body) = launcher {
writer.start_file("launcher/artcraft-launcher.exe", zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(body).unwrap();
}
writer.finish().unwrap();
let tmp = dir.path().join(PORTABLE_STAGING);
let step = Finish::Portable { zip: zip.clone(), tmp: tmp.clone() };
let error = run_step(&system_program("cmd.exe"), exited_pid(), &exe, &step, std::time::Duration::from_secs(5)).unwrap_err();
assert!(error.contains(if launcher.is_some() { "isn't signed" } else { "doesn't contain" }), "{error}");
assert_eq!(std::fs::read(&exe).unwrap(), b"old launcher");
assert_eq!(std::fs::read(&settings).unwrap(), b"settings");
assert!(!folder.join("README.md").exists());
assert!(!zip.exists() && !tmp.exists());
}
}
/// A copy that fails part way through puts the previous files back and removes the new ones,
/// so the launcher that starts again is the old one, whole.
#[cfg(windows)]
@@ -926,13 +966,14 @@ mod tests {
std::fs::write(&exe, "0.1.0").unwrap();
let zip = dir.path().join("artcraft-launcher-0.2.0-windows-x64-portable.zip");
let mut writer = zip::ZipWriter::new(std::fs::File::create(&zip).unwrap());
let signed_exe = std::fs::read(system_program("cmd.exe")).unwrap();
for (name, body) in [
("artcraft-launcher-0.2.0-windows-x64-portable/artcraft-launcher.exe", "0.2.0"),
("artcraft-launcher-0.2.0-windows-x64-portable/README.md", "# ArtCraft Launcher"),
("artcraft-launcher-0.2.0-windows-x64-portable/NOTICE", "notice"),
("artcraft-launcher-0.2.0-windows-x64-portable/artcraft-launcher.exe", signed_exe.as_slice()),
("artcraft-launcher-0.2.0-windows-x64-portable/README.md", b"# ArtCraft Launcher".as_slice()),
("artcraft-launcher-0.2.0-windows-x64-portable/NOTICE", b"notice".as_slice()),
] {
writer.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(body.as_bytes()).unwrap();
writer.write_all(body).unwrap();
}
writer.finish().unwrap();
let tmp = dir.path().join("cache").join(PORTABLE_STAGING);