1use 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#[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 #[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 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#[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 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
159pub 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 #[must_use]
176 pub fn version(&self) -> &str {
177 &self.inner.version
178 }
179
180 #[must_use]
182 pub fn notes(&self) -> Option<&str> {
183 self.inner.body.as_deref()
184 }
185
186 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
206pub 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 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 pub(crate) fn install_now(self) -> Result<(), Error> {
253 self.update.install(self.bytes).map_err(Error::update)
254 }
255}
256
257static EVENT_LOOP: Mutex<Option<EventLoopProxy<Event>>> = Mutex::new(None);
261
262pub(crate) fn event_loop(proxy: Option<EventLoopProxy<Event>>) {
265 *EVENT_LOOP.lock().unwrap_or_else(PoisonError::into_inner) = proxy;
266}
267
268fn 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
281const 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
318const 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
339const 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
358const 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
373const 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
434const 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
446const 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
462const 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 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 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}