cranpose-services 0.1.160

Multiplatform system services for Cranpose (HTTP, URI, and OS integrations)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Typed application update discovery, verification, and platform installation.
//!
//! An update is the one download an application performs that can replace the
//! application, so what arrives is checked against what was promised before it
//! reaches a platform installer. The check lives here, once, rather than in each
//! platform's installer: a digest computed four different ways is four chances
//! to compute it wrongly, and one of them will be the one nobody tested.

use std::sync::{
    Arc, Mutex, OnceLock,
    atomic::{AtomicU64, Ordering},
};

use sha2::{Digest, Sha256};

use crate::registry::ServiceRegistry;

/// How a package's bytes are checked against what the release promised.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DigestAlgorithm {
    /// SHA-256, which is what release feeds publish.
    #[default]
    Sha256,
}

impl DigestAlgorithm {
    /// The name a release feed writes, and the name a platform's own digest API
    /// answers to.
    pub fn name(self) -> &'static str {
        match self {
            DigestAlgorithm::Sha256 => "sha256",
        }
    }

    /// Reads an algorithm a release feed named, or `None` for one this
    /// framework cannot compute — which is refused rather than skipped, because
    /// a digest nobody checks is worse than no digest at all.
    pub fn parse(name: &str) -> Option<Self> {
        match name.trim().to_ascii_lowercase().as_str() {
            "sha256" | "sha-256" => Some(DigestAlgorithm::Sha256),
            _ => None,
        }
    }
}

/// The digest a downloaded package must match.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PackageDigest {
    pub algorithm: DigestAlgorithm,
    /// Lower-case hexadecimal.
    pub value: String,
}

impl PackageDigest {
    /// A SHA-256 digest, from hexadecimal in either case.
    pub fn sha256(value: impl AsRef<str>) -> Self {
        Self {
            algorithm: DigestAlgorithm::Sha256,
            value: value.as_ref().trim().to_ascii_lowercase(),
        }
    }

    /// Reads the `sha256:<hex>` form release feeds publish.
    pub fn parse(value: &str) -> Option<Self> {
        let (algorithm, digest) = value.split_once(':')?;
        let algorithm = DigestAlgorithm::parse(algorithm)?;
        let digest = digest.trim().to_ascii_lowercase();
        (!digest.is_empty()).then_some(Self {
            algorithm,
            value: digest,
        })
    }

    /// Whether this digest could be one: the right length, and hexadecimal.
    ///
    /// A malformed digest is refused before a download starts rather than after
    /// it, so nobody waits for two hundred megabytes to learn the release feed
    /// was misconfigured.
    pub fn is_well_formed(&self) -> bool {
        let expected = match self.algorithm {
            DigestAlgorithm::Sha256 => 64,
        };
        self.value.len() == expected && self.value.bytes().all(|byte| byte.is_ascii_hexdigit())
    }

    /// The `sha256:<hex>` form.
    pub fn to_feed_string(&self) -> String {
        format!("{}:{}", self.algorithm.name(), self.value)
    }
}

/// The SHA-256 of `bytes`, as lower-case hexadecimal.
pub fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex(&hasher.finalize())
}

fn hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(char::from_digit((byte >> 4) as u32, 16).unwrap_or('0'));
        out.push(char::from_digit((byte & 0x0f) as u32, 16).unwrap_or('0'));
    }
    out
}

/// Checks a package as it is read, so a package too large to hold in memory is
/// still checked.
///
/// An installer feeds every chunk it writes through this and calls
/// [`DigestVerifier::finish`] before committing; nothing installs a package
/// whose bytes were never seen in full.
pub struct DigestVerifier {
    expected: PackageDigest,
    hasher: Sha256,
    len: u64,
}

