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