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) if is_newer(self.source.channel, &release.version, &self.app.version) => {
169 CheckOutcome::Newer(release)
170 }
171 Some(_) => CheckOutcome::UpToDate,
172 None => CheckOutcome::NoRelease {
173 repository: self.source.repository.clone(),
174 },
175 })
176 }
177
178 pub fn latest(&self) -> Result<Release> {
180 self.client()?
181 .newest()?
182 .with_context(|| no_release_message(&self.source))
183 }
184
185 pub fn find(&self, version: &str) -> Result<Release> {
187 let version = require_release_version(self.source.channel, version)?;
188 self.client()?.find(&version)
189 }
190
191 pub fn install(&self, release: &Release) -> Result<Installed> {
194 self.install_at(release, ¤t_executable()?)
195 }
196
197 pub fn install_with_progress(
200 &self,
201 release: &Release,
202 progress: impl Fn(UpdateProgress),
203 ) -> Result<Installed> {
204 self.install_at_with_progress(release, ¤t_executable()?, &progress)
205 }
206
207 fn install_at_with_progress(
208 &self,
209 release: &Release,
210 executable: &Path,
211 progress: &dyn Fn(UpdateProgress),
212 ) -> Result<Installed> {
213 progress(UpdateProgress::Preparing);
214 require_own_executable_name(executable, &self.app.binary_name)?;
215 let wanted = wanted_asset(&self.source, &release.version, executable)?;
216 let client = self.client()?;
217 let release = client.find(&release.version)?;
219 Job {
220 app: &self.app,
221 client,
222 release: &release,
223 executable,
224 }
225 .run_with_progress(&wanted, progress)
226 }
227
228 fn install_at(&self, release: &Release, executable: &Path) -> Result<Installed> {
230 self.install_at_with_progress(release, executable, &|_| {})
231 }
232
233 fn client(&self) -> Result<Client<'_>> {
236 Ok(Client::new(&self.api, &self.source, self.token()?))
237 }
238
239 fn token(&self) -> Result<Token> {
240 match &self.auth {
241 Auth::Process => token::resolve(
242 &self.source,
243 self.account.as_deref(),
244 &ProcessEnvironment,
245 &token::signed_in_token,
246 &SystemRunner,
247 ),
248 #[cfg(test)]
249 Auth::Fixed(token) => Ok(token.clone()),
250 }
251 }
252
253 #[cfg(test)]
255 fn against(mut self, api: &str, token: &str) -> Self {
256 self.api = api.to_owned();
257 self.auth = Auth::Fixed(Token::new(token));
258 self
259 }
260}
261
262fn current_executable() -> Result<PathBuf> {
263 let executable = std::env::current_exe().context("locate the executable to update")?;
264 fs::canonicalize(&executable).context("locate the executable to update")
265}
266
267struct Job<'a> {
270 app: &'a App,
271 client: Client<'a>,
272 release: &'a Release,
273 executable: &'a Path,
274}
275
276impl Job<'_> {
277 #[cfg(test)]
278 fn run(&self, wanted: &Wanted) -> Result<Installed> {
279 self.run_with_progress(wanted, &|_| {})
280 }
281
282 fn run_with_progress(
283 &self,
284 wanted: &Wanted,
285 progress: &dyn Fn(UpdateProgress),
286 ) -> Result<Installed> {
287 let archive = self.verified_asset(wanted.name(), progress)?;
288 self.apply(wanted, &archive, progress)?;
289 Ok(Installed {
290 previous_version: self.app.version.clone(),
291 version: self.release.version.clone(),
292 path: self.executable.to_owned(),
293 })
294 }
295
296 fn verified_asset(&self, name: &str, progress: &dyn Fn(UpdateProgress)) -> Result<Vec<u8>> {
299 anyhow::ensure!(
300 self.release.assets.contains_key(name)
301 && self.release.assets.contains_key(&format!("{name}.sha256")),
302 "release {} has no {name} archive or checksum yet; check for updates again later. Nothing was installed",
303 self.release.tag
304 );
305 let bytes = self
306 .client
307 .asset_with_progress(self.release, name, progress)?;
308 progress(UpdateProgress::DownloadingChecksum);
309 let checksum = self.client.asset(self.release, &format!("{name}.sha256"))?;
310 progress(UpdateProgress::VerifyingChecksum);
311 verify_checksum(&checksum, name, &bytes)?;
312 Ok(bytes)
313 }
314
315 fn apply(
316 &self,
317 wanted: &Wanted,
318 archive: &[u8],
319 progress: &dyn Fn(UpdateProgress),
320 ) -> Result<()> {
321 match wanted {
322 Wanted::Plain { zip, .. } => self.plain(archive, *zip, progress),
323 Wanted::Bundle { .. } => self.bundle(archive, progress),
324 }
325 }
326
327 fn plain(&self, archive: &[u8], zip: bool, progress: &dyn Fn(UpdateProgress)) -> Result<()> {
328 let binary = binary_entry_name(&self.app.binary_name, zip);
329 progress(UpdateProgress::Extracting);
330 let contents = extract(archive, zip, &binary)?;
331 verify_product(&contents.product, &self.app.id, &self.release.version, None)?;
332 progress(UpdateProgress::Installing);
333 replace_executable(self.executable, &contents.binary, cfg!(windows))
334 }
335
336 fn bundle(&self, archive: &[u8], progress: &dyn Fn(UpdateProgress)) -> Result<()> {
337 let root = archive::bundle_root(self.executable)
338 .context("the executable is not inside an app bundle")?;
339 let install = BundleInstall {
340 bundle: root,
341 bundle_name: &self.app.display_name,
342 binary_name: &self.app.binary_name,
343 product_id: &self.app.id,
344 bundle_id: &self.app.bundle_id,
345 version: &self.release.version,
346 };
347 install_bundle_with_progress(&install, archive, &SystemTools, progress)
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use std::collections::BTreeMap;
354
355 use subspace_product::{ValidatedProduct, fixture};
356
357 use super::{Release, Updater};
358
359 pub(crate) fn known_product() -> ValidatedProduct {
360 fixture::products()
361 .expect("the known products validate")
362 .into_iter()
363 .find(|product| product.id.as_str() == "subspace")
364 .expect("the product exists")
365 }
366
367 #[test]
368 fn the_known_app_has_an_updater_and_reports_the_running_version() {
369 for product in fixture::products().expect("the known products validate") {
370 let updater = Updater::for_product(&product, "1.1.0")
371 .unwrap_or_else(|| panic!("{} has an update source", product.id.as_str()));
372 assert_eq!(updater.current_version(), "1.1.0");
373 }
374 }
375
376 #[test]
379 fn a_release_crosses_threads_for_a_background_check() {
380 let release = Release {
381 tag: "subspace-desktop-v1.2.0".into(),
382 version: "1.2.0".into(),
383 html_url: "https://example.test/release".into(),
384 assets: BTreeMap::new(),
385 };
386 let sent = release.clone();
387 let received = std::thread::spawn(move || sent)
388 .join()
389 .expect("the release crosses threads");
390 assert_eq!(received, release);
391 }
392
393 #[test]
394 fn an_app_without_an_update_source_has_no_updater() {
395 let mut product = known_product();
396 product.update = None;
397 assert!(Updater::for_product(&product, "1.1.0").is_none());
398 }
399
400 #[test]
401 fn integration_versions_cannot_create_an_updater_even_with_a_stable_source() {
402 assert!(
403 Updater::for_product(
404 &known_product(),
405 "0.3.0-feat-subspace-desktop.202611151345.gabc1234"
406 )
407 .is_none()
408 );
409 }
410
411 #[test]
412 fn an_installed_version_must_be_of_the_release_form_before_any_request() {
413 let updater = Updater::for_product(&known_product(), "1.1.0")
414 .expect("the standalone product has an update source")
415 .against("http://127.0.0.1:1/unused", "fixture-token");
416 let error = updater.find("not-a-version").unwrap_err();
417 assert!(error.to_string().contains("1.2.3"), "{error}");
418 }
419
420 #[test]
421 fn a_nightly_updater_refuses_a_pinned_stable_version_before_any_request() {
422 let product = subspace_product::validate_product(
423 &subspace_product::fixture::descriptor_for(subspace_product::Channel::Nightly),
424 )
425 .expect("the nightly descriptor validates");
426 let updater = Updater::for_product(&product, "1.10.2-nightly.202611010200.ga43a333")
427 .expect("the nightly product has an update source")
428 .against("http://127.0.0.1:1/unused", "fixture-token");
429 let error = updater.find("1.10.1").unwrap_err();
430 assert!(
431 error.to_string().contains("only nightly versions"),
432 "{error}"
433 );
434 }
435
436 #[test]
437 fn an_executable_a_package_manager_installed_is_refused_before_any_download() {
438 let directory = tempfile::tempdir().expect("a temporary installation folder");
439 let executable = directory.path().join("subspace-packaged");
440 std::fs::write(&executable, b"feed installation").expect("write the executable");
441 let updater = Updater::for_product(&known_product(), "1.1.0")
442 .expect("the standalone product has an update source")
443 .against("http://127.0.0.1:1/unused", "fixture-token");
444 let release = Release {
445 tag: "subspace-desktop-v1.2.0".into(),
446 version: "1.2.0".into(),
447 html_url: String::new(),
448 assets: BTreeMap::new(),
449 };
450 let error = updater.install_at(&release, &executable).unwrap_err();
451 assert!(error.to_string().contains("package manager"), "{error}");
452 assert_eq!(std::fs::read(&executable).unwrap(), b"feed installation");
453 }
454
455 #[test]
456 fn an_asset_url_outside_the_api_base_is_refused_before_the_token_is_sent() {
457 let updater = Updater::for_product(&known_product(), "1.1.0")
458 .expect("the standalone product has an update source")
459 .against("https://api.example.test", "fixture-token");
460 let release = Release {
461 tag: "subspace-desktop-v1.2.0".into(),
462 version: "1.2.0".into(),
463 html_url: String::new(),
464 assets: BTreeMap::from([(
465 "asset".to_owned(),
466 "https://elsewhere.invalid/asset".to_owned(),
467 )]),
468 };
469 let client = updater.client().expect("a fixed token needs no lookup");
470 let error = client.asset(&release, "asset").unwrap_err();
471 assert!(
472 error.to_string().contains("not on the GitHub API"),
473 "{error}"
474 );
475 }
476}