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
//! Integrity and authenticity checks for downloaded artifacts.
#![doc = include_str!("../docs/verification.md")]

use std::fmt::Write as _;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use sha2::{Digest, Sha256};

use crate::error::{Error, Result};

/// Read buffer for streaming hashes and signature checks over large artifacts.
const CHUNK: usize = 64 * 1024;

/// Compute the lowercase hex SHA-256 of a file, streaming it in chunks.
///
/// # Errors
/// Returns [`Error::Io`] if the file cannot be read.
pub fn sha256_hex(path: &Path) -> Result<String> {
    let mut hasher = Sha256::new();
    for_each_chunk(path, |chunk| hasher.update(chunk))?;
    let mut out = String::with_capacity(64);
    for byte in hasher.finalize() {
        let _ = write!(out, "{byte:02x}");
    }
    Ok(out)
}

/// Feed the contents of the file at `path` to `consume`, one chunk at a time,
/// so large artifacts are never held in memory.
fn for_each_chunk(path: &Path, mut consume: impl FnMut(&[u8])) -> Result<()> {
    let mut file = File::open(path)?;
    let mut buf = vec![0u8; CHUNK];
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            return Ok(());
        }
        consume(&buf[..n]);
    }
}

/// Verify a file against an expected hex SHA-256 (case-insensitive).
///
/// # Errors
/// Returns [`Error::ChecksumMismatch`] if the digests differ.
pub fn verify_sha256(path: &Path, expected_hex: &str) -> Result<()> {
    let actual = sha256_hex(path)?;
    if actual.eq_ignore_ascii_case(expected_hex.trim()) {
        Ok(())
    } else {
        Err(Error::ChecksumMismatch {
            expected: expected_hex.trim().to_ascii_lowercase(),
            actual,
        })
    }
}

/// Verify a file against a detached [minisign] signature.
///
/// - `public_key`: the base64 minisign public key (the second line of a
///   `minisign.pub`, or the whole single-line key).
/// - `signature`: the contents of the `.minisig` file.
///
/// The file is streamed, so large disk images are not read into memory.
///
/// [minisign]: https://jedisct1.github.io/minisign/
///
/// # Errors
/// Returns [`Error::Signature`] if the key/signature cannot be decoded or the
/// signature does not match the file's contents.
pub fn verify_minisign(path: &Path, public_key: &str, signature: &str) -> Result<()> {
    verify_minisign_file(path, &[public_key], signature).map(drop)
}

/// Verify the file at `path` against a detached minisign signature made by
/// any of `public_keys`, and return the signature's trusted comment.
///
/// Like [`verify_minisign_bytes`], but the file is streamed rather than read
/// into memory. Only the default, pre-hashed minisign signatures are accepted
/// (legacy ones are rejected either way).
///
/// # Errors
/// Returns [`Error::Signature`] if no key is given, the signature cannot be
/// decoded, or no key verifies it, and [`Error::Io`] if the file cannot be
/// read.
pub fn verify_minisign_file(path: &Path, public_keys: &[&str], signature: &str) -> Result<String> {
    let sig = decode_minisign(signature)?;
    let mut last = Error::Signature("no minisign public key configured".into());
    for key in public_keys {
        let pk = match decode_minisign_key(key) {
            Ok(pk) => pk,
            Err(e) => {
                last = e;
                continue;
            }
        };
        // Fails without reading the file when the key ID does not match, so a
        // file is normally streamed once even with several keys configured.
        let mut verifier = match pk.verify_stream(&sig) {
            Ok(verifier) => verifier,
            Err(e) => {
                last = Error::Signature(e.to_string());
                continue;
            }
        };
        for_each_chunk(path, |chunk| verifier.update(chunk))?;
        match verifier.finalize() {
            Ok(()) => return Ok(sig.trusted_comment().to_string()),
            Err(e) => last = Error::Signature(e.to_string()),
        }
    }
    Err(last)
}

