feat(client): signed updater with check, download and install steps

This commit is contained in:
Loki 2026-11-01 16:14:56 +01:00
parent ebea98e9a4
commit cd22254027
Signed by: boba
GPG key ID: 253067914055423B
14 changed files with 3068 additions and 0 deletions

38
Cargo.lock generated
View file

@ -5797,6 +5797,12 @@ dependencies = [
"serde",
]
[[package]]
name = "typed-path"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typenum"
version = "1.20.1"
@ -5966,10 +5972,12 @@ version = "0.1.0"
dependencies = [
"anyhow",
"argon2",
"base64",
"chacha20poly1305",
"cpal",
"dirs",
"ed25519-dalek",
"flate2",
"gstreamer",
"gstreamer-app",
"gstreamer-sdp",
@ -5986,6 +5994,7 @@ dependencies = [
"rcgen",
"rfd",
"rustls",
"semver",
"serde",
"serde_bytes",
"serde_json",
@ -5993,6 +6002,8 @@ dependencies = [
"slint",
"slint-build",
"sys-locale",
"tar",
"tempfile",
"tokio",
"tokio-rustls",
"tracing",
@ -6002,6 +6013,7 @@ dependencies = [
"webpki-roots",
"x25519-dalek",
"zbus",
"zip",
]
[[package]]
@ -7098,6 +7110,20 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "zip"
version = "8.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
dependencies = [
"crc32fast",
"flate2",
"indexmap",
"memchr",
"typed-path",
"zopfli",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
@ -7110,6 +7136,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zruntime"
version = "0.2.1"

View file

@ -50,6 +50,11 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
anyhow = "1"
hex = "0.4"
flate2 = "1"
tar = "0.4"
semver = "1"
base64 = "0.23"
zip = { version = "8", default-features = false, features = ["deflate"] }
uuid = { version = "1", features = ["v4"] }
argon2 = "0.6"
opus = "0.4"
@ -65,6 +70,7 @@ rfd = { version = "0.17.2", default-features = false, features =
[dev-dependencies]
# Test gateway certificates, and a TLS 1.2 only server for the downgrade test.
rcgen = "0.14"
tempfile = "3"
rustls = { version = "0.23", features = ["tls12"] }
[features]

View file

@ -4,6 +4,7 @@ pub mod identity;
pub mod identity_vault;
pub mod jitter;
pub mod net;
pub mod update;
pub mod media;

466
src/update/archive.rs Normal file
View file

@ -0,0 +1,466 @@
//! Safe extraction of a release archive.
//!
//! A release archive is a `.tar.gz` (Linux) or `.zip` (Windows) as built by the release CI: an
//! optional single wrapper directory holding the client binary plus `LICENSE` and `README.md`.
//! Nothing is unpacked by the archive libraries themselves: the one expected binary is read
//! through a size limit and written by us to a path we chose, the other known files are skipped,
//! and anything else (other names, `..`, absolute paths, deeper nesting, links, devices) makes
//! the whole archive rejected.
use std::io::{Read, Write};
use std::path::Path;
use flate2::read::GzDecoder;
use tar::{Archive, EntryType};
use super::UpdateError;
/// Name of the client binary inside the archive and in a release directory.
pub const BINARY_NAME: &str = if cfg!(windows) {
"vnox-client.exe"
} else {
"vnox-client"
};
/// Files besides the binary that a release archive may carry.
const EXTRA_FILES: [&str; 2] = ["LICENSE", "README.md"];
/// Archives with more entries than this are refused.
const MAX_ENTRIES: usize = 16;
/// Slack allowed on top of the binary size for the other files of an archive.
const EXTRA_BUDGET: u64 = 8 * 1024 * 1024;
#[derive(PartialEq, Eq)]
enum Kind {
Binary,
Ignored,
Directory,
}
/// Tracks the layout (flat or one wrapper directory) while entries are checked.
#[derive(Default)]
struct Layout {
wrapper: Option<String>,
flat_seen: bool,
}
impl Layout {
fn classify(&mut self, raw: &str, is_dir: bool, expected: &str) -> Result<Kind, UpdateError> {
let bad = |why: &str| UpdateError::UnsafeArchive(format!("{why}: {raw}"));
if raw.contains(['\\', ':', '\0']) || raw.starts_with('/') {
return Err(bad("unsafe path"));
}
let parts: Vec<&str> = raw
.split('/')
.filter(|p| !p.is_empty() && *p != ".")
.collect();
if parts.contains(&"..") {
return Err(bad("path traversal"));
}
let wrapper_ok = |this: &mut Layout, name: &str| -> Result<(), UpdateError> {
match &this.wrapper {
Some(existing) if existing != name => Err(bad("several top-level directories")),
Some(_) => Ok(()),
None if this.flat_seen => Err(bad("mixed layout")),
None => {
this.wrapper = Some(name.to_string());
Ok(())
}
}
};
let file_kind = |name: &str| -> Result<Kind, UpdateError> {
if name == expected {
Ok(Kind::Binary)
} else if EXTRA_FILES.contains(&name) {
Ok(Kind::Ignored)
} else {
Err(bad("unexpected file"))
}
};
match (parts.as_slice(), is_dir) {
([], true) => Ok(Kind::Directory),
([dir], true) => {
wrapper_ok(self, dir)?;
Ok(Kind::Directory)
}
([name], false) => {
if self.wrapper.is_some() {
return Err(bad("mixed layout"));
}
self.flat_seen = true;
file_kind(name)
}
([dir, name], false) => {
wrapper_ok(self, dir)?;
file_kind(name)
}
_ => Err(bad("unexpected entry")),
}
}
}
/// Extracts the expected binary from `archive` (`.zip` or tar.gz, told apart by content) into
/// `dest` (created new, executable on Unix). Returns the number of bytes written. The binary is
/// limited to `max_binary_bytes`.
pub fn extract_binary(
archive: &Path,
expected_name: &str,
dest: &Path,
max_binary_bytes: u64,
) -> Result<u64, UpdateError> {
let mut magic = [0u8; 2];
std::fs::File::open(archive)
.and_then(|mut f| f.read_exact(&mut magic))
.map_err(|_| UpdateError::UnsafeArchive("unreadable archive".into()))?;
if &magic == b"PK" {
extract_zip(archive, expected_name, dest, max_binary_bytes)
} else {
extract_tar_gz(archive, expected_name, dest, max_binary_bytes)
}
}
fn write_binary(
source: &mut dyn Read,
dest: &Path,
max_binary_bytes: u64,
) -> Result<u64, UpdateError> {
let mut out = std::fs::OpenOptions::new();
out.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut out, 0o755);
let mut out = out.open(dest).map_err(UpdateError::io)?;
let copied =
std::io::copy(&mut source.take(max_binary_bytes + 1), &mut out).map_err(UpdateError::io)?;
if copied > max_binary_bytes {
return Err(UpdateError::TooLarge);
}
out.flush().map_err(UpdateError::io)?;
out.sync_all().map_err(UpdateError::io)?;
Ok(copied)
}
fn extract_tar_gz(
archive: &Path,
expected_name: &str,
dest: &Path,
max_binary_bytes: u64,
) -> Result<u64, UpdateError> {
let file = std::fs::File::open(archive).map_err(UpdateError::io)?;
// Bounds the decompressed stream so a gzip bomb cannot burn time or disk.
let decoder = GzDecoder::new(file).take(max_binary_bytes + EXTRA_BUDGET);
let mut tar = Archive::new(decoder);
let unsafe_archive = |why: &str| UpdateError::UnsafeArchive(why.to_string());
let mut layout = Layout::default();
let mut written = None;
let entries = tar
.entries()
.map_err(|error| UpdateError::UnsafeArchive(error.to_string()))?;
for (index, entry) in entries.enumerate() {
if index >= MAX_ENTRIES {
return Err(unsafe_archive("too many entries"));
}
let mut entry = entry.map_err(|error| UpdateError::UnsafeArchive(error.to_string()))?;
let is_dir = match entry.header().entry_type() {
EntryType::Regular => false,
EntryType::Directory => true,
EntryType::XGlobalHeader => continue,
_ => return Err(unsafe_archive("entry is not a regular file")),
};
let raw = entry
.path()
.map_err(|_| unsafe_archive("bad entry path"))?
.to_string_lossy()
.into_owned();
match layout.classify(&raw, is_dir, expected_name)? {
Kind::Binary => {
if written.is_some() {
return Err(unsafe_archive("duplicate binary entry"));
}
if entry.size() > max_binary_bytes {
return Err(UpdateError::TooLarge);
}
written = Some(write_binary(&mut entry, dest, max_binary_bytes)?);
}
Kind::Ignored | Kind::Directory => {}
}
}
written.ok_or_else(|| unsafe_archive("binary missing from archive"))
}
fn extract_zip(
archive: &Path,
expected_name: &str,
dest: &Path,
max_binary_bytes: u64,
) -> Result<u64, UpdateError> {
let unsafe_archive = |why: String| UpdateError::UnsafeArchive(why);
let file = std::fs::File::open(archive).map_err(UpdateError::io)?;
let mut zip = zip::ZipArchive::new(file).map_err(|e| unsafe_archive(e.to_string()))?;
if zip.len() > MAX_ENTRIES {
return Err(unsafe_archive("too many entries".into()));
}
let mut layout = Layout::default();
let mut written = None;
for index in 0..zip.len() {
let mut entry = zip
.by_index(index)
.map_err(|e| unsafe_archive(e.to_string()))?;
if entry.is_symlink() {
return Err(unsafe_archive("entry is a link".into()));
}
let (raw, is_dir) = (entry.name().to_string(), entry.is_dir());
match layout.classify(&raw, is_dir, expected_name)? {
Kind::Binary => {
if written.is_some() {
return Err(unsafe_archive("duplicate binary entry".into()));
}
if entry.size() > max_binary_bytes {
return Err(UpdateError::TooLarge);
}
written = Some(write_binary(&mut entry, dest, max_binary_bytes)?);
}
Kind::Ignored | Kind::Directory => {}
}
}
written.ok_or_else(|| unsafe_archive("binary missing from archive".into()))
}
#[cfg(test)]
pub(crate) mod test_archives {
use flate2::Compression;
use flate2::write::GzEncoder;
/// One entry of a hand-built test archive.
pub struct Entry<'a> {
pub name: &'a str,
pub kind: u8,
pub data: &'a [u8],
pub link: &'a str,
}
/// Builds a tar.gz writing the raw header name, so names tar refuses to create (`..`,
/// absolute) can be tested.
pub fn build(entries: &[Entry]) -> Vec<u8> {
let mut tar = Vec::new();
for entry in entries {
let mut header = tar::Header::new_ustar();
let name = entry.name.as_bytes();
header.as_old_mut().name[..name.len()].copy_from_slice(name);
let link = entry.link.as_bytes();
header.as_old_mut().linkname[..link.len()].copy_from_slice(link);
header.set_size(entry.data.len() as u64);
header.set_mode(0o755);
header.set_entry_type(tar::EntryType::new(entry.kind));
header.set_cksum();
tar.extend_from_slice(header.as_bytes());
tar.extend_from_slice(entry.data);
let pad = (512 - entry.data.len() % 512) % 512;
tar.extend(std::iter::repeat_n(0u8, pad));
}
tar.extend(std::iter::repeat_n(0u8, 1024));
let mut gz = GzEncoder::new(Vec::new(), Compression::default());
std::io::Write::write_all(&mut gz, &tar).unwrap();
gz.finish().unwrap()
}
pub fn single(name: &str, data: &[u8]) -> Vec<u8> {
build(&[Entry {
name,
kind: b'0',
data,
link: "",
}])
}
}
#[cfg(test)]
mod tests {
use super::test_archives::*;
use super::*;
fn run(bytes: &[u8], limit: u64) -> (tempfile::TempDir, Result<u64, UpdateError>) {
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("a.tar.gz");
std::fs::write(&archive, bytes).unwrap();
let result = extract_binary(&archive, "vnox-client", &dir.path().join("out"), limit);
(dir, result)
}
#[test]
fn extracts_the_expected_binary() {
let (dir, result) = run(&single("vnox-client", b"BIN"), 100);
assert_eq!(result.unwrap(), 3);
assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"BIN");
}
#[test]
fn accepts_dot_slash_prefix() {
assert!(run(&single("./vnox-client", b"BIN"), 100).1.is_ok());
}
#[test]
fn rejects_path_traversal() {
for name in [
"../vnox-client",
"../../etc/passwd",
"/etc/passwd",
"a/../vnox-client",
] {
let (dir, result) = run(&single(name, b"x"), 100);
assert!(
matches!(result, Err(UpdateError::UnsafeArchive(_))),
"{name}"
);
assert!(!dir.path().join("out").exists());
}
}
#[test]
fn rejects_nested_and_extra_entries() {
assert!(run(&single("a/b/vnox-client", b"x"), 100).1.is_err());
assert!(run(&single("dir/other", b"x"), 100).1.is_err());
let two = build(&[
Entry {
name: "vnox-client",
kind: b'0',
data: b"x",
link: "",
},
Entry {
name: "other",
kind: b'0',
data: b"x",
link: "",
},
]);
assert!(run(&two, 100).1.is_err());
let dup = build(&[
Entry {
name: "vnox-client",
kind: b'0',
data: b"x",
link: "",
},
Entry {
name: "vnox-client",
kind: b'0',
data: b"y",
link: "",
},
]);
assert!(run(&dup, 100).1.is_err());
}
#[test]
fn rejects_symlink_and_hardlink_entries() {
for kind in *b"21" {
let bytes = build(&[Entry {
name: "vnox-client",
kind,
data: b"",
link: "/etc/passwd",
}]);
let (dir, result) = run(&bytes, 100);
assert!(matches!(result, Err(UpdateError::UnsafeArchive(_))));
assert!(!dir.path().join("out").exists());
}
}
#[test]
fn rejects_directory_entry() {
let bytes = build(&[Entry {
name: "vnox-client",
kind: b'5',
data: b"",
link: "",
}]);
assert!(run(&bytes, 100).1.is_err());
}
#[test]
fn rejects_oversized_binary() {
let (_dir, result) = run(&single("vnox-client", &[0u8; 500]), 100);
assert!(matches!(result, Err(UpdateError::TooLarge)));
}
#[test]
fn rejects_missing_binary_and_garbage() {
assert!(run(&build(&[]), 100).1.is_err());
assert!(run(b"not gzip", 100).1.is_err());
}
fn file<'a>(name: &'a str, data: &'a [u8]) -> Entry<'a> {
Entry {
name,
kind: b'0',
data,
link: "",
}
}
#[test]
fn accepts_the_release_ci_layout() {
let bytes = build(&[
Entry {
name: "vnox-client-0.2.0-linux-x86_64/",
kind: b'5',
data: b"",
link: "",
},
file("vnox-client-0.2.0-linux-x86_64/vnox-client", b"BIN"),
file("vnox-client-0.2.0-linux-x86_64/LICENSE", b"lic"),
file("vnox-client-0.2.0-linux-x86_64/README.md", b"readme"),
]);
let (dir, result) = run(&bytes, 100);
assert_eq!(result.unwrap(), 3);
assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"BIN");
// Only the binary is written.
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2);
}
#[test]
fn rejects_mixed_or_multiple_wrappers() {
let two = build(&[file("a/vnox-client", b"x"), file("b/LICENSE", b"x")]);
assert!(run(&two, 100).1.is_err());
let mixed = build(&[file("LICENSE", b"x"), file("a/vnox-client", b"x")]);
assert!(run(&mixed, 100).1.is_err());
}
fn zip_bytes(entries: &[(&str, &[u8])]) -> Vec<u8> {
use std::io::Write;
let mut out = std::io::Cursor::new(Vec::new());
let mut zip = zip::ZipWriter::new(&mut out);
for (name, data) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(data).unwrap();
}
zip.finish().unwrap();
out.into_inner()
}
#[test]
fn extracts_from_a_zip_and_rejects_bad_zips() {
let good = zip_bytes(&[("w/vnox-client", b"EXE"), ("w/LICENSE", b"l")]);
let (dir, result) = run(&good, 100);
assert_eq!(result.unwrap(), 3);
assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"EXE");
for name in [
"../vnox-client",
"/abs/vnox-client",
"w\\..\\vnox-client",
"w/x/vnox-client",
] {
let bad = zip_bytes(&[(name, b"x")]);
assert!(
matches!(run(&bad, 100).1, Err(UpdateError::UnsafeArchive(_))),
"{name}"
);
}
assert!(matches!(
run(&zip_bytes(&[("vnox-client", &[0u8; 500])]), 100).1,
Err(UpdateError::TooLarge)
));
}
}

