1use std::{
12 collections::BTreeMap,
13 fs,
14 path::{Path, PathBuf},
15};
16
17use anyhow::{Context, Result};
18use subspace_core::credentials::{ProcessEnvironment, SystemRunner};
19use subspace_product::{UpdateSource, ValidatedProduct};
20
21mod archive;
22mod bundle;
23mod cli;
24mod github;
25mod install;
26mod token;
27mod version;
28
29#[cfg(test)]
30mod http_tests;
31#[cfg(test)]
32mod test_archive;
33
34pub use cli::run_cli;
35pub use install::cleanup_previous;
36
37use archive::{Wanted, binary_entry_name, extract, verify_checksum, verify_product, wanted_asset};
38use bundle::{BundleInstall, SystemTools, install_bundle_with_progress};
39use github::{API_URL_ENV, Client, api_base, no_release_message};
40use install::{replace_executable, require_own_executable_name};
41use token::Token;
42use version::{is_newer, require_release_version};
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Release {
47 pub tag: String,
49 pub version: String,
51 pub html_url: String,
53 assets: BTreeMap<String, String>,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum CheckOutcome {
61 Newer(Release),
62 UpToDate,
63 NoRelease { repository: String },
64}
65
66impl CheckOutcome {
67 pub fn newer(&self) -> Option<&Release> {
68 match self {
69 Self::Newer(release) => Some(release),
70 _ => None,
71 }
72 }
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct Installed {
78 pub previous_version: String,
79 pub version: String,
80 pub path: PathBuf,
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub enum UpdateProgress {
86 Preparing,
87 Downloading { received: u64, total: Option<u64> },
88 DownloadingChecksum,
89 VerifyingChecksum,
90 Extracting,
91 VerifyingSignature,
92 Installing,
93}
94
95#[derive(Clone, Debug)]
99enum Auth {
100 Process,
101 #[cfg(test)]
102 Fixed(Token),
103}
104
105#[derive(Clone, Debug)]
108struct App {
109 id: String,
110 binary_name: String,
111 display_name: String,
114 bundle_id: String,
115 version: String,
116}
117
118#[derive(Clone, Debug)]
120pub struct Updater {
121 source: UpdateSource,
122 app: App,
123 api: String,
124 auth: Auth,
125 account: Option<String>,
126}
127
128impl Updater {
129 pub fn for_product(product: &ValidatedProduct, current_version: &str) -> Option<Self> {
132 if subspace_product::is_integration_version(current_version) {
133 return None;
134 }
135 Some(Self {
136 source: product.update.clone()?,
137 app: App {
138 id: product.id.as_str().to_owned(),
139 binary_name: product.binary_name.as_str().to_owned(),
140 display_name: product.display_name.clone(),
141 bundle_id: product.bundle_id.clone(),
142 version: current_version.to_owned(),
143 },
144 api: api_base(std::env::var(API_URL_ENV).ok()),
145 auth: Auth::Process,
146 account: None,
147 })
148 }
149
150 pub fn with_account(mut self, login: Option<String>) -> Self {
152 self.account = login;
153 self
154 }
155
156 pub fn account(&self) -> Option<&str> {
157 self.account.as_deref()
158 }
159
160 pub fn current_version(&self) -> &str {
161 &self.app.version
162 }
163
164 pub fn check(&self) -> Result<CheckOutcome> {
166 let newest = self.client()?.newest()?;
167 Ok(match newest {
168 Some(release)
169 if is_newer(self.source.channel, &release.version, &self.app.version)
170 && self.offers(&release) =>
171 {
172 CheckOutcome::Newer(release)
173 }
174 Some(_) => CheckOutcome::UpToDate,
175 None => CheckOutcome::NoRelease {
176 repository: self.source.repository.clone(),
177 },
178 })
179 }
180
181 fn offers(&self, release: &Release) -> bool {
186 !self.source.exclusive
187 || current_executable().is_ok_and(|executable| self.publishes_own(release, &executable))
188 }
189
190 fn publishes_own(&self, release: &Release, executable: &Path) -> bool {
193 wanted_asset(&self.source, &release.version, executable).is_ok_and(|wanted| {
194 let name = wanted.name();
195 release.assets.contains_key(name)
196 && release.assets.contains_key(&format!("{name}.sha256"))
197 })
198 }
199
200 pub fn latest(&self) -> Result<Release> {
202 self.client()?
203 .newest()?
204 .with_context(|| no_release_message(&self.source))
205 }
206
207 pub fn find(&self, version: &str) -> Result<Release> {
209 let version = require_release_version(self.source.channel, version)?;
210 self.client()?.find(&version)
211 }
212
213 pub fn install(&self, release: &Release) -> Result<Installed> {
216 self.install_at(release, ¤t_executable()?)
217 }
218
219 pub fn install_with_progress(
222 &self,
223 release: &Release,
224 progress: impl Fn(UpdateProgress),
225 ) -> Result<Installed> {
226 self.install_at_with_progress(release, ¤t_executable()?, &progress)
227 }
228
229 fn install_at_with_progress(
230 &self,
231 release: &Release,
232 executable: &Path,
233 progress: &dyn Fn(UpdateProgress),
234 ) -> Result<Installed> {
235 progress(UpdateProgress::Preparing);
236 require_own_executable_name(executable, &self.app.binary_name)?;
237 let wanted = wanted_asset(&self.source, &release.version, executable)?;
238 let client = self.client()?;
239 let release = client.find(&release.version)?;
241 Job {
242 app: &self.app,
243 client,
244 release: &release,
245 executable,
246 }
247 .run_with_progress(&wanted, progress)
248 }
249
250 fn install_at(&self, release: &Release, executable: &Path) -> Result<Installed> {
252 self.install_at_with_progress(release, executable, &|_| {})
253 }
254
255 fn client(&self) -> Result<Client<'_>> {
258 Ok(Client::new(&self.api, &self.source, self.token()?))
259 }
260
261 fn token(&self) -> Result<Token> {
262 match &self.auth {
263 Auth::Process => token::resolve(
264 &self.source,
265 self.account.as_deref(),
266 &ProcessEnvironment,
267 &token::signed_in_token,
268 &SystemRunner,
269 ),
270 #[cfg(test)]
271 Auth::Fixed(token) => Ok(token.clone()),
272 }
273 }
274
275 #[cfg(test)]
277 fn against(mut self, api: &str, token: &str) -> Self {
278 self.api = api.to_owned();
279 self.auth = Auth::Fixed(Token::new(token));
280 self
281 }
282}
283
284fn current_executable() -> Result<PathBuf> {
285 let executable = std::env::current_exe().context("locate the executable to update")?;
286 fs::canonicalize(&executable).context("locate the executable to update")
287}
288
289struct Job<'a> {
292 app: &'a App,
293 client: Client<'a>,
294 release: &'a Release,
295 executable: &'a Path,
296}
297
298impl Job<'_> {
299 #[cfg(test)]
300 fn run(&self, wanted: &Wanted) -> Result<Installed> {
301 self.run_with_progress(wanted, &|_| {})
302 }
303
304 fn run_with_progress(
305 &self,
306 wanted: &Wanted,
307 progress: &dyn Fn(UpdateProgress),
308 ) -> Result<Installed> {
309 let archive = self.verified_asset(wanted.name(), progress)?;
310 self.apply(wanted, &archive, progress)?;
311 Ok(Installed {
312 previous_version: self.app.version.clone(),
313 version: self.release.version.clone(),
314 path: self.executable.to_owned(),
315 })
316 }
317
318 fn verified_asset(&self, name: &str, progress: &dyn Fn(UpdateProgress)) -> Result<Vec<u8>> {
321 anyhow::ensure!(
322 self.release.assets.contains_key(name)
323 && self.release.assets.contains_key(&format!("{name}.sha256")),
324 "release {} has no {name} archive or checksum yet; check for updates again later. Nothing was installed",
325 self.release.tag
326 );
327 let bytes = self
328 .client
329 .asset_with_progress(self.release, name, progress)?;
330 progress(UpdateProgress::DownloadingChecksum);
331 let checksum = self.client.asset(self.release, &format!("{name}.sha256"))?;
332 progress(UpdateProgress::VerifyingChecksum);
333 verify_checksum(&checksum, name, &bytes)?;
334 Ok(bytes)
335 }
336
337 fn apply(
338 &self,
339 wanted: &Wanted,
340 archive: &[u8],
341 progress: &dyn Fn(UpdateProgress),
342 ) -> Result<()> {
343 match wanted {
344 Wanted::Plain { zip, .. } => self.plain(archive, *zip, progress),
345 Wanted::Bundle { .. } => self.bundle(archive, progress),
346 }
347 }
348
349 fn plain(&self, archive: &[u8], zip: bool, progress: &dyn Fn(UpdateProgress)) -> Result<()> {
350 let binary = binary_entry_name(&self.app.binary_name, zip);
351 progress(UpdateProgress::Extracting);
352 let contents = extract(archive, zip, &binary)?;
353 verify_product(&contents.product, &self.app.id, &self.release.version, None)?;
354 progress(UpdateProgress::Installing);
355 replace_executable(self.executable, &contents.binary, cfg!(windows))
356 }
357
358 fn bundle(&self, archive: &[u8], progress: &dyn Fn(UpdateProgress)) -> Result<()> {
359 let root = archive::bundle_root(self.executable)
360 .context("the executable is not inside an app bundle")?;
361 let install = BundleInstall {
362 bundle: root,
363 bundle_name: &self.app.display_name,
364 binary_name: &self.app.binary_name,
365 product_id: &self.app.id,
366 bundle_id: &self.app.bundle_id,
367 version: &self.release.version,
368 };
369 install_bundle_with_progress(&install, archive, &SystemTools, progress)
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use std::collections::BTreeMap;
376
377 use subspace_product::{ValidatedProduct, fixture};
378
379 use super::{Release, Updater};
380
381 pub(crate) fn known_product() -> ValidatedProduct {
382 fixture::products()
383 .expect("the known products validate")
384 .into_iter()
385 .find(|product| product.id.as_str() == "subspace")
386 .expect("the product exists")
387 }
388
389 #[test]
390 fn the_known_app_has_an_updater_and_reports_the_running_version() {
391 for product in fixture::products().expect("the known products validate") {
392 let updater = Updater::for_product(&product, "1.1.0")
393 .unwrap_or_else(|| panic!("{} has an update source", product.id.as_str()));
394 assert_eq!(updater.current_version(), "1.1.0");
395 }
396 }
397
398 #[test]
401 fn a_release_crosses_threads_for_a_background_check() {
402 let release = Release {
403 tag: "subspace-desktop-v1.2.0".into(),
404 version: "1.2.0".into(),
405 html_url: "https://example.test/release".into(),
406 assets: BTreeMap::new(),
407 };
408 let sent = release.clone();
409 let received = std::thread::spawn(move || sent)
410 .join()
411 .expect("the release crosses threads");
412 assert_eq!(received, release);
413 }
414
415 #[test]
419 fn an_exclusive_build_is_offered_only_releases_with_its_own_archive() {
420 let executable = std::path::Path::new("/opt/example/subspace");
421 let release = |names: &[String]| Release {
422 tag: "subspace-desktop-v9.0.0".into(),
423 version: "9.0.0".into(),
424 html_url: "https://example.test/release".into(),
425 assets: names
426 .iter()
427 .map(|name| (name.clone(), format!("https://api.example.test/{name}")))
428 .collect(),
429 };
430 let name = |updater: &Updater| {
431 super::wanted_asset(&updater.source, "9.0.0", executable)
432 .unwrap()
433 .name()
434 .to_owned()
435 };
436 let standard = Updater::for_product(&known_product(), "1.0.0").unwrap();
437 let mut variant = standard.clone();
438 variant.source.archive_prefix = "subspace-no-api".into();
439 variant.source.exclusive = true;
440 let (own, theirs) = (name(&variant), name(&standard));
441 assert!(own.starts_with("subspace-no-api-9.0.0-") && theirs.starts_with("subspace-9.0.0-"));
442 let only_standard = release(&[theirs.clone(), format!("{theirs}.sha256")]);
443 let both = release(&[
444 theirs.clone(),
445 format!("{theirs}.sha256"),
446 own.clone(),
447 format!("{own}.sha256"),
448 ]);
449 assert!(!variant.publishes_own(&only_standard, executable));
450 assert!(variant.publishes_own(&both, executable));
451 assert!(
452 !variant.publishes_own(&release(std::slice::from_ref(&own)), executable),
453 "no checksum"
454 );
455 assert!(standard.offers(&release(&[])));
457 assert!(standard.offers(&only_standard));
458 }
459
460 #[test]
461 fn an_app_without_an_update_source_has_no_updater() {
462 let mut product = known_product();
463 product.update = None;
464 assert!(Updater::for_product(&product, "1.1.0").is_none());
465 }
466
467 #[test]
468 fn integration_versions_cannot_create_an_updater_even_with_a_stable_source() {
469 assert!(
470 Updater::for_product(
471 &known_product(),
472 "0.3.0-feat-subspace-desktop.202611151345.gabc1234"
473 )
474 .is_none()
475 );
476 }
477
478 #[test]
479 fn an_installed_version_must_be_of_the_release_form_before_any_request() {
480 let updater = Updater::for_product(&known_product(), "1.1.0")
481 .expect("the standalone product has an update source")
482 .against("http://127.0.0.1:1/unused", "fixture-token");
483 let error = updater.find("not-a-version").unwrap_err();
484 assert!(error.to_string().contains("1.2.3"), "{error}");
485 }
486
487 #[test]
488 fn a_nightly_updater_refuses_a_pinned_stable_version_before_any_request() {
489 let product = subspace_product::validate_product(
490 &subspace_product::fixture::descriptor_for(subspace_product::Channel::Nightly),
491 )
492 .expect("the nightly descriptor validates");
493 let updater = Updater::for_product(&product, "1.10.2-nightly.202611010200.ga43a333")
494 .expect("the nightly product has an update source")
495 .against("http://127.0.0.1:1/unused", "fixture-token");
496 let error = updater.find("1.10.1").unwrap_err();
497 assert!(
498 error.to_string().contains("only nightly versions"),
499 "{error}"
500 );
501 }
502
503 #[test]
504 fn an_executable_a_package_manager_installed_is_refused_before_any_download() {
505 let directory = tempfile::tempdir().expect("a temporary installation folder");
506 let executable = directory.path().join("subspace-packaged");
507 std::fs::write(&executable, b"feed installation").expect("write the executable");
508 let updater = Updater::for_product(&known_product(), "1.1.0")
509 .expect("the standalone product has an update source")
510 .against("http://127.0.0.1:1/unused", "fixture-token");
511 let release = Release {
512 tag: "subspace-desktop-v1.2.0".into(),
513 version: "1.2.0".into(),
514 html_url: String::new(),
515 assets: BTreeMap::new(),
516 };
517 let error = updater.install_at(&release, &executable).unwrap_err();
518 assert!(error.to_string().contains("package manager"), "{error}");
519 assert_eq!(std::fs::read(&executable).unwrap(), b"feed installation");
520 }
521
522 #[test]
523 fn an_asset_url_outside_the_api_base_is_refused_before_the_token_is_sent() {
524 let updater = Updater::for_product(&known_product(), "1.1.0")
525 .expect("the standalone product has an update source")
526 .against("https://api.example.test", "fixture-token");
527 let release = Release {
528 tag: "subspace-desktop-v1.2.0".into(),
529 version: "1.2.0".into(),
530 html_url: String::new(),
531 assets: BTreeMap::from([(
532 "asset".to_owned(),
533 "https://elsewhere.invalid/asset".to_owned(),
534 )]),
535 };
536 let client = updater.client().expect("a fixed token needs no lookup");
537 let error = client.asset(&release, "asset").unwrap_err();
538 assert!(
539 error.to_string().contains("not on the GitHub API"),
540 "{error}"
541 );
542 }
543}