relswap 0.0.11

Signed-release install/update engine with durable activation and crash recovery
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
//! Signed release manifest schema and canonical validation.

use super::target::Target;
use super::{MAX_ARCHIVE_SIZE, MAX_MEMBER_SIZE, ReleaseError, Result};
use crate::App;
use chrono::{DateTime, Utc};
use semver::Version;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::ops::Deref;

/// The only manifest schema accepted by this build.
pub const MANIFEST_SCHEMA_VERSION: u32 = 2;

/// Host-clock tolerance applied by [`ReleaseManifest::ensure_not_expired`].
///
/// Large enough to absorb an unsynchronised clock, small enough to be irrelevant against the
/// year-scale validity window a publisher is expected to sign.
pub const EXPIRY_CLOCK_SKEW: chrono::TimeDelta = chrono::TimeDelta::hours(12);

/// Metadata for the exact executable member selected from an archive.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadInfo {
    pub path: String,
    pub sha256: String,
    pub size: u64,
}

impl PayloadInfo {
    pub fn new(path: impl Into<String>, size: u64, sha256: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            sha256: sha256.into(),
            size,
        }
    }
}

/// Metadata for the Windows-only launcher protocol member.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LauncherInfo {
    pub path: String,
    pub sha256: String,
    pub size: u64,
    pub protocol: u32,
}

impl LauncherInfo {
    pub fn new(
        path: impl Into<String>,
        protocol: u32,
        size: u64,
        sha256: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            sha256: sha256.into(),
            size,
            protocol,
        }
    }
}

/// One target's signed release asset record.
///
/// The target is intentionally not serialized here. It is the authenticated map key in
/// [`ReleaseManifest::targets`], so a caller cannot trust a redundant target field inside a signed
/// value after selecting an entry.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ReleaseAsset {
    pub archive: String,
    pub archive_sha256: String,
    pub archive_size: u64,
    pub payload: PayloadInfo,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launcher: Option<LauncherInfo>,
}

pub type Asset = ReleaseAsset;
pub type FileDigest = PayloadInfo;

impl ReleaseAsset {
    /// Construct an asset with canonical names and no launcher. Windows callers should use
    /// [`Self::with_launcher`] so the protocol field is explicit.
    pub fn new(
        app: &App,
        version: &Version,
        target: Target,
        archive_size: u64,
        archive_sha256: impl Into<String>,
        payload_size: u64,
        payload_sha256: impl Into<String>,
    ) -> Self {
        Self {
            archive: target.archive_name(app, version),
            archive_sha256: archive_sha256.into(),
            archive_size,
            payload: PayloadInfo::new(
                target.payload_path(app, version),
                payload_size,
                payload_sha256,
            ),
            launcher: None,
        }
    }

    pub fn with_launcher(
        mut self,
        app: &App,
        version: &Version,
        target: Target,
        protocol: u32,
        launcher_size: u64,
        launcher_sha256: impl Into<String>,
    ) -> Self {
        if let Some(path) = target.launcher_path(app, version) {
            self.launcher = Some(LauncherInfo::new(
                path,
                protocol,
                launcher_size,
                launcher_sha256,
            ));
        }
        self
    }