62
src/update/feed.rs Normal file
View file

@ -0,0 +1,62 @@
//! Where release metadata comes from.
use std::future::Future;
use std::pin::Pin;
use serde::Deserialize;
use super::UpdateError;
use super::http::{self, HttpPolicy};
use super::manifest::MAX_MANIFEST_BYTES;
const MAX_RELEASE_JSON_BYTES: u64 = 512 * 1024;
const MAX_SIGNATURE_BYTES: u64 = 4096;
/// Optional hook for asking the Central server which client version is latest.
///
/// No Central endpoint for this is documented yet, so the client ships without an implementation.
/// A source is advisory only: its answer is shown to the person but never causes anything to be
/// downloaded or installed; only the signed Gitea manifest does.
pub trait CentralVersionSource: Send + Sync {
fn latest_version(
&self,
) -> Pin<Box<dyn Future<Output = Result<Option<String>, UpdateError>> + Send + '_>>;
}
#[derive(Deserialize)]
struct Release {
#[serde(default)]
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// Downloads `manifest.json` and `manifest.json.sig` of the latest Gitea release.
/// Returns `(manifest_bytes, signature_bytes)`, both still unverified.
pub async fn fetch_latest_manifest(
policy: &HttpPolicy,
api_base: &str,
repo: &str,
) -> Result<(Vec<u8>, Vec<u8>), UpdateError> {
let api = format!("{api_base}/api/v1/repos/{repo}/releases/latest");
let json = http::fetch_bytes(policy, &api, MAX_RELEASE_JSON_BYTES).await?;
let release: Release =
serde_json::from_slice(&json).map_err(|e| UpdateError::Manifest(e.to_string()))?;
let find = |name: &str| {
release
.assets
.iter()
.find(|asset| asset.name == name)
.map(|asset| asset.browser_download_url.clone())
.ok_or_else(|| UpdateError::Manifest(format!("release has no `{name}` asset")))
};
let manifest_url = find("manifest.json")?;
let signature_url = find("manifest.json.sig")?;
let manifest = http::fetch_bytes(policy, &manifest_url, MAX_MANIFEST_BYTES as u64).await?;
let signature = http::fetch_bytes(policy, &signature_url, MAX_SIGNATURE_BYTES).await?;
Ok((manifest, signature))
}

462
src/update/http.rs Normal file
View file

@ -0,0 +1,462 @@
//! A small, strict HTTP/1.1 GET client for the updater.
//!
//! It only talks to allow-listed hosts, over HTTPS unless a test policy says otherwise, follows a
//! bounded number of redirects (each one re-checked against the same policy) and never keeps more
//! than a caller-given number of body bytes.
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use super::UpdateError;
const MAX_HEADER_BYTES: usize = 16 * 1024;
const MAX_HEADER_LINES: usize = 100;
/// Which URLs the updater may fetch.
#[derive(Clone, Debug)]
pub struct HttpPolicy {
/// Lower case host names that may be contacted, including after a redirect.
pub allowed_hosts: Vec<String>,
/// When true only `https://` URLs are accepted. Only tests turn this off.
pub require_https: bool,
pub max_redirects: u8,
/// Limit for connecting and for receiving the response headers.
pub connect_timeout: Duration,
/// Limit for reading each chunk of the body, so a stalled server cannot hang an update.
pub read_timeout: Duration,
}
impl HttpPolicy {
/// The production policy: HTTPS to the release host only.
pub fn production() -> Self {
Self {
allowed_hosts: vec![super::RELEASE_HOST.to_string()],
require_https: true,
max_redirects: 3,
connect_timeout: Duration::from_secs(15),
read_timeout: Duration::from_secs(30),
}
}
}
/// A parsed `http(s)` URL.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Url {
pub https: bool,
pub host: String,
pub port: u16,
/// Path and query, always starting with `/`.
pub target: String,
}
impl Url {
/// Parses and validates `text` against `policy`.
pub fn parse(text: &str, policy: &HttpPolicy) -> Result<Url, UpdateError> {
let reject = |why: &str| UpdateError::UrlRejected(format!("{why}: {text}"));
if !text.is_ascii() || text.bytes().any(|b| b.is_ascii_control() || b == b' ') {
return Err(reject("invalid characters"));
}
let (https, rest) = if let Some(rest) = text.strip_prefix("https://") {
(true, rest)
} else if let Some(rest) = text.strip_prefix("http://") {
if policy.require_https {
return Err(reject("plain HTTP is not allowed"));
}
(false, rest)
} else {
return Err(reject("unsupported scheme"));
};
let rest = rest.split('#').next().unwrap_or("");
let (authority, target) = match rest.find(['/', '?']) {
Some(index) => {
let (authority, tail) = rest.split_at(index);
let target = if tail.starts_with('/') {
tail.to_string()
} else {
format!("/{tail}")
};
(authority, target)
}
None => (rest, "/".to_string()),
};
if authority.contains('@') || authority.is_empty() || authority.starts_with('[') {
return Err(reject("invalid authority"));
}
let (host, port) = match authority.rsplit_once(':') {
Some((host, port)) => (
host,
port.parse::<u16>().map_err(|_| reject("invalid port"))?,
),
None => (authority, if https { 443 } else { 80 }),
};
let host = host.to_ascii_lowercase();
if !policy.allowed_hosts.contains(&host) {
return Err(reject("host is not allowed"));
}
Ok(Url {
https,
host,
port,
target,
})
}
fn origin(&self) -> String {
let scheme = if self.https { "https" } else { "http" };
format!("{scheme}://{}:{}", self.host, self.port)
}
}
fn tls_config() -> Result<Arc<rustls::ClientConfig>, UpdateError> {
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|error| UpdateError::Network(error.to_string()))?
.with_root_certificates(roots)
.with_no_client_auth();
Ok(Arc::new(config))
}
async fn within<T>(
limit: Duration,
what: &str,
future: impl std::future::Future<Output = std::io::Result<T>>,
) -> Result<T, UpdateError> {
match tokio::time::timeout(limit, future).await {
Ok(Ok(value)) => Ok(value),
Ok(Err(error)) => Err(UpdateError::Network(format!("{what}: {error}"))),
Err(_) => Err(UpdateError::Network(format!("{what}: timed out"))),
}
}
/// Fetches `url` and feeds the body to `sink` in pieces. The body must not exceed `max_bytes`;
/// a larger announced or actual body aborts the transfer with [`UpdateError::TooLarge`].
pub async fn fetch(
policy: &HttpPolicy,
url: &str,
max_bytes: u64,
sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send),
) -> Result<(), UpdateError> {
let mut current = Url::parse(url, policy)?;
for _ in 0..=policy.max_redirects {
match fetch_once(policy, &current, max_bytes, sink).await? {
Outcome::Done => return Ok(()),
Outcome::Redirect(location) => {
let next = if location.starts_with('/') {
format!("{}{}", current.origin(), location)
} else {
location
};
current = Url::parse(&next, policy)?;
}
}
}
Err(UpdateError::Network("too many redirects".into()))
}
/// Convenience wrapper that collects the body in memory.
pub async fn fetch_bytes(
policy: &HttpPolicy,
url: &str,
max_bytes: u64,
) -> Result<Vec<u8>, UpdateError> {
let mut body = Vec::new();
fetch(policy, url, max_bytes, &mut |chunk| {
body.extend_from_slice(chunk);
Ok(())
})
.await?;
Ok(body)
}
enum Outcome {
Done,
Redirect(String),
}
async fn fetch_once(
policy: &HttpPolicy,
url: &Url,
max_bytes: u64,
sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send),
) -> Result<Outcome, UpdateError> {
let tcp = within(
policy.connect_timeout,
"connect",
TcpStream::connect((url.host.as_str(), url.port)),
)
.await?;
if url.https {
let name = rustls::pki_types::ServerName::try_from(url.host.clone())
.map_err(|_| UpdateError::UrlRejected(url.host.clone()))?;
let connector = tokio_rustls::TlsConnector::from(tls_config()?);
let tls = within(
policy.connect_timeout,
"tls handshake",
connector.connect(name, tcp),
)
.await?;
exchange(policy, url, tls, max_bytes, sink).await
} else {
exchange(policy, url, tcp, max_bytes, sink).await
}
}
async fn read_line<R: AsyncRead + Unpin>(
reader: &mut BufReader<R>,
timeout: Duration,
budget: &mut usize,
) -> Result<String, UpdateError> {
let mut line = Vec::new();
let read = within(timeout, "read", async {
reader
.take(*budget as u64 + 1)
.read_until(b'\n', &mut line)
.await
})
.await?;
if read == 0 || read > *budget || !line.ends_with(b"\n") {
return Err(UpdateError::Network(
"malformed or oversized response".into(),
));
}
*budget -= read;
let text = String::from_utf8_lossy(&line);
Ok(text.trim_end_matches(['\r', '\n']).to_string())
}
async fn exchange<S>(
policy: &HttpPolicy,
url: &Url,
stream: S,
max_bytes: u64,
sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send),
) -> Result<Outcome, UpdateError>
where
S: AsyncRead + AsyncWriteExt + Unpin,
{
let mut stream = stream;
let request = format!(
"GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: vnox-client-updater/{}\r\nAccept: */*\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n",
url.target,
url.host,
super::CLIENT_VERSION
);
within(policy.connect_timeout, "send request", async {
stream.write_all(request.as_bytes()).await?;
stream.flush().await
})
.await?;
let mut reader = BufReader::new(stream);
let mut budget = MAX_HEADER_BYTES;
let status_line = read_line(&mut reader, policy.connect_timeout, &mut budget).await?;
let status: u16 = status_line
.split_whitespace()
.nth(1)
.and_then(|code| code.parse().ok())
.filter(|_| status_line.starts_with("HTTP/1."))
.ok_or_else(|| UpdateError::Network("malformed status line".into()))?;
let mut content_length: Option<u64> = None;
let mut chunked = false;
let mut location = None;
for _ in 0..MAX_HEADER_LINES {
let line = read_line(&mut reader, policy.connect_timeout, &mut budget).await?;
if line.is_empty() {
return finish(
policy,
&mut reader,
status,
content_length,
chunked,
location,
max_bytes,
sink,
)
.await;
}
if let Some((name, value)) = line.split_once(':') {
let value = value.trim();
match name.trim().to_ascii_lowercase().as_str() {
"content-length" => {
content_length = Some(
value
.parse()
.map_err(|_| UpdateError::Network("bad content-length".into()))?,
);
}
"transfer-encoding" => chunked = value.eq_ignore_ascii_case("chunked"),
"location" => location = Some(value.to_string()),
_ => {}
}
}
}
Err(UpdateError::Network("too many response headers".into()))
}
#[allow(clippy::too_many_arguments)]
async fn finish<R: AsyncRead + Unpin>(
policy: &HttpPolicy,
reader: &mut BufReader<R>,
status: u16,
content_length: Option<u64>,
chunked: bool,
location: Option<String>,
max_bytes: u64,
sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send),
) -> Result<Outcome, UpdateError> {
if matches!(status, 301 | 302 | 303 | 307 | 308) {
return location
.map(Outcome::Redirect)
.ok_or_else(|| UpdateError::Network("redirect without location".into()));
}
if status != 200 {
return Err(UpdateError::Http(status));
}
if content_length.is_some_and(|length| length > max_bytes) {
return Err(UpdateError::TooLarge);
}
let mut total: u64 = 0;
let mut emit = |data: &[u8]| -> Result<(), UpdateError> {
total += data.len() as u64;
if total > max_bytes {
return Err(UpdateError::TooLarge);
}
sink(data)
};
if chunked {
loop {
let mut budget = 1024;
let size_line = read_line(reader, policy.read_timeout, &mut budget).await?;
let size_text = size_line.split(';').next().unwrap_or("").trim();
let mut size = u64::from_str_radix(size_text, 16)
.map_err(|_| UpdateError::Network("bad chunk size".into()))?;
if size == 0 {
return Ok(Outcome::Done);
}
if size > max_bytes {
return Err(UpdateError::TooLarge);
}
let mut buffer = [0u8; 16 * 1024];
while size > 0 {
let want = size.min(buffer.len() as u64) as usize;
let read = within(
policy.read_timeout,
"read body",
reader.read(&mut buffer[..want]),
)
.await?;
if read == 0 {
return Err(UpdateError::Network("truncated body".into()));
}
emit(&buffer[..read])?;
size -= read as u64;
}
let mut budget = 16;
read_line(reader, policy.read_timeout, &mut budget).await?;
}
}
let mut buffer = [0u8; 16 * 1024];
loop {
let read = within(policy.read_timeout, "read body", reader.read(&mut buffer)).await?;
if read == 0 {
break;
}
emit(&buffer[..read])?;
}
match content_length {
Some(length) if length != total => Err(UpdateError::Network("truncated body".into())),
_ => Ok(Outcome::Done),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_policy() -> HttpPolicy {
HttpPolicy {
allowed_hosts: vec!["127.0.0.1".into(), "git.wihuk.pro".into()],
require_https: false,
max_redirects: 3,
connect_timeout: Duration::from_secs(2),
read_timeout: Duration::from_secs(2),
}
}
#[test]
fn production_policy_rejects_http_and_foreign_hosts() {
let policy = HttpPolicy::production();
assert!(Url::parse("https://git.wihuk.pro/a/b", &policy).is_ok());
assert!(Url::parse("http://git.wihuk.pro/a", &policy).is_err());
assert!(Url::parse("https://evil.example/a", &policy).is_err());
assert!(Url::parse("https://git.wihuk.pro.evil.example/a", &policy).is_err());
assert!(Url::parse("https://git.wihuk.pro@evil.example/a", &policy).is_err());
assert!(Url::parse("ftp://git.wihuk.pro/a", &policy).is_err());
assert!(Url::parse("https://GIT.wihuk.pro/a", &policy).is_ok());
}
#[tokio::test]
async fn fetches_plain_body_and_chunked_body() {
let server = crate::update::test_support::FakeServer::start().await;
server.route("/plain", 200, b"hello".to_vec());
server.route_chunked("/chunked", b"hello world".to_vec());
let policy = test_policy();
let got = fetch_bytes(&policy, &server.url("/plain"), 100)
.await
.unwrap();
assert_eq!(got, b"hello");
let got = fetch_bytes(&policy, &server.url("/chunked"), 100)
.await
.unwrap();
assert_eq!(got, b"hello world");
}
#[tokio::test]
async fn body_over_limit_is_rejected() {
let server = crate::update::test_support::FakeServer::start().await;
server.route("/big", 200, vec![1u8; 5000]);
server.route_chunked("/bigchunk", vec![1u8; 5000]);
let policy = test_policy();
assert!(matches!(
fetch_bytes(&policy, &server.url("/big"), 1000).await,
Err(UpdateError::TooLarge)
));
assert!(matches!(
fetch_bytes(&policy, &server.url("/bigchunk"), 1000).await,
Err(UpdateError::TooLarge)
));
}
#[tokio::test]
async fn redirect_to_disallowed_host_is_refused() {
let server = crate::update::test_support::FakeServer::start().await;
server.redirect("/r", "http://evil.example/x");
server.redirect("/ok", "/plain");
server.route("/plain", 200, b"fine".to_vec());
let policy = test_policy();
assert!(matches!(
fetch_bytes(&policy, &server.url("/r"), 100).await,
Err(UpdateError::UrlRejected(_))
));
assert_eq!(
fetch_bytes(&policy, &server.url("/ok"), 100).await.unwrap(),
b"fine"
);
}
#[tokio::test]
async fn error_status_is_reported() {
let server = crate::update::test_support::FakeServer::start().await;
let policy = test_policy();
assert!(matches!(
fetch_bytes(&policy, &server.url("/missing"), 100).await,
Err(UpdateError::Http(404))
));
}
}

175
src/update/keys.rs Normal file
View file

@ -0,0 +1,175 @@
//! Release signing key and detached signature verification.
//!
//! The manifest is signed with Ed25519 over its exact bytes. The signature is verified before the
//! manifest is parsed, so a forged or tampered document never reaches the JSON parser.
use ed25519_dalek::{Signature, VerifyingKey};
use super::UpdateError;
/// Public half of the release signing key, embedded in the binary.
///
/// This is a PLACEHOLDER (all zeros). While it is unchanged the updater refuses to run
/// ([`is_placeholder`]), so a build without a real key can never accept an update.
///
/// To replace it: generate an Ed25519 key pair offline, keep the secret key only in the CI
/// secret store (`manifest.json.sig` is produced from it), and paste the 32 byte public key
/// here. Rotating the key requires shipping a release signed with the old key that embeds the new
/// one.
pub const RELEASE_PUBLIC_KEY: [u8; 32] = [0u8; 32];
/// Second public key accepted during a key rotation, `None` otherwise. A release that embeds both
/// keys is signed with the old one; the next releases are signed with the new one.
pub const RELEASE_PUBLIC_KEY_NEXT: Option<[u8; 32]> = None;
/// The keys a production build accepts.
pub fn production_keys() -> Vec<[u8; 32]> {
std::iter::once(RELEASE_PUBLIC_KEY)
.chain(RELEASE_PUBLIC_KEY_NEXT)
.collect()
}
/// True when `key` is the unconfigured placeholder.
pub fn is_placeholder(key: &[u8; 32]) -> bool {
key.iter().all(|byte| *byte == 0)
}
/// Decodes a detached signature. The release CI writes base64 text; raw 64 bytes and 128
/// character hex text are accepted too.
pub fn decode_signature(bytes: &[u8]) -> Result<Signature, UpdateError> {
let raw: [u8; 64] = if bytes.len() == 64 {
bytes.try_into().map_err(|_| UpdateError::BadSignature)?
} else {
let text = std::str::from_utf8(bytes)
.map_err(|_| UpdateError::BadSignature)?
.trim();
let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, text)
.ok()
.filter(|decoded| decoded.len() == 64)
.or_else(|| hex::decode(text).ok())
.ok_or(UpdateError::BadSignature)?;
decoded.try_into().map_err(|_| UpdateError::BadSignature)?
};
Ok(Signature::from_bytes(&raw))
}
/// Verifies against any of `keys` (placeholders are skipped). With no usable key, updates are off.
pub fn verify_any(keys: &[[u8; 32]], message: &[u8], signature: &[u8]) -> Result<(), UpdateError> {
let usable: Vec<&[u8; 32]> = keys.iter().filter(|k| !is_placeholder(k)).collect();
if usable.is_empty() {
return Err(UpdateError::NoReleaseKey);
}
let mut last = UpdateError::BadSignature;
for key in usable {
match verify(key, message, signature) {
Ok(()) => return Ok(()),
Err(error) => last = error,
}
}
Err(last)
}
/// Verifies `signature` over exactly `message` with the strict Ed25519 rules.
pub fn verify(key: &[u8; 32], message: &[u8], signature: &[u8]) -> Result<(), UpdateError> {
if is_placeholder(key) {
return Err(UpdateError::NoReleaseKey);
}
let key = VerifyingKey::from_bytes(key).map_err(|_| UpdateError::NoReleaseKey)?;
let signature = decode_signature(signature)?;
key.verify_strict(message, &signature)
.map_err(|_| UpdateError::BadSignature)
}
#[cfg(test)]
pub(crate) mod test_keys {
use ed25519_dalek::{Signer, SigningKey};
/// Deterministic key used only by tests.
pub fn signing_key() -> SigningKey {
SigningKey::from_bytes(&[7u8; 32])
}
pub fn public() -> [u8; 32] {
signing_key().verifying_key().to_bytes()
}
pub fn sign(message: &[u8]) -> Vec<u8> {
signing_key().sign(message).to_bytes().to_vec()
}
}
#[cfg(test)]
mod tests {
use super::test_keys::*;
use super::*;
#[test]
fn valid_signature_verifies() {
let msg = b"{\"version\":\"1.0.0\"}";
verify(&public(), msg, &sign(msg)).unwrap();
}
#[test]
fn hex_signature_is_accepted() {
let msg = b"manifest";
let text = format!("{}\n", hex::encode(sign(msg)));
verify(&public(), msg, text.as_bytes()).unwrap();
}
#[test]
fn tampered_message_fails() {
let sig = sign(b"manifest");
assert!(matches!(
verify(&public(), b"manifesT", &sig),
Err(UpdateError::BadSignature)
));
}
#[test]
fn bad_signature_fails() {
let mut sig = sign(b"manifest");
sig[3] ^= 1;
assert!(verify(&public(), b"manifest", &sig).is_err());
assert!(verify(&public(), b"manifest", b"short").is_err());
}
#[test]
fn wrong_key_fails() {
let other = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
let key = other.verifying_key().to_bytes();
assert!(verify(&key, b"manifest", &sign(b"manifest")).is_err());
}
#[test]
fn base64_signature_from_the_ci_is_accepted() {
let msg = b"manifest";
let text = format!(
"{}\n",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, sign(msg))
);
verify(&public(), msg, text.as_bytes()).unwrap();
}
#[test]
fn either_rotation_key_may_sign() {
let old = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32])
.verifying_key()
.to_bytes();
let msg = b"manifest";
verify_any(&[old, public()], msg, &sign(msg)).unwrap();
assert!(verify_any(&[old], msg, &sign(msg)).is_err());
assert!(matches!(
verify_any(&[RELEASE_PUBLIC_KEY], msg, &sign(msg)),
Err(UpdateError::NoReleaseKey)
));
}
#[test]
fn placeholder_key_never_verifies() {
assert!(is_placeholder(&RELEASE_PUBLIC_KEY));
assert!(matches!(
verify(&RELEASE_PUBLIC_KEY, b"m", &sign(b"m")),
Err(UpdateError::NoReleaseKey)
));
}
}