impl DigestVerifier {
    /// A verifier for `expected`, or an error when the digest is malformed.
    pub fn new(expected: PackageDigest) -> Result<Self, AppUpdateError> {
        if !expected.is_well_formed() {
            return Err(AppUpdateError::MalformedDigest(expected.to_feed_string()));
        }
        Ok(Self {
            expected,
            hasher: Sha256::new(),
            len: 0,
        })
    }

    /// Feeds the next chunk of the package.
    pub fn update(&mut self, chunk: &[u8]) {
        self.hasher.update(chunk);
        self.len += chunk.len() as u64;
    }

    /// How many bytes have been read so far.
    pub fn len(&self) -> u64 {
        self.len
    }

    /// Whether nothing has been read yet.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Checks what was read against what was promised.
    pub fn finish(self) -> Result<(), AppUpdateError> {
        let actual = hex(&self.hasher.finalize());
        if actual == self.expected.value {
            Ok(())
        } else {
            Err(AppUpdateError::VerificationFailed {
                expected: self.expected.value,
                actual,
            })
        }
    }
}

/// Checks a package held in memory against `digest`.
pub fn verify_package(bytes: &[u8], digest: &PackageDigest) -> Result<(), AppUpdateError> {
    let mut verifier = DigestVerifier::new(digest.clone())?;
    verifier.update(bytes);
    verifier.finish()
}

/// A package an update would install.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct UpdatePackage {
    /// The version this package installs.
    pub version: String,
    /// Where the package is downloaded from.
    pub download_url: String,
    /// How large it is, when the release feed says.
    pub size: Option<u64>,
    /// What its bytes must hash to.
    ///
    /// `None` means the release feed published none, and
    /// [`install_app_update`] refuses such a package: the platform's own
    /// signature check catches a package signed by someone else, but not one
    /// that arrived corrupted, and this is the one download that replaces the
    /// application. A feed with no digest is a feed to fix.
    pub digest: Option<PackageDigest>,
    /// Release notes, when the feed carries them.
    pub notes: Option<String>,
}

impl UpdatePackage {
    /// A package at `download_url` installing `version`.
    pub fn new(version: impl Into<String>, download_url: impl Into<String>) -> Self {
        Self {
            version: version.into(),
            download_url: download_url.into(),
            ..Self::default()
        }
    }

    pub fn with_size(mut self, size: u64) -> Self {
        self.size = Some(size);
        self
    }

    pub fn with_digest(mut self, digest: PackageDigest) -> Self {
        self.digest = Some(digest);
        self
    }

    pub fn with_notes(mut self, notes: impl Into<String>) -> Self {
        self.notes = Some(notes.into());
        self
    }

    /// Whether this package can be checked against what the feed promised.
    pub fn is_verifiable(&self) -> bool {
        self.digest
            .as_ref()
            .is_some_and(PackageDigest::is_well_formed)
    }
}

/// A GitHub release feed used to discover an application package.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct GitHubReleaseUpdate {
    /// Repository in `owner/name` form.
    pub repository: String,
    /// Version of the running application.
    pub current_version: String,
    /// File-name suffix selected from the release assets, such as `.apk`.
    pub asset_suffix: String,
}

impl GitHubReleaseUpdate {
    /// Creates a GitHub release request.
    pub fn new(
        repository: impl Into<String>,
        current_version: impl Into<String>,
        asset_suffix: impl Into<String>,
    ) -> Self {
        Self {
            repository: repository.into(),
            current_version: current_version.into(),
            asset_suffix: asset_suffix.into(),
        }
    }
}

/// Observable state of the application update flow.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum AppUpdateStatus {
    /// No operation has started.
    #[default]
    Idle,
    /// The release feed is being queried.
    Checking,
    /// The running application is current.
    UpToDate,
    /// A package can be installed.
    Available {
        /// What the release feed offers, including its size and digest when it
        /// published them.
        package: UpdatePackage,
    },
    /// A package is being transferred to the platform installer.
    Downloading {
        /// Bytes transferred so far.
        downloaded: u64,
        /// Total bytes when supplied by the server.
        total: Option<u64>,
    },
    /// The transfer finished and the package is being checked against the
    /// digest the release feed published.
    Verifying,
    /// The platform is asking the user to approve installation.
    AwaitingConfirmation,
    /// The platform installer accepted the package.
    Installing,
    /// The operation could not continue.
    Error(String),
}