    pub fn validate(&self, app: &App, version: &Version, target: Target) -> Result<()> {
        let expected_archive = target.archive_name(app, version);
        if self.archive != expected_archive {
            return Err(ReleaseError::invalid(format!(
                "noncanonical archive name for {}: expected {expected_archive}, got {}",
                target, self.archive
            )));
        }
        validate_basename(&self.archive, "archive name")?;
        validate_size(self.archive_size, MAX_ARCHIVE_SIZE, "archive")?;
        validate_sha256(&self.archive_sha256, "archive")?;

        let expected_payload = target.payload_path(app, version);
        if self.payload.path != expected_payload {
            return Err(ReleaseError::invalid(format!(
                "noncanonical payload path for {}: expected {expected_payload}, got {}",
                target, self.payload.path
            )));
        }
        validate_member_path(&self.payload.path, "payload path")?;
        validate_size(self.payload.size, MAX_MEMBER_SIZE, "payload")?;
        validate_sha256(&self.payload.sha256, "payload")?;

        match (target.is_windows(), &self.launcher) {
            (true, Some(launcher)) => {
                let expected = target.launcher_path(app, version).ok_or_else(|| {
                    ReleaseError::invalid(format!(
                        "app does not configure a Windows launcher required by {target}"
                    ))
                })?;
                if launcher.path != expected {
                    return Err(ReleaseError::invalid(format!(
                        "noncanonical launcher path for {}: expected {expected}, got {}",
                        target, launcher.path
                    )));
                }
                if launcher.protocol != target.launcher_protocol(app).unwrap_or(0) {
                    return Err(ReleaseError::invalid(format!(
                        "unsupported launcher protocol {} for {}",
                        launcher.protocol, target
                    )));
                }
                validate_member_path(&launcher.path, "launcher path")?;
                validate_size(launcher.size, MAX_MEMBER_SIZE, "launcher")?;
                validate_sha256(&launcher.sha256, "launcher")?;
                if launcher.path == self.payload.path {
                    return Err(ReleaseError::invalid(
                        "payload and launcher paths must be distinct",
                    ));
                }
            }
            (true, None) => {
                return Err(ReleaseError::invalid(
                    "Windows release asset is missing its protocol-1 launcher",
                ));
            }
            (false, Some(_)) => {
                return Err(ReleaseError::invalid(format!(
                    "non-Windows release asset {} must not contain a launcher",
                    target
                )));
            }
            (false, None) => {}
        }
        Ok(())
    }

    pub fn archive_name(&self) -> &str {
        &self.archive
    }

    pub fn archive_size(&self) -> u64 {
        self.archive_size
    }

    pub fn archive_sha256(&self) -> &str {
        &self.archive_sha256
    }
}

/// A selected asset whose target comes from the authenticated map key, never from signed fields.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SelectedAsset<'a> {
    pub target: Target,
    pub asset: &'a ReleaseAsset,
}

impl<'a> SelectedAsset<'a> {
    pub fn new(target: Target, asset: &'a ReleaseAsset) -> Self {
        Self { target, asset }
    }

    pub fn archive(&self) -> &str {
        &self.asset.archive
    }

    pub fn archive_sha256(&self) -> &str {
        &self.asset.archive_sha256
    }

    pub fn archive_size(&self) -> u64 {
        self.asset.archive_size
    }

    pub fn payload(&self) -> &PayloadInfo {
        &self.asset.payload
    }

    pub fn launcher(&self) -> Option<&LauncherInfo> {
        self.asset.launcher.as_ref()
    }
}

impl Deref for SelectedAsset<'_> {
    type Target = ReleaseAsset;

    fn deref(&self) -> &Self::Target {
        self.asset
    }
}

/// Schema-versioned release metadata.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ReleaseManifest {
    pub schema_version: u32,
    #[serde(deserialize_with = "deserialize_canonical_version")]
    pub version: Version,
    pub published_at: String,
    pub expires_at: String,
    pub targets: BTreeMap<Target, ReleaseAsset>,
}

pub type Manifest = ReleaseManifest;

impl ReleaseManifest {
    pub fn new(
        app: &App,
        version: Version,
        published_at: impl Into<String>,
        expires_at: impl Into<String>,
        targets: BTreeMap<Target, ReleaseAsset>,
    ) -> Result<Self> {
        let manifest = Self {
            schema_version: MANIFEST_SCHEMA_VERSION,
            version,
            published_at: published_at.into(),
            expires_at: expires_at.into(),
            targets,
        };
        manifest.validate(app)?;
        Ok(manifest)
    }

