gpui-updater-core 0.4.3

Blocking cross-platform update engine, independent of GPUI
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
//! Engine configuration and the verification of one downloaded file.

use std::path::{Path, PathBuf};

use semver::Version;

use crate::error::{Error, Result};
use crate::http::{self, HttpOptions, Metadata};
use crate::install::InstallOptions;
use crate::release::{DeltaAsset, Release};
use crate::verify;

/// Longest chain of deltas the engine downloads by default.
pub const DEFAULT_MAX_DELTA_HOPS: usize = 4;

/// Largest download the engine accepts by default: 4 GiB, twice what GitHub
/// Releases allows for a single asset.
pub const DEFAULT_MAX_DOWNLOAD_SIZE: u64 = 4 * 1024 * 1024 * 1024;

/// How strictly [`UpdateEngine`](crate::UpdateEngine) enforces integrity and
/// authenticity checks on a release.
///
/// A "signature" is either a minisign signature (checked against
/// [`EngineConfig::minisign_public_key`]) or a Sparkle-style Ed25519
/// signature (checked against [`EngineConfig::ed25519_public_key`]). Every
/// signature the release publishes *and* a configured key can check is
/// verified, and any mismatch fails the download. The same applies to deltas.
///
/// The default, [`BestEffort`](Verification::BestEffort), verifies whatever the
/// release provides and *skips* a check when its input is absent — so an
/// unsigned release installs with only a checksum, or with nothing. The
/// `Signature`/`Strict` modes instead fail closed: a release that cannot be
/// verified is rejected at [`check`](crate::UpdateEngine::check) time (before
/// it is surfaced as available) and again at
/// [`download`](crate::UpdateEngine::download) time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Verification {
    /// Verify whatever the release and config provide; skip a check when its
    /// input is missing (no checksum, no signature, or no public key). The
    /// backwards-compatible default — note it fails *open*.
    #[default]
    BestEffort,
    /// Skip all integrity, authenticity, and payload checks. For tests and
    /// local development only.
    Off,
    /// Require a matching SHA-256. Fails closed when the release publishes no
    /// checksum. A signature is still verified when one is available.
    Checksum,
    /// Require a valid signature: the release must publish a minisign or
    /// Ed25519 signature for which a public key is configured. A checksum is
    /// still verified when available, but is not itself required.
    Signature,
    /// Require both a valid signature and a matching SHA-256.
    Strict,
}

impl Verification {
    pub(super) fn skips_all(self) -> bool {
        matches!(self, Self::Off)
    }

    fn requires_signature(self) -> bool {
        matches!(self, Self::Signature | Self::Strict)
    }

    fn requires_checksum(self) -> bool {
        matches!(self, Self::Checksum | Self::Strict)
    }
}

/// Whether a signature must name the version it was made for.
///
/// minisign signs a *trusted comment* along with the file. When it carries a
/// `version:<semver>` token (see [`verify::signed_version`]), the engine
/// checks it against the version the file is supposed to be: the release
/// version for a full artifact, the target version for a delta. That stops an
/// older, validly signed artifact from being served as a newer one.
///
/// Sparkle-style Ed25519 signatures sign the file alone and cannot name a
/// version; on macOS, [`BundleVersion`] covers them instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum VersionBinding {
    /// Check the `version:` token when a verified signature carries one.
    #[default]
    IfPresent,
    /// Reject a verified signature without a `version:` token. Use once every
    /// artifact you publish is signed with one.
    Required,
}