/// Failure to start an update operation.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum AppUpdateError {
    /// This platform has no registered installer.
    #[error("application updates are unavailable on this platform")]
    Unsupported,
    /// The platform rejected the request before work started.
    #[error("application update request failed: {0}")]
    Request(String),
    /// The release feed published no digest for this package.
    ///
    /// Refused rather than installed: this is an application replacing itself
    /// with bytes off the network, and bytes nobody checked are bytes nobody
    /// checked whether or not the feed mentioned it. A feed that publishes no
    /// digest is a feed to fix, not a check to skip.
    #[error("the release feed published no digest for this package, so it cannot be checked")]
    Unverifiable,
    /// The release feed published a digest this framework cannot check.
    ///
    /// Refused rather than ignored: a digest nobody checks reads as a package
    /// that was verified.
    #[error("the release feed published a digest that cannot be checked: {0}")]
    MalformedDigest(String),
    /// What arrived is not what the release feed promised.
    #[error("the downloaded package does not match its digest (expected {expected}, got {actual})")]
    VerificationFailed {
        /// The digest the release feed published.
        expected: String,
        /// The digest the bytes that arrived actually have.
        actual: String,
    },
}

/// Platform implementation for update discovery and package installation.
pub trait AppUpdater: Send + Sync {
    /// What this backend can do.
    ///
    /// Defaults to neither, so a backend states what it can do rather than
    /// inheriting a claim: the two entry points below refuse a half a backend
    /// has not claimed, and a backend that forgot to declare one is refused
    /// rather than allowed to fail at the platform boundary.
    fn capabilities(&self) -> AppUpdateCapabilities {
        AppUpdateCapabilities::default()
    }

    /// Starts release discovery. Progress is published through
    /// [`set_app_update_status`].
    fn check(&self, source: &GitHubReleaseUpdate) -> Result<(), AppUpdateError> {
        let _ = source;
        Err(AppUpdateError::Unsupported)
    }

    /// Transfers a package to the platform installer.
    ///
    /// An implementation checks the package against
    /// [`UpdatePackage::digest`] before committing it — nothing is installed
    /// whose bytes were not the ones the release feed promised.
    fn install(&self, package: &UpdatePackage) -> Result<(), AppUpdateError> {
        let _ = package;
        Err(AppUpdateError::Unsupported)
    }
}

/// What an update backend can do on this platform.
///
/// The two halves are separate because a platform can genuinely have one
/// without the other: an iOS application may discover that a newer version
/// exists and send the reader to the store, while installing a replacement
/// binary is something the platform does not allow it to do at all. Reporting
/// one flag for both would make `check` look unavailable where it works, or
/// make `install` look available where it can only fail.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AppUpdateCapabilities {
    /// Whether this platform can discover a newer release.
    pub check: bool,
    /// Whether this platform can install one.
    pub install: bool,
}

/// Shared updater service.
pub type AppUpdaterRef = Arc<dyn AppUpdater>;

static PLATFORM_UPDATER: ServiceRegistry<dyn AppUpdater> = ServiceRegistry::new();

/// Installs the platform updater.
pub fn set_platform_app_updater(updater: AppUpdaterRef) {
    PLATFORM_UPDATER.set(updater);
}

/// Removes the platform updater.
pub fn clear_platform_app_updater() {
    PLATFORM_UPDATER.clear();
}

/// What this host can do about application updates.
pub fn app_update_capabilities() -> AppUpdateCapabilities {
    PLATFORM_UPDATER
        .get()
        .map(|updater| updater.capabilities())
        .unwrap_or_default()
}

