1use std::{
31 path::{Path, PathBuf},
32 sync::{
33 Arc, Mutex,
34 atomic::{AtomicBool, Ordering},
35 },
36};
37
38use nsh_package::{PackageReceipt, PublicKey, TrustStore};
39
40use crate::{AppError, Bundle, LoadedPackage, Trial};
41
42pub const DIR: &str = "updates";
44pub const NEXT: &str = "next.nshpkg";
46pub const CURRENT: &str = "current.nshpkg";
48pub const TRYING: &str = "trying.nshpkg";
50const TRUST: &str = "trust";
51const PACKAGES: &str = "packages";
52
53pub fn updates_dir(data_dir: &Path, app_id: &str) -> PathBuf {
57 data_dir.join(crate::app_dir_name(Some(app_id))).join(DIR)
58}
59
60#[derive(Debug, Default)]
62#[non_exhaustive]
63pub struct Launch {
64 pub bundle: Bundle,
66 pub assets: PathBuf,
69 pub package: Option<nsh_package::App>,
71}
72
73pub fn launch(shipped: Bundle, resources: &Path, data_dir: Option<&Path>) -> Launch {
80 let assets = resources.join("assets");
81 let config = std::fs::read(assets.join(nsh_updater::CONFIG_ASSET)).ok();
82 let mut shipped = shipped;
83 match package_to_run(&mut shipped, config, data_dir) {
84 Some(run) => Launch {
85 bundle: run.bundle,
86 assets: run.assets,
87 package: Some(run.app),
88 },
89 None => Launch {
90 bundle: shipped,
91 assets,
92 package: None,
93 },
94 }
95}
96
97#[derive(Debug)]
99#[non_exhaustive]
100pub struct PackageRun {
101 pub bundle: Bundle,
103 pub assets: PathBuf,
105 pub app: nsh_package::App,
107}
108
109pub fn package_to_run(
114 shipped: &mut Bundle,
115 config: Option<Vec<u8>>,
116 data_dir: Option<&Path>,
117) -> Option<PackageRun> {
118 shipped.updater_config = config.map(Arc::from);
120 let update = Shipped::read(
121 shipped.updater_config.as_deref()?,
122 shipped.app_id.as_deref(),
123 )?;
124 let dir = updates_dir(data_dir?, &update.app_id);
125 let chosen = choose(&dir, &update)?;
126 let app = chosen.loaded.app.clone();
127 log::info!(
128 "running package {} {} (build {}), shipped build {}",
129 app.id,
130 app.version,
131 app.build,
132 update.build
133 );
134 Some(PackageRun {
135 assets: chosen.loaded.assets.clone(),
136 bundle: as_shipped(chosen.loaded.bundle, shipped, chosen.trial),
137 app,
138 })
139}
140
141fn as_shipped(mut bundle: Bundle, shipped: &Bundle, trial: Option<Arc<dyn Trial>>) -> Bundle {
145 bundle.url_schemes = shipped.url_schemes.clone();
146 bundle.system_paths = shipped.system_paths.clone();
147 bundle.main_window = shipped.main_window.clone();
148 bundle.updater_config = shipped.updater_config.clone();
149 bundle.policy.granted = match (&shipped.policy.granted, &shipped.policy.declared) {
152 (Some(granted), _) => Some(granted.clone()),
153 (None, declared) => declared.clone(),
154 };
155 bundle.trial = trial;
156 bundle
157}
158
159#[derive(Debug, Clone)]
161struct Shipped {
162 app_id: String,
163 build: u64,
164 roots: Vec<PublicKey>,
165}
166
167impl Shipped {
168 fn read(config: &[u8], app_id: Option<&str>) -> Option<Shipped> {
171 let config = match nsh_updater::Config::parse(config) {
172 Ok(config) => config,
173 Err(err) => {
174 log::warn!("{}: {err}", nsh_updater::CONFIG_ASSET);
175 return None;
176 }
177 };
178 if config.package_roots().is_empty() {
179 return None;
180 }
181 if app_id.is_some_and(|id| id != config.id) {
182 log::warn!(
183 "{} is for {}, the app is {app_id:?}: no packages",
184 nsh_updater::CONFIG_ASSET,
185 config.id
186 );
187 return None;
188 }
189 let roots = config
190 .package_roots()
191 .iter()
192 .filter_map(|root| PublicKey::from_base64(root).ok())
193 .collect();
194 Some(Shipped {
195 app_id: config.id,
196 build: config.build.unwrap_or(1),
197 roots,
198 })
199 }
200
201 fn trust(&self, dir: &Path) -> Result<TrustStore, String> {
202 let mut trust = TrustStore::open(dir.join(TRUST)).map_err(|e| e.to_string())?;
203 for root in &self.roots {
204 trust.add_root(*root);
205 }
206 Ok(trust)
207 }
208}
209
210struct Chosen {
212 loaded: LoadedPackage,
213 trial: Option<Arc<dyn Trial>>,
214}
215
216fn choose(dir: &Path, shipped: &Shipped) -> Option<Chosen> {
218 let (next, trying, current) = (dir.join(NEXT), dir.join(TRYING), dir.join(CURRENT));
219 if !next.exists() && !trying.exists() && !current.exists() {
220 return None;
221 }
222 let trust = match shipped.trust(dir) {
223 Ok(trust) => trust,
224 Err(err) => {
225 log::error!("updates: cannot open the trust store: {err}");
226 return None;
227 }
228 };
229 let packages = dir.join(PACKAGES);
230 if trying.exists() {
231 log::warn!(
232 "updates: the package started last never ran {}s without a fatal error; it is \
233 deleted and the app goes back",
234 crate::TRIAL_PERIOD.as_secs()
235 );
236 remove(&trying);
237 }
238 let mut chosen = None;
239 if next.exists() {
240 match open(&trust, &next, &packages, shipped) {
241 Ok(loaded) => match std::fs::rename(&next, &trying) {
242 Ok(()) => {
243 let trial = PackageTrial {
244 dir: dir.to_owned(),
245 shipped: shipped.clone(),
246 receipt: loaded.receipt.clone(),
247 done: AtomicBool::new(false),
248 lock: Mutex::new(()),
249 };
250 chosen = Some(Chosen {
251 loaded,
252 trial: Some(Arc::new(trial)),
253 });
254 }
255 Err(err) => log::error!("updates: cannot start the package's trial: {err}"),
256 },
257 Err(err) => {
258 log::warn!("updates: downloaded package refused: {err}");
259 remove(&next);
260 }
261 }
262 }
263 if chosen.is_none() && current.exists() {
264 match open(&trust, ¤t, &packages, shipped) {
265 Ok(loaded) => {
266 chosen = Some(Chosen {
267 loaded,
268 trial: None,
269 })
270 }
271 Err(err) => {
272 log::warn!("updates: the installed package does not run: {err}");
273 remove(¤t);
274 }
275 }
276 }
277 let keep = chosen.as_ref().map(|c| c.loaded.receipt.sha256.clone());
279 if let Ok(entries) = std::fs::read_dir(packages.join(&shipped.app_id)) {
280 for entry in entries.flatten() {
281 if keep.as_deref() != entry.file_name().to_str() {
282 let _ = std::fs::remove_dir_all(entry.path());
283 }
284 }
285 }
286 chosen
287}
288
289fn open(
293 trust: &TrustStore,
294 path: &Path,
295 packages: &Path,
296 shipped: &Shipped,
297) -> Result<LoadedPackage, String> {
298 let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
299 let package = trust
301 .verify(&bytes, crate::BYTECODE_VERSION)
302 .map_err(|e| e.to_string())?;
303 check_app(&package.app, shipped)?;
304 drop(package);
305 crate::verify_package(trust, &bytes, packages)
306}
307
308fn check_app(app: &nsh_package::App, shipped: &Shipped) -> Result<(), String> {
309 if app.id != shipped.app_id {
310 return Err(format!("it is {}, the app is {}", app.id, shipped.app_id));
311 }
312 if app.build <= shipped.build {
313 return Err(format!(
314 "its build {} is not newer than the app's {}",
315 app.build, shipped.build
316 ));
317 }
318 Ok(())
319}
320
321fn remove(path: &Path) {
322 if let Err(err) = std::fs::remove_file(path)
323 && err.kind() != std::io::ErrorKind::NotFound
324 {
325 log::error!("updates: cannot remove {}: {err}", path.display());
326 }
327}
328
329pub fn verify_download(
335 file: &Path,
336 dir: &Path,
337 app_id: &str,
338 roots: &[String],
339 newer_than: u64,
340) -> Result<nsh_package::App, String> {
341 let roots = roots
342 .iter()
343 .map(|root| PublicKey::from_base64(root).map_err(|e| format!("package root: {e}")))
344 .collect::<Result<Vec<_>, _>>()?;
345 if roots.is_empty() {
346 return Err("the app trusts no package roots".into());
347 }
348 let shipped = Shipped {
349 app_id: app_id.to_owned(),
350 build: newer_than,
351 roots,
352 };
353 let trust = shipped.trust(dir)?;
354 let bytes = std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?;
355 let package = trust
356 .verify(&bytes, crate::BYTECODE_VERSION)
357 .map_err(|e| e.to_string())?;
358 check_app(&package.app, &shipped)?;
359 Ok(package.app)
360}
361
362#[derive(Debug)]
365struct PackageTrial {
366 dir: PathBuf,
367 shipped: Shipped,
368 receipt: PackageReceipt,
369 done: AtomicBool,
371 lock: Mutex<()>,
372}
373
374impl PackageTrial {
375 fn decide(&self) -> Option<std::sync::MutexGuard<'_, ()>> {
376 let guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
377 (!self.done.swap(true, Ordering::SeqCst)).then_some(guard)
378 }
379
380 fn accept(&self) -> Result<(), String> {
381 let mut trust = self.shipped.trust(&self.dir)?;
382 trust
383 .accept_receipt(&self.receipt)
384 .map_err(|e| e.to_string())?;
385 std::fs::rename(self.dir.join(TRYING), self.dir.join(CURRENT)).map_err(|e| e.to_string())
386 }
387}
388
389impl Trial for PackageTrial {
390 fn healthy(&self) {
391 let Some(_guard) = self.decide() else { return };
392 match self.accept() {
393 Ok(()) => log::info!(
394 "updates: package {} build {} is healthy: installed",
395 self.receipt.app.id,
396 self.receipt.app.build
397 ),
398 Err(err) => log::error!("updates: cannot install the healthy package: {err}"),
399 }
400 }
401
402 fn failed(&self, error: &AppError) {
403 let Some(_guard) = self.decide() else { return };
404 log::error!(
405 "updates: package {} build {} failed ({}): the next launch goes back",
406 self.receipt.app.id,
407 self.receipt.app.build,
408 error.message
409 );
410 remove(&self.dir.join(TRYING));
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use nsh_package::{Certificate, Contents, SecretKey, build, certify};
417
418 use super::*;
419 use crate::AppErrorKind;
420
421 const ID: &str = "com.example.app";
422
423 struct Keys {
424 root: SecretKey,
425 release: SecretKey,
426 cert: Certificate,
427 }
428
429 impl Keys {
430 fn new() -> Keys {
431 let root = SecretKey::generate().unwrap();
432 let release = SecretKey::generate().unwrap();
433 let cert = certify(&root, &release.public(), &[ID.into()], 0, u64::MAX);
434 Keys {
435 root,
436 release,
437 cert,
438 }
439 }
440
441 fn package(&self, id: &str, build_number: u64) -> Vec<u8> {
442 let contents = Contents {
443 app: nsh_package::App {
444 id: id.into(),
445 name: "App".into(),
446 version: format!("1.0.{build_number}"),
447 build: build_number,
448 },
449 capabilities: Some(serde_json::json!({ "clipboard": true })),
450 source: format!("globalThis.build = {build_number};"),
451 bytecode: None,
452 source_map: None,
453 assets: vec![("a.txt".into(), build_number.to_string().into_bytes())],
454 min_runtime: None,
455 };
456 let cert = if id == ID {
457 self.cert.clone()
458 } else {
459 certify(
460 &self.root,
461 &self.release.public(),
462 &["*".into()],
463 0,
464 u64::MAX,
465 )
466 };
467 build(&contents, &self.release, &cert).unwrap()
468 }
469
470 fn shipped(&self, build: u64) -> Shipped {
471 Shipped {
472 app_id: ID.into(),
473 build,
474 roots: vec![self.root.public()],
475 }
476 }
477 }
478
479 fn temp(name: &str) -> PathBuf {
480 let dir = std::env::temp_dir().join(format!("nsh-updates-{name}-{}", std::process::id()));
481 let _ = std::fs::remove_dir_all(&dir);
482 std::fs::create_dir_all(&dir).unwrap();
483 dir
484 }
485
486 fn put(dir: &Path, name: &str, bytes: &[u8]) {
487 std::fs::write(dir.join(name), bytes).unwrap();
488 }
489
490 fn chosen_build(chosen: &Option<Chosen>) -> Option<u64> {
491 chosen.as_ref().map(|c| c.loaded.app.build)
492 }
493
494 fn fatal() -> AppError {
495 AppError::new(AppErrorKind::Load, "Error: boom")
496 }
497
498 #[test]
499 fn nothing_downloaded_runs_the_shipped_bundle() {
500 let (keys, dir) = (Keys::new(), temp("none"));
501 assert!(choose(&dir, &keys.shipped(1)).is_none());
502 }
503
504 #[test]
505 fn a_new_package_runs_on_trial_and_is_installed_once_healthy() {
506 let (keys, dir) = (Keys::new(), temp("healthy"));
507 put(&dir, NEXT, &keys.package(ID, 2));
508 let chosen = choose(&dir, &keys.shipped(1));
509 assert_eq!(chosen_build(&chosen), Some(2));
510 let chosen = chosen.unwrap();
511 assert!(dir.join(TRYING).exists() && !dir.join(NEXT).exists());
512 assert_eq!(
513 std::fs::read(chosen.loaded.assets.join("a.txt")).unwrap(),
514 b"2"
515 );
516 let trial = chosen.trial.expect("on trial");
517 trial.healthy();
518 trial.failed(&fatal());
520 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
521 assert!(dir.join(CURRENT).exists());
522 let again = choose(&dir, &keys.shipped(1)).unwrap();
524 assert_eq!(again.loaded.app.build, 2);
525 assert!(again.trial.is_none());
526 let trust = keys.shipped(1).trust(&dir).unwrap();
528 assert_eq!(trust.accepted_build(ID), Some(2));
529 }
530
531 #[test]
532 fn a_package_that_crashed_is_rolled_back_to_the_installed_one() {
533 let (keys, dir) = (Keys::new(), temp("crash"));
534 put(&dir, CURRENT, &keys.package(ID, 2));
535 put(&dir, NEXT, &keys.package(ID, 3));
536 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(3));
537 let rolled_back = choose(&dir, &keys.shipped(1));
539 assert_eq!(chosen_build(&rolled_back), Some(2));
540 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
541 let kept: Vec<_> = std::fs::read_dir(dir.join(PACKAGES).join(ID))
543 .unwrap()
544 .collect();
545 assert_eq!(kept.len(), 1);
546 }
547
548 #[test]
549 fn a_fatal_error_deletes_the_package() {
550 let (keys, dir) = (Keys::new(), temp("fatal"));
551 put(&dir, NEXT, &keys.package(ID, 2));
552 let chosen = choose(&dir, &keys.shipped(1)).unwrap();
553 let trial = chosen.trial.unwrap();
554 trial.failed(&fatal());
555 trial.healthy();
556 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
557 assert!(!dir.join(CURRENT).exists());
558 assert!(choose(&dir, &keys.shipped(1)).is_none());
559 }
560
561 #[test]
562 fn tampered_foreign_and_old_packages_are_deleted() {
563 let keys = Keys::new();
564 let mut tampered = keys.package(ID, 2);
565 let at = tampered.len() / 2;
566 tampered[at] ^= 1;
567 let untrusted = Keys::new().package(ID, 2);
568 for (name, bytes) in [
569 ("tampered", tampered),
570 ("untrusted", untrusted),
571 ("foreign", keys.package("com.example.other", 2)),
572 ("old", keys.package(ID, 1)),
573 ] {
574 let dir = temp(name);
575 put(&dir, NEXT, &bytes);
576 assert!(choose(&dir, &keys.shipped(1)).is_none(), "{name}");
577 assert!(!dir.join(NEXT).exists(), "{name}");
578 }
579 }
580
581 #[test]
582 fn a_newer_app_replaces_the_installed_package() {
583 let (keys, dir) = (Keys::new(), temp("newer-app"));
584 put(&dir, CURRENT, &keys.package(ID, 2));
585 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(2));
586 assert!(choose(&dir, &keys.shipped(2)).is_none());
588 assert!(!dir.join(CURRENT).exists());
589 }
590
591 #[test]
592 fn an_older_download_than_the_installed_package_is_refused() {
593 let (keys, dir) = (Keys::new(), temp("older"));
594 put(&dir, NEXT, &keys.package(ID, 3));
595 choose(&dir, &keys.shipped(1))
596 .unwrap()
597 .trial
598 .unwrap()
599 .healthy();
600 put(&dir, NEXT, &keys.package(ID, 2));
601 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(3));
602 assert!(!dir.join(NEXT).exists());
603 }
604
605 #[test]
606 fn a_download_during_a_trial_waits_for_the_next_launch() {
607 let (keys, dir) = (Keys::new(), temp("during"));
608 put(&dir, NEXT, &keys.package(ID, 2));
609 let trial = choose(&dir, &keys.shipped(1)).unwrap().trial.unwrap();
610 put(&dir, NEXT, &keys.package(ID, 3));
611 trial.healthy();
612 let trust = keys.shipped(1).trust(&dir).unwrap();
613 assert_eq!(trust.accepted_build(ID), Some(2));
614 let next = choose(&dir, &keys.shipped(1)).unwrap();
615 assert_eq!(next.loaded.app.build, 3);
616 assert!(next.trial.is_some());
617 }
618
619 #[test]
620 fn downloads_are_verified_without_being_accepted() {
621 let (keys, dir) = (Keys::new(), temp("download"));
622 let roots = [keys.root.public().to_base64()];
623 let file = dir.join("next.nshpkg.part");
624 put(&dir, "next.nshpkg.part", &keys.package(ID, 3));
625 let app = verify_download(&file, &dir, ID, &roots, 2).unwrap();
626 assert_eq!(app.build, 3);
627 assert!(verify_download(&file, &dir, ID, &roots, 3).is_err());
628 assert!(verify_download(&file, &dir, "com.example.other", &roots, 2).is_err());
629 let other = [Keys::new().root.public().to_base64()];
630 assert!(verify_download(&file, &dir, ID, &other, 2).is_err());
631 assert!(verify_download(&file, &dir, ID, &[], 2).is_err());
632 let trust = keys.shipped(1).trust(&dir).unwrap();
633 assert_eq!(trust.accepted_build(ID), None);
634 }
635
636 #[test]
637 fn packages_run_as_the_shipped_app() {
638 let (keys, dir) = (Keys::new(), temp("launch"));
639 let resources = dir.join("nsh");
640 std::fs::create_dir_all(resources.join("assets")).unwrap();
641 let config = serde_json::json!({
642 "id": ID, "version": "1.0.0", "github": "o/r", "build": 1,
643 "packages": { "roots": [keys.root.public().to_base64()] },
644 });
645 std::fs::write(
646 resources.join("assets/nsh-updater.json"),
647 config.to_string(),
648 )
649 .unwrap();
650 let data = dir.join("data");
651 let updates = updates_dir(&data, ID);
652 std::fs::create_dir_all(&updates).unwrap();
653 put(&updates, NEXT, &keys.package(ID, 2));
654 let declared =
655 crate::parse_capabilities(r#"{"network":{"hosts":["api.example.com"]}}"#).unwrap();
656 let shipped = Bundle::source("1".into())
657 .with_app_id(Some(ID))
658 .with_url_schemes(["example"])
659 .with_main_window(Some(r#"{"defaultSize":{"width":900,"height":640}}"#))
660 .with_policy(crate::Policy {
661 declared: Some(declared),
662 ..Default::default()
663 });
664
665 assert!(shipped.main_window.is_some());
666 let launched = launch(shipped.clone(), &resources, Some(&data));
667 assert_eq!(launched.package.as_ref().map(|a| a.build), Some(2));
668 let bundle = &launched.bundle;
669 assert_eq!(bundle.url_schemes, ["example"]);
670 assert_eq!(bundle.main_window, shipped.main_window);
671 assert!(bundle.updater_config.is_some() && bundle.trial.is_some());
672 assert!(!bundle.policy.access().allows_clipboard());
674 assert!(launched.assets.join("a.txt").exists());
675
676 let plain = launch(shipped.clone(), &resources, None);
678 assert!(plain.package.is_none() && plain.bundle.updater_config.is_some());
679 assert_eq!(plain.assets, resources.join("assets"));
680 let elsewhere = dir.join("other");
681 let shipped_only = launch(shipped, &elsewhere, Some(&data));
682 assert!(shipped_only.package.is_none() && shipped_only.bundle.updater_config.is_none());
683 }
684}