Skip to main content

nsh_engine/
updates.rs

1//! Over-the-air updates of a packaged app's code (`docs/dev/updater.md`,
2//! "Packages"): signed packages (`.nshpkg`) the app downloaded with
3//! `nsh/updater`'s `downloadPackage` run instead of the bundle it shipped
4//! with, when they are newer, verify against the roots its `nsh.json`
5//! trusts and proved they run.
6//!
7//! Everything lives in [`updates_dir`], `<data dir>/<app id>/updates/`:
8//!
9//! - `next.nshpkg`: downloaded and verified, never run;
10//! - `trying.nshpkg`: `next.nshpkg` once a launch starts it, until it
11//!   proves healthy (it then becomes `current.nshpkg`) or fails (it is
12//!   deleted). Still there at a launch, the run before never proved
13//!   healthy (the process crashed): it is deleted and the app goes back.
14//!   A download during the trial writes `next.nshpkg` without touching it;
15//! - `current.nshpkg`: the package that last proved healthy;
16//! - `trust/`: the trust store's state (accepted builds, revocations);
17//! - `packages/`: the running package's extracted assets.
18//!
19//! [`launch`] picks what a packaged app's launcher runs; any failure there
20//! runs the shipped bundle. A package runs with the shipped app's id, URL
21//! schemes and trusted paths, its own declared capabilities granted at most
22//! what the shipped app declares, and `nsh/updater` reads the shipped
23//! app's update configuration ([`Bundle::updater_config`]).
24//!
25//! Failures and fallbacks are warnings or errors, which packaged apps log
26//! on every platform: the app's developer needs to see why a package does
27//! not run. What runs and what is installed are info, which they log on
28//! Android.
29
30use 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
42/// The directory of the state, in an app's own data directory.
43pub const DIR: &str = "updates";
44/// A downloaded package, run at the next launch.
45pub const NEXT: &str = "next.nshpkg";
46/// The package that proved healthy.
47pub const CURRENT: &str = "current.nshpkg";
48/// A package started and not yet healthy.
49pub const TRYING: &str = "trying.nshpkg";
50const TRUST: &str = "trust";
51const PACKAGES: &str = "packages";
52
53/// The update state of app `app_id` under `support_dir` (the directory
54/// each app has a directory of its own in, as
55/// [`crate::EngineConfig::support_dir`]): `<support_dir>/<app id>/updates`,
56/// wherever the app's data directory is.
57pub 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/// What a packaged app's launcher runs ([`launch`]).
64#[derive(Debug, Default)]
65#[non_exhaustive]
66pub struct Launch {
67    /// The bundle to run.
68    pub bundle: Bundle,
69    /// Where its assets are: the package's when it runs one, else the
70    /// shipped `assets` directory.
71    pub assets: PathBuf,
72    /// The package it runs (`None`: the shipped bundle).
73    pub package: Option<nsh_package::App>,
74}
75
76/// Picks what a packaged app runs: `shipped`, the bundle in its resources
77/// directory `resources` (`nsh`, holding `assets/nsh-updater.json`), or a
78/// newer signed package from its updates when its `nsh.json` trusts
79/// package roots (`"updater": { "packages": { "roots": [...] } }`) and
80/// `support_dir` is its engine's [`crate::EngineConfig::support_dir`].
81/// Never fails: any problem with a package is
82/// logged and the shipped bundle runs.
83pub 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/// A package to run instead of the shipped bundle ([`package_to_run`]).
102#[derive(Debug)]
103#[non_exhaustive]
104pub struct PackageRun {
105    /// Its bundle, as the shipped app's ([`launch`]).
106    pub bundle: Bundle,
107    /// Where its assets are.
108    pub assets: PathBuf,
109    /// Its app.
110    pub app: nsh_package::App,
111}
112
113/// [`launch`] for a launcher that reads its resources itself (Android's,
114/// from the APK): `config` is the shipped `nsh-updater.json`, which
115/// `shipped` gets as its [`Bundle::updater_config`]. `None`: the shipped
116/// bundle runs.
117pub fn package_to_run(
118    shipped: &mut Bundle,
119    config: Option<Vec<u8>>,
120    support_dir: Option<&Path>,
121) -> Option<PackageRun> {
122    // `nsh/updater` reads the shipped configuration, whatever runs.
123    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
145/// A package's bundle with what belongs to the installed app: its id
146/// (checked equal), URL schemes, trusted paths and update configuration,
147/// and at most the capabilities it declares.
148fn 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    // The package's declaration, granted at most what the shipped app
154    // declares: an update reaches nothing the installed app could not.
155    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/// The shipped app, as its update configuration says.
164#[derive(Debug, Clone)]
165struct Shipped {
166    app_id: String,
167    build: u64,
168    roots: Vec<PublicKey>,
169}
170
171impl Shipped {
172    /// `None` when the app takes no packages, or its configuration is not
173    /// for the shipped bundle's app.
174    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
214/// A package to run, and its trial when it has not proved healthy yet.
215struct Chosen {
216    loaded: LoadedPackage,
217    trial: Option<Arc<dyn Trial>>,
218}
219
220/// The launch decision (module docs).
221fn 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, &current, &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(&current);
278            }
279        }
280    }
281    // Only the running package's assets stay.
282    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
293/// Verifies the package at `path` for the shipped app and extracts its
294/// assets: refused unless it is the app's, newer than the shipped build
295/// and runs here (`TrustStore::verify`).
296fn 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    // The header's claims are checked before anything is extracted.
304    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
333/// Verifies a downloaded package as [`launch`] will (`nsh/updater`'s
334/// `downloadPackage`): signed by a release key one of `roots` certifies,
335/// for app `app_id`, newer than `newer_than` (the running build) and the
336/// builds accepted before, for this runtime. Accepts nothing and extracts
337/// nothing; `dir` is the app's [`updates_dir`]. Returns its app.
338pub 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/// The trial of `trying.nshpkg`: healthy, it becomes `current.nshpkg` and
367/// its build is accepted; failed, it is deleted.
368#[derive(Debug)]
369struct PackageTrial {
370    dir: PathBuf,
371    shipped: Shipped,
372    receipt: PackageReceipt,
373    /// Decided: later calls change nothing.
374    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        // A later failure changes nothing.
523        trial.failed(&fatal());
524        assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
525        assert!(dir.join(CURRENT).exists());
526        // Installed: the next launch runs it, off trial.
527        let again = choose(&dir, &keys.shipped(1)).unwrap();
528        assert_eq!(again.loaded.app.build, 2);
529        assert!(again.trial.is_none());
530        // Accepted: build 1 would now be refused.
531        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        // The process died before the trial ended: it is still on trial.
542        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        // Only the running package's assets are kept.
546        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        // The app was updated to build 2 (or later): it runs its own.
591        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        // The package declares the clipboard; the app did not.
677        assert!(!bundle.policy.access().allows_clipboard());
678        assert!(launched.assets.join("a.txt").exists());
679
680        // Without a data directory, or roots, the shipped bundle runs.
681        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}