    pub fn from_bytes(app: &App, bytes: &[u8]) -> Result<Self> {
        if bytes.len() > super::MAX_METADATA_SIZE {
            return Err(ReleaseError::invalid(format!(
                "release manifest exceeds {} bytes",
                super::MAX_METADATA_SIZE
            )));
        }
        let manifest: Self = serde_json::from_slice(bytes)?;
        manifest.validate(app)?;
        Ok(manifest)
    }

    pub fn from_json(app: &App, text: &str) -> Result<Self> {
        Self::from_bytes(app, text.as_bytes())
    }

    pub fn to_bytes(&self, app: &App) -> Result<Vec<u8>> {
        self.validate(app)?;
        Ok(serde_json::to_vec(self)?)
    }

    pub fn to_json(&self, app: &App) -> Result<String> {
        Ok(String::from_utf8(self.to_bytes(app)?)
            .expect("serde_json emits UTF-8 for a Rust string model"))
    }

    pub fn validate(&self, app: &App) -> Result<()> {
        if self.schema_version != MANIFEST_SCHEMA_VERSION {
            return Err(ReleaseError::invalid(format!(
                "unsupported release manifest schema_version {}",
                self.schema_version
            )));
        }
        if self.version.to_string().is_empty() {
            return Err(ReleaseError::invalid("release manifest version is empty"));
        }
        DateTime::parse_from_rfc3339(&self.published_at).map_err(|error| {
            ReleaseError::invalid(format!("invalid published_at RFC3339 timestamp: {error}"))
        })?;
        DateTime::parse_from_rfc3339(&self.expires_at).map_err(|error| {
            ReleaseError::invalid(format!("invalid expires_at RFC3339 timestamp: {error}"))
        })?;
        if self.targets.is_empty() {
            return Err(ReleaseError::invalid(
                "release manifest must contain at least one target",
            ));
        }
        if self.targets.len() > Target::ALL.len() {
            return Err(ReleaseError::invalid(format!(
                "release manifest contains too many targets: {}",
                self.targets.len()
            )));
        }
        let mut seen = HashSet::with_capacity(self.targets.len());
        for (target, asset) in &self.targets {
            if !seen.insert(*target) {
                return Err(ReleaseError::invalid(format!(
                    "duplicate release target {}",
                    target
                )));
            }
            asset.validate(app, &self.version, *target)?;
        }
        Ok(())
    }

    /// Reject a manifest whose validity window has closed.
    ///
    /// This is the freeze-attack defence: a signature stays valid forever, so without an expiry an
    /// attacker who can withhold responses could pin a client to a stale-but-authentic manifest.
    ///
    /// `now` comes from the host clock, which is not always right - a fresh VM before its first NTP
    /// sync can be hours or days off. [`EXPIRY_CLOCK_SKEW`] is subtracted so a modest skew degrades
    /// into a late expiry rather than a machine that cannot update at all. It is deliberately small
    /// relative to the year-scale validity window a publisher is expected to use.
    pub fn ensure_not_expired(&self, now: DateTime<Utc>) -> Result<()> {
        let expires_at = DateTime::parse_from_rfc3339(&self.expires_at)
            .map_err(|error| {
                ReleaseError::invalid(format!("invalid expires_at RFC3339 timestamp: {error}"))
            })?
            .with_timezone(&Utc);
        if now - EXPIRY_CLOCK_SKEW > expires_at {
            return Err(ReleaseError::invalid("release manifest has expired"));
        }
        Ok(())
    }

    /// Select metadata using the authenticated map key as the target authority.
    pub fn asset_for(&self, app: &App, target: Target) -> Result<SelectedAsset<'_>> {
        self.validate(app)?;
        let asset = self
            .targets
            .get(&target)
            .ok_or_else(|| ReleaseError::invalid(format!("release has no asset for {target}")))?;
        Ok(SelectedAsset { target, asset })
    }

    pub fn target_assets(&self) -> &BTreeMap<Target, ReleaseAsset> {
        &self.targets
    }
}

