core.rs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use super::error::{Error, Result};
  5. #[cfg(desktop)]
  6. use crate::api::file::{ArchiveFormat, Extract, Move};
  7. use crate::{
  8. api::http::{ClientBuilder, HttpRequestBuilder},
  9. AppHandle, Manager, Runtime,
  10. };
  11. use base64::Engine;
  12. use http::{
  13. header::{HeaderName, HeaderValue},
  14. HeaderMap, StatusCode,
  15. };
  16. use minisign_verify::{PublicKey, Signature};
  17. use semver::Version;
  18. use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
  19. use tauri_utils::{platform::current_exe, Env};
  20. use time::OffsetDateTime;
  21. use url::Url;
  22. #[cfg(desktop)]
  23. use std::io::Seek;
  24. use std::{
  25. collections::HashMap,
  26. env,
  27. fmt::{self},
  28. io::{Cursor, Read},
  29. path::{Path, PathBuf},
  30. str::{from_utf8, FromStr},
  31. time::Duration,
  32. };
  33. #[cfg(any(target_os = "linux", windows))]
  34. use std::ffi::OsStr;
  35. #[cfg(all(desktop, not(target_os = "windows")))]
  36. use crate::api::file::Compression;
  37. #[cfg(target_os = "windows")]
  38. use std::{
  39. fs::read_dir,
  40. process::{exit, Command},
  41. };
  42. type ShouldInstall = dyn FnOnce(&Version, &RemoteRelease) -> bool + Send;
  43. #[derive(Debug, Deserialize, Serialize)]
  44. #[serde(untagged)]
  45. pub enum RemoteReleaseInner {
  46. Dynamic(ReleaseManifestPlatform),
  47. Static {
  48. platforms: HashMap<String, ReleaseManifestPlatform>,
  49. },
  50. }
  51. /// Information about a release returned by the remote update server.
  52. ///
  53. /// This type can have one of two shapes: Server Format (Dynamic Format) and Static Format.
  54. #[derive(Debug)]
  55. pub struct RemoteRelease {
  56. /// Version to install.
  57. version: Version,
  58. /// Release notes.
  59. notes: Option<String>,
  60. /// Release date.
  61. pub_date: Option<OffsetDateTime>,
  62. /// Release data.
  63. data: RemoteReleaseInner,
  64. }
  65. impl<'de> Deserialize<'de> for RemoteRelease {
  66. fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
  67. where
  68. D: Deserializer<'de>,
  69. {
  70. #[derive(Deserialize)]
  71. struct InnerRemoteRelease {
  72. #[serde(alias = "name", deserialize_with = "parse_version")]
  73. version: Version,
  74. notes: Option<String>,
  75. pub_date: Option<String>,
  76. platforms: Option<HashMap<String, ReleaseManifestPlatform>>,
  77. // dynamic platform response
  78. url: Option<Url>,
  79. signature: Option<String>,
  80. #[cfg(target_os = "windows")]
  81. #[serde(default)]
  82. with_elevated_task: bool,
  83. }
  84. let release = InnerRemoteRelease::deserialize(deserializer)?;
  85. let pub_date = if let Some(date) = release.pub_date {
  86. Some(
  87. OffsetDateTime::parse(&date, &time::format_description::well_known::Rfc3339)
  88. .map_err(|e| DeError::custom(format!("invalid value for `pub_date`: {e}")))?,
  89. )
  90. } else {
  91. None
  92. };
  93. Ok(RemoteRelease {
  94. version: release.version,
  95. notes: release.notes,
  96. pub_date,
  97. data: if let Some(platforms) = release.platforms {
  98. RemoteReleaseInner::Static { platforms }
  99. } else {
  100. RemoteReleaseInner::Dynamic(ReleaseManifestPlatform {
  101. url: release.url.ok_or_else(|| {
  102. DeError::custom("the `url` field was not set on the updater response")
  103. })?,
  104. signature: release.signature.ok_or_else(|| {
  105. DeError::custom("the `signature` field was not set on the updater response")
  106. })?,
  107. #[cfg(target_os = "windows")]
  108. with_elevated_task: release.with_elevated_task,
  109. })
  110. },
  111. })
  112. }
  113. }
  114. #[derive(Debug, Deserialize, Serialize)]
  115. pub struct ReleaseManifestPlatform {
  116. /// Download URL for the platform
  117. pub url: Url,
  118. /// Signature for the platform
  119. pub signature: String,
  120. #[cfg(target_os = "windows")]
  121. #[serde(default)]
  122. /// Optional: Windows only try to use elevated task
  123. pub with_elevated_task: bool,
  124. }
  125. fn parse_version<'de, D>(deserializer: D) -> std::result::Result<Version, D::Error>
  126. where
  127. D: serde::Deserializer<'de>,
  128. {
  129. let str = String::deserialize(deserializer)?;
  130. Version::from_str(str.trim_start_matches('v')).map_err(serde::de::Error::custom)
  131. }
  132. impl RemoteRelease {
  133. /// The release version.
  134. pub fn version(&self) -> &Version {
  135. &self.version
  136. }
  137. /// The release notes.
  138. pub fn notes(&self) -> Option<&String> {
  139. self.notes.as_ref()
  140. }
  141. /// The release date.
  142. pub fn pub_date(&self) -> Option<&OffsetDateTime> {
  143. self.pub_date.as_ref()
  144. }
  145. /// The release's download URL for the given target.
  146. pub fn download_url(&self, target: &str) -> Result<&Url> {
  147. match self.data {
  148. RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.url),
  149. RemoteReleaseInner::Static { ref platforms } => platforms
  150. .get(target)
  151. .map_or(Err(Error::TargetNotFound(target.to_string())), |p| {
  152. Ok(&p.url)
  153. }),
  154. }
  155. }
  156. /// The release's signature for the given target.
  157. pub fn signature(&self, target: &str) -> Result<&String> {
  158. match self.data {
  159. RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.signature),
  160. RemoteReleaseInner::Static { ref platforms } => platforms
  161. .get(target)
  162. .map_or(Err(Error::TargetNotFound(target.to_string())), |platform| {
  163. Ok(&platform.signature)
  164. }),
  165. }
  166. }
  167. #[cfg(target_os = "windows")]
  168. /// Optional: Windows only try to use elevated task
  169. pub fn with_elevated_task(&self, target: &str) -> Result<bool> {
  170. match self.data {
  171. RemoteReleaseInner::Dynamic(ref platform) => Ok(platform.with_elevated_task),
  172. RemoteReleaseInner::Static { ref platforms } => platforms
  173. .get(target)
  174. .map_or(Err(Error::TargetNotFound(target.to_string())), |platform| {
  175. Ok(platform.with_elevated_task)
  176. }),
  177. }
  178. }
  179. }
  180. pub struct UpdateBuilder<R: Runtime> {
  181. /// Application handle.
  182. pub app: AppHandle<R>,
  183. /// Current version we are running to compare with announced version
  184. pub current_version: Version,
  185. /// The URLs to checks updates. We suggest at least one fallback on a different domain.
  186. pub urls: Vec<String>,
  187. /// The platform the updater will check and install the update. Default is from `get_updater_target`
  188. pub target: Option<String>,
  189. /// The current executable path. Default is automatically extracted.
  190. pub executable_path: Option<PathBuf>,
  191. should_install: Option<Box<ShouldInstall>>,
  192. timeout: Option<Duration>,
  193. headers: HeaderMap,
  194. }
  195. impl<R: Runtime> fmt::Debug for UpdateBuilder<R> {
  196. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  197. f.debug_struct("UpdateBuilder")
  198. .field("app", &self.app)
  199. .field("current_version", &self.current_version)
  200. .field("urls", &self.urls)
  201. .field("target", &self.target)
  202. .field("executable_path", &self.executable_path)
  203. .field("timeout", &self.timeout)
  204. .field("headers", &self.headers)
  205. .finish()
  206. }
  207. }
  208. // Create new updater instance and return an Update
  209. impl<R: Runtime> UpdateBuilder<R> {
  210. pub fn new(app: AppHandle<R>) -> Self {
  211. UpdateBuilder {
  212. app,
  213. urls: Vec::new(),
  214. target: None,
  215. executable_path: None,
  216. // safe to unwrap: CARGO_PKG_VERSION is also a valid semver value
  217. current_version: env!("CARGO_PKG_VERSION").parse().unwrap(),
  218. should_install: None,
  219. timeout: None,
  220. headers: Default::default(),
  221. }
  222. }
  223. #[allow(dead_code)]
  224. pub fn url(mut self, url: String) -> Self {
  225. self.urls.push(
  226. percent_encoding::percent_decode(url.as_bytes())
  227. .decode_utf8_lossy()
  228. .to_string(),
  229. );
  230. self
  231. }
  232. /// Add multiple URLS at once inside a Vec for future reference
  233. pub fn urls(mut self, urls: &[String]) -> Self {
  234. let mut formatted_vec: Vec<String> = Vec::new();
  235. for url in urls {
  236. formatted_vec.push(
  237. percent_encoding::percent_decode(url.as_bytes())
  238. .decode_utf8_lossy()
  239. .to_string(),
  240. );
  241. }
  242. self.urls = formatted_vec;
  243. self
  244. }
  245. /// Set the current app version, used to compare against the latest available version.
  246. /// The `cargo_crate_version!` macro can be used to pull the version from your `Cargo.toml`
  247. pub fn current_version(mut self, ver: Version) -> Self {
  248. self.current_version = ver;
  249. self
  250. }
  251. /// Set the target name. Represents the string that is looked up on the updater API or response JSON.
  252. pub fn target(mut self, target: impl Into<String>) -> Self {
  253. self.target.replace(target.into());
  254. self
  255. }
  256. /// Set the executable path
  257. #[allow(dead_code)]
  258. pub fn executable_path<A: AsRef<Path>>(mut self, executable_path: A) -> Self {
  259. self.executable_path = Some(PathBuf::from(executable_path.as_ref()));
  260. self
  261. }
  262. pub fn should_install<F: FnOnce(&Version, &RemoteRelease) -> bool + Send + 'static>(
  263. mut self,
  264. f: F,
  265. ) -> Self {
  266. self.should_install.replace(Box::new(f));
  267. self
  268. }
  269. pub fn timeout(mut self, timeout: Duration) -> Self {
  270. self.timeout.replace(timeout);
  271. self
  272. }
  273. /// Add a `Header` to the request.
  274. pub fn header<K, V>(mut self, key: K, value: V) -> Result<Self>
  275. where
  276. HeaderName: TryFrom<K>,
  277. <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
  278. HeaderValue: TryFrom<V>,
  279. <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
  280. {
  281. let key: std::result::Result<HeaderName, http::Error> = key.try_into().map_err(Into::into);
  282. let value: std::result::Result<HeaderValue, http::Error> = value.try_into().map_err(Into::into);
  283. self.headers.insert(key?, value?);
  284. Ok(self)
  285. }
  286. pub async fn build(mut self) -> Result<Update<R>> {
  287. let mut remote_release: Option<RemoteRelease> = None;
  288. // make sure we have at least one url
  289. if self.urls.is_empty() {
  290. return Err(Error::Builder(
  291. "Unable to check update, `url` is required.".into(),
  292. ));
  293. };
  294. // If no executable path provided, we use current_exe from tauri_utils
  295. let executable_path = self.executable_path.unwrap_or(current_exe()?);
  296. let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?;
  297. // `target` is the `{{target}}` variable we replace in the endpoint
  298. // `json_target` is the value we search if the updater server returns a JSON with the `platforms` object
  299. let (target, json_target) = if let Some(target) = self.target {
  300. (target.clone(), target)
  301. } else {
  302. let target = get_updater_target().ok_or(Error::UnsupportedOs)?;
  303. (target.to_string(), format!("{target}-{arch}"))
  304. };
  305. // Get the extract_path from the provided executable_path
  306. let extract_path = extract_path_from_executable(&self.app.state::<Env>(), &executable_path);
  307. // Set SSL certs for linux if they aren't available.
  308. // We do not require to recheck in the download_and_install as we use
  309. // ENV variables, we can expect them to be set for the second call.
  310. #[cfg(target_os = "linux")]
  311. {
  312. if env::var_os("SSL_CERT_FILE").is_none() {
  313. env::set_var("SSL_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt");
  314. }
  315. if env::var_os("SSL_CERT_DIR").is_none() {
  316. env::set_var("SSL_CERT_DIR", "/etc/ssl/certs");
  317. }
  318. }
  319. // we want JSON only
  320. let mut headers = self.headers;
  321. headers.insert("Accept", HeaderValue::from_str("application/json").unwrap());
  322. // Allow fallback if more than 1 urls is provided
  323. let mut last_error: Option<Error> = None;
  324. for url in &self.urls {
  325. // replace {{current_version}}, {{target}} and {{arch}} in the provided URL
  326. // this is useful if we need to query example
  327. // https://releases.myapp.com/update/{{target}}/{{arch}}/{{current_version}}
  328. // will be translated into ->
  329. // https://releases.myapp.com/update/darwin/aarch64/1.0.0
  330. // The main objective is if the update URL is defined via the Cargo.toml
  331. // the URL will be generated dynamically
  332. let fixed_link = url
  333. .replace("{{current_version}}", &self.current_version.to_string())
  334. .replace("{{target}}", &target)
  335. .replace("{{arch}}", arch);
  336. let mut request = HttpRequestBuilder::new("GET", &fixed_link)?.headers(headers.clone());
  337. if let Some(timeout) = self.timeout {
  338. request = request.timeout(timeout);
  339. }
  340. let resp = ClientBuilder::new().build()?.send(request).await;
  341. // If we got a success, we stop the loop
  342. // and we set our remote_release variable
  343. if let Ok(res) = resp {
  344. let status = res.status();
  345. // got status code 2XX
  346. if status.is_success() {
  347. // if we got 204
  348. if status == StatusCode::NO_CONTENT {
  349. // return with `UpToDate` error
  350. // we should catch on the client
  351. return Err(Error::UpToDate);
  352. };
  353. let res = res.read().await?;
  354. // Convert the remote result to our local struct
  355. let built_release = serde_json::from_value(res.data).map_err(Into::into);
  356. // make sure all went well and the remote data is compatible
  357. // with what we need locally
  358. match built_release {
  359. Ok(release) => {
  360. last_error = None;
  361. remote_release = Some(release);
  362. break;
  363. }
  364. Err(err) => last_error = Some(err),
  365. }
  366. } // if status code is not 2XX we keep loopin' our urls
  367. }
  368. }
  369. // Last error is cleaned on success -- shouldn't be triggered if
  370. // we have a successful call
  371. if let Some(error) = last_error {
  372. return Err(error);
  373. }
  374. // Extracted remote metadata
  375. let final_release = remote_release.ok_or(Error::ReleaseNotFound)?;
  376. // is the announced version greater than our current one?
  377. let should_update = if let Some(comparator) = self.should_install.take() {
  378. comparator(&self.current_version, &final_release)
  379. } else {
  380. final_release.version() > &self.current_version
  381. };
  382. headers.remove("Accept");
  383. // create our new updater
  384. Ok(Update {
  385. app: self.app,
  386. target,
  387. extract_path,
  388. should_update,
  389. version: final_release.version().to_string(),
  390. date: final_release.pub_date().cloned(),
  391. current_version: self.current_version,
  392. download_url: final_release.download_url(&json_target)?.to_owned(),
  393. body: final_release.notes().cloned(),
  394. signature: final_release.signature(&json_target)?.to_owned(),
  395. #[cfg(target_os = "windows")]
  396. with_elevated_task: final_release.with_elevated_task(&json_target)?,
  397. timeout: self.timeout,
  398. headers,
  399. })
  400. }
  401. }
  402. pub fn builder<R: Runtime>(app: AppHandle<R>) -> UpdateBuilder<R> {
  403. UpdateBuilder::new(app)
  404. }
  405. #[derive(Debug)]
  406. pub struct Update<R: Runtime> {
  407. /// Application handle.
  408. pub app: AppHandle<R>,
  409. /// Update description
  410. pub body: Option<String>,
  411. /// Should we update or not
  412. pub should_update: bool,
  413. /// Version announced
  414. pub version: String,
  415. /// Running version
  416. pub current_version: Version,
  417. /// Update publish date
  418. pub date: Option<OffsetDateTime>,
  419. /// Target
  420. #[allow(dead_code)]
  421. target: String,
  422. /// Extract path
  423. extract_path: PathBuf,
  424. /// Download URL announced
  425. download_url: Url,
  426. /// Signature announced
  427. signature: String,
  428. #[cfg(target_os = "windows")]
  429. /// Optional: Windows only try to use elevated task
  430. /// Default to false
  431. with_elevated_task: bool,
  432. /// Request timeout
  433. timeout: Option<Duration>,
  434. /// Request headers
  435. headers: HeaderMap,
  436. }
  437. impl<R: Runtime> Clone for Update<R> {
  438. fn clone(&self) -> Self {
  439. Self {
  440. app: self.app.clone(),
  441. body: self.body.clone(),
  442. should_update: self.should_update,
  443. version: self.version.clone(),
  444. current_version: self.current_version.clone(),
  445. date: self.date,
  446. target: self.target.clone(),
  447. extract_path: self.extract_path.clone(),
  448. download_url: self.download_url.clone(),
  449. signature: self.signature.clone(),
  450. #[cfg(target_os = "windows")]
  451. with_elevated_task: self.with_elevated_task,
  452. timeout: self.timeout,
  453. headers: self.headers.clone(),
  454. }
  455. }
  456. }
  457. impl<R: Runtime> Update<R> {
  458. // Download and install our update
  459. // @todo(lemarier): Split into download and install (two step) but need to be thread safe
  460. pub(crate) async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
  461. &self,
  462. pub_key: String,
  463. on_chunk: C,
  464. on_download_finish: D,
  465. ) -> Result {
  466. // make sure we can install the update on linux
  467. // We fail here because later we can add more linux support
  468. // actually if we use APPIMAGE, our extract path should already
  469. // be set with our APPIMAGE env variable, we don't need to do
  470. // anything with it yet
  471. #[cfg(target_os = "linux")]
  472. if self.app.state::<Env>().appimage.is_none() {
  473. return Err(Error::UnsupportedLinuxPackage);
  474. }
  475. // set our headers
  476. let mut headers = self.headers.clone();
  477. headers.insert(
  478. "Accept",
  479. HeaderValue::from_str("application/octet-stream").unwrap(),
  480. );
  481. headers.insert(
  482. "User-Agent",
  483. HeaderValue::from_str("tauri/updater").unwrap(),
  484. );
  485. let client = ClientBuilder::new().build()?;
  486. // Create our request
  487. let mut req = HttpRequestBuilder::new("GET", self.download_url.as_str())?.headers(headers);
  488. if let Some(timeout) = self.timeout {
  489. req = req.timeout(timeout);
  490. }
  491. let response = client.send(req).await?;
  492. // make sure it's success
  493. if !response.status().is_success() {
  494. return Err(Error::Network(format!(
  495. "Download request failed with status: {}",
  496. response.status()
  497. )));
  498. }
  499. let content_length: Option<u64> = response
  500. .headers()
  501. .get("Content-Length")
  502. .and_then(|value| value.to_str().ok())
  503. .and_then(|value| value.parse().ok());
  504. let mut buffer = Vec::new();
  505. #[cfg(feature = "reqwest-client")]
  506. {
  507. use futures_util::StreamExt;
  508. let mut stream = response.bytes_stream();
  509. while let Some(chunk) = stream.next().await {
  510. let chunk = chunk?;
  511. let bytes = chunk.as_ref().to_vec();
  512. on_chunk(bytes.len(), content_length);
  513. buffer.extend(bytes);
  514. }
  515. }
  516. #[cfg(not(feature = "reqwest-client"))]
  517. {
  518. let mut reader = response.reader();
  519. let mut buf = [0; 16384];
  520. loop {
  521. match reader.read(&mut buf) {
  522. Ok(b) => {
  523. if b == 0 {
  524. break;
  525. } else {
  526. let bytes = buf[0..b].to_vec();
  527. on_chunk(bytes.len(), content_length);
  528. buffer.extend(bytes);
  529. }
  530. }
  531. Err(e) => return Err(e.into()),
  532. }
  533. }
  534. }
  535. on_download_finish();
  536. // create memory buffer from our archive (Seek + Read)
  537. let mut archive_buffer = Cursor::new(buffer);
  538. // We need an announced signature by the server
  539. // if there is no signature, bail out.
  540. verify_signature(&mut archive_buffer, &self.signature, &pub_key)?;
  541. // TODO: implement updater in mobile
  542. #[cfg(desktop)]
  543. {
  544. // we copy the files depending of the operating system
  545. // we run the setup, appimage re-install or overwrite the
  546. // macos .app
  547. #[cfg(target_os = "windows")]
  548. copy_files_and_run(
  549. archive_buffer,
  550. &self.extract_path,
  551. self.with_elevated_task,
  552. &self.app.config(),
  553. )?;
  554. #[cfg(not(target_os = "windows"))]
  555. copy_files_and_run(archive_buffer, &self.extract_path)?;
  556. }
  557. // We are done!
  558. Ok(())
  559. }
  560. }
  561. // Linux (AppImage)
  562. // ### Expected structure:
  563. // ├── [AppName]_[version]_amd64.AppImage.tar.gz # GZ generated by tauri-bundler
  564. // │ └──[AppName]_[version]_amd64.AppImage # Application AppImage
  565. // └── ...
  566. // We should have an AppImage already installed to be able to copy and install
  567. // the extract_path is the current AppImage path
  568. // tmp_dir is where our new AppImage is found
  569. #[cfg(target_os = "linux")]
  570. fn copy_files_and_run<R: Read + Seek>(archive_buffer: R, extract_path: &Path) -> Result {
  571. use std::os::unix::fs::{MetadataExt, PermissionsExt};
  572. let extract_path_metadata = extract_path.metadata()?;
  573. let tmp_dir_locations = vec![
  574. Box::new(|| Some(env::temp_dir())) as Box<dyn FnOnce() -> Option<PathBuf>>,
  575. Box::new(dirs_next::cache_dir),
  576. Box::new(|| Some(extract_path.parent().unwrap().to_path_buf())),
  577. ];
  578. for tmp_dir_location in tmp_dir_locations {
  579. if let Some(tmp_dir_location) = tmp_dir_location() {
  580. let tmp_dir = tempfile::Builder::new()
  581. .prefix("tauri_current_app")
  582. .tempdir_in(tmp_dir_location)?;
  583. let tmp_dir_metadata = tmp_dir.path().metadata()?;
  584. if extract_path_metadata.dev() == tmp_dir_metadata.dev() {
  585. let mut perms = tmp_dir_metadata.permissions();
  586. perms.set_mode(0o700);
  587. std::fs::set_permissions(tmp_dir.path(), perms)?;
  588. let tmp_app_image = &tmp_dir.path().join("current_app.AppImage");
  589. // create a backup of our current app image
  590. Move::from_source(extract_path).to_dest(tmp_app_image)?;
  591. // extract the buffer to the tmp_dir
  592. // we extract our signed archive into our final directory without any temp file
  593. let mut extractor =
  594. Extract::from_cursor(archive_buffer, ArchiveFormat::Tar(Some(Compression::Gz)));
  595. return extractor
  596. .with_files(|entry| {
  597. let path = entry.path()?;
  598. if path.extension() == Some(OsStr::new("AppImage")) {
  599. // if something went wrong during the extraction, we should restore previous app
  600. if let Err(err) = entry.extract(extract_path) {
  601. Move::from_source(tmp_app_image).to_dest(extract_path)?;
  602. return Err(crate::api::Error::Extract(err.to_string()));
  603. }
  604. // early finish we have everything we need here
  605. return Ok(true);
  606. }
  607. Ok(false)
  608. })
  609. .map_err(Into::into);
  610. }
  611. }
  612. }
  613. Err(Error::TempDirNotOnSameMountPoint)
  614. }
  615. // Windows
  616. //
  617. // ### Expected structure:
  618. // ├── [AppName]_[version]_x64.msi.zip # ZIP generated by tauri-bundler
  619. // │ └──[AppName]_[version]_x64.msi # Application MSI
  620. // ├── [AppName]_[version]_x64-setup.exe.zip # ZIP generated by tauri-bundler
  621. // │ └──[AppName]_[version]_x64-setup.exe # NSIS installer
  622. // └── ...
  623. //
  624. // ## MSI
  625. // Update server can provide a MSI for Windows. (Generated with tauri-bundler from *Wix*)
  626. // To replace current version of the application. In later version we'll offer
  627. // incremental update to push specific binaries.
  628. //
  629. // ## EXE
  630. // Update server can provide a custom EXE (installer) who can run any task.
  631. #[cfg(target_os = "windows")]
  632. #[allow(clippy::unnecessary_wraps)]
  633. fn copy_files_and_run<R: Read + Seek>(
  634. archive_buffer: R,
  635. _extract_path: &Path,
  636. with_elevated_task: bool,
  637. config: &crate::Config,
  638. ) -> Result {
  639. // FIXME: We need to create a memory buffer with the MSI and then run it.
  640. // (instead of extracting the MSI to a temp path)
  641. //
  642. // The tricky part is the MSI need to be exposed and spawned so the memory allocation
  643. // shouldn't drop but we should be able to pass the reference so we can drop it once the installation
  644. // is done, otherwise we have a huge memory leak.
  645. let tmp_dir = tempfile::Builder::new().tempdir()?.into_path();
  646. // extract the buffer to the tmp_dir
  647. // we extract our signed archive into our final directory without any temp file
  648. let mut extractor = Extract::from_cursor(archive_buffer, ArchiveFormat::Zip);
  649. // extract the msi
  650. extractor.extract_into(&tmp_dir)?;
  651. let paths = read_dir(&tmp_dir)?;
  652. for path in paths {
  653. let found_path = path?.path();
  654. // we support 2 type of files exe & msi for now
  655. // If it's an `exe` we expect an installer not a runtime.
  656. if found_path.extension() == Some(OsStr::new("exe")) {
  657. // Run the EXE
  658. let mut installer = Command::new(found_path);
  659. if crate::utils::config::WindowsUpdateInstallMode::Quiet
  660. == config.tauri.updater.windows.install_mode
  661. {
  662. installer.arg("/S");
  663. }
  664. installer.args(&config.tauri.updater.windows.installer_args);
  665. installer.spawn().expect("installer failed to start");
  666. exit(0);
  667. } else if found_path.extension() == Some(OsStr::new("msi")) {
  668. if with_elevated_task {
  669. if let Some(bin_name) = current_exe()
  670. .ok()
  671. .and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
  672. .and_then(|s| s.into_string().ok())
  673. {
  674. let product_name = bin_name.replace(".exe", "");
  675. // Check if there is a task that enables the updater to skip the UAC prompt
  676. let update_task_name = format!("Update {product_name} - Skip UAC");
  677. if let Ok(output) = Command::new("schtasks")
  678. .arg("/QUERY")
  679. .arg("/TN")
  680. .arg(update_task_name.clone())
  681. .output()
  682. {
  683. if output.status.success() {
  684. // Rename the MSI to the match file name the Skip UAC task is expecting it to be
  685. let temp_msi = tmp_dir.with_file_name(bin_name).with_extension("msi");
  686. Move::from_source(&found_path)
  687. .to_dest(&temp_msi)
  688. .expect("Unable to move update MSI");
  689. let exit_status = Command::new("schtasks")
  690. .arg("/RUN")
  691. .arg("/TN")
  692. .arg(update_task_name)
  693. .status()
  694. .expect("failed to start updater task");
  695. if exit_status.success() {
  696. // Successfully launched task that skips the UAC prompt
  697. exit(0);
  698. }
  699. }
  700. // Failed to run update task. Following UAC Path
  701. }
  702. }
  703. }
  704. // we need to wrap the current exe path in quotes for Start-Process
  705. let mut current_exe_arg = std::ffi::OsString::new();
  706. current_exe_arg.push("\"");
  707. current_exe_arg.push(current_exe()?);
  708. current_exe_arg.push("\"");
  709. let mut msi_path_arg = std::ffi::OsString::new();
  710. msi_path_arg.push("\"\"\"");
  711. msi_path_arg.push(&found_path);
  712. msi_path_arg.push("\"\"\"");
  713. let mut msiexec_args = config
  714. .tauri
  715. .updater
  716. .windows
  717. .install_mode
  718. .clone()
  719. .msiexec_args()
  720. .iter()
  721. .map(|p| p.to_string())
  722. .collect::<Vec<String>>();
  723. msiexec_args.extend(config.tauri.updater.windows.installer_args.clone());
  724. // run the installer and relaunch the application
  725. let system_root = std::env::var("SYSTEMROOT");
  726. let powershell_path = system_root.as_ref().map_or_else(
  727. |_| "powershell.exe".to_string(),
  728. |p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"),
  729. );
  730. let powershell_install_res = Command::new(powershell_path)
  731. .args(["-NoProfile", "-windowstyle", "hidden"])
  732. .args([
  733. "Start-Process",
  734. "-Wait",
  735. "-FilePath",
  736. "$env:SYSTEMROOT\\System32\\msiexec.exe",
  737. "-ArgumentList",
  738. ])
  739. .arg("/i,")
  740. .arg(msi_path_arg)
  741. .arg(format!(", {}, /promptrestart;", msiexec_args.join(", ")))
  742. .arg("Start-Process")
  743. .arg(current_exe_arg)
  744. .spawn();
  745. if powershell_install_res.is_err() {
  746. // fallback to running msiexec directly - relaunch won't be available
  747. // we use this here in case powershell fails in an older machine somehow
  748. let msiexec_path = system_root.as_ref().map_or_else(
  749. |_| "msiexec.exe".to_string(),
  750. |p| format!("{p}\\System32\\msiexec.exe"),
  751. );
  752. let _ = Command::new(msiexec_path)
  753. .arg("/i")
  754. .arg(found_path)
  755. .args(msiexec_args)
  756. .arg("/promptrestart")
  757. .spawn();
  758. }
  759. exit(0);
  760. }
  761. }
  762. Ok(())
  763. }
  764. // MacOS
  765. // ### Expected structure:
  766. // ├── [AppName]_[version]_x64.app.tar.gz # GZ generated by tauri-bundler
  767. // │ └──[AppName].app # Main application
  768. // │ └── Contents # Application contents...
  769. // │ └── ...
  770. // └── ...
  771. #[cfg(target_os = "macos")]
  772. fn copy_files_and_run<R: Read + Seek>(archive_buffer: R, extract_path: &Path) -> Result {
  773. let mut extracted_files: Vec<PathBuf> = Vec::new();
  774. // extract the buffer to the tmp_dir
  775. // we extract our signed archive into our final directory without any temp file
  776. let mut extractor =
  777. Extract::from_cursor(archive_buffer, ArchiveFormat::Tar(Some(Compression::Gz)));
  778. // the first file in the tar.gz will always be
  779. // <app_name>/Contents
  780. let tmp_dir = tempfile::Builder::new()
  781. .prefix("tauri_current_app")
  782. .tempdir()?;
  783. // create backup of our current app
  784. Move::from_source(extract_path).to_dest(tmp_dir.path())?;
  785. // extract all the files
  786. extractor.with_files(|entry| {
  787. let path = entry.path()?;
  788. // skip the first folder (should be the app name)
  789. let collected_path: PathBuf = path.iter().skip(1).collect();
  790. let extraction_path = extract_path.join(collected_path);
  791. // if something went wrong during the extraction, we should restore previous app
  792. if let Err(err) = entry.extract(&extraction_path) {
  793. for file in &extracted_files {
  794. // delete all the files we extracted
  795. if file.is_dir() {
  796. std::fs::remove_dir(file)?;
  797. } else {
  798. std::fs::remove_file(file)?;
  799. }
  800. }
  801. Move::from_source(tmp_dir.path()).to_dest(extract_path)?;
  802. return Err(crate::api::Error::Extract(err.to_string()));
  803. }
  804. extracted_files.push(extraction_path);
  805. Ok(false)
  806. })?;
  807. let _ = std::process::Command::new("touch")
  808. .arg(extract_path)
  809. .status();
  810. Ok(())
  811. }
  812. pub(crate) fn get_updater_target() -> Option<&'static str> {
  813. if cfg!(target_os = "linux") {
  814. Some("linux")
  815. } else if cfg!(target_os = "macos") {
  816. Some("darwin")
  817. } else if cfg!(target_os = "windows") {
  818. Some("windows")
  819. } else {
  820. None
  821. }
  822. }
  823. pub(crate) fn get_updater_arch() -> Option<&'static str> {
  824. if cfg!(target_arch = "x86") {
  825. Some("i686")
  826. } else if cfg!(target_arch = "x86_64") {
  827. Some("x86_64")
  828. } else if cfg!(target_arch = "arm") {
  829. Some("armv7")
  830. } else if cfg!(target_arch = "aarch64") {
  831. Some("aarch64")
  832. } else {
  833. None
  834. }
  835. }
  836. /// Get the extract_path from the provided executable_path
  837. #[allow(unused_variables)]
  838. pub fn extract_path_from_executable(env: &Env, executable_path: &Path) -> PathBuf {
  839. // Return the path of the current executable by default
  840. // Example C:\Program Files\My App\
  841. let extract_path = executable_path
  842. .parent()
  843. .map(PathBuf::from)
  844. .expect("Can't determine extract path");
  845. // MacOS example binary is in /Applications/TestApp.app/Contents/MacOS/myApp
  846. // We need to get /Applications/<app>.app
  847. // todo(lemarier): Need a better way here
  848. // Maybe we could search for <*.app> to get the right path
  849. #[cfg(target_os = "macos")]
  850. if extract_path
  851. .display()
  852. .to_string()
  853. .contains("Contents/MacOS")
  854. {
  855. return extract_path
  856. .parent()
  857. .map(PathBuf::from)
  858. .expect("Unable to find the extract path")
  859. .parent()
  860. .map(PathBuf::from)
  861. .expect("Unable to find the extract path");
  862. }
  863. // We should use APPIMAGE exposed env variable
  864. // This is where our APPIMAGE should sit and should be replaced
  865. #[cfg(target_os = "linux")]
  866. if let Some(app_image_path) = &env.appimage {
  867. return PathBuf::from(app_image_path);
  868. }
  869. extract_path
  870. }
  871. // Convert base64 to string and prevent failing
  872. fn base64_to_string(base64_string: &str) -> Result<String> {
  873. let decoded_string = &base64::engine::general_purpose::STANDARD.decode(base64_string)?;
  874. let result = from_utf8(decoded_string)
  875. .map_err(|_| Error::SignatureUtf8(base64_string.into()))?
  876. .to_string();
  877. Ok(result)
  878. }
  879. // Validate signature
  880. // need to be public because its been used
  881. // by our tests in the bundler
  882. //
  883. // NOTE: The buffer position is not reset.
  884. pub fn verify_signature<R>(
  885. archive_reader: &mut R,
  886. release_signature: &str,
  887. pub_key: &str,
  888. ) -> Result<bool>
  889. where
  890. R: Read,
  891. {
  892. // we need to convert the pub key
  893. let pub_key_decoded = base64_to_string(pub_key)?;
  894. let public_key = PublicKey::decode(&pub_key_decoded)?;
  895. let signature_base64_decoded = base64_to_string(release_signature)?;
  896. let signature = Signature::decode(&signature_base64_decoded)?;
  897. // read all bytes until EOF in the buffer
  898. let mut data = Vec::new();
  899. archive_reader.read_to_end(&mut data)?;
  900. // Validate signature or bail out
  901. public_key.verify(&data, &signature, true)?;
  902. Ok(true)
  903. }
  904. #[cfg(test)]
  905. mod test {
  906. use super::*;
  907. #[cfg(target_os = "macos")]
  908. use std::fs::File;
  909. macro_rules! block {
  910. ($e:expr) => {
  911. tokio_test::block_on($e)
  912. };
  913. }
  914. fn generate_sample_raw_json() -> String {
  915. r#"{
  916. "version": "v2.0.0",
  917. "notes": "Test version !",
  918. "pub_date": "2020-06-22T19:25:57Z",
  919. "platforms": {
  920. "darwin-aarch64": {
  921. "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUldUTE5QWWxkQnlZOVJZVGdpKzJmRWZ0SkRvWS9TdFpqTU9xcm1mUmJSSG5OWVlwSklrWkN1SFpWbmh4SDlBcTU3SXpjbm0xMmRjRkphbkpVeGhGcTdrdzlrWGpGVWZQSWdzPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNTkyOTE1MDU3CWZpbGU6L1VzZXJzL3J1bm5lci9ydW5uZXJzLzIuMjYzLjAvd29yay90YXVyaS90YXVyaS90YXVyaS9leGFtcGxlcy9jb21tdW5pY2F0aW9uL3NyYy10YXVyaS90YXJnZXQvZGVidWcvYnVuZGxlL29zeC9hcHAuYXBwLnRhci5negp4ZHFlUkJTVnpGUXdDdEhydTE5TGgvRlVPeVhjTnM5RHdmaGx3c0ZPWjZXWnFwVDRNWEFSbUJTZ1ZkU1IwckJGdmlwSzJPd00zZEZFN2hJOFUvL1FDZz09Cg==",
  922. "url": "https://github.com/tauri-apps/updater-test/releases/download/v1.0.0/app.app.tar.gz"
  923. },
  924. "darwin-x86_64": {
  925. "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUldUTE5QWWxkQnlZOVJZVGdpKzJmRWZ0SkRvWS9TdFpqTU9xcm1mUmJSSG5OWVlwSklrWkN1SFpWbmh4SDlBcTU3SXpjbm0xMmRjRkphbkpVeGhGcTdrdzlrWGpGVWZQSWdzPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNTkyOTE1MDU3CWZpbGU6L1VzZXJzL3J1bm5lci9ydW5uZXJzLzIuMjYzLjAvd29yay90YXVyaS90YXVyaS90YXVyaS9leGFtcGxlcy9jb21tdW5pY2F0aW9uL3NyYy10YXVyaS90YXJnZXQvZGVidWcvYnVuZGxlL29zeC9hcHAuYXBwLnRhci5negp4ZHFlUkJTVnpGUXdDdEhydTE5TGgvRlVPeVhjTnM5RHdmaGx3c0ZPWjZXWnFwVDRNWEFSbUJTZ1ZkU1IwckJGdmlwSzJPd00zZEZFN2hJOFUvL1FDZz09Cg==",
  926. "url": "https://github.com/tauri-apps/updater-test/releases/download/v1.0.0/app.app.tar.gz"
  927. },
  928. "linux-x86_64": {
  929. "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUldUTE5QWWxkQnlZOWZSM29hTFNmUEdXMHRoOC81WDFFVVFRaXdWOUdXUUdwT0NlMldqdXkyaWVieXpoUmdZeXBJaXRqSm1YVmczNXdRL1Brc0tHb1NOTzhrL1hadFcxdmdnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNTkyOTE3MzQzCWZpbGU6L2hvbWUvcnVubmVyL3dvcmsvdGF1cmkvdGF1cmkvdGF1cmkvZXhhbXBsZXMvY29tbXVuaWNhdGlvbi9zcmMtdGF1cmkvdGFyZ2V0L2RlYnVnL2J1bmRsZS9hcHBpbWFnZS9hcHAuQXBwSW1hZ2UudGFyLmd6CmRUTUM2bWxnbEtTbUhOZGtERUtaZnpUMG5qbVo5TGhtZWE1SFNWMk5OOENaVEZHcnAvVW0zc1A2ajJEbWZUbU0yalRHT0FYYjJNVTVHOHdTQlYwQkF3PT0K",
  930. "url": "https://github.com/tauri-apps/updater-test/releases/download/v1.0.0/app.AppImage.tar.gz"
  931. },
  932. "windows-x86_64": {
  933. "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUldUTE5QWWxkQnlZOVJHMWlvTzRUSlQzTHJOMm5waWpic0p0VVI2R0hUNGxhQVMxdzBPRndlbGpXQXJJakpTN0toRURtVzBkcm15R0VaNTJuS1lZRWdzMzZsWlNKUVAzZGdJPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNTkyOTE1NTIzCWZpbGU6RDpcYVx0YXVyaVx0YXVyaVx0YXVyaVxleGFtcGxlc1xjb21tdW5pY2F0aW9uXHNyYy10YXVyaVx0YXJnZXRcZGVidWdcYXBwLng2NC5tc2kuemlwCitXa1lQc3A2MCs1KzEwZnVhOGxyZ2dGMlZqbjBaVUplWEltYUdyZ255eUF6eVF1dldWZzFObStaVEQ3QU1RS1lzcjhDVU4wWFovQ1p1QjJXbW1YZUJ3PT0K",
  934. "url": "https://github.com/tauri-apps/updater-test/releases/download/v1.0.0/app.x64.msi.zip"
  935. }
  936. }
  937. }"#.into()
  938. }
  939. fn generate_sample_platform_json(
  940. version: &str,
  941. public_signature: &str,
  942. download_url: &str,
  943. ) -> String {
  944. format!(
  945. r#"
  946. {{
  947. "name": "v{version}",
  948. "notes": "This is the latest version! Once updated you shouldn't see this prompt.",
  949. "pub_date": "2020-06-25T14:14:19Z",
  950. "signature": "{public_signature}",
  951. "url": "{download_url}"
  952. }}
  953. "#
  954. )
  955. }
  956. fn generate_sample_with_elevated_task_platform_json(
  957. version: &str,
  958. public_signature: &str,
  959. download_url: &str,
  960. with_elevated_task: bool,
  961. ) -> String {
  962. format!(
  963. r#"
  964. {{
  965. "name": "v{version}",
  966. "notes": "This is the latest version! Once updated you shouldn't see this prompt.",
  967. "pub_date": "2020-06-25T14:14:19Z",
  968. "signature": "{public_signature}",
  969. "url": "{download_url}",
  970. "with_elevated_task": {with_elevated_task}
  971. }}
  972. "#
  973. )
  974. }
  975. #[test]
  976. fn simple_http_updater() {
  977. let _m = mockito::mock("GET", "/")
  978. .with_status(200)
  979. .with_header("content-type", "application/json")
  980. .with_body(generate_sample_raw_json())
  981. .create();
  982. let app = crate::test::mock_app();
  983. let check_update = block!(builder(app.handle())
  984. .current_version("0.0.0".parse().unwrap())
  985. .url(mockito::server_url())
  986. .build());
  987. let updater = check_update.expect("Can't check update");
  988. assert!(updater.should_update);
  989. }
  990. #[test]
  991. fn simple_http_updater_raw_json() {
  992. let _m = mockito::mock("GET", "/")
  993. .with_status(200)
  994. .with_header("content-type", "application/json")
  995. .with_body(generate_sample_raw_json())
  996. .create();
  997. let app = crate::test::mock_app();
  998. let check_update = block!(builder(app.handle())
  999. .current_version("0.0.0".parse().unwrap())
  1000. .url(mockito::server_url())
  1001. .build());
  1002. let updater = check_update.expect("Can't check update");
  1003. assert!(updater.should_update);
  1004. }
  1005. #[test]
  1006. fn simple_http_updater_raw_json_windows_x86_64() {
  1007. let _m = mockito::mock("GET", "/")
  1008. .with_status(200)
  1009. .with_header("content-type", "application/json")
  1010. .with_body(generate_sample_raw_json())
  1011. .create();
  1012. let app = crate::test::mock_app();
  1013. let check_update = block!(builder(app.handle())
  1014. .current_version("0.0.0".parse().unwrap())
  1015. .target("windows-x86_64")
  1016. .url(mockito::server_url())
  1017. .build());
  1018. let updater = check_update.expect("Can't check update");
  1019. assert!(updater.should_update);
  1020. assert_eq!(updater.version, "2.0.0");
  1021. assert_eq!(updater.signature, "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUldUTE5QWWxkQnlZOVJHMWlvTzRUSlQzTHJOMm5waWpic0p0VVI2R0hUNGxhQVMxdzBPRndlbGpXQXJJakpTN0toRURtVzBkcm15R0VaNTJuS1lZRWdzMzZsWlNKUVAzZGdJPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNTkyOTE1NTIzCWZpbGU6RDpcYVx0YXVyaVx0YXVyaVx0YXVyaVxleGFtcGxlc1xjb21tdW5pY2F0aW9uXHNyYy10YXVyaVx0YXJnZXRcZGVidWdcYXBwLng2NC5tc2kuemlwCitXa1lQc3A2MCs1KzEwZnVhOGxyZ2dGMlZqbjBaVUplWEltYUdyZ255eUF6eVF1dldWZzFObStaVEQ3QU1RS1lzcjhDVU4wWFovQ1p1QjJXbW1YZUJ3PT0K");
  1022. assert_eq!(
  1023. updater.download_url.to_string(),
  1024. "https://github.com/tauri-apps/updater-test/releases/download/v1.0.0/app.x64.msi.zip"
  1025. );
  1026. }
  1027. #[test]
  1028. fn simple_http_updater_raw_json_uptodate() {
  1029. let _m = mockito::mock("GET", "/")
  1030. .with_status(200)
  1031. .with_header("content-type", "application/json")
  1032. .with_body(generate_sample_raw_json())
  1033. .create();
  1034. let app = crate::test::mock_app();
  1035. let check_update = block!(builder(app.handle())
  1036. .current_version("10.0.0".parse().unwrap())
  1037. .url(mockito::server_url())
  1038. .build());
  1039. let updater = check_update.expect("Can't check update");
  1040. assert!(!updater.should_update);
  1041. }
  1042. #[test]
  1043. fn simple_http_updater_without_version() {
  1044. let _m = mockito::mock("GET", "/darwin-aarch64/1.0.0")
  1045. .with_status(200)
  1046. .with_header("content-type", "application/json")
  1047. .with_body(generate_sample_platform_json(
  1048. "2.0.0",
  1049. "SampleTauriKey",
  1050. "https://tauri.app",
  1051. ))
  1052. .create();
  1053. let app = crate::test::mock_app();
  1054. let check_update = block!(builder(app.handle())
  1055. .current_version("1.0.0".parse().unwrap())
  1056. .url(format!(
  1057. "{}/darwin-aarch64/{{{{current_version}}}}",
  1058. mockito::server_url()
  1059. ))
  1060. .build());
  1061. let updater = check_update.expect("Can't check update");
  1062. assert!(updater.should_update);
  1063. }
  1064. #[test]
  1065. fn simple_http_updater_percent_decode() {
  1066. let _m = mockito::mock("GET", "/darwin-aarch64/1.0.0")
  1067. .with_status(200)
  1068. .with_header("content-type", "application/json")
  1069. .with_body(generate_sample_platform_json(
  1070. "2.0.0",
  1071. "SampleTauriKey",
  1072. "https://tauri.app",
  1073. ))
  1074. .create();
  1075. let app = crate::test::mock_app();
  1076. let check_update = block!(builder(app.handle())
  1077. .current_version("1.0.0".parse().unwrap())
  1078. .url(
  1079. url::Url::parse(&format!(
  1080. "{}/darwin-aarch64/{{{{current_version}}}}",
  1081. mockito::server_url()
  1082. ))
  1083. .unwrap()
  1084. .to_string()
  1085. )
  1086. .build());
  1087. let updater = check_update.expect("Can't check update");
  1088. assert!(updater.should_update);
  1089. let app = crate::test::mock_app();
  1090. let check_update = block!(builder(app.handle())
  1091. .current_version("1.0.0".parse().unwrap())
  1092. .urls(&[url::Url::parse(&format!(
  1093. "{}/darwin-aarch64/{{{{current_version}}}}",
  1094. mockito::server_url()
  1095. ))
  1096. .unwrap()
  1097. .to_string()])
  1098. .build());
  1099. let updater = check_update.expect("Can't check update");
  1100. assert!(updater.should_update);
  1101. }
  1102. #[test]
  1103. fn simple_http_updater_with_elevated_task() {
  1104. let _m = mockito::mock("GET", "/windows-x86_64/1.0.0")
  1105. .with_status(200)
  1106. .with_header("content-type", "application/json")
  1107. .with_body(generate_sample_with_elevated_task_platform_json(
  1108. "2.0.0",
  1109. "SampleTauriKey",
  1110. "https://tauri.app",
  1111. true,
  1112. ))
  1113. .create();
  1114. let app = crate::test::mock_app();
  1115. let check_update = block!(builder(app.handle())
  1116. .current_version("1.0.0".parse().unwrap())
  1117. .url(format!(
  1118. "{}/windows-x86_64/{{{{current_version}}}}",
  1119. mockito::server_url()
  1120. ))
  1121. .build());
  1122. let updater = check_update.expect("Can't check update");
  1123. assert!(updater.should_update);
  1124. }
  1125. #[test]
  1126. fn http_updater_uptodate() {
  1127. let _m = mockito::mock("GET", "/darwin-aarch64/10.0.0")
  1128. .with_status(200)
  1129. .with_header("content-type", "application/json")
  1130. .with_body(generate_sample_platform_json(
  1131. "2.0.0",
  1132. "SampleTauriKey",
  1133. "https://tauri.app",
  1134. ))
  1135. .create();
  1136. let app = crate::test::mock_app();
  1137. let check_update = block!(builder(app.handle())
  1138. .current_version("10.0.0".parse().unwrap())
  1139. .url(format!(
  1140. "{}/darwin-aarch64/{{{{current_version}}}}",
  1141. mockito::server_url()
  1142. ))
  1143. .build());
  1144. let updater = check_update.expect("Can't check update");
  1145. assert!(!updater.should_update);
  1146. }
  1147. #[test]
  1148. fn http_updater_fallback_urls() {
  1149. let _m = mockito::mock("GET", "/")
  1150. .with_status(200)
  1151. .with_header("content-type", "application/json")
  1152. .with_body(generate_sample_raw_json())
  1153. .create();
  1154. let app = crate::test::mock_app();
  1155. let check_update = block!(builder(app.handle())
  1156. .url("http://badurl.www.tld/1".into())
  1157. .url(mockito::server_url())
  1158. .current_version("0.0.1".parse().unwrap())
  1159. .build());
  1160. let updater = check_update.expect("Can't check remote update");
  1161. assert!(updater.should_update);
  1162. }
  1163. #[test]
  1164. fn http_updater_fallback_urls_with_array() {
  1165. let _m = mockito::mock("GET", "/")
  1166. .with_status(200)
  1167. .with_header("content-type", "application/json")
  1168. .with_body(generate_sample_raw_json())
  1169. .create();
  1170. let app = crate::test::mock_app();
  1171. let check_update = block!(builder(app.handle())
  1172. .urls(&["http://badurl.www.tld/1".into(), mockito::server_url(),])
  1173. .current_version("0.0.1".parse().unwrap())
  1174. .build());
  1175. let updater = check_update.expect("Can't check remote update");
  1176. assert!(updater.should_update);
  1177. }
  1178. #[test]
  1179. fn http_updater_invalid_remote_data() {
  1180. let invalid_signature = r#"{
  1181. "version": "v0.0.3",
  1182. "notes": "Blablaa",
  1183. "pub_date": "2020-02-20T15:41:00Z",
  1184. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1185. "signature": true
  1186. }"#;
  1187. let invalid_version = r#"{
  1188. "version": 5,
  1189. "notes": "Blablaa",
  1190. "pub_date": "2020-02-20T15:41:00Z",
  1191. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1192. "signature": "x"
  1193. }"#;
  1194. let invalid_name = r#"{
  1195. "name": false,
  1196. "notes": "Blablaa",
  1197. "pub_date": "2020-02-20T15:41:00Z",
  1198. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1199. "signature": "x"
  1200. }"#;
  1201. let invalid_date = r#"{
  1202. "version": "1.0.0",
  1203. "notes": "Blablaa",
  1204. "pub_date": 345645646,
  1205. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1206. "signature": "x"
  1207. }"#;
  1208. let invalid_notes = r#"{
  1209. "version": "v0.0.3",
  1210. "notes": ["bla", "bla"],
  1211. "pub_date": "2020-02-20T15:41:00Z",
  1212. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1213. "signature": "x"
  1214. }"#;
  1215. let invalid_url = r#"{
  1216. "version": "v0.0.3",
  1217. "notes": "Blablaa",
  1218. "pub_date": "2020-02-20T15:41:00Z",
  1219. "url": ["https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz", "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz"],
  1220. "signature": "x"
  1221. }"#;
  1222. let invalid_platform_signature = r#"{
  1223. "version": "v0.0.3",
  1224. "notes": "Blablaa",
  1225. "pub_date": "2020-02-20T15:41:00Z",
  1226. "platforms": {
  1227. "test-target": {
  1228. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1229. "signature": {
  1230. "test-target": "x"
  1231. }
  1232. }
  1233. }
  1234. }"#;
  1235. let invalid_platform_url = r#"{
  1236. "version": "v0.0.3",
  1237. "notes": "Blablaa",
  1238. "pub_date": "2020-02-20T15:41:00Z",
  1239. "platforms": {
  1240. "test-target": {
  1241. "url": {
  1242. "first": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz"
  1243. }
  1244. "signature": "x"
  1245. }
  1246. }
  1247. }"#;
  1248. let test_cases = [
  1249. (
  1250. invalid_signature,
  1251. Box::new(|e| matches!(e, Error::InvalidResponseType("signature", "string", _)))
  1252. as Box<dyn FnOnce(Error) -> bool>,
  1253. ),
  1254. (
  1255. invalid_version,
  1256. Box::new(|e| matches!(e, Error::InvalidResponseType("version", "string", _)))
  1257. as Box<dyn FnOnce(Error) -> bool>,
  1258. ),
  1259. (
  1260. invalid_name,
  1261. Box::new(|e| matches!(e, Error::InvalidResponseType("name", "string", _)))
  1262. as Box<dyn FnOnce(Error) -> bool>,
  1263. ),
  1264. (
  1265. invalid_date,
  1266. Box::new(|e| matches!(e, Error::InvalidResponseType("pub_date", "string", _)))
  1267. as Box<dyn FnOnce(Error) -> bool>,
  1268. ),
  1269. (
  1270. invalid_notes,
  1271. Box::new(|e| matches!(e, Error::InvalidResponseType("notes", "string", _)))
  1272. as Box<dyn FnOnce(Error) -> bool>,
  1273. ),
  1274. (
  1275. invalid_url,
  1276. Box::new(|e| matches!(e, Error::InvalidResponseType("url", "string", _)))
  1277. as Box<dyn FnOnce(Error) -> bool>,
  1278. ),
  1279. (
  1280. invalid_platform_signature,
  1281. Box::new(|e| matches!(e, Error::InvalidResponseType("signature", "string", _)))
  1282. as Box<dyn FnOnce(Error) -> bool>,
  1283. ),
  1284. (
  1285. invalid_platform_url,
  1286. Box::new(|e| matches!(e, Error::InvalidResponseType("url", "string", _)))
  1287. as Box<dyn FnOnce(Error) -> bool>,
  1288. ),
  1289. ];
  1290. for (response, validator) in test_cases {
  1291. let _m = mockito::mock("GET", "/")
  1292. .with_status(200)
  1293. .with_header("content-type", "application/json")
  1294. .with_body(response)
  1295. .create();
  1296. let app = crate::test::mock_app();
  1297. let check_update = block!(builder(app.handle())
  1298. .url(mockito::server_url())
  1299. .current_version("0.0.1".parse().unwrap())
  1300. .target("test-target")
  1301. .build());
  1302. if let Err(e) = check_update {
  1303. validator(e);
  1304. } else {
  1305. panic!("unexpected Ok response");
  1306. }
  1307. }
  1308. }
  1309. #[test]
  1310. fn http_updater_missing_remote_data() {
  1311. let missing_signature = r#"{
  1312. "version": "v0.0.3",
  1313. "notes": "Blablaa",
  1314. "pub_date": "2020-02-20T15:41:00Z",
  1315. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz"
  1316. }"#;
  1317. let missing_version = r#"{
  1318. "notes": "Blablaa",
  1319. "pub_date": "2020-02-20T15:41:00Z",
  1320. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1321. "signature": "x"
  1322. }"#;
  1323. let missing_url = r#"{
  1324. "version": "v0.0.3",
  1325. "notes": "Blablaa",
  1326. "pub_date": "2020-02-20T15:41:00Z",
  1327. "signature": "x"
  1328. }"#;
  1329. let missing_target = r#"{
  1330. "version": "v0.0.3",
  1331. "notes": "Blablaa",
  1332. "pub_date": "2020-02-20T15:41:00Z",
  1333. "platforms": {
  1334. "unknown-target": {
  1335. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz",
  1336. "signature": "x"
  1337. }
  1338. }
  1339. }"#;
  1340. let missing_platform_signature = r#"{
  1341. "version": "v0.0.3",
  1342. "notes": "Blablaa",
  1343. "pub_date": "2020-02-20T15:41:00Z",
  1344. "platforms": {
  1345. "test-target": {
  1346. "url": "https://github.com/tauri-apps/updater-test/releases/download/v0.0.1/update3.tar.gz"
  1347. }
  1348. }
  1349. }"#;
  1350. let missing_platform_url = r#"{
  1351. "version": "v0.0.3",
  1352. "notes": "Blablaa",
  1353. "pub_date": "2020-02-20T15:41:00Z",
  1354. "platforms": {
  1355. "test-target": {
  1356. "signature": "x"
  1357. }
  1358. }
  1359. }"#;
  1360. fn missing_field_error(field: &str) -> String {
  1361. format!("the `{field}` field was not set on the updater response")
  1362. }
  1363. let test_cases = [
  1364. (missing_signature, missing_field_error("signature")),
  1365. (missing_version, "missing field `version`".to_string()),
  1366. (missing_url, missing_field_error("url")),
  1367. (
  1368. missing_target,
  1369. Error::TargetNotFound("test-target".into()).to_string(),
  1370. ),
  1371. (
  1372. missing_platform_signature,
  1373. "missing field `signature`".to_string(),
  1374. ),
  1375. (missing_platform_url, "missing field `url`".to_string()),
  1376. ];
  1377. for (response, error) in test_cases {
  1378. let _m = mockito::mock("GET", "/")
  1379. .with_status(200)
  1380. .with_header("content-type", "application/json")
  1381. .with_body(response)
  1382. .create();
  1383. let app = crate::test::mock_app();
  1384. let check_update = block!(builder(app.handle())
  1385. .url(mockito::server_url())
  1386. .current_version("0.0.1".parse().unwrap())
  1387. .target("test-target")
  1388. .build());
  1389. if let Err(e) = check_update {
  1390. println!("ERROR: {e}, expected: {error}");
  1391. assert!(e.to_string().contains(&error));
  1392. } else {
  1393. panic!("unexpected Ok response");
  1394. }
  1395. }
  1396. }
  1397. // run complete process on mac only for now as we don't have
  1398. // server (api) that we can use to test
  1399. #[test]
  1400. #[cfg(target_os = "macos")]
  1401. fn http_updater_complete_process() {
  1402. #[cfg(target_os = "macos")]
  1403. let archive_file = "archive.macos.tar.gz";
  1404. #[cfg(target_os = "linux")]
  1405. let archive_file = "archive.linux.tar.gz";
  1406. #[cfg(target_os = "windows")]
  1407. let archive_file = "archive.windows.zip";
  1408. let good_archive_url = format!("{}/{archive_file}", mockito::server_url());
  1409. let mut signature_file = File::open(format!(
  1410. "./test/updater/fixture/archives/{archive_file}.sig"
  1411. ))
  1412. .expect("Unable to open signature");
  1413. let mut signature = String::new();
  1414. signature_file
  1415. .read_to_string(&mut signature)
  1416. .expect("Unable to read signature as string");
  1417. let mut pubkey_file = File::open("./test/updater/fixture/good_signature/update.key.pub")
  1418. .expect("Unable to open pubkey");
  1419. let mut pubkey = String::new();
  1420. pubkey_file
  1421. .read_to_string(&mut pubkey)
  1422. .expect("Unable to read signature as string");
  1423. // add sample file
  1424. let _m = mockito::mock("GET", format!("/{archive_file}").as_str())
  1425. .with_status(200)
  1426. .with_header("content-type", "application/octet-stream")
  1427. .with_body_from_file(format!("./test/updater/fixture/archives/{archive_file}"))
  1428. .create();
  1429. // sample mock for update file
  1430. let _m = mockito::mock("GET", "/")
  1431. .with_status(200)
  1432. .with_header("content-type", "application/json")
  1433. .with_body(generate_sample_platform_json(
  1434. "2.0.1",
  1435. signature.as_ref(),
  1436. good_archive_url.as_ref(),
  1437. ))
  1438. .create();
  1439. // Build a tmpdir so we can test our extraction inside
  1440. // We dont want to overwrite our current executable or the directory
  1441. // Otherwise tests are failing...
  1442. let executable_path = current_exe().expect("Can't extract executable path");
  1443. let parent_path = executable_path
  1444. .parent()
  1445. .expect("Can't find the parent path");
  1446. let tmp_dir = tempfile::Builder::new()
  1447. .prefix("tauri_updater_test")
  1448. .tempdir_in(parent_path);
  1449. assert!(tmp_dir.is_ok());
  1450. let tmp_dir_unwrap = tmp_dir.expect("Can't find tmp_dir");
  1451. let tmp_dir_path = tmp_dir_unwrap.path();
  1452. #[cfg(target_os = "linux")]
  1453. let my_executable = &tmp_dir_path.join("updater-example_0.1.0_amd64.AppImage");
  1454. #[cfg(target_os = "macos")]
  1455. let my_executable = &tmp_dir_path.join("my_app");
  1456. #[cfg(target_os = "windows")]
  1457. let my_executable = &tmp_dir_path.join("my_app.exe");
  1458. // configure the updater
  1459. let app = crate::test::mock_app();
  1460. let check_update = block!(builder(app.handle())
  1461. .url(mockito::server_url())
  1462. // It should represent the executable path, that's why we add my_app.exe in our
  1463. // test path -- in production you shouldn't have to provide it
  1464. .executable_path(my_executable)
  1465. // make sure we force an update
  1466. .current_version("1.0.0".parse().unwrap())
  1467. .build());
  1468. #[cfg(target_os = "linux")]
  1469. {
  1470. env::set_var("APPIMAGE", my_executable);
  1471. }
  1472. // unwrap our results
  1473. let updater = check_update.expect("Can't check remote update");
  1474. // make sure we need to update
  1475. assert!(updater.should_update);
  1476. // make sure we can read announced version
  1477. assert_eq!(updater.version, "2.0.1");
  1478. // download, install and validate signature
  1479. let install_process = block!(updater.download_and_install(pubkey, |_, _| (), || ()));
  1480. assert!(install_process.is_ok());
  1481. // make sure the extraction went well (it should have skipped the main app.app folder)
  1482. // as we can't extract in /Applications directly
  1483. #[cfg(target_os = "macos")]
  1484. let bin_file = tmp_dir_path.join("Contents").join("MacOS").join("app");
  1485. #[cfg(target_os = "linux")]
  1486. // linux should extract at same place as the executable path
  1487. let bin_file = my_executable;
  1488. #[cfg(target_os = "windows")]
  1489. let bin_file = tmp_dir_path.join("with").join("long").join("path.json");
  1490. assert!(bin_file.exists());
  1491. }
  1492. }