423
src/update/layout.rs Normal file
View file

@ -0,0 +1,423 @@
//! On-disk release layout: atomic install, rollback and Windows swap-on-start.
//!
//! Linux layout (matches the existing install):
//!
//! ```text
//! ~/.local/bin/vnox-client symlink to the active release binary
//! ~/.local/lib/vnox/releases/<version>/vnox-client
//! ~/.local/lib/vnox/releases/state.json {current, previous, pending}
//! ```
//!
//! Installing builds the new release in a hidden staging directory, renames it into place, then
//! replaces the symlink with an atomic `rename`, so the launcher always points at a complete
//! binary. The release that was active stays on disk as `previous` for [`rollback`].
//! Profile and chat data live under the config and data directories and are never touched.
//!
//! On Windows a running executable cannot be replaced, so the new binary is only staged and
//! recorded as `pending`; [`apply_pending`] swaps it in at the next start.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::UpdateError;
use super::archive::{self, BINARY_NAME};
/// How a new release becomes the active one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Activation {
/// Atomically repoint the launcher symlink (Unix).
SwapLink,
/// Stage only; swap the executable on the next start (Windows).
StageForRestart,
}
/// Where releases, the launcher and downloads live.
#[derive(Clone, Debug)]
pub struct Layout {
pub releases_dir: PathBuf,
/// Symlink (Unix) or the executable itself (Windows) that starts the client.
pub launcher: PathBuf,
/// Verified downloads waiting for installation.
pub downloads_dir: PathBuf,
pub activation: Activation,
}
/// What the layout knows about releases, stored next to them.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InstallState {
pub current: Option<PathBuf>,
pub previous: Option<PathBuf>,
pub pending: Option<PathBuf>,
}
impl Layout {
/// The default per-user layout for this platform.
pub fn user_default() -> Option<Layout> {
let downloads_dir = dirs::data_local_dir()?.join("vnox/updates");
if cfg!(windows) {
Some(Layout {
releases_dir: dirs::data_local_dir()?.join("vnox/releases"),
launcher: std::env::current_exe().ok()?,
downloads_dir,
activation: Activation::StageForRestart,
})
} else {
let home = dirs::home_dir()?;
Some(Layout {
releases_dir: home.join(".local/lib/vnox/releases"),
launcher: home.join(".local/bin/vnox-client"),
downloads_dir,
activation: Activation::SwapLink,
})
}
}
fn state_path(&self) -> PathBuf {
self.releases_dir.join("state.json")
}
/// Reads the install state; a missing or unreadable file means nothing is recorded.
pub fn state(&self) -> InstallState {
std::fs::read(self.state_path())
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
fn save_state(&self, state: &InstallState) -> Result<(), UpdateError> {
let bytes = serde_json::to_vec_pretty(state).map_err(|e| UpdateError::Io(e.to_string()))?;
write_atomic(&self.state_path(), &bytes)
}
/// Extracts `archive` as release `version` and makes it the active (or pending) release.
/// `max_binary_bytes` bounds the extracted binary.
pub fn install_archive(
&self,
version: &str,
archive_path: &Path,
max_binary_bytes: u64,
) -> Result<PathBuf, UpdateError> {
validate_version_dir(version)?;
std::fs::create_dir_all(&self.releases_dir).map_err(UpdateError::io)?;
let final_dir = self.releases_dir.join(version);
let state = self.state();
let in_use = [&state.current, &state.previous, &state.pending]
.into_iter()
.flatten()
.any(|path| path.starts_with(&final_dir));
if in_use {
return Err(UpdateError::AlreadyInstalled);
}
let staging = self
.releases_dir
.join(format!(".staging-{version}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir(&staging).map_err(UpdateError::io)?;
let built = (|| {
archive::extract_binary(
archive_path,
BINARY_NAME,
&staging.join(BINARY_NAME),
max_binary_bytes,
)?;
// A leftover directory from an interrupted install is replaced.
if final_dir.exists() {
std::fs::remove_dir_all(&final_dir).map_err(UpdateError::io)?;
}
std::fs::rename(&staging, &final_dir).map_err(UpdateError::io)
})();
if let Err(error) = built {
let _ = std::fs::remove_dir_all(&staging);
return Err(error);
}
let binary = final_dir.join(BINARY_NAME);
self.activate(&binary)?;
self.prune();
Ok(binary)
}
/// Makes `target` the active release (or the pending one, for the restart mode).
fn activate(&self, target: &Path) -> Result<(), UpdateError> {
let mut state = self.state();
match self.activation {
Activation::StageForRestart => {
state.pending = Some(target.to_path_buf());
}
Activation::SwapLink => {
let old = self.current_target();
swap_link(target, &self.launcher)?;
if let Some(old) = old.filter(|old| old != target) {
state.previous = Some(old);
}
state.current = Some(target.to_path_buf());
}
}
self.save_state(&state)
}
/// The binary the launcher points at now, if it can be determined.
fn current_target(&self) -> Option<PathBuf> {
match std::fs::symlink_metadata(&self.launcher) {
Ok(meta) if meta.file_type().is_symlink() => std::fs::read_link(&self.launcher).ok(),
Ok(meta) if meta.is_file() => {
// A plain file (not a symlink): keep a copy so it can be rolled back to.
let legacy = self.releases_dir.join("legacy").join(BINARY_NAME);
std::fs::create_dir_all(legacy.parent()?).ok()?;
std::fs::copy(&self.launcher, &legacy).ok()?;
Some(legacy)
}
_ => None,
}
}
/// Switches back to the previous release. Rolling back twice returns to the newer one.
pub fn rollback(&self) -> Result<PathBuf, UpdateError> {
let state = self.state();
let previous = state.previous.ok_or(UpdateError::NoPreviousRelease)?;
if !previous.is_file() {
return Err(UpdateError::NoPreviousRelease);
}
self.activate(&previous)?;
Ok(previous)
}
/// Windows start-up step: swaps a staged binary over the launcher. Returns true when a swap
/// happened and the process should restart into the new binary.
pub fn apply_pending(&self) -> Result<bool, UpdateError> {
let mut state = self.state();
let Some(pending) = state.pending.clone() else {
return Ok(false);
};
if !pending.is_file() {
state.pending = None;
self.save_state(&state)?;
return Ok(false);
}
let sibling = |suffix: &str| {
let mut name = self.launcher.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
};
let (fresh, swap, backup) = (sibling(".new"), sibling(".swap"), sibling(".old"));
let _ = std::fs::remove_file(&fresh);
std::fs::copy(&pending, &fresh).map_err(UpdateError::io)?;
if self.launcher.exists() {
std::fs::rename(&self.launcher, &swap).map_err(UpdateError::io)?;
if let Err(error) = std::fs::rename(&fresh, &self.launcher) {
// Put the running executable back so the client can still start.
let _ = std::fs::rename(&swap, &self.launcher);
return Err(UpdateError::io(error));
}
let _ = std::fs::remove_file(&backup);
std::fs::rename(&swap, &backup).map_err(UpdateError::io)?;
state.previous = Some(backup);
} else {
std::fs::rename(&fresh, &self.launcher).map_err(UpdateError::io)?;
}
state.current = Some(self.launcher.clone());
state.pending = None;
self.save_state(&state)?;
Ok(true)
}
/// Deletes old version directories, keeping the current, previous and pending releases.
/// Directories whose names are not plain versions are left alone.
fn prune(&self) {
let state = self.state();
let keep: Vec<&PathBuf> = [&state.current, &state.previous, &state.pending]
.into_iter()
.flatten()
.collect();
let Ok(entries) = std::fs::read_dir(&self.releases_dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let is_version = entry
.file_name()
.to_str()
.is_some_and(|name| semver::Version::parse(name).is_ok());
if is_version && path.is_dir() && !keep.iter().any(|kept| kept.starts_with(&path)) {
let _ = std::fs::remove_dir_all(&path);
}
}
}
}
/// A version used as a directory name must be a plain semver, never a path.
fn validate_version_dir(version: &str) -> Result<(), UpdateError> {
if semver::Version::parse(version).is_err() || version.contains(['/', '\\']) {
return Err(UpdateError::Manifest(format!(
"invalid version `{version}`"
)));
}
Ok(())
}
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), UpdateError> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes).map_err(UpdateError::io)?;
std::fs::rename(&tmp, path).map_err(UpdateError::io)
}
#[cfg(unix)]
fn swap_link(target: &Path, launcher: &Path) -> Result<(), UpdateError> {
if let Some(parent) = launcher.parent() {
std::fs::create_dir_all(parent).map_err(UpdateError::io)?;
}
let tmp = launcher.with_file_name(".vnox-client.swap");
let _ = std::fs::remove_file(&tmp);
std::os::unix::fs::symlink(target, &tmp).map_err(UpdateError::io)?;
std::fs::rename(&tmp, launcher).map_err(|error| {
let _ = std::fs::remove_file(&tmp);
UpdateError::io(error)
})
}
#[cfg(not(unix))]
fn swap_link(_target: &Path, _launcher: &Path) -> Result<(), UpdateError> {
Err(UpdateError::Io("link swap is not supported here".into()))
}
#[cfg(test)]
mod tests {
use super::super::archive::test_archives::single;
use super::*;
fn fixture(mode: Activation) -> (tempfile::TempDir, Layout) {
let dir = tempfile::tempdir().unwrap();
let layout = Layout {
releases_dir: dir.path().join("lib/releases"),
launcher: dir.path().join("bin/vnox-client"),
downloads_dir: dir.path().join("dl"),
activation: mode,
};
(dir, layout)
}
fn archive(dir: &Path, name: &str, body: &[u8]) -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, single(BINARY_NAME, body)).unwrap();
path
}
#[cfg(unix)]
#[test]
fn install_swaps_link_and_keeps_previous_then_rolls_back() {
let (dir, layout) = fixture(Activation::SwapLink);
let a1 = archive(dir.path(), "1.tgz", b"v1");
let a2 = archive(dir.path(), "2.tgz", b"v2");
layout.install_archive("0.1.0", &a1, 1000).unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1");
layout.install_archive("0.2.0", &a2, 1000).unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v2");
let state = layout.state();
assert!(
state
.previous
.as_ref()
.unwrap()
.starts_with(layout.releases_dir.join("0.1.0"))
);
layout.rollback().unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1");
// Rolling back again returns to the newer release.
layout.rollback().unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v2");
}
#[cfg(unix)]
#[test]
fn old_releases_are_pruned_but_current_and_previous_stay() {
let (dir, layout) = fixture(Activation::SwapLink);
for (i, v) in ["0.1.0", "0.2.0", "0.3.0"].iter().enumerate() {
let a = archive(dir.path(), &format!("{i}.tgz"), v.as_bytes());
layout.install_archive(v, &a, 1000).unwrap();
}
assert!(!layout.releases_dir.join("0.1.0").exists());
assert!(layout.releases_dir.join("0.2.0").exists());
assert!(layout.releases_dir.join("0.3.0").exists());
}
#[cfg(unix)]
#[test]
fn plain_file_launcher_is_preserved_for_rollback() {
let (dir, layout) = fixture(Activation::SwapLink);
std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap();
std::fs::write(&layout.launcher, b"legacy").unwrap();
let a = archive(dir.path(), "1.tgz", b"new");
layout.install_archive("0.2.0", &a, 1000).unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"new");
layout.rollback().unwrap();
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"legacy");
}
#[cfg(unix)]
#[test]
fn failed_extraction_leaves_the_active_release_untouched() {
let (dir, layout) = fixture(Activation::SwapLink);
let a1 = archive(dir.path(), "1.tgz", b"v1");
layout.install_archive("0.1.0", &a1, 1000).unwrap();
let bad = dir.path().join("bad.tgz");
std::fs::write(&bad, single("../evil", b"x")).unwrap();
assert!(layout.install_archive("0.2.0", &bad, 1000).is_err());
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1");
assert!(!layout.releases_dir.join("0.2.0").exists());
let leftovers: Vec<_> = std::fs::read_dir(&layout.releases_dir)
.unwrap()
.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with(".staging"))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn rollback_without_previous_is_an_error() {
let (_dir, layout) = fixture(Activation::SwapLink);
assert!(matches!(
layout.rollback(),
Err(UpdateError::NoPreviousRelease)
));
}
#[test]
fn version_must_not_be_a_path() {
let (dir, layout) = fixture(Activation::SwapLink);
let a = archive(dir.path(), "1.tgz", b"x");
assert!(layout.install_archive("../../x", &a, 1000).is_err());
}
#[test]
fn windows_style_install_stages_then_swaps_on_start() {
let (dir, layout) = fixture(Activation::StageForRestart);
std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap();
std::fs::write(&layout.launcher, b"old").unwrap();
let a = archive(dir.path(), "1.tgz", b"new");
layout.install_archive("0.2.0", &a, 1000).unwrap();
// Nothing replaced yet: the running executable stays as it is.
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"old");
assert!(layout.state().pending.is_some());
assert!(layout.apply_pending().unwrap());
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"new");
let state = layout.state();
assert!(state.pending.is_none());
assert_eq!(std::fs::read(state.previous.unwrap()).unwrap(), b"old");
assert!(!layout.apply_pending().unwrap());
}
#[test]
fn windows_style_rollback_stages_previous() {
let (dir, layout) = fixture(Activation::StageForRestart);
std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap();
std::fs::write(&layout.launcher, b"old").unwrap();
let a = archive(dir.path(), "1.tgz", b"new");
layout.install_archive("0.2.0", &a, 1000).unwrap();
layout.apply_pending().unwrap();
layout.rollback().unwrap();
assert!(layout.apply_pending().unwrap());
assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"old");
}
}

