Skip to main content

toolblox_lib/
update.rs

1//! Fail-closed startup update decisions.
2
3#![cfg_attr(all(debug_assertions, not(test)), allow(dead_code))]
4
5use std::collections::BTreeMap;
6use std::fmt;
7
8use semver::Version;
9use serde::Deserialize;
10
11/// Manifest schema version this build understands.
12pub const MANIFEST_SCHEMA_VERSION: u32 = 1;
13/// How far in the future a manifest's `publishedAt` may be, to tolerate slow clocks.
14pub const MAX_CLOCK_SKEW_SECONDS: u64 = 300;
15/// Longest allowed time between a manifest's `publishedAt` and `expiresAt`.
16pub const MAX_MANIFEST_LIFETIME_SECONDS: u64 = 7 * 24 * 60 * 60;
17
18/// The signed release manifest. Unknown fields are rejected.
19#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
20#[serde(rename_all = "camelCase", deny_unknown_fields)]
21pub struct ReleaseManifest {
22    pub schema_version: u32,
23    pub channel: String,
24    pub version: Version,
25    /// Unix time the manifest was signed.
26    pub published_at: u64,
27    /// Unix time after which the manifest is refused.
28    pub expires_at: u64,
29    /// Installers keyed by Tauri updater target, such as `windows-x86_64`.
30    pub platforms: BTreeMap<String, UpdateArtifact>,
31}
32
33/// One platform's installer.
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
35#[serde(rename_all = "camelCase", deny_unknown_fields)]
36pub struct UpdateArtifact {
37    /// HTTPS download URL.
38    pub url: String,
39    /// Lowercase hex SHA-256 of the installer.
40    pub sha256: String,
41    /// Tauri updater signature of the installer.
42    pub signature: String,
43}
44
45/// A manifest whose signature has been checked. Only `verify_and_parse` creates one.
46pub struct VerifiedManifest(ReleaseManifest);
47
48impl VerifiedManifest {
49    /// Returns the verified manifest.
50    pub fn manifest(&self) -> &ReleaseManifest {
51        &self.0
52    }
53}
54
55/// Checks a detached manifest signature.
56pub trait ManifestSignatureVerifier {
57    /// Fails unless `detached_signature` signs exactly `manifest_bytes`.
58    fn verify(&self, manifest_bytes: &[u8], detached_signature: &[u8]) -> Result<(), String>;
59}
60
61/// Persists the highest verified release version.
62pub trait HighestSeenStore {
63    /// Returns the stored version, or `None` when none is stored.
64    fn load(&self) -> Result<Option<Version>, String>;
65    /// Replaces the stored version.
66    fn store(&self, version: &Version) -> Result<(), String>;
67}
68
69/// The installed app's state, used to judge a manifest.
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct ReleaseContext<'a> {
72    pub installed: &'a Version,
73    pub channel: &'a str,
74    /// Tauri updater target of this build.
75    pub target: &'a str,
76    /// Current Unix time.
77    pub now: u64,
78    /// Highest version verified before, which the manifest may not go below.
79    pub highest_seen: Option<&'a Version>,
80}
81
82/// What a valid manifest means for this install.
83#[derive(Clone, Debug, Eq, PartialEq)]
84pub enum ReleaseDecision {
85    /// The installed version is current; the app may open.
86    Current { version: Version },
87    /// A newer version must be installed before the app opens.
88    UpdateRequired {
89        version: Version,
90        artifact: UpdateArtifact,
91    },
92}
93
94/// Why a manifest was refused. Displays as a user-facing message.
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub enum ReleaseError {
97    BadSignature,
98    InvalidManifest(String),
99    UnsupportedSchema(u32),
100    WrongChannel { expected: String, found: String },
101    MissingTarget(String),
102    NotYetValid,
103    Expired,
104    ExcessiveLifetime,
105    Rollback { floor: Version, found: Version },
106    Persistence(String),
107}
108
109impl fmt::Display for ReleaseError {
110    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
111        let message = match self {
112            Self::BadSignature => {
113                "The update information couldn't be verified. Can you try again?".into()
114            }
115            Self::InvalidManifest(reason) => {
116                format!("The update information isn't valid ({reason}). Can you try again?")
117            }
118            Self::UnsupportedSchema(version) => format!(
119                "This updater can't read update format {version}. Would reinstalling Toolblox help?"
120            ),
121            Self::WrongChannel { expected, found } => format!(
122                "The update channel is {found}, not {expected}. Would reinstalling Toolblox help?"
123            ),
124            Self::MissingTarget(target) => {
125                format!("No update is available for {target}. Would reinstalling Toolblox help?")
126            }
127            Self::NotYetValid => {
128                "The update information is dated in the future. Is the system clock correct?".into()
129            }
130            Self::Expired => {
131                "The update information has expired. Is the connection working?".into()
132            }
133            Self::ExcessiveLifetime => {
134                "The update information has an excessive validity period. Can you try again?".into()
135            }
136            Self::Rollback { .. } => {
137                "The update service offered an older release. Can you try again later?".into()
138            }
139            Self::Persistence(reason) => {
140                format!("The verified version couldn't be saved ({reason}). Can you try again?")
141            }
142        };
143        formatter.write_str(&message)
144    }
145}
146
147impl std::error::Error for ReleaseError {}
148
149/// Verifies the signature before parsing, so unsigned bytes are never interpreted.
150pub fn verify_and_parse(
151    manifest_bytes: &[u8],
152    detached_signature: &[u8],
153    verifier: &impl ManifestSignatureVerifier,
154) -> Result<VerifiedManifest, ReleaseError> {
155    verifier
156        .verify(manifest_bytes, detached_signature)
157        .map_err(|_| ReleaseError::BadSignature)?;
158    let manifest = serde_json::from_slice(manifest_bytes)
159        .map_err(|error| ReleaseError::InvalidManifest(error.to_string()))?;
160    Ok(VerifiedManifest(manifest))
161}
162
163/// Judges a verified manifest: checks the schema, channel, validity window, lifetime, rollback
164/// floor, and this platform's artifact, then compares versions.
165///
166/// Only an exact version match admits the app. An older manifest is a rollback error.
167pub fn decide_release(
168    verified: &VerifiedManifest,
169    context: &ReleaseContext<'_>,
170) -> Result<ReleaseDecision, ReleaseError> {
171    let manifest = verified.manifest();
172    if manifest.schema_version != MANIFEST_SCHEMA_VERSION {
173        return Err(ReleaseError::UnsupportedSchema(manifest.schema_version));
174    }
175    if manifest.channel != context.channel {
176        return Err(ReleaseError::WrongChannel {
177            expected: context.channel.into(),
178            found: manifest.channel.clone(),
179        });
180    }
181    if manifest.published_at > context.now.saturating_add(MAX_CLOCK_SKEW_SECONDS) {
182        return Err(ReleaseError::NotYetValid);
183    }
184    if manifest.expires_at <= context.now {
185        return Err(ReleaseError::Expired);
186    }
187    if manifest.expires_at <= manifest.published_at
188        || manifest.expires_at - manifest.published_at > MAX_MANIFEST_LIFETIME_SECONDS
189    {
190        return Err(ReleaseError::ExcessiveLifetime);
191    }
192
193    let floor = context
194        .highest_seen
195        .filter(|seen| *seen > context.installed)
196        .unwrap_or(context.installed);
197    if &manifest.version < floor {
198        return Err(ReleaseError::Rollback {
199            floor: floor.clone(),
200            found: manifest.version.clone(),
201        });
202    }
203
204    validate_artifact(
205        manifest
206            .platforms
207            .get(context.target)
208            .ok_or_else(|| ReleaseError::MissingTarget(context.target.into()))?,
209    )?;
210
211    if manifest.version == *context.installed {
212        return Ok(ReleaseDecision::Current {
213            version: manifest.version.clone(),
214        });
215    }
216    if manifest.version < *context.installed {
217        return Err(ReleaseError::Rollback {
218            floor: context.installed.clone(),
219            found: manifest.version.clone(),
220        });
221    }
222
223    Ok(ReleaseDecision::UpdateRequired {
224        version: manifest.version.clone(),
225        artifact: manifest.platforms[context.target].clone(),
226    })
227}
228
229/// Runs `decide_release` with the stored highest version and records a newer verified version,
230/// even when an update is then required.
231pub fn decide_and_record(
232    verified: &VerifiedManifest,
233    installed: &Version,
234    channel: &str,
235    target: &str,
236    now: u64,
237    store: &impl HighestSeenStore,
238) -> Result<ReleaseDecision, ReleaseError> {
239    let highest_seen = store.load().map_err(ReleaseError::Persistence)?;
240    let decision = decide_release(
241        verified,
242        &ReleaseContext {
243            installed,
244            channel,
245            target,
246            now,
247            highest_seen: highest_seen.as_ref(),
248        },
249    )?;
250    let verified_version = &verified.manifest().version;
251    if highest_seen
252        .as_ref()
253        .is_none_or(|seen| verified_version > seen)
254    {
255        store
256            .store(verified_version)
257            .map_err(ReleaseError::Persistence)?;
258    }
259    Ok(decision)
260}
261
262/// Requires an HTTPS URL, a 64-character hex SHA-256, and a non-empty signature.
263fn validate_artifact(artifact: &UpdateArtifact) -> Result<(), ReleaseError> {
264    if !artifact.url.starts_with("https://") {
265        return Err(ReleaseError::InvalidManifest(
266            "the artifact URL isn't HTTPS".into(),
267        ));
268    }
269    if artifact.sha256.len() != 64 || !artifact.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
270    {
271        return Err(ReleaseError::InvalidManifest(
272            "the artifact SHA-256 is malformed".into(),
273        ));
274    }
275    if artifact.signature.trim().is_empty() {
276        return Err(ReleaseError::InvalidManifest(
277            "the updater signature is missing".into(),
278        ));
279    }
280    Ok(())
281}
282
283#[cfg(test)]
284mod tests {
285    use std::cell::RefCell;
286
287    use super::*;
288
289    struct AcceptSignature;
290
291    impl ManifestSignatureVerifier for AcceptSignature {
292        fn verify(&self, _: &[u8], _: &[u8]) -> Result<(), String> {
293            Ok(())
294        }
295    }
296
297    #[derive(Default)]
298    struct MemoryStore(RefCell<Option<Version>>);
299
300    impl HighestSeenStore for MemoryStore {
301        fn load(&self) -> Result<Option<Version>, String> {
302            Ok(self.0.borrow().clone())
303        }
304
305        fn store(&self, version: &Version) -> Result<(), String> {
306            self.0.replace(Some(version.clone()));
307            Ok(())
308        }
309    }
310
311    fn manifest(version: &str) -> VerifiedManifest {
312        let json = format!(
313            r#"{{"schemaVersion":1,"channel":"stable","version":"{version}","publishedAt":1000,"expiresAt":2000,"platforms":{{"windows-x86_64":{{"url":"https://example.test/update.zip","sha256":"{}","signature":"signed"}}}}}}"#,
314            "a".repeat(64)
315        );
316        verify_and_parse(json.as_bytes(), b"signature", &AcceptSignature).unwrap()
317    }
318
319    fn version(value: &str) -> Version {
320        Version::parse(value).unwrap()
321    }
322
323    #[test]
324    fn current_release_is_the_only_release_decision_that_admits_the_ui() {
325        let current = ReleaseDecision::Current {
326            version: version("1.1.0"),
327        };
328        let update = ReleaseDecision::UpdateRequired {
329            version: version("1.1.0"),
330            artifact: manifest("1.1.0").manifest().platforms["windows-x86_64"].clone(),
331        };
332        assert!(matches!(current, ReleaseDecision::Current { .. }));
333        assert!(!matches!(update, ReleaseDecision::Current { .. }));
334    }
335
336    #[test]
337    fn expired_and_rollback_manifests_fail_closed() {
338        let release = manifest("1.1.0");
339        let expired = decide_release(
340            &release,
341            &ReleaseContext {
342                installed: &version("1.0.0"),
343                channel: "stable",
344                target: "windows-x86_64",
345                now: 2000,
346                highest_seen: None,
347            },
348        );
349        assert_eq!(expired, Err(ReleaseError::Expired));
350
351        let installed = version("1.0.0");
352        let highest = version("1.2.0");
353        let rollback = decide_release(
354            &release,
355            &ReleaseContext {
356                installed: &installed,
357                channel: "stable",
358                target: "windows-x86_64",
359                now: 1500,
360                highest_seen: Some(&highest),
361            },
362        );
363        assert!(matches!(rollback, Err(ReleaseError::Rollback { .. })));
364    }
365
366    #[test]
367    fn valid_new_release_is_recorded_before_installation() {
368        let store = MemoryStore::default();
369        let decision = decide_and_record(
370            &manifest("1.1.0"),
371            &version("1.0.0"),
372            "stable",
373            "windows-x86_64",
374            1500,
375            &store,
376        )
377        .unwrap();
378        assert!(matches!(decision, ReleaseDecision::UpdateRequired { .. }));
379        assert_eq!(store.load().unwrap(), Some(version("1.1.0")));
380    }
381
382    #[test]
383    fn bad_signature_is_rejected_before_json_parsing() {
384        struct RejectSignature;
385        impl ManifestSignatureVerifier for RejectSignature {
386            fn verify(&self, _: &[u8], _: &[u8]) -> Result<(), String> {
387                Err("secret verifier detail".into())
388            }
389        }
390
391        assert!(matches!(
392            verify_and_parse(b"not json", b"bad", &RejectSignature),
393            Err(ReleaseError::BadSignature)
394        ));
395    }
396}