fn validate_size(size: u64, maximum: u64, label: &str) -> Result<()> {
    if size == 0 {
        return Err(ReleaseError::invalid(format!(
            "{label} size must be nonzero"
        )));
    }
    if size > maximum {
        return Err(ReleaseError::invalid(format!(
            "{label} size {size} exceeds maximum {maximum}"
        )));
    }
    Ok(())
}

pub(crate) fn validate_sha256(value: &str, label: &str) -> Result<()> {
    if value.len() != 64
        || !value
            .as_bytes()
            .iter()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(byte))
    {
        return Err(ReleaseError::invalid(format!(
            "invalid {label} SHA-256: expected 64 lowercase hexadecimal characters"
        )));
    }
    Ok(())
}

fn validate_basename(value: &str, label: &str) -> Result<()> {
    if value.is_empty()
        || value == "."
        || value == ".."
        || value.contains('/')
        || value.contains('\\')
        || value.contains('\0')
        || value.contains(':')
    {
        return Err(ReleaseError::invalid(format!(
            "noncanonical {label}: {value:?}"
        )));
    }
    Ok(())
}

fn validate_member_path(value: &str, label: &str) -> Result<()> {
    if value.is_empty()
        || value.starts_with('/')
        || value.contains('\\')
        || value.contains('\0')
        || value
            .split('/')
            .any(|part| part.is_empty() || part == "." || part == "..")
    {
        return Err(ReleaseError::invalid(format!(
            "noncanonical {label}: {value:?}"
        )));
    }
    if value
        .split('/')
        .next()
        .is_some_and(|component| component.contains(':'))
    {
        return Err(ReleaseError::invalid(format!(
            "noncanonical {label}: {value:?}"
        )));
    }
    Ok(())
}