539
src/update/manager.rs Normal file
View file

@ -0,0 +1,539 @@
//! The update state machine: check, download and install as separate steps.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use sha2::{Digest, Sha256};
use super::feed::{self, CentralVersionSource};
use super::http::{self, HttpPolicy, Url};
use super::layout::Layout;
use super::manifest::{Artifact, Manifest, parse_version};
use super::settings::UpdateSettings;
use super::{
CHANNEL, CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_HOST, RELEASE_REPO, UpdateError, keys,
};
const MANIFEST_FILE: &str = "manifest.json";
const SIGNATURE_FILE: &str = "manifest.json.sig";
const ARCHIVE_FILE: &str = "artifact.tar.gz";
/// Everything the updater needs to know about its environment.
#[derive(Clone, Debug)]
pub struct UpdateConfig {
/// Gitea base URL, without a trailing slash.
pub api_base: String,
pub repo: String,
pub channel: String,
/// Accepted release keys; more than one only while a key is being rotated.
pub public_keys: Vec<[u8; 32]>,
pub http: HttpPolicy,
pub layout: Layout,
/// Version of the running client.
pub installed_version: String,
pub os: String,
pub arch: String,
/// Largest archive accepted.
pub max_artifact_bytes: u64,
/// Largest binary extracted from an archive.
pub max_binary_bytes: u64,
}
impl UpdateConfig {
/// Production configuration: the embedded key, the release host only, this build's version.
pub fn production(layout: Layout) -> Self {
Self {
api_base: format!("https://{RELEASE_HOST}"),
repo: RELEASE_REPO.to_string(),
channel: CHANNEL.to_string(),
public_keys: keys::production_keys(),
http: HttpPolicy::production(),
layout,
installed_version: CLIENT_VERSION.to_string(),
os: std::env::consts::OS.to_string(),
arch: std::env::consts::ARCH.to_string(),
max_artifact_bytes: 256 * 1024 * 1024,
max_binary_bytes: 512 * 1024 * 1024,
}
}
}
/// Where the updater is in its flow.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UpdatePhase {
Idle,
Checking,
UpToDate,
Available {
version: String,
},
Downloading {
version: String,
},
/// Downloaded and verified; waiting to be installed.
Ready {
version: String,
},
/// Install requested during a voice session; it runs once the session ends.
InstallDeferred {
version: String,
},
Installing {
version: String,
},
/// Installed; takes effect on the next start.
Installed {
version: String,
},
/// The installed version is older than the release's `min_version`.
ManualInstallRequired {
version: String,
},
Error(String),
}
/// A snapshot for the UI.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UpdateStatus {
pub phase: UpdatePhase,
pub installed_version: String,
pub lnex_version: String,
pub auto_update: bool,
/// Latest version reported by the optional Central source. Advisory only.
pub central_latest: Option<String>,
}
/// Result of [`UpdateManager::install`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InstallOutcome {
Installed {
version: String,
},
/// A voice session is active; the install runs when it ends.
Deferred {
version: String,
},
}
struct Candidate {
manifest_bytes: Vec<u8>,
signature: Vec<u8>,
version: String,
artifact: Artifact,
}
struct Inner {
phase: UpdatePhase,
candidate: Option<Candidate>,
staged: Option<(String, PathBuf)>,
install_deferred: bool,
central_latest: Option<String>,
settings: UpdateSettings,
}
/// Drives updates. Share it as `Arc<UpdateManager>`; every method takes `&self`.
pub struct UpdateManager {
cfg: UpdateConfig,
inner: Mutex<Inner>,
voice_active: AtomicBool,
central: Option<Arc<dyn CentralVersionSource>>,
settings_path: PathBuf,
/// Serialises check, download and install so they never overlap.
busy: tokio::sync::Mutex<()>,
}
impl UpdateManager {
pub fn new(
cfg: UpdateConfig,
central: Option<Arc<dyn CentralVersionSource>>,
settings_path: PathBuf,
) -> Arc<Self> {
let settings = UpdateSettings::load(&settings_path);
Arc::new(Self {
cfg,
inner: Mutex::new(Inner {
phase: UpdatePhase::Idle,
candidate: None,
staged: None,
install_deferred: false,
central_latest: None,
settings,
}),
voice_active: AtomicBool::new(false),
central,
settings_path,
busy: tokio::sync::Mutex::new(()),
})
}
fn lock(&self) -> MutexGuard<'_, Inner> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn set_phase(&self, phase: UpdatePhase) {
self.lock().phase = phase;
}
fn fail<T>(&self, error: UpdateError) -> Result<T, UpdateError> {
self.set_phase(UpdatePhase::Error(error.to_string()));
Err(error)
}
pub fn status(&self) -> UpdateStatus {
let inner = self.lock();
UpdateStatus {
phase: inner.phase.clone(),
installed_version: self.cfg.installed_version.clone(),
lnex_version: LNEX_PROTOCOL.to_string(),
auto_update: inner.settings.auto_update,
central_latest: inner.central_latest.clone(),
}
}
pub fn auto_update(&self) -> bool {
self.lock().settings.auto_update
}
/// Changes and persists the automatic update switch.
pub fn set_auto_update(&self, enabled: bool) -> std::io::Result<()> {
let settings = {
let mut inner = self.lock();
inner.settings.auto_update = enabled;
inner.settings.clone()
};
settings.save(&self.settings_path)
}
/// Tells the updater whether a voice session is running. Installs never run during one.
pub fn set_voice_active(&self, active: bool) {
self.voice_active.store(active, Ordering::SeqCst);
}
/// True when an install was requested during a voice session and is still waiting.
pub fn install_waiting(&self) -> bool {
self.lock().install_deferred
}
/// Step 1: looks for a newer signed release. Nothing is downloaded.
pub async fn check(&self) -> Result<UpdatePhase, UpdateError> {
let _guard = self.busy.lock().await;
self.set_phase(UpdatePhase::Checking);
if let Some(central) = &self.central {
// Advisory only; a failing Central never blocks the signed Gitea feed.
let latest = central.latest_version().await.ok().flatten();
self.lock().central_latest = latest;
}
match self.check_inner().await {
Ok(phase) => {
self.set_phase(phase.clone());
Ok(phase)
}
Err(error) => self.fail(error),
}
}
async fn check_inner(&self) -> Result<UpdatePhase, UpdateError> {
if self.cfg.public_keys.iter().all(keys::is_placeholder) {
return Err(UpdateError::NoReleaseKey);
}
let (bytes, signature) =
feed::fetch_latest_manifest(&self.cfg.http, &self.cfg.api_base, &self.cfg.repo).await?;
let manifest = Manifest::verify_and_parse(&self.cfg.public_keys, &bytes, &signature)?;
let candidate = self.cfg.evaluate(&manifest)?;
let Some(artifact) = candidate else {
self.lock().candidate = None;
return Ok(UpdatePhase::UpToDate);
};
let version = manifest.version.trim_start_matches('v').to_string();
let installed = parse_version(&self.cfg.installed_version)?;
if installed < manifest.min_version()? {
self.lock().candidate = None;
return Ok(UpdatePhase::ManualInstallRequired { version });
}
self.lock().candidate = Some(Candidate {
manifest_bytes: bytes,
signature,
version: version.clone(),
artifact,
});
Ok(UpdatePhase::Available { version })
}
/// Step 2: downloads and verifies the archive found by [`check`](Self::check).
pub async fn download(&self) -> Result<UpdatePhase, UpdateError> {
let _guard = self.busy.lock().await;
let (version, artifact, manifest_bytes, signature) = {
let inner = self.lock();
match &inner.candidate {
Some(c) => (
c.version.clone(),
c.artifact.clone(),
c.manifest_bytes.clone(),
c.signature.clone(),
),
None => {
drop(inner);
return self.fail(UpdateError::NothingDownloaded);
}
}
};
self.set_phase(UpdatePhase::Downloading {
version: version.clone(),
});
match self
.download_inner(&version, &artifact, &manifest_bytes, &signature)
.await
{
Ok(dir) => {
let mut inner = self.lock();
inner.staged = Some((version.clone(), dir));
inner.phase = UpdatePhase::Ready { version };
Ok(inner.phase.clone())
}
Err(error) => self.fail(error),
}
}
async fn download_inner(
&self,
version: &str,
artifact: &Artifact,
manifest_bytes: &[u8],
signature: &[u8],
) -> Result<PathBuf, UpdateError> {
let dir = self.cfg.layout.downloads_dir.join(version);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(UpdateError::io)?;
let partial = dir.join(format!("{ARCHIVE_FILE}.part"));
let result = self.fetch_archive(artifact, &partial).await;
if let Err(error) = result {
let _ = std::fs::remove_dir_all(&dir);
return Err(error);
}
std::fs::write(dir.join(MANIFEST_FILE), manifest_bytes).map_err(UpdateError::io)?;
std::fs::write(dir.join(SIGNATURE_FILE), signature).map_err(UpdateError::io)?;
std::fs::rename(&partial, dir.join(ARCHIVE_FILE)).map_err(UpdateError::io)?;
Ok(dir)
}
async fn fetch_archive(&self, artifact: &Artifact, partial: &Path) -> Result<(), UpdateError> {
let mut file = std::fs::File::create(partial).map_err(UpdateError::io)?;
let mut hasher = Sha256::new();
let mut total = 0u64;
http::fetch(&self.cfg.http, &artifact.url, artifact.size, &mut |chunk| {
hasher.update(chunk);
total += chunk.len() as u64;
std::io::Write::write_all(&mut file, chunk).map_err(UpdateError::io)
})
.await?;
file.sync_all().map_err(UpdateError::io)?;
if total != artifact.size {
return Err(UpdateError::SizeMismatch);
}
if hex::encode(hasher.finalize()) != artifact.sha256 {
return Err(UpdateError::HashMismatch);
}
Ok(())
}
/// Looks for a verified download left by an earlier run and makes it ready to install.
/// Invalid or outdated leftovers are deleted. Returns the ready version, if any.
pub fn restore_staged(&self) -> Option<String> {
let entries = std::fs::read_dir(&self.cfg.layout.downloads_dir).ok()?;
let mut best: Option<(semver::Version, String, PathBuf)> = None;
for entry in entries.flatten() {
let dir = entry.path();
match self.cfg.verify_staged(&dir) {
Ok((version, _)) => {
if let Ok(parsed) = parse_version(&version)
&& best.as_ref().is_none_or(|(b, _, _)| parsed > *b)
{
best = Some((parsed, version, dir));
continue;
}
let _ = std::fs::remove_dir_all(&dir);
}
Err(_) => {
let _ = std::fs::remove_dir_all(&dir);
}
}
}
let (_, version, dir) = best?;
let mut inner = self.lock();
inner.staged = Some((version.clone(), dir));
inner.phase = UpdatePhase::Ready {
version: version.clone(),
};
Some(version)
}
/// Step 3: installs the verified download. During a voice session the install is deferred
/// and runs from [`run_deferred`](Self::run_deferred) after the session ends.
pub async fn install(&self) -> Result<InstallOutcome, UpdateError> {
let _guard = self.busy.lock().await;
let Some((version, dir)) = self.lock().staged.clone() else {
return self.fail(UpdateError::NothingDownloaded);
};
if self.voice_active.load(Ordering::SeqCst) {
let mut inner = self.lock();
inner.install_deferred = true;
inner.phase = UpdatePhase::InstallDeferred {
version: version.clone(),
};
return Ok(InstallOutcome::Deferred { version });
}
self.install_now(version, dir).await
}
async fn install_now(
&self,
version: String,
dir: PathBuf,
) -> Result<InstallOutcome, UpdateError> {
self.lock().install_deferred = false;
self.set_phase(UpdatePhase::Installing {
version: version.clone(),
});
let cfg = self.cfg.clone();
let (this_version, this_dir) = (version.clone(), dir.clone());
let outcome = tokio::task::spawn_blocking(move || {
let (verified_version, archive) = cfg.verify_staged(&this_dir)?;
if verified_version != this_version {
return Err(UpdateError::Manifest("staged version changed".into()));
}
cfg.layout
.install_archive(&this_version, &archive, cfg.max_binary_bytes)
})
.await
.unwrap_or_else(|error| Err(UpdateError::Io(error.to_string())));
match outcome {
Ok(_) => {
let _ = std::fs::remove_dir_all(&dir);
let mut inner = self.lock();
inner.staged = None;
inner.candidate = None;
inner.phase = UpdatePhase::Installed {
version: version.clone(),
};
Ok(InstallOutcome::Installed { version })
}
Err(error) => self.fail(error),
}
}
/// Runs an install that was deferred by a voice session, once the session is over.
/// Returns `None` when nothing was waiting or voice is still active.
pub async fn run_deferred(&self) -> Option<Result<InstallOutcome, UpdateError>> {
if !self.install_waiting() || self.voice_active.load(Ordering::SeqCst) {
return None;
}
Some(self.install().await)
}
/// Start-up step: swaps in a staged Windows binary (returns true when the process should
/// restart), then restores a verified download. With automatic updates on, that download is
/// installed now, before any voice session can exist.
pub async fn startup(&self) -> bool {
let restart = self.cfg.layout.apply_pending().unwrap_or(false);
if self.restore_staged().is_some()
&& self.auto_update()
&& let Err(error) = self.install().await
{
tracing::warn!("startup update install failed: {error}");
}
restart
}
/// One background pass for automatic updates: check, then download. Never installs.
pub async fn auto_pass(&self) {
if !self.auto_update() {
return;
}
match self.check().await {
Ok(UpdatePhase::Available { .. }) => {
if let Err(error) = self.download().await {
tracing::warn!("automatic update download failed: {error}");
}
}
Ok(_) => {}
Err(error) => tracing::warn!("automatic update check failed: {error}"),
}
}
/// Switches back to the previous release. Takes effect on the next start.
pub fn rollback(&self) -> Result<(), UpdateError> {
self.cfg.layout.rollback().map(|_| ())
}
}
impl UpdateConfig {
/// Applies the version, channel and artifact rules to a verified manifest. Returns the
/// artifact to download, or `None` when the installed version is already current.
pub(crate) fn evaluate(&self, manifest: &Manifest) -> Result<Option<Artifact>, UpdateError> {
if manifest.channel != self.channel {
return Err(UpdateError::ChannelMismatch(manifest.channel.clone()));
}
let offered = manifest.version()?;
let installed = parse_version(&self.installed_version)?;
if offered == installed {
return Ok(None);
}
if offered < installed {
return Err(UpdateError::Downgrade {
installed: installed.to_string(),
offered: offered.to_string(),
});
}
let artifact = manifest
.artifact_for(&format!("{}-{}", self.os, self.arch))
.ok_or(UpdateError::NoArtifact)?
.clone();
let digest_ok = artifact.sha256.len() == 64
&& artifact
.sha256
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !digest_ok || artifact.size == 0 || artifact.size > self.max_artifact_bytes {
return Err(UpdateError::Manifest("bad artifact entry".into()));
}
Url::parse(&artifact.url, &self.http)?;
Ok(Some(artifact))
}
/// Re-verifies a staged download from disk: signature, version, size and checksum.
/// Nothing from `dir` is trusted until this succeeds.
pub(crate) fn verify_staged(&self, dir: &Path) -> Result<(String, PathBuf), UpdateError> {
let read = |name: &str| std::fs::read(dir.join(name)).map_err(UpdateError::io);
let bytes = read(MANIFEST_FILE)?;
let signature = read(SIGNATURE_FILE)?;
let manifest = Manifest::verify_and_parse(&self.public_keys, &bytes, &signature)?;
let artifact = self
.evaluate(&manifest)?
.ok_or(UpdateError::AlreadyInstalled)?;
let archive = dir.join(ARCHIVE_FILE);
let meta = std::fs::metadata(&archive).map_err(UpdateError::io)?;
if meta.len() != artifact.size {
return Err(UpdateError::SizeMismatch);
}
let mut hasher = Sha256::new();
let mut file = std::fs::File::open(&archive).map_err(UpdateError::io)?;
let mut buffer = [0u8; 64 * 1024];
loop {
let read = std::io::Read::read(&mut file, &mut buffer).map_err(UpdateError::io)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
if hex::encode(hasher.finalize()) != artifact.sha256 {
return Err(UpdateError::HashMismatch);
}
Ok((
manifest.version.trim_start_matches('v').to_string(),
archive,
))
}
}

438
src/update/manager_tests.rs Normal file
View file

@ -0,0 +1,438 @@
//! Integration tests for the update flow against a local fake release server.
use std::sync::Arc;
use std::time::Duration;
use sha2::{Digest, Sha256};
use super::archive::{BINARY_NAME, test_archives::single};
use super::feed::CentralVersionSource;
use super::http::HttpPolicy;
use super::keys::test_keys::{public, sign};
use super::layout::{Activation, Layout};
use super::manager::{InstallOutcome, UpdateConfig, UpdateManager, UpdatePhase};
use super::manifest::{Manifest, sample};
use super::test_support::FakeServer;
use super::{CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_REPO, UpdateError, keys};
const API: &str = "/api/v1/repos/boba/VNOX-Client/releases/latest";
struct Fixture {
server: FakeServer,
dir: tempfile::TempDir,
archive: Vec<u8>,
}
impl Fixture {
async fn new() -> Self {
let fixture = Fixture {
server: FakeServer::start().await,
dir: tempfile::tempdir().unwrap(),
archive: single(BINARY_NAME, b"new-binary"),
};
// The installed client: a launcher symlink to an old release binary.
let old = fixture.dir.path().join("lib/releases/old");
std::fs::create_dir_all(&old).unwrap();
std::fs::write(old.join(BINARY_NAME), b"old-binary").unwrap();
std::fs::create_dir_all(fixture.dir.path().join("bin")).unwrap();
std::os::unix::fs::symlink(
old.join(BINARY_NAME),
fixture.dir.path().join("bin/vnox-client"),
)
.unwrap();
fixture
}
fn launcher(&self) -> Vec<u8> {
std::fs::read(self.dir.path().join("bin/vnox-client")).unwrap()
}
/// Publishes a signed release whose artifact is served by the fake server.
fn publish(&self, mut manifest: Manifest, archive: &[u8]) {
manifest.artifacts[0].url = self.server.url("/artifact");
self.publish_manifest(&manifest, archive, false);
}
fn publish_manifest(&self, manifest: &Manifest, archive: &[u8], wrong_key: bool) {
let bytes = serde_json::to_vec(manifest).unwrap();
let signature = if wrong_key {
use ed25519_dalek::Signer;
ed25519_dalek::SigningKey::from_bytes(&[1u8; 32])
.sign(&bytes)
.to_bytes()
.to_vec()
} else {
sign(&bytes)
};
let release = serde_json::json!({
"tag_name": format!("v{}", manifest.version),
"assets": [
{"name": "manifest.json", "browser_download_url": self.server.url("/manifest.json")},
{"name": "manifest.json.sig", "browser_download_url": self.server.url("/manifest.json.sig")},
],
});
self.server
.route(API, 200, serde_json::to_vec(&release).unwrap());
self.server.route("/manifest.json", 200, bytes);
self.server.route("/manifest.json.sig", 200, signature);
self.server.route("/artifact", 200, archive.to_vec());
}
/// Publishes the fixture archive with a correct hash and size.
fn publish_good(&self, version: &str) {
let manifest = sample(
version,
"",
&hex::encode(Sha256::digest(&self.archive)),
self.archive.len() as u64,
);
self.publish(manifest, &self.archive.clone());
}
fn config(&self) -> UpdateConfig {
UpdateConfig {
api_base: self.server.url(""),
repo: RELEASE_REPO.into(),
channel: "stable".into(),
public_keys: vec![public()],
http: HttpPolicy {
allowed_hosts: vec!["127.0.0.1".into()],
require_https: false,
max_redirects: 2,
connect_timeout: Duration::from_secs(3),
read_timeout: Duration::from_secs(3),
},
layout: Layout {
releases_dir: self.dir.path().join("lib/releases"),
launcher: self.dir.path().join("bin/vnox-client"),
downloads_dir: self.dir.path().join("dl"),
activation: Activation::SwapLink,
},
installed_version: "0.1.0".into(),
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
max_artifact_bytes: 1024 * 1024,
max_binary_bytes: 1024 * 1024,
}
}
fn manager(&self) -> Arc<UpdateManager> {
UpdateManager::new(self.config(), None, self.dir.path().join("update.json"))
}
}
#[tokio::test]
async fn full_flow_installs_then_rolls_back() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
let manager = fx.manager();
assert_eq!(
manager.check().await.unwrap(),
UpdatePhase::Available {
version: "0.2.0".into()
}
);
// Checking alone downloads nothing.
assert!(!fx.server.hits().contains(&"/artifact".to_string()));
manager.download().await.unwrap();
assert_eq!(fx.launcher(), b"old-binary");
assert_eq!(
manager.install().await.unwrap(),
InstallOutcome::Installed {
version: "0.2.0".into()
}
);
assert_eq!(fx.launcher(), b"new-binary");
assert!(matches!(
manager.status().phase,
UpdatePhase::Installed { .. }
));
manager.rollback().unwrap();
assert_eq!(fx.launcher(), b"old-binary");
}
#[tokio::test]
async fn bad_or_tampered_signature_is_rejected() {
let fx = Fixture::new().await;
let manifest = sample("0.2.0", &fx.server.url("/artifact"), &"a".repeat(64), 10);
fx.publish_manifest(&manifest, &fx.archive, true);
let manager = fx.manager();
assert!(matches!(
manager.check().await,
Err(UpdateError::BadSignature)
));
assert!(matches!(manager.status().phase, UpdatePhase::Error(_)));
// Valid signature, but the manifest bytes served were modified afterwards.
fx.publish_good("0.2.0");
let mut bytes = serde_json::to_vec(&sample("0.2.0", "x", "y", 1)).unwrap();
bytes.push(b' ');
fx.server.route("/manifest.json", 200, bytes);
assert!(matches!(
manager.check().await,
Err(UpdateError::BadSignature)
));
}
#[tokio::test]
async fn placeholder_key_disables_updates() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
let mut cfg = fx.config();
cfg.public_keys = keys::production_keys();
let manager = UpdateManager::new(cfg, None, fx.dir.path().join("u.json"));
assert!(matches!(
manager.check().await,
Err(UpdateError::NoReleaseKey)
));
}
#[tokio::test]
async fn downgrade_is_rejected_and_same_version_is_up_to_date() {
let fx = Fixture::new().await;
let manager = fx.manager();
fx.publish_good("0.0.9");
assert!(matches!(
manager.check().await,
Err(UpdateError::Downgrade { .. })
));
fx.publish_good("0.1.0");
assert_eq!(manager.check().await.unwrap(), UpdatePhase::UpToDate);
assert!(matches!(
manager.download().await,
Err(UpdateError::NothingDownloaded)
));
}
#[tokio::test]
async fn old_client_below_min_version_must_reinstall() {
let fx = Fixture::new().await;
let mut manifest = sample("0.5.0", "", &"a".repeat(64), 10);
manifest.min_version = "0.3.0".into();
manifest.artifacts[0].url = fx.server.url("/artifact");
fx.publish_manifest(&manifest, b"", false);
assert_eq!(
fx.manager().check().await.unwrap(),
UpdatePhase::ManualInstallRequired {
version: "0.5.0".into()
}
);
}
#[tokio::test]
async fn hash_mismatch_discards_the_download() {
let fx = Fixture::new().await;
let manifest = sample("0.2.0", "", &"0".repeat(64), fx.archive.len() as u64);
fx.publish(manifest, &fx.archive.clone());
let manager = fx.manager();
manager.check().await.unwrap();
assert!(matches!(
manager.download().await,
Err(UpdateError::HashMismatch)
));
assert!(!fx.dir.path().join("dl/0.2.0").exists());
assert_eq!(fx.launcher(), b"old-binary");
}
#[tokio::test]
async fn download_larger_than_declared_size_is_aborted() {
let fx = Fixture::new().await;
let big = vec![7u8; 5000];
let manifest = sample("0.2.0", "", &hex::encode(Sha256::digest(&big)), 100);
fx.publish(manifest, &big);
let manager = fx.manager();
manager.check().await.unwrap();
assert!(matches!(
manager.download().await,
Err(UpdateError::TooLarge)
));
assert!(!fx.dir.path().join("dl/0.2.0").exists());
}
#[tokio::test]
async fn short_download_is_a_size_mismatch() {
let fx = Fixture::new().await;
let small = vec![7u8; 50];
let manifest = sample("0.2.0", "", &hex::encode(Sha256::digest(&small)), 100);
fx.publish(manifest, &small);
let manager = fx.manager();
manager.check().await.unwrap();
assert!(matches!(
manager.download().await,
Err(UpdateError::SizeMismatch)
));
}
#[tokio::test]
async fn declared_size_over_the_global_limit_is_refused_at_check() {
let fx = Fixture::new().await;
let manifest = sample("0.2.0", "", &"a".repeat(64), 10 * 1024 * 1024);
fx.publish(manifest, b"");
assert!(matches!(
fx.manager().check().await,
Err(UpdateError::Manifest(_))
));
}
#[tokio::test]
async fn manifest_url_outside_the_allowlist_is_refused() {
let fx = Fixture::new().await;
let manifest = sample("0.2.0", "http://evil.example/a", &"a".repeat(64), 10);
fx.publish_manifest(&manifest, b"", false);
assert!(matches!(
fx.manager().check().await,
Err(UpdateError::UrlRejected(_))
));
}
#[tokio::test]
async fn traversal_archive_is_never_installed() {
let fx = Fixture::new().await;
let evil = single("../escape", b"pwn");
let manifest = sample(
"0.2.0",
"",
&hex::encode(Sha256::digest(&evil)),
evil.len() as u64,
);
fx.publish(manifest, &evil);
let manager = fx.manager();
manager.check().await.unwrap();
manager.download().await.unwrap();
assert!(matches!(
manager.install().await,
Err(UpdateError::UnsafeArchive(_))
));
assert_eq!(fx.launcher(), b"old-binary");
assert!(!fx.dir.path().join("lib/escape").exists());
assert!(!fx.dir.path().join("lib/releases/escape").exists());
}
#[tokio::test]
async fn install_is_deferred_during_voice_and_runs_afterwards() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
let manager = fx.manager();
manager.check().await.unwrap();
manager.download().await.unwrap();
manager.set_voice_active(true);
assert_eq!(
manager.install().await.unwrap(),
InstallOutcome::Deferred {
version: "0.2.0".into()
}
);
assert_eq!(fx.launcher(), b"old-binary");
assert!(matches!(
manager.status().phase,
UpdatePhase::InstallDeferred { .. }
));
// The call is still going: nothing happens.
assert!(manager.run_deferred().await.is_none());
assert_eq!(fx.launcher(), b"old-binary");
manager.set_voice_active(false);
let outcome = manager.run_deferred().await.unwrap().unwrap();
assert_eq!(
outcome,
InstallOutcome::Installed {
version: "0.2.0".into()
}
);
assert_eq!(fx.launcher(), b"new-binary");
assert!(manager.run_deferred().await.is_none());
}
#[tokio::test]
async fn auto_pass_downloads_but_does_not_install() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
let manager = fx.manager();
manager.auto_pass().await;
assert!(matches!(manager.status().phase, UpdatePhase::Ready { .. }));
assert_eq!(fx.launcher(), b"old-binary");
}
#[tokio::test]
async fn auto_pass_does_nothing_when_disabled() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
let manager = fx.manager();
manager.set_auto_update(false).unwrap();
manager.auto_pass().await;
assert_eq!(manager.status().phase, UpdatePhase::Idle);
assert!(fx.server.hits().is_empty());
// The choice survives a restart.
assert!(!fx.manager().auto_update());
}
#[tokio::test]
async fn startup_installs_a_staged_download_when_auto_is_on() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
fx.manager().auto_pass().await;
// "Restart": a new manager finds the verified download on disk.
let second = fx.manager();
assert!(!second.startup().await);
assert_eq!(fx.launcher(), b"new-binary");
}
#[tokio::test]
async fn startup_keeps_the_download_ready_when_auto_is_off() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
fx.manager().auto_pass().await;
let second = fx.manager();
second.set_auto_update(false).unwrap();
second.startup().await;
assert_eq!(fx.launcher(), b"old-binary");
assert!(matches!(second.status().phase, UpdatePhase::Ready { .. }));
}
#[tokio::test]
async fn tampered_staged_download_is_discarded_on_restore() {
let fx = Fixture::new().await;
fx.publish_good("0.2.0");
fx.manager().auto_pass().await;
std::fs::write(fx.dir.path().join("dl/0.2.0/artifact.tar.gz"), b"tampered").unwrap();
let second = fx.manager();
assert!(second.restore_staged().is_none());
assert!(!fx.dir.path().join("dl/0.2.0").exists());
assert!(matches!(
second.install().await,
Err(UpdateError::NothingDownloaded)
));
}
#[tokio::test]
async fn central_source_is_advisory_only() {
struct Central;
impl CentralVersionSource for Central {
fn latest_version(
&self,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Option<String>, UpdateError>> + Send + '_>,
> {
Box::pin(async { Ok(Some("9.9.9".to_string())) })
}
}
let fx = Fixture::new().await;
fx.publish_good("0.1.0");
let manager = UpdateManager::new(
fx.config(),
Some(Arc::new(Central)),
fx.dir.path().join("u.json"),
);
assert_eq!(manager.check().await.unwrap(), UpdatePhase::UpToDate);
assert_eq!(manager.status().central_latest.as_deref(), Some("9.9.9"));
}
#[test]
fn exposes_client_and_protocol_versions() {
assert_eq!(CLIENT_VERSION, env!("CARGO_PKG_VERSION"));
assert_eq!(LNEX_PROTOCOL, crate::net::payloads::LNEX_VERSION);
}

144
src/update/manifest.rs Normal file
View file

@ -0,0 +1,144 @@
//! Release manifest: the signed description of one release.
use semver::Version;
use serde::{Deserialize, Serialize};
use super::{UpdateError, keys};
/// Manifest format version understood by this client.
pub const SCHEMA: u32 = 1;
/// Product name expected in the manifest.
pub const PRODUCT: &str = "vnox-client";
/// Largest manifest accepted, in bytes.
pub const MAX_MANIFEST_BYTES: usize = 64 * 1024;
/// One downloadable build of the client.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
/// File name of the release asset.
#[serde(default)]
pub name: String,
/// `<os>-<arch>` using `std::env::consts` values, for example `linux-x86_64`.
pub platform: String,
pub url: String,
/// Lower case hex SHA-256 of the downloaded archive.
pub sha256: String,
pub size: u64,
}
/// The release manifest published as the `manifest.json` release asset.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
/// Manifest format version, currently 1.
pub schema: u32,
/// Always `vnox-client`.
pub product: String,
pub version: String,
pub channel: String,
/// Oldest installed version that may update in place. Older clients must reinstall.
pub min_version: String,
/// RFC 3339 publication time, informational.
pub published_at: String,
pub artifacts: Vec<Artifact>,
}
impl Manifest {
/// Verifies the detached signature over the exact `bytes`, then parses them.
pub fn verify_and_parse(
public_keys: &[[u8; 32]],
bytes: &[u8],
signature: &[u8],
) -> Result<Manifest, UpdateError> {
keys::verify_any(public_keys, bytes, signature)?;
if bytes.len() > MAX_MANIFEST_BYTES {
return Err(UpdateError::Manifest("manifest too large".into()));
}
let manifest: Manifest = serde_json::from_slice(bytes)
.map_err(|error| UpdateError::Manifest(error.to_string()))?;
if manifest.schema != SCHEMA || manifest.product != PRODUCT {
return Err(UpdateError::Manifest(
"unsupported schema or product".into(),
));
}
manifest.version()?;
manifest.min_version()?;
Ok(manifest)
}
pub fn version(&self) -> Result<Version, UpdateError> {
parse_version(&self.version)
}
pub fn min_version(&self) -> Result<Version, UpdateError> {
parse_version(&self.min_version)
}
/// The artifact built for this platform, if the release has one.
pub fn artifact_for(&self, platform: &str) -> Option<&Artifact> {
self.artifacts
.iter()
.find(|artifact| artifact.platform == platform)
}
}
/// Parses a version, tolerating a leading `v`.
pub fn parse_version(text: &str) -> Result<Version, UpdateError> {
Version::parse(text.trim().trim_start_matches('v'))
.map_err(|_| UpdateError::Manifest(format!("invalid version `{text}`")))
}
#[cfg(test)]
pub(crate) fn sample(version: &str, url: &str, sha256: &str, size: u64) -> Manifest {
Manifest {
schema: SCHEMA,
product: PRODUCT.into(),
version: version.into(),
channel: "stable".into(),
min_version: "0.1.0".into(),
published_at: "2026-11-01T00:00:00Z".into(),
artifacts: vec![Artifact {
name: "artifact".into(),
platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
url: url.into(),
sha256: sha256.into(),
size,
}],
}
}
#[cfg(test)]
mod tests {
use super::super::keys::test_keys::{public, sign};
use super::*;
#[test]
fn signed_manifest_parses() {
let bytes =
serde_json::to_vec(&sample("0.2.0", "https://git.wihuk.pro/x", "ab", 1)).unwrap();
let manifest = Manifest::verify_and_parse(&[public()], &bytes, &sign(&bytes)).unwrap();
assert_eq!(manifest.version().unwrap(), Version::new(0, 2, 0));
}
#[test]
fn tampered_manifest_is_rejected_before_parsing() {
let mut bytes =
serde_json::to_vec(&sample("0.2.0", "https://git.wihuk.pro/x", "ab", 1)).unwrap();
let sig = sign(&bytes);
bytes[2] ^= 0x20;
assert!(matches!(
Manifest::verify_and_parse(&[public()], &bytes, &sig),
Err(UpdateError::BadSignature)
));
}
#[test]
fn signed_garbage_is_a_manifest_error() {
let bytes = b"not json";
assert!(matches!(
Manifest::verify_and_parse(&[public()], bytes, &sign(bytes)),
Err(UpdateError::Manifest(_))
));
}
}