/// Verify `data` against a detached minisign signature made by any of
/// `public_keys`, and return the signature's trusted comment.
///
/// Accepting several keys lets a publisher rotate keys: ship the new key next
/// to the old one, then start signing with it. The trusted comment is covered
/// by the signature, so it can carry authenticated metadata such as the
/// `version:` token read by [`signed_version`].
///
/// # Errors
/// Returns [`Error::Signature`] if no key is given, the signature cannot be
/// decoded, or no key verifies it.
pub fn verify_minisign_bytes(data: &[u8], public_keys: &[&str], signature: &str) -> Result<String> {
    let sig = decode_minisign(signature)?;
    let mut last = Error::Signature("no minisign public key configured".into());
    for key in public_keys {
        let verified = decode_minisign_key(key).and_then(|pk| {
            pk.verify(data, &sig, false)
                .map_err(|e| Error::Signature(e.to_string()))
        });
        match verified {
            Ok(()) => return Ok(sig.trusted_comment().to_string()),
            Err(e) => last = e,
        }
    }
    Err(last)
}

fn decode_minisign(signature: &str) -> Result<minisign_verify::Signature> {
    minisign_verify::Signature::decode(signature)
        .map_err(|e| Error::Signature(format!("invalid signature: {e}")))
}

fn decode_minisign_key(key: &str) -> Result<minisign_verify::PublicKey> {
    minisign_verify::PublicKey::from_base64(key.trim())
        .map_err(|e| Error::Signature(format!("invalid public key: {e}")))
}

/// The value of the `version:` token in a minisign trusted comment, if any.
///
/// Tokens are separated by whitespace, as in minisign's own
/// `timestamp:<n>\tfile:<name>` comments. Sign with, for example,
/// `minisign -S -t "version:1.2.3 file:App.dmg" -m App.dmg` to bind a file to
/// the version it claims to be, so an older signed file cannot be served in
/// place of a newer one.
pub fn signed_version(trusted_comment: &str) -> Option<&str> {
    trusted_comment
        .split_whitespace()
        .find_map(|token| token.strip_prefix("version:"))
        .filter(|v| !v.is_empty())
}

/// Find the SHA-256 for `asset_name` in the contents of a `shasum`-style file.
///
/// Lines look like `<hex>  <path>` (an optional `*` marks binary mode); the
/// `<path>` may carry a directory prefix, so matching is by basename.
pub(crate) fn sha256_from_sums(sums: &str, asset_name: &str) -> Option<String> {
    for line in sums.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let (Some(hash), Some(path)) = (parts.next(), parts.next()) else {
            continue;
        };
        let path = path.strip_prefix('*').unwrap_or(path);
        let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
        if base == asset_name {
            return Some(hash.to_ascii_lowercase());
        }
    }
    None
}

/// Verify a file against a Sparkle-style Ed25519 signature.
///
/// This is the scheme behind a Sparkle appcast's `sparkle:edSignature`: a plain
/// (non-prehashed) Ed25519 signature over the file's raw bytes, checked against
/// the app's `SUPublicEDKey`. Signatures printed by Sparkle's `sign_update`
/// verify here unchanged.
///
/// - `public_key`: base64 of the 32-byte public key (`SUPublicEDKey`).
/// - `signature`: base64 of the 64-byte signature (`sparkle:edSignature`).
///
/// The file is streamed, so large disk images are not read into memory.
///
/// # Errors
/// Returns [`Error::Signature`] if the key or signature cannot be decoded or
/// the signature does not match the file's contents, and [`Error::Io`] if the
/// file cannot be read.
pub fn verify_ed25519(path: &Path, public_key: &str, signature: &str) -> Result<()> {
    let pk = decode_base64("public key", public_key).and_then(|bytes| {
        ed25519_compact::PublicKey::from_slice(&bytes)
            .map_err(|e| Error::Signature(format!("invalid Ed25519 public key: {e}")))
    })?;
    let sig = decode_base64("signature", signature).and_then(|bytes| {
        ed25519_compact::Signature::from_slice(&bytes)
            .map_err(|e| Error::Signature(format!("invalid Ed25519 signature: {e}")))
    })?;
    let mut state = pk
        .verify_incremental(&sig)
        .map_err(|e| Error::Signature(format!("invalid Ed25519 signature: {e}")))?;
    for_each_chunk(path, |chunk| state.absorb(chunk))?;
    state
        .verify()
        .map_err(|_| Error::Signature("Ed25519 signature does not match the file".into()))
}