/// Returns whether this host can install application updates.
pub fn app_updates_supported() -> bool {
    app_update_capabilities().install
}

/// Returns whether this host can discover a newer release.
///
/// A host may answer yes here and no to [`app_updates_supported`]: knowing an
/// update exists is what lets an application point at the store it cannot
/// install from itself.
pub fn app_update_checks_supported() -> bool {
    app_update_capabilities().check
}

fn publish_failure(error: AppUpdateError) -> Result<(), AppUpdateError> {
    set_app_update_status(AppUpdateStatus::Error(error.to_string()));
    Err(error)
}

/// Starts update discovery and publishes the initial state.
pub fn check_for_app_update(source: &GitHubReleaseUpdate) -> Result<(), AppUpdateError> {
    let Some(updater) = PLATFORM_UPDATER.get() else {
        return publish_failure(AppUpdateError::Unsupported);
    };
    if !updater.capabilities().check {
        return publish_failure(AppUpdateError::Unsupported);
    }
    set_app_update_status(AppUpdateStatus::Checking);
    updater.check(source).inspect_err(|error| {
        set_app_update_status(AppUpdateStatus::Error(error.to_string()));
    })
}

/// Starts package installation and publishes the initial transfer state.
///
/// A digest the release feed published but this framework cannot check is
/// refused here, before anything is downloaded: nobody waits for two hundred
/// megabytes to learn the feed was misconfigured, and nothing reaches an
/// installer unchecked because its digest was unreadable.
pub fn install_app_update(package: &UpdatePackage) -> Result<(), AppUpdateError> {
    let Some(updater) = PLATFORM_UPDATER.get() else {
        return publish_failure(AppUpdateError::Unsupported);
    };
    if !updater.capabilities().install {
        return publish_failure(AppUpdateError::Unsupported);
    }
    let error = match &package.digest {
        None => Some(AppUpdateError::Unverifiable),
        Some(digest) if !digest.is_well_formed() => {
            Some(AppUpdateError::MalformedDigest(digest.to_feed_string()))
        }
        Some(_) => None,
    };
    if let Some(error) = error {
        return publish_failure(error);
    }
    set_app_update_status(AppUpdateStatus::Downloading {
        downloaded: 0,
        total: package.size,
    });
    updater.install(package).inspect_err(|error| {
        set_app_update_status(AppUpdateStatus::Error(error.to_string()));
    })
}

fn status_slot() -> &'static Mutex<AppUpdateStatus> {
    static STATUS: OnceLock<Mutex<AppUpdateStatus>> = OnceLock::new();
    STATUS.get_or_init(|| Mutex::new(AppUpdateStatus::Idle))
}

/// Returns the latest update state.
pub fn app_update_status() -> AppUpdateStatus {
    status_slot().lock().map_or_else(
        |poisoned| poisoned.into_inner().clone(),
        |status| status.clone(),
    )
}

#[cfg(not(target_arch = "wasm32"))]
type Observer = Arc<dyn Fn(AppUpdateStatus) + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type Observer = std::rc::Rc<dyn Fn(AppUpdateStatus)>;

#[cfg(not(target_arch = "wasm32"))]
fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
    static OBSERVERS: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
    OBSERVERS.get_or_init(|| Mutex::new(Vec::new()))
}

#[cfg(target_arch = "wasm32")]
thread_local! {
    static OBSERVERS: std::cell::RefCell<Vec<(u64, Observer)>> = const { std::cell::RefCell::new(Vec::new()) };
}

static NEXT_OBSERVER_ID: AtomicU64 = AtomicU64::new(1);

/// Registration returned by [`observe_app_update_status`].
pub struct AppUpdateObserver {
    id: u64,
}