128
src/update/mod.rs Normal file
View file

@ -0,0 +1,128 @@
//! Versioning and the signed self-updater.
//!
//! The version has one source, `CARGO_PKG_VERSION` ([`CLIENT_VERSION`]); the wire protocol
//! version is [`LNEX_PROTOCOL`].
//!
//! Update flow (each step is separate, see [`UpdateManager`]):
//!
//! 1. **check** reads the latest Gitea release of `boba/VNOX-Client`, downloads the
//! `manifest.json` and `manifest.json.sig` assets and verifies the Ed25519 signature over the
//! exact manifest bytes before parsing them;
//! 2. **download** fetches the archive for this platform with a hard size bound, verifies size
//! and SHA-256 and stores it together with the signed manifest;
//! 3. **install** re-verifies everything from disk, extracts only the expected binary and
//! activates it atomically, keeping the previous release for rollback. It is deferred while a
//! voice session is active.
//!
//! Release feed format produced by CI (assets of the latest, non-prerelease Gitea release):
//!
//! * `manifest.json`: `{"version","channel","min_version","published_at","artifacts":[{"os","arch","url","sha256","size"}]}`
//! where `os`/`arch` are Rust `std::env::consts` values (`linux`/`x86_64`), `url` is an HTTPS
//! URL on `git.wihuk.pro`, `sha256` is lower case hex of the archive and `size` its byte length;
//! * `manifest.json.sig`: detached Ed25519 signature over the exact bytes of `manifest.json`,
//! as 64 raw bytes or 128 hex characters;
//! * the artifact: a `.tar.gz` holding exactly one regular file, `vnox-client`
//! (`vnox-client.exe` on Windows), at its top level.
//!
//! `min_version` is the oldest installed version allowed to update in place; older clients are
//! told to reinstall by hand.
pub mod archive;
pub mod feed;
pub mod http;
pub mod keys;
pub mod layout;
pub mod manager;
pub mod manifest;
pub mod settings;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(all(test, unix))]
mod manager_tests;
pub use feed::CentralVersionSource;
pub use layout::{Activation, Layout};
pub use manager::{InstallOutcome, UpdateConfig, UpdateManager, UpdatePhase, UpdateStatus};
pub use manifest::Manifest;
/// Version of this client, from `Cargo.toml`.
pub const CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION");
/// LNEx protocol version this client speaks.
pub const LNEX_PROTOCOL: &str = crate::net::payloads::LNEX_VERSION;
/// The only host updates may be fetched from.
pub const RELEASE_HOST: &str = "git.wihuk.pro";
/// Gitea repository that publishes client releases.
pub const RELEASE_REPO: &str = "boba/VNOX-Client";
/// Release channel this build follows.
pub const CHANNEL: &str = "stable";
/// Why an update step failed.
#[derive(Debug, Clone)]
pub enum UpdateError {
/// The embedded release key is the unconfigured placeholder, so updates are disabled.
NoReleaseKey,
BadSignature,
Manifest(String),
/// The release is older than the installed version.
Downgrade {
installed: String,
offered: String,
},
ChannelMismatch(String),
NoArtifact,
UrlRejected(String),
Network(String),
Http(u16),
TooLarge,
SizeMismatch,
HashMismatch,
UnsafeArchive(String),
Io(String),
AlreadyInstalled,
NoPreviousRelease,
NothingDownloaded,
NoLayout,
}
impl UpdateError {
pub(crate) fn io(error: std::io::Error) -> Self {
UpdateError::Io(error.to_string())
}
}
impl std::fmt::Display for UpdateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UpdateError::NoReleaseKey => write!(f, "no release signing key is configured"),
UpdateError::BadSignature => write!(f, "release signature is invalid"),
UpdateError::Manifest(why) => write!(f, "invalid release manifest: {why}"),
UpdateError::Downgrade { installed, offered } => {
write!(f, "refusing to downgrade from {installed} to {offered}")
}
UpdateError::ChannelMismatch(channel) => {
write!(f, "release is on channel `{channel}`")
}
UpdateError::NoArtifact => write!(f, "release has no build for this platform"),
UpdateError::UrlRejected(url) => write!(f, "URL not allowed: {url}"),
UpdateError::Network(why) => write!(f, "network error: {why}"),
UpdateError::Http(status) => write!(f, "server answered HTTP {status}"),
UpdateError::TooLarge => write!(f, "download exceeds the allowed size"),
UpdateError::SizeMismatch => write!(f, "download size does not match the manifest"),
UpdateError::HashMismatch => write!(f, "download checksum does not match"),
UpdateError::UnsafeArchive(why) => write!(f, "unsafe archive: {why}"),
UpdateError::Io(why) => write!(f, "disk error: {why}"),
UpdateError::AlreadyInstalled => write!(f, "this release is already installed"),
UpdateError::NoPreviousRelease => write!(f, "there is no previous release"),
UpdateError::NothingDownloaded => write!(f, "no verified update is downloaded"),
UpdateError::NoLayout => write!(f, "install location is unknown"),
}
}
}
impl std::error::Error for UpdateError {}