/// Which code signature an update must carry: the app bundle's on macOS, the
/// `.exe` or `.msi` Authenticode signature on Windows. Linux has no platform
/// code signature, so nothing is checked there.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum CodeSigning {
    /// Require the update to be signed like the installed app, when the
    /// installed app is signed. On macOS, a team-signed app needs an update
    /// that passes `codesign --verify --deep --strict` and is signed by the
    /// same team; unsigned and ad-hoc signed apps are not checked. On Windows,
    /// an app with a valid Authenticode signature needs an update with a valid
    /// signature whose certificate has the same common name (CN); unsigned
    /// apps are not checked.
    #[default]
    MatchInstalled,
    /// Require a valid signature by this Team ID, whatever the installed app
    /// carries (macOS; ignored on Windows).
    TeamId(String),
    /// Require a valid Authenticode signature whose certificate's common name
    /// (CN) is this publisher name, such as `Example Corp`, whatever the
    /// installed app carries (Windows; ignored on macOS).
    Publisher(String),
    /// Do not check code signatures.
    Off,
}

/// Whether the app bundle of an update must declare the release's version
/// (macOS).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum BundleVersion {
    /// Require `CFBundleShortVersionString` to equal the release version
    /// (missing components count as zero, so `1.2` matches `1.2.0`).
    #[default]
    MustMatch,
    /// Do not compare bundle versions.
    Ignore,
}

/// Configuration for an [`UpdateEngine`](crate::UpdateEngine).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct EngineConfig {
    /// The currently running version, compared against the source's latest.
    pub current_version: Version,
    /// Base64 minisign public keys. A signature made by any of them is
    /// accepted, so a new key can ship next to the old one before releases
    /// switch to it.
    pub minisign_public_keys: Vec<String>,
    /// Base64 Ed25519 public key in Sparkle's format (the `SUPublicEDKey`
    /// value printed by Sparkle's `generate_keys`). When set and the release
    /// publishes an [`ed25519_signature`](Release::ed25519_signature), the
    /// download is signature-checked.
    pub ed25519_public_key: Option<String>,
    /// How strictly downloads are verified. See [`Verification`].
    pub verification: Verification,
    /// Whether signatures must name the version they were made for.
    pub version_binding: VersionBinding,
    /// Which code signature the update must carry (macOS).
    pub code_signing: CodeSigning,
    /// Whether the update's bundle version must equal the release (macOS).
    pub bundle_version: BundleVersion,
    /// Where to install. Defaults to [`crate::install::current_install_root`].
    pub install_root: Option<PathBuf>,
    /// Directory for downloads. Defaults to a fresh temp directory that only
    /// the current user can access. A directory set here should not be
    /// writable by other users either; the engine creates it (and missing
    /// parents) with owner-only permissions if it does not exist.
    pub download_dir: Option<PathBuf>,
    /// Largest file, in bytes, the engine downloads: a release publishing a
    /// larger size is refused before anything is fetched, and a body growing
    /// past this is cut off even when no size is published. Defaults to
    /// [`DEFAULT_MAX_DOWNLOAD_SIZE`].
    pub max_download_size: u64,
    /// Whether to try published binary deltas before the full artifact.
    /// Defaults to `true`; only takes effect with the `delta` feature on macOS
    /// and Linux.
    pub deltas: bool,
    /// Longest chain of deltas to download when none starts at the installed
    /// version. Defaults to [`DEFAULT_MAX_DELTA_HOPS`].
    pub max_delta_hops: usize,
    /// Extra headers and the proxy for artifacts, deltas, and their
    /// checksum and signature files. Sources have their own.
    pub http: HttpOptions,
    /// How [`UpdateEngine::install`](crate::UpdateEngine::install) installs
    /// the update, such as the Windows Installer UI for an `.msi`.
    pub install_options: InstallOptions,
}

impl EngineConfig {
    /// Start a config for the given running version.
    pub fn new(current_version: Version) -> Self {
        Self {
            current_version,
            minisign_public_keys: Vec::new(),
            ed25519_public_key: None,
            verification: Verification::default(),
            version_binding: VersionBinding::default(),
            code_signing: CodeSigning::default(),
            bundle_version: BundleVersion::default(),
            install_root: None,
            download_dir: None,
            max_download_size: DEFAULT_MAX_DOWNLOAD_SIZE,
            deltas: true,
            max_delta_hops: DEFAULT_MAX_DELTA_HOPS,
            http: HttpOptions::new(),
            install_options: InstallOptions::new(),
        }
    }

