Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
update.rs

1//! The update channel of a Mac app: `stable` by default, `beta` when the person (or the product's admin) chooses it.
2//!
3//! The channel is data: the product gives the feed address as a template with `{channel}` (for instance
4//! `https://github.com/krizaka/verikora/releases/download/desktop-{channel}/latest.json`), the kit fills it.
5//!
6//! What the kit wires, and what it does not:
7//! - it stores the channel on the Mac and gives the feed of that channel ([`feed_url`]: HTTPS, no credentials, names the
8//!   channel);
9//! - it downloads nothing and installs nothing. An app that ships updates registers Tauri's updater plugin itself, and
10//!   that plugin checks each download against the `pubkey` of the app's `plugins.updater` configuration;
11//! - so the kit refuses to start when the app gives a feed, or configures the updater, without a public key
12//!   ([`require_pubkey`]): a feed address alone must never be able to install anything.
13
14use serde::{Deserialize, Serialize};
15use std::fmt;
16use std::str::FromStr;
17use url::Url;
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Channel {
22    #[default]
23    Stable,
24    Beta,
25}
26
27impl Channel {
28    pub const ALL: [Channel; 2] = [Channel::Stable, Channel::Beta];
29
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Channel::Stable => "stable",
33            Channel::Beta => "beta",
34        }
35    }
36}
37
38impl fmt::Display for Channel {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(self.as_str())
41    }
42}
43
44/// The text is not the name of a channel. The text is not repeated: it came from outside.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct UnknownChannel;
47
48impl UnknownChannel {
49    /// The stable code the page reads.
50    pub fn code(self) -> &'static str {
51        "unknown_channel"
52    }
53}
54
55impl fmt::Display for UnknownChannel {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str("unknown update channel")
58    }
59}
60
61impl std::error::Error for UnknownChannel {}
62
63impl FromStr for Channel {
64    type Err = UnknownChannel;
65
66    fn from_str(input: &str) -> Result<Self, Self::Err> {
67        Channel::ALL
68            .into_iter()
69            .find(|c| c.as_str() == input.trim())
70            .ok_or(UnknownChannel)
71    }
72}
73
74/// Why a feed template cannot be used.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum FeedError {
77    /// The template does not contain `{channel}`.
78    MissingChannel,
79    NotAUrl,
80    NotHttps,
81    Credentials,
82}
83
84impl FeedError {
85    /// The stable code the page reads.
86    pub fn code(self) -> &'static str {
87        match self {
88            FeedError::MissingChannel => "feed_missing_channel",
89            FeedError::NotAUrl => "feed_not_a_url",
90            FeedError::NotHttps => "feed_not_https",
91            FeedError::Credentials => "feed_credentials",
92        }
93    }
94}
95
96impl fmt::Display for FeedError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(match self {
99            FeedError::MissingChannel => "the update feed must name {channel}",
100            FeedError::NotAUrl => "the update feed is not a valid URL",
101            FeedError::NotHttps => "the update feed must be served over https",
102            FeedError::Credentials => "no credentials in the update feed",
103        })
104    }
105}
106
107impl std::error::Error for FeedError {}
108
109/// The app configures the updater (or gives a feed) without a public key.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct MissingPubkey;
112
113impl MissingPubkey {
114    /// The stable code the page reads.
115    pub fn code(self) -> &'static str {
116        "updater_missing_pubkey"
117    }
118}
119
120impl fmt::Display for MissingPubkey {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.write_str("the updater needs a pubkey in plugins.updater of tauri.conf.json")
123    }
124}
125
126impl std::error::Error for MissingPubkey {}
127
128/// The feed of `channel`: the template with `{channel}` filled in. The template must be an HTTPS address without
129/// credentials and must name the channel, so a beta build never reads the stable feed by mistake.
130pub fn feed_url(template: &str, channel: Channel) -> Result<Url, FeedError> {
131    if !template.contains("{channel}") {
132        return Err(FeedError::MissingChannel);
133    }
134    let url = Url::parse(&template.replace("{channel}", channel.as_str()))
135        .map_err(|_| FeedError::NotAUrl)?;
136    if url.scheme() != "https" {
137        return Err(FeedError::NotHttps);
138    }
139    if !url.username().is_empty() || url.password().is_some() {
140        return Err(FeedError::Credentials);
141    }
142    Ok(url)
143}
144
145/// The app's updater configuration (`plugins.updater` of `tauri.conf.json`, `None` when it has none) holds a public key.
146///
147/// Called before the kit offers a feed or when the app configures the updater: without a key, nothing would check what
148/// the feed points to.
149pub fn require_pubkey(updater: Option<&serde_json::Value>) -> Result<(), MissingPubkey> {
150    let has_key = updater
151        .and_then(|section| section.get("pubkey"))
152        .and_then(serde_json::Value::as_str)
153        .is_some_and(|key| !key.trim().is_empty());
154    if has_key {
155        Ok(())
156    } else {
157        Err(MissingPubkey)
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    const FEED: &str =
166        "https://github.com/krizaka/verikora/releases/download/desktop-{channel}/latest.json";
167
168    #[test]
169    fn stable_is_the_default_and_a_channel_reads_back_from_its_name() {
170        assert_eq!(Channel::default(), Channel::Stable);
171        for channel in Channel::ALL {
172            assert_eq!(channel.as_str().parse::<Channel>().unwrap(), channel);
173        }
174        assert_eq!(" beta ".parse::<Channel>().unwrap(), Channel::Beta);
175        assert!("nightly".parse::<Channel>().is_err());
176        assert!("".parse::<Channel>().is_err());
177        assert_eq!(serde_json::to_string(&Channel::Beta).unwrap(), "\"beta\"");
178    }
179
180    #[test]
181    fn the_feed_names_the_channel() {
182        assert_eq!(
183            feed_url(FEED, Channel::Beta).unwrap().as_str(),
184            "https://github.com/krizaka/verikora/releases/download/desktop-beta/latest.json"
185        );
186        assert!(feed_url(FEED, Channel::Stable)
187            .unwrap()
188            .as_str()
189            .contains("desktop-stable"));
190    }
191
192    #[test]
193    fn refuses_a_feed_that_is_not_https_names_no_channel_or_carries_credentials() {
194        for bad in [
195            "http://github.com/{channel}/latest.json",
196            "https://github.com/latest.json",
197            "https://user:pw@github.com/{channel}/latest.json",
198            "file:///{channel}/latest.json",
199            "{channel}",
200        ] {
201            assert!(feed_url(bad, Channel::Stable).is_err(), "{bad}");
202        }
203    }
204
205    #[test]
206    fn the_updater_is_refused_without_a_public_key() {
207        let missing = [
208            None,
209            Some(serde_json::json!({})),
210            Some(serde_json::json!({ "endpoints": [FEED] })),
211            Some(serde_json::json!({ "pubkey": "" })),
212            Some(serde_json::json!({ "pubkey": "  \n" })),
213            Some(serde_json::json!({ "pubkey": null })),
214            Some(serde_json::json!({ "pubkey": 42 })),
215        ];
216        for updater in &missing {
217            assert!(require_pubkey(updater.as_ref()).is_err(), "{updater:?}");
218        }
219        let configured =
220            serde_json::json!({ "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk=" });
221        assert_eq!(require_pubkey(Some(&configured)), Ok(()));
222    }
223}