fn decode_base64(what: &str, value: &str) -> Result<Vec<u8>> {
    BASE64
        .decode(value.trim())
        .map_err(|e| Error::Signature(format!("Ed25519 {what} is not valid base64: {e}")))
}

/// Helpers shared by tests across the crate.
#[cfg(test)]
pub(crate) mod test_support {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::BASE64;
    use base64::Engine as _;

    /// A temp file signed with a fixed Ed25519 test key. Deleted on drop.
    pub(crate) struct Ed25519Fixture {
        pub(crate) path: PathBuf,
        pub(crate) public_key: String,
        pub(crate) signature: String,
    }

    impl Ed25519Fixture {
        pub(crate) fn new(contents: &[u8]) -> Self {
            let seed = ed25519_compact::Seed::new([7; ed25519_compact::Seed::BYTES]);
            let pair = ed25519_compact::KeyPair::from_seed(seed);
            let signature = pair.sk.sign(contents, None);
            let path = unique_temp_path("ed25519");
            std::fs::write(&path, contents).unwrap();
            Self {
                path,
                public_key: BASE64.encode(*pair.pk),
                signature: BASE64.encode(*signature),
            }
        }
    }

    impl Drop for Ed25519Fixture {
        fn drop(&mut self) {
            // Best-effort cleanup of a temp file; a leftover is harmless.
            let _ = std::fs::remove_file(&self.path);
        }
    }