impl Drop for AppUpdateObserver {
    fn drop(&mut self) {
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut observers) = observers().lock() {
            observers.retain(|(id, _)| *id != self.id);
        }
        #[cfg(target_arch = "wasm32")]
        OBSERVERS.with(|observers| observers.borrow_mut().retain(|(id, _)| *id != self.id));
    }
}

/// Observes update state changes. The current state is delivered immediately.
#[cfg(not(target_arch = "wasm32"))]
pub fn observe_app_update_status(
    observer: impl Fn(AppUpdateStatus) + Send + Sync + 'static,
) -> AppUpdateObserver {
    let id = NEXT_OBSERVER_ID.fetch_add(1, Ordering::Relaxed);
    let observer: Observer = Arc::new(observer);
    if let Ok(mut observers) = observers().lock() {
        observers.push((id, Arc::clone(&observer)));
    }
    observer(app_update_status());
    AppUpdateObserver { id }
}

/// Observes update state changes. The current state is delivered immediately.
#[cfg(target_arch = "wasm32")]
pub fn observe_app_update_status(
    observer: impl Fn(AppUpdateStatus) + 'static,
) -> AppUpdateObserver {
    let id = NEXT_OBSERVER_ID.fetch_add(1, Ordering::Relaxed);
    let observer: Observer = std::rc::Rc::new(observer);
    OBSERVERS.with(|observers| {
        observers
            .borrow_mut()
            .push((id, std::rc::Rc::clone(&observer)));
    });
    observer(app_update_status());
    AppUpdateObserver { id }
}