    /// Trust a base64 minisign public key. Call again to trust several, for
    /// example while rotating keys.
    #[must_use]
    pub fn minisign_public_key(mut self, key: impl Into<String>) -> Self {
        self.minisign_public_keys.push(key.into());
        self
    }

    /// Set the base64 Ed25519 public key (Sparkle's `SUPublicEDKey`) used to
    /// verify `sparkle:edSignature` signatures.
    #[must_use]
    pub fn ed25519_public_key(mut self, key: impl Into<String>) -> Self {
        self.ed25519_public_key = Some(key.into());
        self
    }

    /// Set how strictly downloads are verified. Defaults to
    /// [`Verification::BestEffort`].
    #[must_use]
    pub fn verification(mut self, verification: Verification) -> Self {
        self.verification = verification;
        self
    }

    /// Set whether signatures must name their version. Defaults to
    /// [`VersionBinding::IfPresent`].
    #[must_use]
    pub fn version_binding(mut self, binding: VersionBinding) -> Self {
        self.version_binding = binding;
        self
    }

    /// Set which code signature updates must carry. Defaults to
    /// [`CodeSigning::MatchInstalled`].
    #[must_use]
    pub fn code_signing(mut self, code_signing: CodeSigning) -> Self {
        self.code_signing = code_signing;
        self
    }

    /// Set how updates are installed. Defaults to
    /// [`InstallOptions::new`].
    #[must_use]
    pub fn install_options(mut self, options: InstallOptions) -> Self {
        self.install_options = options;
        self
    }

    /// Set whether bundle versions are compared. Defaults to
    /// [`BundleVersion::MustMatch`].
    #[must_use]
    pub fn bundle_version(mut self, bundle_version: BundleVersion) -> Self {
        self.bundle_version = bundle_version;
        self
    }

    /// Override the install location (defaults to the running app/bundle).
    #[must_use]
    pub fn install_root(mut self, path: impl Into<PathBuf>) -> Self {
        self.install_root = Some(path.into());
        self
    }

