use std::fs; use std::io::{BufRead, BufReader, Write}; use std::net::TcpListener; use std::ops::ControlFlow; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use arena_tracker_core::{ Error, UpdateChannel, download_update, restart_to_update, update_at_launch, verify_release, }; use base64::prelude::{BASE64_STANDARD, Engine}; use ring::digest; use ring::signature::{Ed25519KeyPair, KeyPair}; use serde_json::{Value, json}; use tempfile::TempDir; const PACKAGE: &str = "ArenaTracker-1.0.0-stable-full.nupkg"; /// A stable 1.0.0 release folder; `signature` None leaves the signature file out. fn release(manifest: &[u8], signature: Option<&[u8]>, package: &[u8]) -> TempDir { let dir = tempfile::tempdir().unwrap(); fs::write(dir.path().join("release-stable.json"), manifest).unwrap(); if let Some(signature) = signature { fs::write(dir.path().join("release-stable.sig"), signature).unwrap(); } fs::write(dir.path().join(PACKAGE), package).unwrap(); dir } #[test] fn only_the_signed_full_package_for_the_expected_release_is_accepted() { let key = Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap(); let manifest = json!({ "app": "ArenaTracker", "target": "win-x64", "channel": "stable", "version": "1.0.0", "commit": "c".repeat(40), "package": PACKAGE, "sha256": "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" }); let check = |dir: &TempDir, channel: &str, version: &str| { verify_release(dir.path(), key.public_key().as_ref(), channel, version) }; let refused = |dir: TempDir| matches!(check(&dir, "stable", "1.0.0"), Err(Error::InvalidUpdate(_))); let doc = serde_json::to_vec(&manifest).unwrap(); let sig = key.sign(&doc); let good = release(&doc, Some(sig.as_ref()), b"abc"); assert_eq!(check(&good, "stable", "1.0.0").unwrap(), "c".repeat(40)); assert!(check(&good, "beta", "1.0.0").is_err()); assert!(check(&good, "stable", "1.1.0").is_err()); assert!(refused(release(&doc, Some(sig.as_ref()), b"abd"))); assert!(refused(release(&doc, None, b"abc"))); assert!(refused(release(&doc, Some(&[]), b"abc"))); assert!(refused(release(&doc, Some(&[0; 64]), b"abc"))); let missing_package = release(&doc, Some(sig.as_ref()), b"abc"); fs::remove_file(missing_package.path().join(PACKAGE)).unwrap(); assert!(refused(missing_package)); let mut padded = doc.clone(); padded.resize(4097, b' '); assert!(refused(release( &padded, Some(key.sign(&padded).as_ref()), b"abc" ))); for (field, wrong) in [ ("app", "Other"), ("target", "win-arm64"), ("channel", "beta"), ("version", "1.1.0"), ("package", "different.nupkg"), ("sha256", ""), ] { let mut other: Value = manifest.clone(); other[field] = wrong.into(); let other = serde_json::to_vec(&other).unwrap(); assert!( refused(release(&other, Some(sig.as_ref()), b"abc")), "{field}" ); assert!( refused(release(&other, Some(key.sign(&other).as_ref()), b"abc")), "{field}" ); } } /// The files of one Release: (name, bytes). Betas are published as pre-releases. struct Published { prerelease: bool, files: Vec<(String, Vec)>, } /// A release of `version` signed by `key`, following the package contract of #57. fn publish(key: &Ed25519KeyPair, channel: &str, version: &str) -> Published { let package = format!("ArenaTracker-{version}-{channel}-full.nupkg"); let bytes = format!("package {version}").into_bytes(); let manifest = serde_json::to_vec(&json!({ "app": "ArenaTracker", "target": "win-x64", "channel": channel, "version": version, "commit": "c".repeat(40), "package": package, "sha256": BASE64_STANDARD.encode(digest::digest(&digest::SHA256, &bytes)), })) .unwrap(); Published { prerelease: channel == "beta", files: vec![ ( format!("release-{channel}.sig"), key.sign(&manifest).as_ref().to_vec(), ), (format!("release-{channel}.json"), manifest), (package, bytes), ], } } /// Serves `releases` like Gitea's API and returns its releases URL and a count of package /// downloads. With `cut`, a package response stops halfway through its announced length. fn serve(releases: Vec, cut: bool) -> (String, Arc) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); let downloads = Arc::new(AtomicUsize::new(0)); let (url, count) = (base.clone(), downloads.clone()); thread::spawn(move || { for stream in listener.incoming() { let mut stream = stream.unwrap(); let mut reader = BufReader::new(&stream); let mut line = String::new(); reader.read_line(&mut line).unwrap(); let path = line.split(' ').nth(1).unwrap().to_string(); // The headers end with an empty line. while !matches!(reader.read_line(&mut String::new()), Ok(0..=2)) {} let (body, cut) = if let Some(query) = path.strip_prefix("/releases?") { let prerelease = query.contains("pre-release=true"); let list: Vec = releases .iter() .enumerate() .filter(|(_, release)| release.prerelease == prerelease) .map(|(i, release)| { let assets: Vec = release .files .iter() .map(|(name, _)| { let link = format!("{url}/files/{i}/{name}"); json!({ "name": name, "browser_download_url": link }) }) .collect(); json!({ "tag_name": format!("t{i}"), "prerelease": prerelease, "assets": assets }) }) .collect(); (serde_json::to_vec(&list).unwrap(), false) } else { let (i, name) = path["/files/".len()..].split_once('/').unwrap(); let files = &releases[i.parse::().unwrap()].files; let (_, bytes) = files.iter().find(|(file, _)| file == name).unwrap(); let package = name.ends_with(".nupkg"); if package { count.fetch_add(1, Ordering::SeqCst); } (bytes.clone(), cut && package) }; let sent = if cut { &body[..body.len() / 2] } else { &body }; let head = format!( "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() ); let _ = stream .write_all(head.as_bytes()) .and_then(|()| stream.write_all(sent)); } }); (format!("{base}/releases"), downloads) } /// A releases URL nothing listens on. fn unreachable() -> String { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); format!("http://{}/releases", listener.local_addr().unwrap()) } fn key() -> Ed25519KeyPair { Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap() } /// The names left in the updates folder. fn kept(dir: &Path) -> Vec { let mut names: Vec = fs::read_dir(dir) .unwrap() .map(|entry| entry.unwrap().file_name().into_string().unwrap()) .collect(); names.sort(); names } #[test] fn each_channel_gets_its_newest_release_above_the_installed_version() { let key = key(); let (url, _) = serve( vec![ publish(&key, "stable", "1.0.0"), publish(&key, "beta", "1.2.0-beta.10"), publish(&key, "stable", "1.1.0"), publish(&key, "beta", "1.2.0-beta.2"), publish(&key, "stable", "1.0.1"), publish(&key, "stable", "2.0"), ], false, ); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = |channel, installed| download_update(&url, dir.path(), public, channel, installed).unwrap(); assert_eq!( check(UpdateChannel::Stable, "1.0.0").as_deref(), Some("1.1.0") ); assert_eq!(kept(dir.path()), ["stable-1.1.0"]); let ready = dir.path().join("stable-1.1.0"); assert!(verify_release(&ready, public, "stable", "1.1.0").is_ok()); // The same version or an older one is ignored, and nothing stays pending. assert_eq!(check(UpdateChannel::Stable, "1.1.0"), None); assert_eq!(check(UpdateChannel::Stable, "1.2.0"), None); assert!(kept(dir.path()).is_empty()); // beta.10 comes after beta.2, and the beta channel never takes a stable. assert_eq!( check(UpdateChannel::Beta, "1.1.0-beta.1").as_deref(), Some("1.2.0-beta.10") ); assert_eq!( check(UpdateChannel::Beta, "1.0.0").as_deref(), Some("1.2.0-beta.10") ); assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.10"]); assert_eq!(check(UpdateChannel::Beta, "1.2.0-beta.10"), None); assert!(kept(dir.path()).is_empty()); } #[test] fn back_to_stable_from_a_newer_beta_waits_for_a_newer_stable() { let key = key(); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = |url: &str| { download_update( url, dir.path(), public, UpdateChannel::Stable, "1.2.0-beta.3", ) .unwrap() }; let older = vec![ publish(&key, "stable", "1.1.0"), publish(&key, "beta", "1.2.0-beta.4"), ]; assert_eq!(check(&serve(older, false).0), None); let newer = vec![ publish(&key, "stable", "1.1.0"), publish(&key, "stable", "1.2.0"), ]; assert_eq!(check(&serve(newer, false).0).as_deref(), Some("1.2.0")); } #[test] fn a_kept_package_is_verified_again_and_downloaded_again_once_altered() { let key = key(); let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0"); assert_eq!(check().unwrap().as_deref(), Some("1.1.0")); assert_eq!(check().unwrap().as_deref(), Some("1.1.0")); assert_eq!(downloads.load(Ordering::SeqCst), 1); let package = dir .path() .join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg"); fs::write(&package, b"altered").unwrap(); assert_eq!(check().unwrap().as_deref(), Some("1.1.0")); assert_eq!(downloads.load(Ordering::SeqCst), 2); assert_eq!(fs::read(&package).unwrap(), b"package 1.1.0"); } #[test] fn a_channel_change_discards_the_other_channels_package_even_offline() { let key = key(); let (url, _) = serve( vec![ publish(&key, "stable", "1.1.0"), publish(&key, "beta", "1.2.0-beta.1"), ], false, ); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = |url: &str, channel| download_update(url, dir.path(), public, channel, "1.0.0"); assert!(check(&url, UpdateChannel::Stable).unwrap().is_some()); // A late stable package goes as soon as a beta check starts, before any network access. let offline = unreachable(); assert!(matches!( check(&offline, UpdateChannel::Beta), Err(Error::Source(_)) )); assert!(kept(dir.path()).is_empty()); assert_eq!( check(&url, UpdateChannel::Beta).unwrap().as_deref(), Some("1.2.0-beta.1") ); // Offline, the channel's own pending package stays for a later launch. assert!(check(&offline, UpdateChannel::Beta).is_err()); assert_eq!(kept(dir.path()), ["beta-1.2.0-beta.1"]); } #[test] fn a_failed_newer_download_keeps_the_older_pending_package() { let key = key(); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = |url: &str| download_update(url, dir.path(), public, UpdateChannel::Beta, "1.0.0"); let first = vec![publish(&key, "beta", "1.1.0-beta.1")]; assert!(check(&serve(first, false).0).is_ok()); let newer = || { vec![ publish(&key, "beta", "1.1.0-beta.1"), publish(&key, "beta", "1.1.0-beta.2"), ] }; assert!(check(&serve(newer(), true).0).is_err()); assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.1"]); let ready = check(&serve(newer(), false).0).unwrap(); assert_eq!(ready.as_deref(), Some("1.1.0-beta.2")); assert_eq!(kept(dir.path()), ["beta-1.1.0-beta.2"]); } #[test] fn network_and_signature_failures_leave_no_update_ready() { let key = key(); let other = Ed25519KeyPair::from_seed_unchecked(&[8; 32]).unwrap(); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = |url: &str| download_update(url, dir.path(), public, UpdateChannel::Stable, "1.0.0"); assert!(matches!(check(&unreachable()), Err(Error::Source(_)))); let (cut, _) = serve(vec![publish(&key, "stable", "1.1.0")], true); assert!(check(&cut).is_err()); assert!(kept(dir.path()).is_empty()); let (forged, _) = serve(vec![publish(&other, "stable", "1.1.0")], false); assert!(matches!(check(&forged), Err(Error::InvalidUpdate(_)))); assert!(kept(dir.path()).is_empty()); let mut altered = publish(&key, "stable", "1.1.0"); altered.files[2].1 = b"package 6.6.6".to_vec(); assert!(matches!( check(&serve(vec![altered], false).0), Err(Error::InvalidUpdate(_)) )); assert!(kept(dir.path()).is_empty()); // A release without its signature is not offered at all. let mut unsigned = publish(&key, "stable", "1.1.0"); unsigned.files.remove(0); assert_eq!(check(&serve(vec![unsigned], false).0).unwrap(), None); } /// Keeps `version` of `channel` in `dir` as a finished download would, and returns its package. fn keep(dir: &Path, key: &Ed25519KeyPair, channel: &str, version: &str) -> PathBuf { let folder = dir.join(format!("{channel}-{version}")); fs::create_dir(&folder).unwrap(); for (name, bytes) in publish(key, channel, version).files { fs::write(folder.join(name), bytes).unwrap(); } folder.join(format!("ArenaTracker-{version}-{channel}-full.nupkg")) } type Start<'a> = &'a mut dyn FnMut(&Path) -> std::io::Result; type Outcome<'a> = &'a mut dyn FnMut(u32) -> Option; fn never_started(_: &Path) -> std::io::Result { panic!("the installer must not start") } fn no_installer(_: u32) -> Option { panic!("no installer was started") } /// Records each package handed to the installer, which gets process id `pid`. fn recording(started: &mut Vec, pid: u32) -> impl FnMut(&Path) -> std::io::Result { move |package| { started.push(package.to_owned()); Ok(pid) } } type Launch = ControlFlow<(), Option>; /// The installer replaces this version and opens the app. fn applying(launch: &Launch) -> bool { matches!(launch, ControlFlow::Break(())) } fn loads_quietly(launch: &Launch) -> bool { matches!(launch, ControlFlow::Continue(None)) } fn reports_failed(launch: &Launch, version: &str) -> bool { matches!(launch, ControlFlow::Continue(Some(Error::UpdateFailed(failed))) if failed == version) } #[test] fn a_launch_hands_the_chosen_channels_package_to_the_installer_once() { let key = key(); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let stable = keep(dir.path(), &key, "stable", "1.1.0"); keep(dir.path(), &key, "stable", "1.0.1"); // Left from before a change to Stable, until the next check removes it. let beta = keep(dir.path(), &key, "beta", "1.2.0-beta.1"); let launch = |channel, installed, start: Start, outcome: Outcome| { update_at_launch(dir.path(), public, channel, installed, start, outcome) }; let stable_launch = |start: Start, outcome: Outcome| launch(UpdateChannel::Stable, "1.0.0", start, outcome); let mut started = Vec::new(); let first = stable_launch(&mut recording(&mut started, 42), &mut no_installer); assert!(applying(&first), "{first:?}"); assert_eq!(started, [stable]); // A launch while the installer runs waits for it and leaves the app to the version it opens. let succeeded = stable_launch(&mut never_started, &mut |pid| (pid == 42).then_some(0)); assert!(applying(&succeeded), "{succeeded:?}"); // After a failure the version in place loads and says so once, then never retries on its own. let failed = stable_launch(&mut never_started, &mut |_| Some(1)); assert!(reports_failed(&failed, "1.1.0"), "{failed:?}"); let next = stable_launch(&mut never_started, &mut no_installer); assert!(loads_quietly(&next), "{next:?}"); // « Redémarrer » retries it; an installer that is gone counts as failed. let restart = restart_to_update(dir.path(), public, UpdateChannel::Stable, "1.0.0", |_| { Ok(43) }); assert!(restart.is_ok()); let gone = stable_launch(&mut never_started, &mut |pid| (pid != 43).then_some(0)); assert!(reports_failed(&gone, "1.1.0"), "{gone:?}"); // Once the new version is installed, nothing is left to apply. let installed = launch( UpdateChannel::Stable, "1.1.0", &mut never_started, &mut no_installer, ); assert!(loads_quietly(&installed), "{installed:?}"); // The Bêta channel takes only its own package. let mut started = Vec::new(); let beta_launch = launch( UpdateChannel::Beta, "1.1.0", &mut recording(&mut started, 44), &mut no_installer, ); assert!(applying(&beta_launch), "{beta_launch:?}"); assert_eq!(started, [beta]); } #[test] fn an_altered_package_or_an_installer_that_cannot_start_leaves_the_installed_version() { let key = key(); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let package = keep(dir.path(), &key, "stable", "1.1.0"); let launch = |start: Start| { update_at_launch( dir.path(), public, UpdateChannel::Stable, "1.0.0", start, no_installer, ) }; // Altered between the download and this launch: refused before the installer sees it. fs::write(&package, b"altered").unwrap(); let refused = launch(&mut never_started); assert!( matches!( refused, ControlFlow::Continue(Some(Error::InvalidUpdate(_))) ), "{refused:?}" ); let restart = restart_to_update( dir.path(), public, UpdateChannel::Stable, "1.0.0", never_started, ); assert!(matches!(restart, Err(Error::InvalidUpdate(_)))); // Downloaded again, then the installer cannot start: reported, and no launch loops on it. fs::write(&package, b"package 1.1.0").unwrap(); let failed = launch(&mut |_| Err(std::io::ErrorKind::NotFound.into())); assert!(reports_failed(&failed, "1.1.0"), "{failed:?}"); let next = launch(&mut never_started); assert!(loads_quietly(&next), "{next:?}"); } #[test] fn a_failed_version_is_not_retried_at_launch_but_a_newer_release_is() { let key = key(); let (url, downloads) = serve(vec![publish(&key, "stable", "1.1.0")], false); let dir = tempfile::tempdir().unwrap(); let public = key.public_key().as_ref(); let check = || download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0"); let launch = |start: Start, outcome: Outcome| { update_at_launch( dir.path(), public, UpdateChannel::Stable, "1.0.0", start, outcome, ) }; assert_eq!(check().unwrap().as_deref(), Some("1.1.0")); assert!(applying(&launch(&mut |_| Ok(42), &mut no_installer))); // Velopack deletes a package it cannot open, then reopens the version in place. let package = dir .path() .join("stable-1.1.0/ArenaTracker-1.1.0-stable-full.nupkg"); fs::remove_file(&package).unwrap(); let failed = launch(&mut never_started, &mut |_| Some(1)); assert!(reports_failed(&failed, "1.1.0"), "{failed:?}"); assert_eq!(check().unwrap().as_deref(), Some("1.1.0")); assert_eq!(downloads.load(Ordering::SeqCst), 2); let next = launch(&mut never_started, &mut no_installer); assert!(loads_quietly(&next), "{next:?}"); // The next release gets its own attempt: the app never stays on the version in place. let newer = vec![ publish(&key, "stable", "1.1.0"), publish(&key, "stable", "1.2.0"), publish(&key, "stable", "1.3.0"), ]; let (url, _) = serve(newer, false); let ready = download_update(&url, dir.path(), public, UpdateChannel::Stable, "1.0.0"); assert_eq!(ready.unwrap().as_deref(), Some("1.3.0")); assert_eq!(kept(dir.path()), ["stable-1.3.0"]); let mut started = Vec::new(); let newest = launch(&mut recording(&mut started, 43), &mut no_installer); assert!(applying(&newest), "{newest:?}"); let package = dir .path() .join("stable-1.3.0/ArenaTracker-1.3.0-stable-full.nupkg"); assert_eq!(started, [package]); }