/// Publishes state from a platform updater.
pub fn set_app_update_status(status: AppUpdateStatus) {
    if let Ok(mut current) = status_slot().lock() {
        if *current == status {
            return;
        }
        *current = status.clone();
    }
    #[cfg(not(target_arch = "wasm32"))]
    let observers = observers()
        .lock()
        .map(|observers| {
            observers
                .iter()
                .map(|(_, observer)| Arc::clone(observer))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    #[cfg(target_arch = "wasm32")]
    let observers = OBSERVERS.with(|observers| {
        observers
            .borrow()
            .iter()
            .map(|(_, observer)| std::rc::Rc::clone(observer))
            .collect::<Vec<_>>()
    });
    for observer in observers {
        observer(status.clone());
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{PoisonError, atomic::AtomicUsize};

    use super::*;

    struct RecordingUpdater {
        checks: AtomicUsize,
        installed: Mutex<Vec<UpdatePackage>>,
    }

    impl RecordingUpdater {
        fn new() -> Self {
            Self {
                checks: AtomicUsize::new(0),
                installed: Mutex::new(Vec::new()),
            }
        }

        fn installs(&self) -> Vec<UpdatePackage> {
            self.installed
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .clone()
        }
    }

    impl AppUpdater for RecordingUpdater {
        fn capabilities(&self) -> AppUpdateCapabilities {
            AppUpdateCapabilities {
                check: true,
                install: true,
            }
        }

        fn check(&self, _source: &GitHubReleaseUpdate) -> Result<(), AppUpdateError> {
            self.checks.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }

        fn install(&self, package: &UpdatePackage) -> Result<(), AppUpdateError> {
            self.installed
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(package.clone());
            Ok(())
        }
    }

    const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    const ABC_SHA256: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";

    #[test]
    fn the_digest_is_the_one_every_other_implementation_computes() {
        assert_eq!(sha256_hex(b""), EMPTY_SHA256);
        assert_eq!(sha256_hex(b"abc"), ABC_SHA256);
    }

    #[test]
    fn a_feed_digest_is_read_in_the_form_feeds_publish_it() {
        let digest = PackageDigest::parse(&format!("sha256:{}", ABC_SHA256.to_uppercase()))
            .expect("a sha256 digest");
        assert_eq!(digest.algorithm, DigestAlgorithm::Sha256);
        assert_eq!(digest.value, ABC_SHA256, "case is normalised on the way in");
        assert_eq!(digest.to_feed_string(), format!("sha256:{ABC_SHA256}"));
        assert!(digest.is_well_formed());
    }

    #[test]
    fn a_digest_this_framework_cannot_check_is_refused_rather_than_ignored() {
        assert_eq!(PackageDigest::parse("md5:abcdef"), None);
        assert_eq!(PackageDigest::parse("sha256:"), None);
        assert_eq!(PackageDigest::parse("no-algorithm"), None);
        assert!(!PackageDigest::sha256("not hexadecimal").is_well_formed());
        assert!(!PackageDigest::sha256("abcd").is_well_formed(), "too short");
        assert!(matches!(
            DigestVerifier::new(PackageDigest::sha256("abcd")),
            Err(AppUpdateError::MalformedDigest(_))
        ));
    }

    #[test]
    fn a_package_that_matches_its_digest_verifies() {
        assert_eq!(
            verify_package(b"abc", &PackageDigest::sha256(ABC_SHA256)),
            Ok(())
        );
    }

    #[test]
    fn a_package_that_does_not_match_reports_both_digests() {
        let error = verify_package(b"abd", &PackageDigest::sha256(ABC_SHA256))
            .expect_err("a changed byte must not verify");
        match error {
            AppUpdateError::VerificationFailed { expected, actual } => {
                assert_eq!(expected, ABC_SHA256);
                assert_ne!(actual, ABC_SHA256);
                assert_eq!(actual, sha256_hex(b"abd"));
            }
            other => panic!("expected a verification failure, got {other}"),
        }
    }

    #[test]
    fn a_package_read_in_chunks_verifies_the_same_as_one_read_whole() {
        let mut verifier =
            DigestVerifier::new(PackageDigest::sha256(ABC_SHA256)).expect("a well-formed digest");
        assert!(verifier.is_empty());
        verifier.update(b"a");
        verifier.update(b"b");
        verifier.update(b"c");
        assert_eq!(verifier.len(), 3);
        assert_eq!(verifier.finish(), Ok(()));
    }

    #[test]
    fn a_package_carries_what_the_feed_promised_about_it() {
        let package = UpdatePackage::new("1.2.3", "https://example.test/app.apk")
            .with_size(4096)
            .with_digest(PackageDigest::sha256(ABC_SHA256))
            .with_notes("Fixes the thing");
        assert_eq!(package.version, "1.2.3");
        assert_eq!(package.size, Some(4096));
        assert!(package.is_verifiable());
        assert_eq!(package.notes.as_deref(), Some("Fixes the thing"));

        assert!(
            !UpdatePackage::new("1.2.3", "https://example.test/app.apk").is_verifiable(),
            "a feed that published no digest leaves nothing to check against"
        );
    }

    #[test]
    fn request_builds_typed_source() {
        let source = GitHubReleaseUpdate::new("owner/app", "1.2.3", ".apk");
        assert_eq!(source.repository, "owner/app");
        assert_eq!(source.current_version, "1.2.3");
        assert_eq!(source.asset_suffix, ".apk");
    }

    #[test]
    fn operations_publish_and_forward() {
        let _guard = crate::registry::test_service_guard();
        let updater = Arc::new(RecordingUpdater::new());
        set_platform_app_updater(updater.clone());
        assert!(app_updates_supported());
        check_for_app_update(&GitHubReleaseUpdate::new("owner/app", "1", ".apk")).unwrap();
        assert_eq!(updater.checks.load(Ordering::Relaxed), 1);
        assert_eq!(app_update_status(), AppUpdateStatus::Checking);

        let package = UpdatePackage::new("2", "https://example.test/app.apk")
            .with_size(4096)
            .with_digest(PackageDigest::sha256(sha256_hex(b"package")));
        install_app_update(&package).unwrap();
        assert_eq!(updater.installs(), vec![package]);
        assert_eq!(
            app_update_status(),
            AppUpdateStatus::Downloading {
                downloaded: 0,
                total: Some(4096)
            },
            "the size the feed published is reported before the first byte arrives"
        );
        clear_platform_app_updater();
        assert!(!app_updates_supported());
    }

    #[test]
    fn a_package_with_an_uncheckable_digest_is_refused_before_it_is_downloaded() {
        let _guard = crate::registry::test_service_guard();
        let updater = Arc::new(RecordingUpdater::new());
        set_platform_app_updater(updater.clone());
        let package = UpdatePackage::new("2", "https://example.test/app.apk")
            .with_digest(PackageDigest::sha256("not-a-digest"));
        assert!(matches!(
            install_app_update(&package),
            Err(AppUpdateError::MalformedDigest(_))
        ));
        assert!(updater.installs().is_empty());
        assert!(matches!(app_update_status(), AppUpdateStatus::Error(_)));
        clear_platform_app_updater();
    }

    #[test]
    fn a_host_that_cannot_update_says_so_through_the_status_and_not_only_the_result() {
        let _guard = crate::registry::test_service_guard();

        clear_platform_app_updater();
        set_app_update_status(AppUpdateStatus::Idle);
        assert_eq!(
            check_for_app_update(&GitHubReleaseUpdate::new("owner/app", "1", ".apk")),
            Err(AppUpdateError::Unsupported)
        );
        assert!(matches!(app_update_status(), AppUpdateStatus::Error(_)));

        struct CheckOnlyUpdater;
        impl AppUpdater for CheckOnlyUpdater {
            fn capabilities(&self) -> AppUpdateCapabilities {
                AppUpdateCapabilities {
                    check: true,
                    install: false,
                }
            }
            fn check(&self, _source: &GitHubReleaseUpdate) -> Result<(), AppUpdateError> {
                Ok(())
            }
        }
        set_platform_app_updater(Arc::new(CheckOnlyUpdater));
        set_app_update_status(AppUpdateStatus::Idle);
        let package = UpdatePackage::new("2", "https://example.test/app.apk")
            .with_digest(PackageDigest::sha256(sha256_hex(b"package")));
        assert_eq!(
            install_app_update(&package),
            Err(AppUpdateError::Unsupported)
        );
        assert!(matches!(app_update_status(), AppUpdateStatus::Error(_)));
        assert!(app_update_checks_supported());
        assert!(!app_updates_supported());
        clear_platform_app_updater();
    }

    #[test]
    fn a_package_with_no_digest_at_all_never_reaches_the_installer() {
        let _guard = crate::registry::test_service_guard();
        let updater = Arc::new(RecordingUpdater::new());
        set_platform_app_updater(updater.clone());
        let package = UpdatePackage::new("2", "https://example.test/app.apk");

        assert!(!package.is_verifiable());
        assert_eq!(
            install_app_update(&package),
            Err(AppUpdateError::Unverifiable)
        );

        assert!(updater.installs().is_empty());
        assert!(matches!(app_update_status(), AppUpdateStatus::Error(_)));
        clear_platform_app_updater();
    }

    #[test]
    fn observer_receives_current_and_changed_status() {
        let _guard = crate::registry::test_service_guard();
        set_app_update_status(AppUpdateStatus::Idle);
        let seen = Arc::new(Mutex::new(Vec::new()));
        let captured = Arc::clone(&seen);
        let observer = observe_app_update_status(move |status| {
            captured
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(status);
        });
        set_app_update_status(AppUpdateStatus::Verifying);
        set_app_update_status(AppUpdateStatus::Installing);
        assert_eq!(
            *seen.lock().unwrap_or_else(PoisonError::into_inner),
            vec![
                AppUpdateStatus::Idle,
                AppUpdateStatus::Verifying,
                AppUpdateStatus::Installing
            ]
        );
        drop(observer);
        set_app_update_status(AppUpdateStatus::Idle);
    }
}