    /// Override the download directory (defaults to a fresh temp directory
    /// for each download).
    ///
    /// A configured directory persists between downloads, so an artifact
    /// that an earlier download left there is reused instead of downloaded
    /// again — but only if it has the published size and passes a published
    /// checksum or signature and the payload check. Without a checksum or
    /// signature to check it against, the file is downloaded again.
    #[must_use]
    pub fn download_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.download_dir = Some(path.into());
        self
    }

    /// Set the largest file, in bytes, the engine downloads. Defaults to
    /// [`DEFAULT_MAX_DOWNLOAD_SIZE`].
    #[must_use]
    pub fn max_download_size(mut self, bytes: u64) -> Self {
        self.max_download_size = bytes;
        self
    }

    /// Enable or disable trying binary deltas before the full artifact.
    /// Defaults to `true`. Has no effect without the `delta` feature.
    #[must_use]
    pub fn deltas(mut self, enabled: bool) -> Self {
        self.deltas = enabled;
        self
    }

    /// Set the longest chain of deltas to download. `1` only uses a delta
    /// from the installed version itself.
    #[must_use]
    pub fn max_delta_hops(mut self, hops: usize) -> Self {
        self.max_delta_hops = hops;
        self
    }

    /// Download with `http`'s extra headers and proxy: the artifact, deltas,
    /// and their checksum and signature files. Metadata requests use the
    /// options set on the source.
    #[must_use]
    pub fn http(mut self, http: HttpOptions) -> Self {
        self.http = http;
        self
    }

    /// Fail closed when the policy requires a check the release *metadata*
    /// cannot satisfy (no public key, no advertised signature, no checksum).
    ///
    /// Run at check time so an obviously unverifiable release is not surfaced
    /// as available, and again before a download. This validates presence
    /// only: a release advertising a `signature_url` passes here even if that
    /// URL later fails to fetch or yields an invalid signature — those are
    /// caught when the download is verified.
    pub(super) fn precheck(&self, release: &Release) -> Result<()> {
        self.precheck_integrity(Integrity::of_release(release))
    }

    /// [`precheck`](Self::precheck) for any downloadable file's metadata.
    pub(super) fn precheck_integrity(&self, file: Integrity<'_>) -> Result<()> {
        let what = file.what;
        if self.verification.requires_signature() && !self.can_verify_signature_of(file) {
            if self.minisign_public_keys.is_empty() && self.ed25519_public_key.is_none() {
                return Err(Error::VerificationRequired(
                    "policy requires a signature, but no minisign or Ed25519 public key is configured"
                        .into(),
                ));
            }
            return Err(Error::VerificationRequired(format!(
                "policy requires a signature, but the {what} publishes none that a configured key can verify"
            )));
        }
        if self.verification.requires_checksum() && !file.has_checksum() {
            return Err(Error::VerificationRequired(format!(
                "policy requires a SHA-256 checksum, but the {what} publishes none"
            )));
        }
        Ok(())
    }

    /// Whether at least one signature the file advertises has a matching
    /// configured key.
    fn can_verify_signature_of(&self, file: Integrity<'_>) -> bool {
        let minisign = !self.minisign_public_keys.is_empty() && file.has_minisign();
        let ed25519 =
            self.ed25519_public_key.is_some() && non_empty(file.ed25519_signature).is_some();
        minisign || ed25519
    }

    /// Verify a downloaded file under the configured policy. `version` is
    /// the version the file must be signed for. Fails closed first (so a
    /// policy-required-but-missing input is rejected before the file is read),
    /// then runs whatever checks the metadata does provide. Returns whether a
    /// published checksum or signature was actually checked.
    pub(super) fn verify_file(
        &self,
        path: &Path,
        file: Integrity<'_>,
        version: &Version,
    ) -> Result<bool> {
        let policy = self.verification;
        if policy.skips_all() {
            return Ok(false);
        }
        // `download` is public and may be called without `check`, so re-run the
        // check-time gate here rather than trusting the caller went through it.
        self.precheck_integrity(file)?;

        let mut verified_checksum = false;
        match resolve_checksum(file, &self.http)? {
            Some(expected) => {
                verify::verify_sha256(path, &expected)?;
                verified_checksum = true;
            }
            None if policy.requires_checksum() => {
                return Err(Error::VerificationRequired(format!(
                    "policy requires a SHA-256 checksum, but the published checksums list no `{}`",
                    file.name
                )));
            }
            None => {}
        }
        let mut verified_signature = false;
        if let (Some(key), Some(signature)) =
            (&self.ed25519_public_key, non_empty(file.ed25519_signature))
        {
            verify::verify_ed25519(path, key, signature)?;
            verified_signature = true;
        }
        if !self.minisign_public_keys.is_empty() {
            if let Some(signature) = resolve_minisign(file, &self.http)? {
                let keys: Vec<&str> = self
                    .minisign_public_keys
                    .iter()
                    .map(String::as_str)
                    .collect();
                let comment = verify::verify_minisign_file(path, &keys, &signature)?;
                self.check_signed_version(&comment, version)?;
                verified_signature = true;
            }
        }
        // `precheck` may have accepted a non-empty `signature_url` whose fetched
        // body turned out blank. Fail closed instead of relying on a verifier to
        // reject an empty signature string.
        if policy.requires_signature() && !verified_signature {
            return Err(Error::VerificationRequired(
                "policy requires a signature, but the published signature is empty".into(),
            ));
        }
        Ok(verified_checksum || verified_signature)
    }

    fn check_signed_version(&self, trusted_comment: &str, expected: &Version) -> Result<()> {
        match verify::signed_version(trusted_comment) {
            Some(signed) => {
                let matches = crate::release::parse_tag(signed)
                    .is_ok_and(|v| v.cmp_precedence(expected).is_eq());
                if matches {
                    Ok(())
                } else {
                    Err(Error::Signature(format!(
                        "file is signed for version {signed}, expected {expected}"
                    )))
                }
            }
            None if self.version_binding == VersionBinding::Required => Err(Error::Signature(
                "the signature's trusted comment names no `version:`".into(),
            )),
            None => Ok(()),
        }
    }
}