fn deserialize_canonical_version<'de, D>(deserializer: D) -> std::result::Result<Version, D::Error>
where
    D: Deserializer<'de>,
{
    let raw = String::deserialize(deserializer)?;
    let parsed = Version::parse(&raw).map_err(serde::de::Error::custom)?;
    if parsed.to_string() != raw {
        return Err(serde::de::Error::custom(format!(
            "release version is not canonical: {raw}"
        )));
    }
    Ok(parsed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ActivationStrategy;

    const PUBLISHED_AT: &str = "2026-08-02T12:00:00Z";
    const EXPIRES_AT: &str = "2027-08-02T12:00:00Z";

    const TEST_APP: App = App {
        name: "hyprmux",
        version: "0.2.0",
        repository_url: "https://example.test/hyprmux/",
        trust_anchor: br#"{"schema_version":1,"keys":[]}"#,
        activation: ActivationStrategy::WindowsLauncher {
            launcher_name: "hyprmux-launcher.exe",
            protocol: 1,
        },
        self_test: None,
    };

    fn unix_asset(version: &Version, target: Target) -> ReleaseAsset {
        ReleaseAsset::new(
            &TEST_APP,
            version,
            target,
            10,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            3,
            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
        )
    }

    #[test]
    fn manifest_round_trips_authoritative_target_map_shape() {
        let version = Version::parse("0.2.0").unwrap();
        let target = Target::X86_64UnknownLinuxGnu;
        let asset = unix_asset(&version, target);
        let manifest = ReleaseManifest::new(
            &TEST_APP,
            version,
            PUBLISHED_AT,
            EXPIRES_AT,
            BTreeMap::from([(target, asset)]),
        )
        .unwrap();
        let bytes = manifest.to_bytes(&TEST_APP).unwrap();
        let json = String::from_utf8(bytes.clone()).unwrap();
        assert!(json.contains("\"published_at\":\"2026-08-02T12:00:00Z\""));
        assert!(json.contains("\"expires_at\":\"2027-08-02T12:00:00Z\""));
        assert!(json.contains("\"targets\":{"));
        assert!(!json.contains("\"target\":"));
        assert!(!json.contains("\"format\":"));
        assert!(!json.contains("\"artifacts\":"));
        assert!(json.contains("\"archive_sha256\":\""));
        assert!(!json.contains("\"archive\":{"));
        assert_eq!(
            ReleaseManifest::from_bytes(&TEST_APP, &bytes).unwrap(),
            manifest
        );
    }

    #[test]
    fn selected_asset_uses_map_key_as_target_authority() {
        let version = Version::parse("0.2.0").unwrap();
        let target = Target::Aarch64AppleDarwin;
        let manifest = ReleaseManifest::new(
            &TEST_APP,
            version.clone(),
            PUBLISHED_AT,
            EXPIRES_AT,
            BTreeMap::from([(target, unix_asset(&version, target))]),
        )
        .unwrap();
        let selected = manifest.asset_for(&TEST_APP, target).unwrap();
        assert_eq!(selected.target, target);
        assert_eq!(selected.archive(), target.archive_name(&TEST_APP, &version));
        assert_eq!(
            selected.asset.payload.path,
            target.payload_path(&TEST_APP, &version)
        );
    }

    #[test]
    fn manifest_rejects_unknown_fields_timestamps_hashes_and_sizes() {
        let version = Version::parse("0.2.0").unwrap();
        let target = Target::X86_64UnknownLinuxGnu;
        let asset = unix_asset(&version, target);
        let mut manifest = ReleaseManifest::new(
            &TEST_APP,
            version.clone(),
            PUBLISHED_AT,
            EXPIRES_AT,
            BTreeMap::from([(target, asset)]),
        )
        .unwrap();
        manifest.published_at = "not-a-timestamp".into();
        assert!(manifest.validate(&TEST_APP).is_err());
        manifest.published_at = PUBLISHED_AT.into();
        manifest.expires_at = "not-a-timestamp".into();
        assert!(manifest.validate(&TEST_APP).is_err());

        let mut oversized = unix_asset(&version, target);
        oversized.archive_size = MAX_ARCHIVE_SIZE + 1;
        assert!(oversized.validate(&TEST_APP, &version, target).is_err());

        let unknown = br#"{
            "schema_version":2,
            "version":"0.2.0",
            "published_at":"2026-08-02T12:00:00Z",
            "expires_at":"2027-08-02T12:00:00Z",
            "targets":{},
            "extra":true
        }"#;
        assert!(ReleaseManifest::from_bytes(&TEST_APP, unknown).is_err());
    }

    #[test]
    fn schema_v1_is_rejected_and_expiry_is_enforced() {
        let version = Version::parse("0.2.0").unwrap();
        let target = Target::X86_64UnknownLinuxGnu;
        let manifest = ReleaseManifest::new(
            &TEST_APP,
            version,
            PUBLISHED_AT,
            EXPIRES_AT,
            BTreeMap::from([(
                target,
                unix_asset(&Version::parse("0.2.0").unwrap(), target),
            )]),
        )
        .unwrap();
        let mut value = serde_json::to_value(&manifest).unwrap();
        value["schema_version"] = serde_json::json!(1);
        assert!(
            ReleaseManifest::from_bytes(&TEST_APP, &serde_json::to_vec(&value).unwrap()).is_err()
        );
        let at = |text: &str| {
            DateTime::parse_from_rfc3339(text)
                .unwrap()
                .with_timezone(&Utc)
        };
        // Inside the window.
        assert!(
            manifest
                .ensure_not_expired(at("2027-08-02T11:59:59Z"))
                .is_ok()
        );
        // Past `expires_at` but inside EXPIRY_CLOCK_SKEW: an unsynchronised host clock must not
        // make a current release uninstallable.
        assert!(
            manifest
                .ensure_not_expired(at("2027-08-02T23:59:59Z"))
                .is_ok()
        );
        // Past `expires_at` by more than the tolerance.
        assert!(
            manifest
                .ensure_not_expired(at("2027-08-03T00:00:01Z"))
                .is_err()
        );
    }
}