    /// A temp-file path no other test in this process will use.
    pub(crate) fn unique_temp_path(tag: &str) -> PathBuf {
        static NEXT: AtomicUsize = AtomicUsize::new(0);
        let n = NEXT.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!(
            "gpui-updater-test-{}-{tag}-{n}.bin",
            std::process::id()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn temp_file(contents: &[u8]) -> std::path::PathBuf {
        let path = test_support::unique_temp_path("sha256");
        let mut f = File::create(&path).unwrap();
        f.write_all(contents).unwrap();
        path
    }

    #[test]
    fn sha256_matches_known_vector() {
        // SHA-256("abc")
        let path = temp_file(b"abc");
        let got = sha256_hex(&path).unwrap();
        assert_eq!(
            got,
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert!(verify_sha256(&path, &got.to_uppercase()).is_ok());
        assert!(verify_sha256(&path, "deadbeef").is_err());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn reads_the_signed_version_token() {
        assert_eq!(
            signed_version("timestamp:1700000000\tfile:App.dmg\tversion:1.2.3"),
            Some("1.2.3")
        );
        assert_eq!(
            signed_version("version:v2.0.0-rc.1 file:x"),
            Some("v2.0.0-rc.1")
        );
        assert_eq!(signed_version("timestamp:1 file:App.dmg"), None);
        assert_eq!(signed_version("version: 1.2.3"), None);
    }

    #[test]
    fn rejects_signatures_without_keys_or_with_garbage() {
        assert!(matches!(
            verify_minisign_bytes(b"x", &[], "not a signature"),
            Err(Error::Signature(_))
        ));
    }

    #[test]
    fn streams_minisign_verification_across_chunks() {
        // Larger than one read chunk, so the signature covers several.
        let data: Vec<u8> = (0u8..=255).cycle().take(CHUNK * 3 + 17).collect();
        let (signer, other) = (
            minisign::KeyPair::generate_unencrypted_keypair().unwrap(),
            minisign::KeyPair::generate_unencrypted_keypair().unwrap(),
        );
        let signature = minisign::sign(
            None,
            &signer.sk,
            std::io::Cursor::new(&data),
            Some("file:app.dmg\tversion:1.0.0"),
            None,
        )
        .unwrap()
        .to_string();
        let (key, other_key) = (signer.pk.to_base64(), other.pk.to_base64());
        let path = temp_file(&data);

        // The signing key may come after keys that do not match.
        let comment = verify_minisign_file(&path, &[&other_key, &key], &signature).unwrap();
        assert_eq!(comment, "file:app.dmg\tversion:1.0.0");
        assert!(verify_minisign(&path, &key, &signature).is_ok());
        assert!(matches!(
            verify_minisign_file(&path, &[&other_key], &signature),
            Err(Error::Signature(_))
        ));

        let mut tampered = data;
        tampered[CHUNK * 2] ^= 1;
        std::fs::write(&path, &tampered).unwrap();
        assert!(matches!(
            verify_minisign_file(&path, &[&key], &signature),
            Err(Error::Signature(_))
        ));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn parses_checksum_by_basename_ignoring_dir_prefix() {
        let sums = "\
abc123  dist/app-macos.dmg
DEF456 *dist/app-linux.tar.gz
";
        assert_eq!(
            sha256_from_sums(sums, "app-macos.dmg").as_deref(),
            Some("abc123")
        );
        assert_eq!(
            sha256_from_sums(sums, "app-linux.tar.gz").as_deref(),
            Some("def456")
        );
        assert!(sha256_from_sums(sums, "app-windows.exe").is_none());
    }

    #[test]
    fn ed25519_accepts_valid_and_rejects_tampered_files() {
        let fixture = test_support::Ed25519Fixture::new(b"abc");
        assert!(verify_ed25519(&fixture.path, &fixture.public_key, &fixture.signature).is_ok());

        std::fs::write(&fixture.path, b"abd").unwrap();
        assert!(matches!(
            verify_ed25519(&fixture.path, &fixture.public_key, &fixture.signature),
            Err(Error::Signature(_))
        ));
    }

    #[test]
    fn ed25519_rejects_malformed_keys_and_signatures() {
        let fixture = test_support::Ed25519Fixture::new(b"abc");
        for (key, sig) in [
            ("not base64!", fixture.signature.as_str()),
            ("AAAA", fixture.signature.as_str()),
            (fixture.public_key.as_str(), "AAAA"),
        ] {
            assert!(matches!(
                verify_ed25519(&fixture.path, key, sig),
                Err(Error::Signature(_))
            ));
        }
    }

    /// Golden values produced by Sparkle 2.10.0's own tools, so this pins
    /// compatibility with `sparkle:edSignature` rather than with ourselves.
    ///
    /// - Private key: the 32-byte seed `[7; 32]`, passed to Sparkle as
    ///   `sign_update --ed-key-file` (base64 `BwcH…Bwc=`).
    /// - Public key: derived from that seed independently with
    ///   `openssl pkey -pubout` (what `SUPublicEDKey` would hold).
    /// - Signature: `sign_update -p` over the payload below.
    #[test]
    fn ed25519_verifies_signatures_made_by_sparkle_sign_update() {
        const SPARKLE_PUBLIC_KEY: &str = "6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=";
        const SPARKLE_SIGNATURE: &str = "fkZSsqZWXCJYAnlGh01EaGCGfLf0DLUpVDF6d7qpDPyexRhMbj85AAF61DR7ksXSCa/Yw1lZk6kDSYJOvioFAQ==";

        // 70 KiB, so the streaming verifier crosses a chunk boundary.
        let payload: Vec<u8> = (0..70 * 1024u32)
            .map(|i| u8::try_from((i * 31 + 7) % 251).unwrap())
            .collect();
        let path = temp_file(&payload);
        assert!(verify_ed25519(&path, SPARKLE_PUBLIC_KEY, SPARKLE_SIGNATURE).is_ok());

        let mut tampered = payload;
        tampered[CHUNK] ^= 1;
        std::fs::write(&path, &tampered).unwrap();
        assert!(verify_ed25519(&path, SPARKLE_PUBLIC_KEY, SPARKLE_SIGNATURE).is_err());
        let _ = std::fs::remove_file(&path);
    }
}