/// The integrity inputs published for one downloadable file.
#[derive(Clone, Copy)]
pub(super) struct Integrity<'a> {
    /// What the file is, for error messages (`release` / `delta`).
    what: &'static str,
    /// The file's published name, looked up in a checksums file.
    name: &'a str,
    sha256: Option<&'a str>,
    checksums_url: Option<&'a str>,
    signature: Option<&'a str>,
    signature_url: Option<&'a str>,
    ed25519_signature: Option<&'a str>,
}

impl<'a> Integrity<'a> {
    pub(super) fn of_release(release: &'a Release) -> Self {
        Self {
            what: "release",
            name: &release.asset.name,
            sha256: release.sha256.as_deref(),
            checksums_url: None,
            signature: release.signature.as_deref(),
            signature_url: release.signature_url.as_deref(),
            ed25519_signature: release.ed25519_signature.as_deref(),
        }
    }

    #[cfg_attr(
        all(not(feature = "delta"), not(test)),
        expect(dead_code, reason = "only deltas are verified this way")
    )]
    pub(super) fn of_delta(delta: &'a DeltaAsset) -> Self {
        Self {
            what: "delta",
            name: &delta.asset.name,
            sha256: delta.sha256.as_deref(),
            checksums_url: delta.checksums_url.as_deref(),
            signature: delta.signature.as_deref(),
            signature_url: delta.signature_url.as_deref(),
            ed25519_signature: delta.ed25519_signature.as_deref(),
        }
    }

    /// Whether a minisign signature is advertised, inline or by URL.
    fn has_minisign(self) -> bool {
        non_empty(self.signature).is_some() || non_empty(self.signature_url).is_some()
    }

    /// Whether a checksum is advertised, inline or in a checksums file.
    fn has_checksum(self) -> bool {
        non_empty(self.sha256).is_some() || non_empty(self.checksums_url).is_some()
    }
}

/// Trim `s` and treat a blank string as absent.
fn non_empty(s: Option<&str>) -> Option<&str> {
    s.map(str::trim).filter(|s| !s.is_empty())
}

/// The expected SHA-256 of a file: the inline value if present, otherwise
/// looked up in the checksums file at `checksums_url`.
fn resolve_checksum(file: Integrity<'_>, http: &HttpOptions) -> Result<Option<String>> {
    if let Some(sha256) = non_empty(file.sha256) {
        return Ok(Some(sha256.to_string()));
    }
    match non_empty(file.checksums_url) {
        Some(url) => Ok(verify::sha256_from_sums(
            &http::get_string(url, &[], Metadata::Sidecar, http)?,
            file.name,
        )),
        None => Ok(None),
    }
}

/// The minisign signature for a file: the inline value if present, otherwise
/// fetched from `signature_url`. `None` when the release advertises neither,
/// or when a fetched signature body is blank.
fn resolve_minisign(file: Integrity<'_>, http: &HttpOptions) -> Result<Option<String>> {
    if let Some(signature) = non_empty(file.signature) {
        return Ok(Some(signature.to_string()));
    }
    if let Some(url) = non_empty(file.signature_url) {
        let body = http::get_string(url, &[], Metadata::Sidecar, http)?;
        return Ok(non_empty(Some(&body)).map(str::to_string));
    }
    Ok(None)
}