62
src/update/settings.rs Normal file
View file

@ -0,0 +1,62 @@
//! Persisted updater preferences.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
/// Updater preferences, stored as `update.json` in the config directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdateSettings {
/// Check and download in the background; install on the next start.
pub auto_update: bool,
}
impl Default for UpdateSettings {
fn default() -> Self {
Self { auto_update: true }
}
}
/// Default location of the settings file.
pub fn default_path() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("vnox/update.json")
}
impl UpdateSettings {
/// Loads settings; a missing or damaged file yields the defaults.
pub fn load(path: &Path) -> Self {
std::fs::read(path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
/// Saves settings atomically.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
std::fs::rename(&tmp, path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_to_auto_update_and_round_trips() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub/update.json");
assert!(UpdateSettings::load(&path).auto_update);
UpdateSettings { auto_update: false }.save(&path).unwrap();
assert!(!UpdateSettings::load(&path).auto_update);
std::fs::write(&path, b"garbage").unwrap();
assert!(UpdateSettings::load(&path).auto_update);
}
}

124
src/update/test_support.rs Normal file
View file

@ -0,0 +1,124 @@
//! A tiny local HTTP server for updater tests. No real network is used.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[derive(Clone)]
enum Route {
Body(u16, Vec<u8>),
Chunked(Vec<u8>),
Redirect(String),
}
pub struct FakeServer {
port: u16,
routes: Arc<Mutex<HashMap<String, Route>>>,
hits: Arc<Mutex<Vec<String>>>,
task: tokio::task::JoinHandle<()>,
}
impl Drop for FakeServer {
fn drop(&mut self) {
self.task.abort();
}
}
impl FakeServer {
pub async fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let routes: Arc<Mutex<HashMap<String, Route>>> = Arc::default();
let hits: Arc<Mutex<Vec<String>>> = Arc::default();
let (shared, seen) = (routes.clone(), hits.clone());
let task = tokio::spawn(async move {
loop {
let Ok((mut stream, _)) = listener.accept().await else {
return;
};
let (routes, hits) = (shared.clone(), seen.clone());
tokio::spawn(async move {
let mut request = Vec::new();
let mut buffer = [0u8; 1024];
while !request.windows(4).any(|w| w == b"\r\n\r\n") {
match stream.read(&mut buffer).await {
Ok(0) | Err(_) => return,
Ok(n) => request.extend_from_slice(&buffer[..n]),
}
}
let text = String::from_utf8_lossy(&request).to_string();
let path = text.split_whitespace().nth(1).unwrap_or("/").to_string();
hits.lock().unwrap().push(path.clone());
let route = routes.lock().unwrap().get(&path).cloned();
let response = match route {
Some(Route::Body(status, body)) => {
let mut out = format!(
"HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n",
body.len()
)
.into_bytes();
out.extend_from_slice(&body);
out
}
Some(Route::Chunked(body)) => {
let mut out =
b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec();
for piece in body.chunks(700) {
out.extend_from_slice(format!("{:x}\r\n", piece.len()).as_bytes());
out.extend_from_slice(piece);
out.extend_from_slice(b"\r\n");
}
out.extend_from_slice(b"0\r\n\r\n");
out
}
Some(Route::Redirect(to)) => format!(
"HTTP/1.1 302 Found\r\nLocation: {to}\r\nContent-Length: 0\r\n\r\n"
)
.into_bytes(),
None => b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".to_vec(),
};
let _ = stream.write_all(&response).await;
let _ = stream.shutdown().await;
});
}
});
Self {
port,
routes,
hits,
task,
}
}
pub fn url(&self, path: &str) -> String {
format!("http://127.0.0.1:{}{path}", self.port)
}
pub fn route(&self, path: &str, status: u16, body: Vec<u8>) {
self.routes
.lock()
.unwrap()
.insert(path.into(), Route::Body(status, body));
}
pub fn route_chunked(&self, path: &str, body: Vec<u8>) {
self.routes
.lock()
.unwrap()
.insert(path.into(), Route::Chunked(body));
}
pub fn redirect(&self, path: &str, to: &str) {
self.routes
.lock()
.unwrap()
.insert(path.into(), Route::Redirect(to.into()));
}
/// Paths requested so far, in order.
pub fn hits(&self) -> Vec<String> {
self.hits.lock().unwrap().clone()
}
}