Each host build pins one engine version in src-tauri/browser-engine.json. The new engine manager downloads that ZIP over HTTPS, makes sure that its size and SHA-256 match the pin, extracts it safely to the local app data folder, and marks the installation last. It can also install a local ZIP, cancel, report progress, and remove the engine. The host refuses an engine that sends another protocol with its ready event.
680 lines
30 KiB
Rust
680 lines
30 KiB
Rust
//! The browser engine is a separate download. Each host build pins one engine version in
|
|
//! `browser-engine.json`. On request, the host downloads that engine, makes sure that its size
|
|
//! and SHA-256 match the pin, and extracts it to the local app data folder.
|
|
//! See docs/development.md#engine-download.
|
|
use reqwest::{blocking::Client, Url};
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
collections::{BTreeSet, HashMap},
|
|
fs,
|
|
io::{Read, Write},
|
|
path::{Path, PathBuf},
|
|
sync::{
|
|
atomic::{AtomicBool, Ordering},
|
|
Arc, Mutex,
|
|
},
|
|
time::{Duration, Instant},
|
|
};
|
|
use tauri::{AppHandle, Emitter, Manager};
|
|
use tauri_plugin_dialog::DialogExt;
|
|
|
|
use crate::error::{Error, Result};
|
|
|
|
/// The protocol between the host and the engine. The engine sends it with its `ready` event.
|
|
pub const PROTOCOL: u64 = 1;
|
|
const PINNED: &str = include_str!("../browser-engine.json");
|
|
/// The extracted engine of Electron 44 has 73 files and 377 MB.
|
|
const MAX_ENTRIES: usize = 10_000;
|
|
const MAX_EXTRACTED: u64 = 1024 * 1024 * 1024;
|
|
const MARKER: &str = "installed.json";
|
|
const WORK: &str = ".download";
|
|
const CANCELLED: &str = "The browser engine download was cancelled.";
|
|
|
|
#[derive(Deserialize, Clone, Debug)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Manifest {
|
|
pub version: String,
|
|
pub protocol: u64,
|
|
#[serde(default)]
|
|
pub platforms: HashMap<String, Package>,
|
|
}
|
|
#[derive(Deserialize, Clone, Debug)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Package {
|
|
pub url: String,
|
|
pub bytes: u64,
|
|
pub sha256: String,
|
|
}
|
|
#[derive(Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct Marker {
|
|
version: String,
|
|
sha256: String,
|
|
installed_at: u64,
|
|
}
|
|
|
|
/// What the interface shows about the engine.
|
|
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Status {
|
|
/// `installed`, `missing`, `update`, `downloading`, `installing`, `unavailable`, or `development`.
|
|
pub state: String,
|
|
/// The engine version that this host needs.
|
|
pub version: String,
|
|
/// The download size in bytes.
|
|
pub bytes: u64,
|
|
pub received: u64,
|
|
pub error: Option<String>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct EngineState {
|
|
job: Mutex<Job>,
|
|
}
|
|
#[derive(Default, Clone)]
|
|
struct Job {
|
|
phase: Option<&'static str>,
|
|
received: u64,
|
|
error: Option<String>,
|
|
cancel: Arc<AtomicBool>,
|
|
}
|
|
enum Source {
|
|
Download,
|
|
File(PathBuf),
|
|
}
|
|
|
|
pub fn platform() -> String {
|
|
format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
|
|
}
|
|
pub fn executable_name() -> &'static str {
|
|
if cfg!(windows) {
|
|
"RuneStone-Browser.exe"
|
|
} else if cfg!(target_os = "macos") {
|
|
"RuneStone-Browser.app/Contents/MacOS/RuneStone-Browser"
|
|
} else {
|
|
"RuneStone-Browser"
|
|
}
|
|
}
|
|
|
|
fn valid_version(value: &str) -> bool {
|
|
!value.is_empty()
|
|
&& value.len() <= 40
|
|
&& value.as_bytes()[0].is_ascii_digit()
|
|
&& value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.')
|
|
&& !value.contains("..")
|
|
}
|
|
fn parse(text: &str) -> Result<Manifest> {
|
|
let manifest: Manifest = serde_json::from_str(text).map_err(|error| format!("The browser engine manifest is invalid: {error}"))?;
|
|
if !valid_version(&manifest.version) {
|
|
return Err("The browser engine manifest has an invalid version.".into());
|
|
}
|
|
for package in manifest.platforms.values() {
|
|
let hex = package.sha256.len() == 64 && package.sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c));
|
|
if !hex || package.bytes == 0 || Url::parse(&package.url).is_err() {
|
|
return Err("The browser engine manifest has an invalid package.".into());
|
|
}
|
|
}
|
|
Ok(manifest)
|
|
}
|
|
/// The manifest file of a native test. Only debug builds read it.
|
|
fn override_path() -> Option<PathBuf> {
|
|
if cfg!(debug_assertions) {
|
|
std::env::var_os("RUNESTONE_BROWSER_ENGINE_MANIFEST").map(PathBuf::from)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
fn manifest() -> Result<Manifest> {
|
|
match override_path() {
|
|
Some(path) => parse(&fs::read_to_string(path)?),
|
|
None => parse(PINNED),
|
|
}
|
|
}
|
|
fn engines(app: &AppHandle) -> Result<PathBuf> {
|
|
Ok(app.path().app_local_data_dir()?.join("browser-engine"))
|
|
}
|
|
/// The engine that `pnpm browser:stage` puts in `src-tauri/browser-engine` for `pnpm tauri dev`.
|
|
/// A manifest override turns it off, so that a native test uses the download.
|
|
fn development_engine() -> Option<PathBuf> {
|
|
if !cfg!(debug_assertions) || override_path().is_some() {
|
|
return None;
|
|
}
|
|
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("browser-engine").join(executable_name());
|
|
path.is_file().then_some(path)
|
|
}
|
|
|
|
/// The installed engine that matches the pin, if any.
|
|
fn installed(root: &Path, manifest: &Manifest) -> Option<PathBuf> {
|
|
let package = manifest.platforms.get(&platform())?;
|
|
let folder = root.join(&manifest.version);
|
|
let marker: Marker = serde_json::from_slice(&fs::read(folder.join(MARKER)).ok()?).ok()?;
|
|
let executable = folder.join(executable_name());
|
|
(marker.version == manifest.version && marker.sha256 == package.sha256 && executable.is_file()).then_some(executable)
|
|
}
|
|
/// Version folders with a complete installation, also for other versions.
|
|
fn installed_versions(root: &Path) -> Vec<String> {
|
|
let Ok(entries) = fs::read_dir(root) else { return Vec::new() };
|
|
entries
|
|
.filter_map(|entry| entry.ok())
|
|
.filter(|entry| entry.path().join(MARKER).is_file())
|
|
.filter_map(|entry| entry.file_name().into_string().ok())
|
|
.collect()
|
|
}
|
|
|
|
/// The engine executable to start.
|
|
pub fn executable(app: &AppHandle) -> Result<PathBuf> {
|
|
if let Some(path) = development_engine() {
|
|
return Ok(path);
|
|
}
|
|
let manifest = manifest()?;
|
|
installed(&engines(app)?, &manifest).ok_or_else(|| "The browser engine is not installed.".into())
|
|
}
|
|
|
|
fn describe(manifest: &Result<Manifest>, root: &Path, job: &Job, development: bool) -> Status {
|
|
let manifest = match manifest {
|
|
Ok(manifest) => manifest,
|
|
Err(error) => return Status { state: "unavailable".into(), error: Some(error.to_string()), ..Status::default() },
|
|
};
|
|
let base = Status { version: manifest.version.clone(), received: job.received, error: job.error.clone(), ..Status::default() };
|
|
if development {
|
|
return Status { state: "development".into(), ..base };
|
|
}
|
|
let Some(package) = manifest.platforms.get(&platform()) else {
|
|
return Status { state: "unavailable".into(), ..base };
|
|
};
|
|
let state = match job.phase {
|
|
Some(phase) => phase,
|
|
None if installed(root, manifest).is_some() => "installed",
|
|
None if !installed_versions(root).is_empty() => "update",
|
|
None => "missing",
|
|
};
|
|
Status { state: state.into(), bytes: package.bytes, ..base }
|
|
}
|
|
fn status(app: &AppHandle) -> Result<Status> {
|
|
let job = app.state::<EngineState>().job.lock()?.clone();
|
|
Ok(describe(&manifest(), &engines(app)?, &job, development_engine().is_some()))
|
|
}
|
|
fn publish(app: &AppHandle) {
|
|
if let Ok(status) = status(app) {
|
|
let _ = app.emit("browser-engine", &status);
|
|
}
|
|
}
|
|
|
|
/// A redirect may not leave HTTPS. A native test can allow HTTP for its local server.
|
|
fn allowed(url: &Url, allow_http: bool) -> bool {
|
|
url.scheme() == "https" || (allow_http && url.scheme() == "http")
|
|
}
|
|
/// Download `package` to `target` and make sure that its size and SHA-256 match.
|
|
/// `target` must not exist. On failure, the function removes it.
|
|
fn download(package: &Package, target: &Path, allow_http: bool, cancel: &AtomicBool, report: &mut dyn FnMut(u64)) -> Result<()> {
|
|
let url = Url::parse(&package.url).map_err(|_| "The browser engine link is invalid.")?;
|
|
if !allowed(&url, allow_http) {
|
|
return Err("The browser engine link must use HTTPS.".into());
|
|
}
|
|
let client = Client::builder()
|
|
.user_agent("RuneStone-browser-engine/1")
|
|
.connect_timeout(Duration::from_secs(15))
|
|
// A limit for each read, not for the whole download.
|
|
.timeout(Duration::from_secs(60))
|
|
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
|
|
if attempt.previous().len() >= 5 {
|
|
attempt.error("The download server redirected too many times.")
|
|
} else if !allowed(attempt.url(), allow_http) {
|
|
attempt.error("The download server redirected away from HTTPS.")
|
|
} else {
|
|
attempt.follow()
|
|
}
|
|
}))
|
|
.build()
|
|
.map_err(|_| "Cannot start the download client.")?;
|
|
let result = (|| -> Result<()> {
|
|
let mut response = client.get(url).send().map_err(|error| format!("Cannot reach the download server: {error}"))?;
|
|
if !response.status().is_success() {
|
|
return Err(format!("The download server answered {}.", response.status()).into());
|
|
}
|
|
if response.content_length().is_some_and(|length| length != package.bytes) {
|
|
return Err("The download does not have the expected size.".into());
|
|
}
|
|
let mut file = fs::File::options().write(true).create_new(true).open(target)?;
|
|
let (mut hasher, mut received, mut buffer) = (Sha256::new(), 0u64, vec![0; 256 * 1024]);
|
|
loop {
|
|
if cancel.load(Ordering::Relaxed) {
|
|
return Err(CANCELLED.into());
|
|
}
|
|
let read = response.read(&mut buffer).map_err(|error| format!("The download stopped: {error}"))?;
|
|
if read == 0 {
|
|
break;
|
|
}
|
|
received += read as u64;
|
|
if received > package.bytes {
|
|
return Err("The download is larger than expected.".into());
|
|
}
|
|
hasher.update(&buffer[..read]);
|
|
file.write_all(&buffer[..read])?;
|
|
report(received);
|
|
}
|
|
if received != package.bytes {
|
|
return Err("The download is incomplete.".into());
|
|
}
|
|
if format!("{:x}", hasher.finalize()) != package.sha256 {
|
|
return Err("The download does not match the expected SHA-256 hash.".into());
|
|
}
|
|
Ok(file.sync_all()?)
|
|
})();
|
|
if result.is_err() {
|
|
let _ = fs::remove_file(target);
|
|
}
|
|
result
|
|
}
|
|
/// Make sure that a local ZIP has the size and SHA-256 of the pin.
|
|
fn verify_file(path: &Path, package: &Package, cancel: &AtomicBool) -> Result<()> {
|
|
let metadata = fs::symlink_metadata(path)?;
|
|
if !metadata.is_file() || metadata.len() != package.bytes {
|
|
return Err("This file is not the browser engine that this RuneStone version needs. Its size is different.".into());
|
|
}
|
|
let (mut file, mut hasher, mut buffer) = (fs::File::open(path)?, Sha256::new(), vec![0; 256 * 1024]);
|
|
loop {
|
|
if cancel.load(Ordering::Relaxed) {
|
|
return Err(CANCELLED.into());
|
|
}
|
|
let read = file.read(&mut buffer)?;
|
|
if read == 0 {
|
|
break;
|
|
}
|
|
hasher.update(&buffer[..read]);
|
|
}
|
|
if format!("{:x}", hasher.finalize()) != package.sha256 {
|
|
return Err("This file is not the browser engine that this RuneStone version needs. Its SHA-256 hash is different.".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn valid_component(name: &str) -> bool {
|
|
crate::fsutil::is_plain_component(name)
|
|
&& name.len() <= 120
|
|
&& !name.starts_with(' ')
|
|
&& !name.ends_with(' ')
|
|
&& name.bytes().all(|c| c.is_ascii_alphanumeric() || b" ._+-".contains(&c))
|
|
}
|
|
/// Extract an engine ZIP into the new folder `target`. Refuse unsafe paths, links, and archives over `limit` bytes.
|
|
fn extract(archive: &Path, target: &Path, limit: u64) -> Result<()> {
|
|
let mut archive = zip::ZipArchive::new(fs::File::open(archive)?).map_err(|_| "The browser engine archive is not a valid ZIP file.")?;
|
|
if archive.len() > MAX_ENTRIES {
|
|
return Err("The browser engine archive contains too many entries.".into());
|
|
}
|
|
fs::create_dir(target)?;
|
|
let (mut names, mut total) = (BTreeSet::new(), 0u64);
|
|
for index in 0..archive.len() {
|
|
let mut file = archive.by_index(index)?;
|
|
let name = std::str::from_utf8(file.name_raw())?.trim_end_matches('/').to_string();
|
|
let parts: Vec<&str> = name.split('/').collect();
|
|
if parts.len() > 16 || !parts.iter().all(|part| valid_component(part)) {
|
|
return Err(format!("The browser engine archive contains an invalid path: {name}").into());
|
|
}
|
|
if !names.insert(name.to_ascii_lowercase()) {
|
|
return Err("The browser engine archive contains duplicate paths.".into());
|
|
}
|
|
let kind = file.unix_mode().map(|mode| mode & 0o170000);
|
|
if kind.is_some_and(|kind| kind != 0 && kind != 0o100000 && kind != 0o040000) || file.is_symlink() {
|
|
return Err("The browser engine archive contains links or special files.".into());
|
|
}
|
|
let path: PathBuf = parts.iter().fold(target.to_path_buf(), |path, part| path.join(part));
|
|
if file.is_dir() {
|
|
fs::create_dir_all(&path)?;
|
|
continue;
|
|
}
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent)?;
|
|
}
|
|
let remaining = limit.saturating_sub(total);
|
|
let mut output = fs::File::options().write(true).create_new(true).open(&path)?;
|
|
let written = std::io::copy(&mut file.by_ref().take(remaining.saturating_add(1)), &mut output)?;
|
|
total += written;
|
|
if written > remaining {
|
|
return Err("The browser engine archive is too large.".into());
|
|
}
|
|
#[cfg(unix)]
|
|
if let Some(mode) = file.unix_mode() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
fs::set_permissions(&path, fs::Permissions::from_mode(mode & 0o755))?;
|
|
}
|
|
}
|
|
if !target.join(executable_name()).is_file() {
|
|
return Err("The browser engine archive does not contain the engine program.".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
/// Extract a verified archive and put it in the version folder of the pin.
|
|
fn install_archive(archive: &Path, root: &Path, manifest: &Manifest, package: &Package) -> Result<()> {
|
|
let work = root.join(WORK);
|
|
fs::create_dir_all(&work)?;
|
|
let staged = work.join(format!("extract-{}", uuid::Uuid::new_v4().simple()));
|
|
let result = (|| -> Result<()> {
|
|
extract(archive, &staged, MAX_EXTRACTED)?;
|
|
let installed_at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_millis() as u64).unwrap_or(0);
|
|
let marker = Marker { version: manifest.version.clone(), sha256: package.sha256.clone(), installed_at };
|
|
fs::write(staged.join(MARKER), serde_json::to_vec_pretty(&marker)?)?;
|
|
let target = root.join(&manifest.version);
|
|
// A folder without a valid marker is an incomplete earlier attempt. No engine runs from it.
|
|
if fs::symlink_metadata(&target).is_ok() {
|
|
fs::remove_dir_all(&target)?;
|
|
}
|
|
Ok(fs::rename(&staged, &target)?)
|
|
})();
|
|
if result.is_err() {
|
|
let _ = fs::remove_dir_all(&staged);
|
|
}
|
|
result
|
|
}
|
|
/// Remove the other version folders and the work folder. No engine runs from them.
|
|
fn remove_others(root: &Path, keep: &str) {
|
|
let Ok(entries) = fs::read_dir(root) else { return };
|
|
for entry in entries.filter_map(|entry| entry.ok()) {
|
|
if entry.file_name() != keep {
|
|
let _ = fs::remove_dir_all(entry.path());
|
|
}
|
|
}
|
|
}
|
|
/// Windows can keep the program file locked for a moment after the engine stops.
|
|
fn remove_with_retries(path: &Path) -> Result<()> {
|
|
for attempt in 0.. {
|
|
match fs::remove_dir_all(path) {
|
|
Ok(()) => return Ok(()),
|
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
|
Err(_) if attempt < 10 => std::thread::sleep(Duration::from_millis(200)),
|
|
Err(error) => return Err(format!("Cannot remove the browser engine: {error}").into()),
|
|
}
|
|
}
|
|
unreachable!()
|
|
}
|
|
|
|
fn run(app: &AppHandle, source: Source, cancel: &AtomicBool) -> Result<()> {
|
|
let manifest = manifest()?;
|
|
let package = manifest.platforms.get(&platform()).cloned().ok_or("No browser engine is available for this platform.")?;
|
|
let root = engines(app)?;
|
|
if installed(&root, &manifest).is_some() {
|
|
return Ok(());
|
|
}
|
|
let work = root.join(WORK);
|
|
let _ = fs::remove_dir_all(&work);
|
|
fs::create_dir_all(&work)?;
|
|
let archive = match source {
|
|
Source::Download => {
|
|
let file = work.join("engine.zip");
|
|
let mut last = Instant::now();
|
|
download(&package, &file, override_path().is_some(), cancel, &mut |received| {
|
|
if last.elapsed() >= Duration::from_millis(250) || received == package.bytes {
|
|
last = Instant::now();
|
|
if let Ok(mut job) = app.state::<EngineState>().job.lock() { job.received = received; }
|
|
publish(app);
|
|
}
|
|
})?;
|
|
file
|
|
}
|
|
Source::File(path) => {
|
|
verify_file(&path, &package, cancel)?;
|
|
path
|
|
}
|
|
};
|
|
app.state::<EngineState>().job.lock()?.phase = Some("installing");
|
|
publish(app);
|
|
install_archive(&archive, &root, &manifest, &package)?;
|
|
remove_others(&root, &manifest.version);
|
|
Ok(())
|
|
}
|
|
fn start(app: &AppHandle, source: Source) -> Result<Status> {
|
|
let state = app.state::<EngineState>();
|
|
let cancel = {
|
|
let mut job = state.job.lock()?;
|
|
// One download at a time. A second request gets the status of the first.
|
|
if job.phase.is_none() {
|
|
let phase = if matches!(source, Source::Download) { "downloading" } else { "installing" };
|
|
*job = Job { phase: Some(phase), ..Job::default() };
|
|
Some(job.cancel.clone())
|
|
} else {
|
|
None
|
|
}
|
|
};
|
|
if let Some(cancel) = cancel {
|
|
let handle = app.clone();
|
|
std::thread::Builder::new().name("browser-engine".into()).spawn(move || {
|
|
let result = run(&handle, source, &cancel);
|
|
if let Ok(mut job) = handle.state::<EngineState>().job.lock() {
|
|
job.phase = None;
|
|
job.error = result.err().map(|error| error.to_string()).filter(|error| error != CANCELLED);
|
|
}
|
|
publish(&handle);
|
|
})?;
|
|
}
|
|
publish(app);
|
|
status(app)
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn browser_engine_status(app: AppHandle) -> Result<Status> {
|
|
tauri::async_runtime::spawn_blocking(move || status(&app)).await?
|
|
}
|
|
#[tauri::command]
|
|
pub async fn browser_engine_install(app: AppHandle) -> Result<Status> {
|
|
tauri::async_runtime::spawn_blocking(move || start(&app, Source::Download)).await?
|
|
}
|
|
#[tauri::command]
|
|
pub async fn browser_engine_install_file(app: AppHandle) -> Result<Status> {
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let chosen = app.dialog().file().set_title("Install the browser engine").add_filter("Browser engine ZIP", &["zip"]).blocking_pick_file();
|
|
match chosen {
|
|
Some(path) => start(&app, Source::File(path.into_path().map_err(Error::from_display)?)),
|
|
None => status(&app),
|
|
}
|
|
})
|
|
.await?
|
|
}
|
|
#[tauri::command]
|
|
pub async fn browser_engine_cancel(app: AppHandle) -> Result<Status> {
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
app.state::<EngineState>().job.lock()?.cancel.store(true, Ordering::Relaxed);
|
|
status(&app)
|
|
})
|
|
.await?
|
|
}
|
|
/// Stop the engine and remove all engine versions. The browser profiles stay.
|
|
#[tauri::command]
|
|
pub async fn browser_engine_remove(app: AppHandle) -> Result<Status> {
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
if app.state::<EngineState>().job.lock()?.phase.is_some() {
|
|
return Err("Wait until the browser engine installation ends.".into());
|
|
}
|
|
// The windows keep their sessions, so that their tabs can start a newly installed engine.
|
|
app.state::<crate::browser::BrowserState>().stop_engine();
|
|
remove_with_retries(&engines(&app)?)?;
|
|
publish(&app);
|
|
status(&app)
|
|
})
|
|
.await?
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::plugin_sources::tests::server;
|
|
|
|
fn base() -> PathBuf {
|
|
let path = std::env::temp_dir().join(format!("runestone-engine-{}", uuid::Uuid::new_v4()));
|
|
fs::create_dir_all(&path).unwrap();
|
|
path
|
|
}
|
|
fn zip(path: &Path, entries: &[(&str, &[u8])]) -> Vec<u8> {
|
|
let mut writer = zip::ZipWriter::new(fs::File::create(path).unwrap());
|
|
for (name, data) in entries {
|
|
writer.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
|
writer.write_all(data).unwrap();
|
|
}
|
|
writer.finish().unwrap();
|
|
fs::read(path).unwrap()
|
|
}
|
|
fn package(url: &str, bytes: &[u8]) -> Package {
|
|
Package { url: url.into(), bytes: bytes.len() as u64, sha256: format!("{:x}", Sha256::digest(bytes)) }
|
|
}
|
|
fn manifest(version: &str, package: Package) -> Manifest {
|
|
Manifest { version: version.into(), protocol: PROTOCOL, platforms: HashMap::from([(platform(), package)]) }
|
|
}
|
|
fn engine_files() -> Vec<(&'static str, &'static [u8])> {
|
|
vec![(executable_name(), b"engine"), ("locales/en-US.pak", b"strings"), ("resources/app.asar", b"app")]
|
|
}
|
|
|
|
#[test]
|
|
fn the_pinned_manifest_parses_and_invalid_manifests_fail() {
|
|
let pinned = parse(PINNED).unwrap();
|
|
assert_eq!(pinned.protocol, PROTOCOL);
|
|
for text in [
|
|
r#"{"version":"../1","protocol":1}"#,
|
|
r#"{"version":"0.1.8","protocol":1,"platforms":{"windows-x86_64":{"url":"x","bytes":1,"sha256":"00"}}}"#,
|
|
r#"{"version":"0.1.8","protocol":1,"extra":true}"#,
|
|
] {
|
|
assert!(parse(text).is_err(), "{text}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn download_checks_size_hash_scheme_and_cancel() {
|
|
let root = base();
|
|
let bytes = b"engine archive".to_vec();
|
|
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
|
|
let target = root.join("engine.zip");
|
|
let mut reports = Vec::new();
|
|
download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |received| reports.push(received)).unwrap();
|
|
assert_eq!(fs::read(&target).unwrap(), bytes);
|
|
assert_eq!(reports.last(), Some(&(bytes.len() as u64)));
|
|
handle.join().unwrap();
|
|
fs::remove_file(&target).unwrap();
|
|
|
|
let (url, handle) = server(vec![("200 OK".into(), b"engine archivX".to_vec())]);
|
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
|
assert!(error.to_string().contains("SHA-256"), "{error}");
|
|
assert!(!target.exists(), "A failed download leaves no file.");
|
|
handle.join().unwrap();
|
|
|
|
let (url, handle) = server(vec![("200 OK".into(), b"engine".to_vec())]);
|
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
|
assert!(error.to_string().contains("expected size"), "{error}");
|
|
handle.join().unwrap();
|
|
|
|
let (url, handle) = server(vec![("404 Not Found".into(), Vec::new())]);
|
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
|
assert!(error.to_string().contains("404"), "{error}");
|
|
handle.join().unwrap();
|
|
|
|
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
|
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(true), &mut |_| {}).unwrap_err();
|
|
assert_eq!(error.to_string(), CANCELLED);
|
|
assert!(!target.exists());
|
|
handle.join().unwrap();
|
|
|
|
let error = download(&package("http://127.0.0.1:9/engine.zip", &bytes), &target, false, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
|
assert!(error.to_string().contains("HTTPS"), "{error}");
|
|
assert!(allowed(&Url::parse("https://example.com").unwrap(), false));
|
|
assert!(!allowed(&Url::parse("http://example.com").unwrap(), false));
|
|
assert!(!allowed(&Url::parse("file:///C:/engine.zip").unwrap(), true));
|
|
fs::remove_dir_all(&root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn redirects_must_stay_on_an_allowed_scheme() {
|
|
let bytes = b"engine archive".to_vec();
|
|
let (target, target_server) = server(vec![("200 OK".into(), bytes.clone())]);
|
|
let (origin, origin_server) = server(vec![(format!("302 Found\r\nLocation: {target}/engine.zip"), Vec::new())]);
|
|
let root = base();
|
|
let file = root.join("engine.zip");
|
|
download(&package(&format!("{origin}/engine.zip"), &bytes), &file, true, &AtomicBool::new(false), &mut |_| {}).unwrap();
|
|
assert_eq!(fs::read(&file).unwrap(), bytes);
|
|
origin_server.join().unwrap();
|
|
target_server.join().unwrap();
|
|
fs::remove_dir_all(&root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn extraction_refuses_unsafe_archives() {
|
|
let root = base();
|
|
let good = root.join("good.zip");
|
|
zip(&good, &engine_files());
|
|
extract(&good, &root.join("good"), MAX_EXTRACTED).unwrap();
|
|
assert_eq!(fs::read(root.join("good").join("locales").join("en-US.pak")).unwrap(), b"strings");
|
|
for (index, name) in ["../evil.txt", "/absolute.txt", "a\\b.txt", "C:evil.txt", "locales/../../evil.txt", "NUL", "con.txt"].iter().enumerate() {
|
|
let archive = root.join(format!("bad-{index}.zip"));
|
|
let mut entries = engine_files();
|
|
entries.push((name, b"evil"));
|
|
zip(&archive, &entries);
|
|
assert!(extract(&archive, &root.join(format!("bad-{index}")), MAX_EXTRACTED).is_err(), "{name}");
|
|
}
|
|
assert!(!root.join("evil.txt").exists() && !root.parent().unwrap().join("evil.txt").exists());
|
|
let duplicate = root.join("duplicate.zip");
|
|
zip(&duplicate, &[(executable_name(), b"a"), ("Locales/A.pak", b"a"), ("locales/a.pak", b"b")]);
|
|
assert!(extract(&duplicate, &root.join("duplicate"), MAX_EXTRACTED).unwrap_err().to_string().contains("duplicate"));
|
|
let missing = root.join("missing.zip");
|
|
zip(&missing, &[("locales/en-US.pak", b"strings")]);
|
|
assert!(extract(&missing, &root.join("missing"), MAX_EXTRACTED).unwrap_err().to_string().contains("engine program"));
|
|
assert!(extract(&good, &root.join("small"), 8).unwrap_err().to_string().contains("too large"));
|
|
let link = root.join("link.zip");
|
|
let mut writer = zip::ZipWriter::new(fs::File::create(&link).unwrap());
|
|
writer.start_file(executable_name(), zip::write::SimpleFileOptions::default()).unwrap();
|
|
writer.write_all(b"engine").unwrap();
|
|
writer.add_symlink("resources", "../../outside", zip::write::SimpleFileOptions::default()).unwrap();
|
|
writer.finish().unwrap();
|
|
assert!(extract(&link, &root.join("link"), MAX_EXTRACTED).unwrap_err().to_string().contains("links"));
|
|
fs::write(root.join("not-a-zip.zip"), b"text").unwrap();
|
|
assert!(extract(&root.join("not-a-zip.zip"), &root.join("text"), MAX_EXTRACTED).is_err());
|
|
fs::remove_dir_all(&root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn installation_marks_the_pinned_version_and_removes_older_ones() {
|
|
let root = base();
|
|
let engines = root.join("browser-engine");
|
|
let first = root.join("first.zip");
|
|
let bytes = zip(&first, &engine_files());
|
|
let old = manifest("0.1.7", package("https://example.com/first.zip", &bytes));
|
|
install_archive(&first, &engines, &old, &old.platforms[&platform()]).unwrap();
|
|
assert_eq!(installed(&engines, &old), Some(engines.join("0.1.7").join(executable_name())));
|
|
// Another pin with a different hash does not accept this folder.
|
|
let other = manifest("0.1.7", package("https://example.com/first.zip", b"other"));
|
|
assert_eq!(installed(&engines, &other), None);
|
|
|
|
let second = root.join("second.zip");
|
|
let mut entries = engine_files();
|
|
entries.push(("version", b"0.1.8"));
|
|
let bytes = zip(&second, &entries);
|
|
let new = manifest("0.1.8", package("https://example.com/second.zip", &bytes));
|
|
let job = Job::default();
|
|
assert_eq!(describe(&Ok(new.clone()), &engines, &job, false).state, "update");
|
|
verify_file(&second, &new.platforms[&platform()], &AtomicBool::new(false)).unwrap();
|
|
assert!(verify_file(&first, &new.platforms[&platform()], &AtomicBool::new(false)).is_err());
|
|
install_archive(&second, &engines, &new, &new.platforms[&platform()]).unwrap();
|
|
remove_others(&engines, &new.version);
|
|
assert!(installed(&engines, &new).is_some());
|
|
assert_eq!(installed_versions(&engines), vec!["0.1.8".to_string()]);
|
|
assert_eq!(fs::read_dir(&engines).unwrap().count(), 1, "No work folder or old version stays.");
|
|
fs::remove_dir_all(&root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn status_names_each_engine_state() {
|
|
let root = base();
|
|
let bytes = b"engine".to_vec();
|
|
let pin = manifest("0.1.8", package("https://example.com/engine.zip", &bytes));
|
|
let idle = Job::default();
|
|
let state = |manifest: &Result<Manifest>, job: &Job, development: bool| describe(manifest, &root, job, development).state;
|
|
assert_eq!(state(&Ok(pin.clone()), &idle, false), "missing");
|
|
assert_eq!(describe(&Ok(pin.clone()), &root, &idle, false).bytes, bytes.len() as u64);
|
|
assert_eq!(state(&Ok(pin.clone()), &idle, true), "development");
|
|
let downloading = Job { phase: Some("downloading"), received: 3, ..Job::default() };
|
|
assert_eq!(describe(&Ok(pin.clone()), &root, &downloading, false), Status { state: "downloading".into(), version: "0.1.8".into(), bytes: 6, received: 3, error: None });
|
|
let failed = Job { error: Some("The download stopped.".into()), ..Job::default() };
|
|
assert_eq!(describe(&Ok(pin.clone()), &root, &failed, false).error.as_deref(), Some("The download stopped."));
|
|
let elsewhere = Manifest { platforms: HashMap::new(), ..pin.clone() };
|
|
assert_eq!(state(&Ok(elsewhere), &idle, false), "unavailable");
|
|
assert_eq!(state(&Err("broken".into()), &idle, false), "unavailable");
|
|
fs::remove_dir_all(&root).unwrap();
|
|
}
|
|
}
|