Skip to main content

hypersig_desktop/
updates.rs

1//! New versions of the application, found, downloaded, and installed with
2//! `cargo-packager-updater`, under the `updater` feature.
3//!
4//! The endpoint answers in the format `cargo-packager` documents: `204 No
5//! Content` when there is no newer version, or JSON naming the version, its
6//! notes, and, for the system and architecture the endpoint's `{{target}}`
7//! and `{{arch}}` stand for, the URL of the package and its minisign
8//! signature. A package whose signature the public key does not verify is
9//! refused before anything is installed.
10//!
11//! On Linux, `cargo-packager-updater` sets `SSL_CERT_FILE` and
12//! `SSL_CERT_DIR` with `std::env::set_var` when they are unset, the first
13//! time it checks, while other threads of the application may read the
14//! environment. Setting both before [`App::run`](crate::App::run) avoids it.
15
16use cargo_packager_updater::semver::Version;
17use cargo_packager_updater::url::Url;
18use cargo_packager_updater::{Config, UpdaterBuilder};
19
20use std::sync::{Mutex, PoisonError};
21
22use tao::event_loop::EventLoopProxy;
23
24use crate::error::Error;
25use crate::run::Event;
26
27/// Where an application finds its new versions, and the key that signs them.
28///
29/// [`App::updates`](crate::App::updates) takes it, and
30/// [`App::run`](crate::App::run) then hands the setup an [`Updater`].
31#[derive(Debug, Clone, Copy)]
32pub struct Updates {
33    version: &'static str,
34    endpoint: &'static str,
35    public_key: &'static str,
36}
37
38impl Updates {
39    /// The versions after `version` that `endpoint` announces, signed by `public_key`.
40    ///
41    /// `version` is the running one, `env!("CARGO_PKG_VERSION")` in the
42    /// application's crate. `endpoint` may hold `{{target}}`, `{{arch}}`,
43    /// and `{{current_version}}`. `public_key` is the one `cargo packager
44    /// signer generate` writes.
45    ///
46    /// # Panics
47    ///
48    /// Panics when `version` is not a semantic version, when `endpoint` is
49    /// not `https://` followed by a host, or `http://` to `127.0.0.1` or
50    /// `localhost` for a test on this machine, and when `public_key` is not
51    /// a minisign public key in base64. In a `const`, each is a compile
52    /// error.
53    ///
54    /// ```compile_fail,E0080
55    /// # use hypersig_desktop::Updates;
56    /// const UPDATES: Updates = Updates::new("1.0", "https://updates.example.com", "");
57    /// ```
58    #[must_use]
59    pub const fn new(
60        version: &'static str,
61        endpoint: &'static str,
62        public_key: &'static str,
63    ) -> Self {
64        assert!(
65            is_version(version.as_bytes()),
66            "`version` is a semantic version such as `1.2.3`"
67        );
68        assert!(
69            is_endpoint(endpoint.as_bytes()),
70            "`endpoint` is `https://` and a host, or `http://` to `127.0.0.1` or `localhost`"
71        );
72        assert!(
73            is_public_key(public_key.as_bytes()),
74            "`public_key` is a minisign public key, in base64, as `cargo packager signer generate` writes it"
75        );
76        Self {
77            version,
78            endpoint,
79            public_key,
80        }
81    }
82
83    /// The newer version the endpoint announces, or `None`.
84    ///
85    /// # Errors
86    ///
87    /// Fails when the endpoint does not parse as a URL, and when it cannot
88    /// be reached or answers with something else.
89    pub(crate) async fn check(self) -> Result<Option<Update>, Error> {
90        let version = Version::parse(self.version).map_err(Error::update)?;
91        let endpoint = Url::parse(self.endpoint).map_err(Error::update)?;
92        let config = Config {
93            endpoints: vec![endpoint],
94            pubkey: self.public_key.to_owned(),
95            windows: None,
96        };
97        tokio::task::spawn_blocking(move || {
98            let updater = UpdaterBuilder::new(version, config).build()?;
99            updater.check()
100        })
101        .await
102        .map_err(Error::update)?
103        .map(|update| update.map(|inner| Update { inner }))
104        .map_err(Error::update)
105    }
106}
107
108/// What finds the application's new versions, from the setup of
109/// [`App::run`](crate::App::run).
110///
111/// The setup puts it in the router's state beside the [`Os`](crate::Os),
112/// so a handler reaches it as `state.updater`. A test gives the handlers
113/// `testing::FakeOs::updater` instead, which finds no newer version.
114#[derive(Debug, Clone, Copy)]
115pub struct Updater {
116    source: Source,
117}
118
119#[derive(Debug, Clone, Copy)]
120enum Source {
121    System(Updates),
122    #[cfg(feature = "testing")]
123    Fake,
124}
125
126impl Updater {
127    pub(crate) const fn system(updates: Updates) -> Self {
128        Self {
129            source: Source::System(updates),
130        }
131    }
132
133    #[cfg(feature = "testing")]
134    pub(crate) const fn fake() -> Self {
135        Self {
136            source: Source::Fake,
137        }
138    }
139
140    /// The newer version the update endpoint announces, or `None`.
141    ///
142    /// The endpoint is the one [`Updates`] names, and the [`Update`] this
143    /// returns downloads and installs the version. A fake updater finds
144    /// none.
145    ///
146    /// # Errors
147    ///
148    /// Fails when the endpoint does not parse as a URL, and when it cannot
149    /// be reached or answers with something else.
150    pub async fn check(&self) -> Result<Option<Update>, Error> {
151        match self.source {
152            Source::System(updates) => updates.check().await,
153            #[cfg(feature = "testing")]
154            Source::Fake => Ok(None),
155        }
156    }
157}
158
159/// A newer version, from [`Updater::check`].
160pub struct Update {
161    inner: cargo_packager_updater::Update,
162}
163
164impl std::fmt::Debug for Update {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.debug_struct("Update")
167            .field("version", &self.inner.version)
168            .finish_non_exhaustive()
169    }
170}
171
172impl Update {
173    /// The version the endpoint announced, written as a semantic version
174    /// such as `1.1.0`.
175    #[must_use]
176    pub fn version(&self) -> &str {
177        &self.inner.version
178    }
179
180    /// The release notes, when the endpoint sent some.
181    #[must_use]
182    pub fn notes(&self) -> Option<&str> {
183        self.inner.body.as_deref()
184    }
185
186    /// Downloads the package and checks its signature.
187    ///
188    /// # Errors
189    ///
190    /// Fails when the package cannot be downloaded, and when the public key
191    /// does not verify its signature.
192    pub async fn download(self) -> Result<Downloaded, Error> {
193        tokio::task::spawn_blocking(move || {
194            let bytes = self.inner.download()?;
195            Ok::<_, cargo_packager_updater::Error>(Downloaded {
196                update: self.inner,
197                bytes,
198            })
199        })
200        .await
201        .map_err(Error::update)?
202        .map_err(Error::update)
203    }
204}
205
206/// A package [`Update::download`] downloaded and verified.
207pub struct Downloaded {
208    update: cargo_packager_updater::Update,
209    bytes: Vec<u8>,
210}
211
212impl std::fmt::Debug for Downloaded {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        f.debug_struct("Downloaded")
215            .field("version", &self.update.version)
216            .field("bytes", &self.bytes.len())
217            .finish_non_exhaustive()
218    }
219}
220
221impl Downloaded {
222    /// Installs the package over the running application.
223    ///
224    /// The new version runs once the application starts again. On macOS
225    /// the `.app` bundle and on Linux the `AppImage` are replaced, and the
226    /// application keeps running.
227    ///
228    /// On Windows the installer replaces the running program, and
229    /// cargo-packager-updater 0.2.3 ends the process with
230    /// `std::process::exit(0)` once it has started it. So the application
231    /// closes first, as Quit closes it: this returns `Ok(())` at once, the
232    /// windows close, the server is given its time to finish the requests
233    /// it is answering, and the installer starts after that, as the last
234    /// thing [`App::run`](crate::App::run) does. When the installer cannot
235    /// start, `App::run` returns the error.
236    ///
237    /// # Errors
238    ///
239    /// Fails when the package cannot be installed, and on Windows when no
240    /// application is running or its event loop has ended.
241    pub async fn install(self) -> Result<(), Error> {
242        if cfg!(target_os = "windows") {
243            return install_on_exit(self);
244        }
245        tokio::task::spawn_blocking(move || self.install_now())
246            .await
247            .map_err(Error::update)?
248    }
249
250    /// Installs the package on this thread, which on Windows starts the
251    /// installer and ends the process.
252    pub(crate) fn install_now(self) -> Result<(), Error> {
253        self.update.install(self.bytes).map_err(Error::update)
254    }
255}
256
257/// The event loop of the [`App::run`](crate::App::run) running, which
258/// installs a package on Windows once the server has stopped. A process
259/// runs one application, so one place holds it.
260static EVENT_LOOP: Mutex<Option<EventLoopProxy<Event>>> = Mutex::new(None);
261
262/// Hands `proxy` to [`Downloaded::install`] for the run, or takes it back
263/// with `None` once the run is over.
264pub(crate) fn event_loop(proxy: Option<EventLoopProxy<Event>>) {
265    *EVENT_LOOP.lock().unwrap_or_else(PoisonError::into_inner) = proxy;
266}
267
268/// Has the event loop close the application, as Quit does, and install
269/// `downloaded` once the server has stopped.
270fn install_on_exit(downloaded: Downloaded) -> Result<(), Error> {
271    let proxy = EVENT_LOOP
272        .lock()
273        .unwrap_or_else(PoisonError::into_inner)
274        .clone()
275        .ok_or_else(Error::closed)?;
276    proxy
277        .send_event(Event::Install(Box::new(downloaded)))
278        .map_err(|_closed| Error::closed())
279}
280
281/// Whether `text` is `MAJOR.MINOR.PATCH`, each a number without a leading
282/// zero, then optionally `-` and a pre-release and `+` and build metadata,
283/// each dot-separated identifiers of ASCII letters, digits, and `-`.
284const fn is_version(text: &[u8]) -> bool {
285    let mut at = 0;
286    let mut part = 0;
287    while part < 3 {
288        let start = at;
289        while at < text.len() && text[at].is_ascii_digit() {
290            at += 1;
291        }
292        if at == start || (text[start] == b'0' && at - start > 1) {
293            return false;
294        }
295        part += 1;
296        if part < 3 {
297            if at == text.len() || text[at] != b'.' {
298                return false;
299            }
300            at += 1;
301        }
302    }
303    if at < text.len() && text[at] == b'-' {
304        at = identifiers(text, at + 1, true);
305        if at == 0 {
306            return false;
307        }
308    }
309    if at < text.len() && text[at] == b'+' {
310        at = identifiers(text, at + 1, false);
311        if at == 0 {
312            return false;
313        }
314    }
315    at == text.len()
316}
317
318/// Where the dot-separated identifiers that start at `at` end, or 0 when
319/// one is empty or holds a byte other than an ASCII letter, digit, or `-`.
320/// In a pre-release, a numeric identifier has no leading zero.
321const fn identifiers(text: &[u8], mut at: usize, pre_release: bool) -> usize {
322    loop {
323        let start = at;
324        let mut numeric = true;
325        while at < text.len() && (text[at].is_ascii_alphanumeric() || text[at] == b'-') {
326            numeric = numeric && text[at].is_ascii_digit();
327            at += 1;
328        }
329        if at == start || (pre_release && numeric && text[start] == b'0' && at - start > 1) {
330            return 0;
331        }
332        if at == text.len() || text[at] != b'.' {
333            return at;
334        }
335        at += 1;
336    }
337}
338
339/// Whether `text` is `https://` and a host, or `http://` to `127.0.0.1` or
340/// `localhost`, each followed by the end, `:`, or `/`.
341const fn is_endpoint(text: &[u8]) -> bool {
342    if let Some(host) = after(text, b"https://") {
343        return !host.is_empty() && host[0] != b'/' && host[0] != b':';
344    }
345    let Some(host) = after(text, b"http://") else {
346        return false;
347    };
348    let rest = match after(host, b"127.0.0.1") {
349        Some(rest) => rest,
350        None => match after(host, b"localhost") {
351            Some(rest) => rest,
352            None => return false,
353        },
354    };
355    rest.is_empty() || rest[0] == b':' || rest[0] == b'/'
356}
357
358/// `text` after `prefix`, when it starts with it.
359const fn after<'a>(text: &'a [u8], prefix: &[u8]) -> Option<&'a [u8]> {
360    if text.len() < prefix.len() {
361        return None;
362    }
363    let mut at = 0;
364    while at < prefix.len() {
365        if text[at] != prefix[at] {
366            return None;
367        }
368        at += 1;
369    }
370    Some(text.split_at(prefix.len()).1)
371}
372
373/// Whether `text` is standard base64 of a minisign public key file: an
374/// `untrusted comment:` line, then the key, which is `RW` and 54 more
375/// base64 characters, and at most a newline after it.
376const fn is_public_key(text: &[u8]) -> bool {
377    if text.is_empty() || !text.len().is_multiple_of(4) {
378        return false;
379    }
380    let mut at = 0;
381    while at < text.len() {
382        let padding = text.len() - at <= 2 && text[at] == b'=';
383        if sextet(text[at]) == NOT_BASE64 && !padding {
384            return false;
385        }
386        if text[at] == b'=' && !(padding && (at + 1 == text.len() || text[at + 1] == b'=')) {
387            return false;
388        }
389        at += 1;
390    }
391    let padded = if text[text.len() - 1] != b'=' {
392        0
393    } else if text[text.len() - 2] == b'=' {
394        2
395    } else {
396        1
397    };
398    let decoded = text.len() / 4 * 3 - padded;
399    let comment = b"untrusted comment:";
400    let mut index = 0;
401    while index < comment.len() {
402        if index >= decoded || decoded_byte(text, index) != comment[index] {
403            return false;
404        }
405        index += 1;
406    }
407    while index < decoded && decoded_byte(text, index) != b'\n' {
408        index += 1;
409    }
410    let key = index + 1;
411    let mut end = decoded;
412    if end > key && decoded_byte(text, end - 1) == b'\n' {
413        end -= 1;
414    }
415    if end < key || end - key != 56 {
416        return false;
417    }
418    if decoded_byte(text, key) != b'R' || decoded_byte(text, key + 1) != b'W' {
419        return false;
420    }
421    let mut index = key;
422    while index < end {
423        let byte = decoded_byte(text, index);
424        if sextet(byte) == NOT_BASE64 && byte != b'=' {
425            return false;
426        }
427        index += 1;
428    }
429    true
430}
431
432const NOT_BASE64: u8 = 64;
433
434/// The value of a standard base64 character, or `NOT_BASE64`.
435const fn sextet(byte: u8) -> u8 {
436    match byte {
437        b'A'..=b'Z' => byte - b'A',
438        b'a'..=b'z' => byte - b'a' + 26,
439        b'0'..=b'9' => byte - b'0' + 52,
440        b'+' => 62,
441        b'/' => 63,
442        _ => NOT_BASE64,
443    }
444}
445
446/// The byte at `index` of what the valid base64 `text` decodes to.
447const fn decoded_byte(text: &[u8], index: usize) -> u8 {
448    let group = index / 3 * 4;
449    let [a, b, c, d] = [
450        bits(text[group]),
451        bits(text[group + 1]),
452        bits(text[group + 2]),
453        bits(text[group + 3]),
454    ];
455    match index % 3 {
456        0 => a << 2 | b >> 4,
457        1 => (b & 0b1111) << 4 | c >> 2,
458        _ => (c & 0b11) << 6 | d,
459    }
460}
461
462/// The six bits of a base64 character, with padding as zero bits, which no
463/// decoded byte uses.
464const fn bits(byte: u8) -> u8 {
465    match sextet(byte) {
466        NOT_BASE64 => 0,
467        value => value,
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use std::io::Cursor;
474
475    use axum::Router;
476    use axum::extract::Path;
477    use axum::http::StatusCode;
478    use axum::response::{IntoResponse, Response};
479    use axum::routing::get;
480    use base64::Engine as _;
481    use base64::engine::general_purpose::STANDARD;
482    use tokio::net::TcpListener;
483
484    use super::{Updates, is_endpoint, is_public_key, is_version};
485    use crate::ErrorKind;
486
487    /// A public key, as `cargo packager signer generate` writes it, and the
488    /// signature of `signed` under its secret key.
489    fn sign(signed: &[u8]) -> (String, String) {
490        let keys = minisign::KeyPair::generate_unencrypted_keypair().unwrap();
491        let public = STANDARD.encode(keys.pk.to_box().unwrap().to_string());
492        let signature =
493            minisign::sign(Some(&keys.pk), &keys.sk, Cursor::new(signed), None, None).unwrap();
494        (public, STANDARD.encode(signature.to_string()))
495    }
496
497    /// Serves version 1.1.0 to a version before it, as the package
498    /// `served`, whose signature is `signature`, and returns the endpoint.
499    async fn endpoint(served: &'static [u8], signature: String) -> &'static str {
500        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
501        let base = format!("http://{}", listener.local_addr().unwrap());
502        let package = format!("{base}/package.tar.gz");
503        let app = Router::new()
504            .route(
505                "/updates/{current}",
506                get(move |Path(current): Path<String>| async move {
507                    if current == "1.1.0" {
508                        return StatusCode::NO_CONTENT.into_response();
509                    }
510                    let release = format!(
511                        r#"{{"version":"1.1.0","notes":"Faster saves.","url":"{package}","signature":"{signature}","format":"app"}}"#
512                    );
513                    ([("content-type", "application/json")], release).into_response()
514                }),
515            )
516            .route("/package.tar.gz", get(move || async move { Response::new(axum::body::Body::from(served)) }));
517        tokio::spawn(async move { axum::serve(listener, app).await });
518        Box::leak(format!("{base}/updates/{{{{current_version}}}}").into_boxed_str())
519    }
520
521    fn leak(text: String) -> &'static str {
522        Box::leak(text.into_boxed_str())
523    }
524
525    #[tokio::test(flavor = "multi_thread")]
526    async fn a_newer_version_is_found_and_its_signature_checked() {
527        let package: &'static [u8] = b"the new version";
528        let (public, signature) = sign(package);
529        let endpoint = endpoint(package, signature).await;
530
531        let update = Updates::new("1.0.0", endpoint, leak(public))
532            .check()
533            .await
534            .unwrap()
535            .expect("1.1.0 is newer than 1.0.0");
536        assert_eq!(update.version(), "1.1.0");
537        assert_eq!(update.notes(), Some("Faster saves."));
538        update.download().await.unwrap();
539    }
540
541    #[tokio::test(flavor = "multi_thread")]
542    async fn a_package_its_signature_does_not_match_is_refused() {
543        let (public, signature) = sign(b"the new version");
544        let endpoint = endpoint(b"something else", signature).await;
545
546        let update = Updates::new("1.0.0", endpoint, leak(public))
547            .check()
548            .await
549            .unwrap()
550            .unwrap();
551        let error = update.download().await.unwrap_err();
552        assert_eq!(error.kind(), ErrorKind::Update);
553    }
554
555    #[tokio::test(flavor = "multi_thread")]
556    async fn the_newest_version_finds_none() {
557        let (public, signature) = sign(b"the new version");
558        let endpoint = endpoint(b"the new version", signature).await;
559
560        let update = Updates::new("1.1.0", endpoint, leak(public))
561            .check()
562            .await
563            .unwrap();
564        assert!(update.is_none());
565    }
566
567    #[test]
568    fn a_version_is_semantic() {
569        for version in [
570            "1.0.0",
571            "0.15.2",
572            "1.0.0-rc.1",
573            "1.0.0-alpha-2+build.7",
574            "1.0.0+20261111",
575        ] {
576            assert!(is_version(version.as_bytes()), "{version}");
577        }
578        for version in [
579            "",
580            "1.0",
581            "v1.0.0",
582            "01.0.0",
583            "1.0.0-",
584            "1.0.0-01",
585            "1.0.0-a..b",
586            "1.0.0 ",
587            "1.0.0+",
588        ] {
589            assert!(!is_version(version.as_bytes()), "{version}");
590        }
591    }
592
593    #[test]
594    fn an_endpoint_elsewhere_is_https() {
595        for endpoint in [
596            "https://updates.example.com/{{target}}",
597            "http://127.0.0.1:4000/updates",
598            "http://localhost/updates",
599        ] {
600            assert!(is_endpoint(endpoint.as_bytes()), "{endpoint}");
601        }
602        for endpoint in [
603            "http://updates.example/{{target}}",
604            "ftp://127.0.0.1/",
605            "http://127.0.0.1.example.com/",
606            "http://localhost.example.com/",
607            "https://",
608            "https:///path",
609            "updates.example.com",
610        ] {
611            assert!(!is_endpoint(endpoint.as_bytes()), "{endpoint}");
612        }
613    }
614
615    #[test]
616    fn a_public_key_is_one_minisign_writes() {
617        let (public, _) = sign(b"anything");
618        assert!(is_public_key(public.as_bytes()));
619        let comment_only = STANDARD.encode("untrusted comment: minisign public key\n");
620        let short = STANDARD.encode("untrusted comment: minisign public key\nRWQ=\n");
621        for key in [
622            "",
623            "key",
624            "not base64!",
625            &comment_only,
626            &short,
627            &public[1..],
628        ] {
629            assert!(!is_public_key(key.as_bytes()), "{key}");
630        }
631    }
632}