Skip to main content

tauri_plugin_update_gate/
source.rs

1//! Fetches the document over HTTP, keeps it briefly so every check doesn't
2//! hit the network, and never lets a failure lock anyone out. The fetch
3//! itself is behind the `Fetch` trait so tests can hand back canned
4//! responses instead of touching a socket.
5
6use std::io::Read;
7use std::sync::{Arc, Mutex};
8use std::time::{Duration, Instant};
9
10use async_trait::async_trait;
11use log::warn;
12
13use crate::decide::{decide, Document, Gate};
14
15/// The most of a response body the gate will read. The document is a few
16/// short strings; anything this large is not it, and reading on would only
17/// spend a phone's memory and data on a mistake.
18const MAX_BODY: u64 = 64 * 1024;
19
20/// Where to fetch the document from, how long to trust a cached copy, and
21/// how long to wait for the network before giving up.
22pub struct Config {
23    url: String,
24    ttl: Duration,
25    timeout: Duration,
26}
27
28impl Config {
29    /// Starts from a URL with the defaults: a 6-hour cache and a 5-second
30    /// network timeout.
31    pub fn url(u: impl Into<String>) -> Self {
32        Self {
33            url: u.into(),
34            ttl: Duration::from_secs(6 * 60 * 60),
35            timeout: Duration::from_secs(5),
36        }
37    }
38
39    /// Overrides how long a fetched document is trusted before it is
40    /// fetched again.
41    #[must_use]
42    pub fn ttl(mut self, d: Duration) -> Self {
43        self.ttl = d;
44        self
45    }
46
47    /// Overrides how long the fetch waits for a response.
48    #[must_use]
49    pub fn timeout(mut self, d: Duration) -> Self {
50        self.timeout = d;
51        self
52    }
53}
54
55/// Fetches the document body as text. Implemented by a real HTTP client in
56/// production and by a canned fake in tests, so `Source`'s caching and
57/// fail-open behaviour can be tested without a network.
58#[async_trait]
59pub trait Fetch: Send + Sync {
60    async fn get(&self, url: &str) -> Result<String, String>;
61}
62
63/// Fetches over HTTP with `ureq`, verifying TLS against the bundled Mozilla
64/// roots rather than the OS: the platform verifier needs JNI set up on
65/// Android, which a plugin with no native code cannot do, and panics without
66/// it. A non-2xx status is a failure, same as a transport error.
67struct UreqFetch(ureq::Agent);
68
69impl UreqFetch {
70    /// Every request, connect to last byte, is bounded by `timeout`. Building
71    /// the agent cannot fail, so there is no fallback client that could
72    /// forget the timeout.
73    fn new(timeout: Duration) -> Self {
74        let agent = ureq::Agent::config_builder()
75            .timeout_global(Some(timeout))
76            .build()
77            .into();
78        Self(agent)
79    }
80}
81
82#[async_trait]
83impl Fetch for UreqFetch {
84    async fn get(&self, url: &str) -> Result<String, String> {
85        // ureq blocks, so the request runs off the async workers.
86        let agent = self.0.clone();
87        let url = url.to_owned();
88        tauri::async_runtime::spawn_blocking(move || {
89            let mut response = agent.get(&url).call().map_err(|e| e.to_string())?;
90            let declared = response.body().content_length();
91            read_capped(declared, response.body_mut().as_reader(), MAX_BODY)
92        })
93        .await
94        .map_err(|e| e.to_string())?
95    }
96}
97
98/// Reads `body` as UTF-8, but no more than `cap` bytes of it: a declared
99/// length over the cap is refused before a byte is read, and a body that
100/// runs past the cap anyway (no length, or a wrong one) is refused as soon
101/// as it does.
102fn read_capped(declared: Option<u64>, body: impl Read, cap: u64) -> Result<String, String> {
103    if let Some(n) = declared.filter(|&n| n > cap) {
104        return Err(format!(
105            "document declares {n} bytes, over the {cap}-byte cap"
106        ));
107    }
108    let mut bytes = Vec::new();
109    body.take(cap + 1)
110        .read_to_end(&mut bytes)
111        .map_err(|e| e.to_string())?;
112    if bytes.len() as u64 > cap {
113        return Err(format!("document runs past the {cap}-byte cap"));
114    }
115    String::from_utf8(bytes).map_err(|e| e.to_string())
116}
117
118/// Fetches the document, caches a successfully parsed copy for `Config::ttl`,
119/// and turns any failure into an open gate rather than an error the caller
120/// has to handle.
121pub struct Source {
122    config: Config,
123    fetcher: Arc<dyn Fetch>,
124    cache: Mutex<Option<(Instant, Document)>>,
125}
126
127impl Source {
128    /// Builds a `Source` that fetches for real, over `ureq`, honouring
129    /// `Config::timeout`.
130    #[must_use]
131    pub fn new(config: Config) -> Self {
132        let fetcher = UreqFetch::new(config.timeout);
133        Self::with(config, fetcher)
134    }
135
136    /// Builds a `Source` around any `Fetch`, real or canned. Tests use this
137    /// to swap in a canned fetcher.
138    pub fn with(config: Config, fetcher: impl Fetch + 'static) -> Self {
139        Self {
140            config,
141            fetcher: Arc::new(fetcher),
142            cache: Mutex::new(None),
143        }
144    }
145
146    /// Decides whether `running` may still play. Reuses the cached document
147    /// while it's within the TTL; otherwise fetches, parses, and caches a
148    /// fresh one. Any failure along the way — network, HTTP status, or
149    /// malformed JSON — is logged and answered with an open gate instead of
150    /// being handed back to the caller.
151    pub async fn gate(&self, running: &str, lang: &str, platform: &str) -> Gate {
152        if let Some(doc) = self.cached() {
153            return decide(&doc, running, lang, platform);
154        }
155
156        match self.fetch_and_cache().await {
157            Ok(doc) => decide(&doc, running, lang, platform),
158            Err(e) => {
159                warn!("update-gate: {e}");
160                decide(&Document::default(), running, lang, platform)
161            }
162        }
163    }
164
165    /// Returns the cached document if it's still within the TTL.
166    fn cached(&self) -> Option<Document> {
167        let cache = self
168            .cache
169            .lock()
170            .unwrap_or_else(std::sync::PoisonError::into_inner);
171        cache.as_ref().and_then(|(at, doc)| {
172            (Instant::now().saturating_duration_since(*at) < self.config.ttl).then(|| doc.clone())
173        })
174    }
175
176    /// Fetches and parses the document, caching it on success only. The
177    /// fetch runs as its own task so that a panic anywhere in the network
178    /// stack comes back as an error here, and so as an open gate, instead
179    /// of unwinding through the command and leaving the app unanswered.
180    async fn fetch_and_cache(&self) -> Result<Document, String> {
181        let fetcher = Arc::clone(&self.fetcher);
182        let url = self.config.url.clone();
183        let body = tauri::async_runtime::spawn(async move { fetcher.get(&url).await })
184            .await
185            .map_err(|e| format!("fetch did not finish: {e}"))??;
186        let doc: Document = serde_json::from_str(&body).map_err(|e| e.to_string())?;
187        *self
188            .cache
189            .lock()
190            .unwrap_or_else(std::sync::PoisonError::into_inner) =
191            Some((Instant::now(), doc.clone()));
192        Ok(doc)
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use std::sync::atomic::{AtomicUsize, Ordering};
199    use std::sync::Arc;
200
201    use super::{read_capped, Config, Fetch, Source};
202    use crate::decide::State;
203
204    struct Canned(Result<String, String>, Arc<AtomicUsize>);
205
206    #[async_trait::async_trait]
207    impl Fetch for Canned {
208        async fn get(&self, _url: &str) -> Result<String, String> {
209            self.1.fetch_add(1, Ordering::SeqCst);
210            self.0.clone()
211        }
212    }
213
214    struct Panics;
215
216    #[async_trait::async_trait]
217    impl Fetch for Panics {
218        async fn get(&self, _url: &str) -> Result<String, String> {
219            panic!("the network stack fell over");
220        }
221    }
222
223    fn n() -> Arc<AtomicUsize> {
224        Arc::new(AtomicUsize::new(0))
225    }
226
227    #[tokio::test]
228    async fn a_network_error_opens_the_gate() {
229        let s = Source::with(Config::url("http://x"), Canned(Err("offline".into()), n()));
230        assert!(matches!(
231            s.gate("1.0.0", "vi", "ios").await.state,
232            State::Ok
233        ));
234    }
235
236    #[tokio::test]
237    async fn a_fetch_that_panics_still_opens_the_gate() {
238        let s = Source::with(Config::url("http://x"), Panics);
239        assert!(matches!(
240            s.gate("1.0.0", "vi", "ios").await.state,
241            State::Ok
242        ));
243    }
244
245    #[tokio::test]
246    async fn malformed_json_opens_the_gate() {
247        let s = Source::with(
248            Config::url("http://x"),
249            Canned(Ok("<html>404</html>".into()), n()),
250        );
251        assert!(matches!(
252            s.gate("1.0.0", "vi", "ios").await.state,
253            State::Ok
254        ));
255    }
256
257    #[tokio::test]
258    async fn it_fetches_once_inside_the_ttl() {
259        let calls = n();
260        let s = Source::with(
261            Config::url("http://x"),
262            Canned(Ok(r#"{"minVersion":"2.0.0"}"#.into()), calls.clone()),
263        );
264        assert!(matches!(
265            s.gate("1.0.0", "vi", "ios").await.state,
266            State::Forced
267        ));
268        assert!(matches!(
269            s.gate("1.0.0", "vi", "ios").await.state,
270            State::Forced
271        ));
272        assert_eq!(calls.load(Ordering::SeqCst), 1);
273    }
274
275    #[tokio::test]
276    async fn it_fetches_again_once_the_ttl_has_passed() {
277        let calls = n();
278        let s = Source::with(
279            Config::url("http://x").ttl(std::time::Duration::ZERO),
280            Canned(Ok(r#"{"minVersion":"2.0.0"}"#.into()), calls.clone()),
281        );
282        s.gate("1.0.0", "vi", "ios").await;
283        s.gate("1.0.0", "vi", "ios").await;
284        assert_eq!(calls.load(Ordering::SeqCst), 2);
285    }
286
287    #[test]
288    fn a_body_within_the_cap_is_read_whole() {
289        let body = r#"{"minVersion":"2.0.0"}"#;
290        assert_eq!(read_capped(None, body.as_bytes(), 64).unwrap(), body);
291        assert_eq!(read_capped(Some(4), &b"abcd"[..], 4).unwrap(), "abcd");
292    }
293
294    #[test]
295    fn a_declared_length_over_the_cap_is_refused_before_reading() {
296        struct Unread;
297        impl std::io::Read for Unread {
298            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
299                panic!("read a body its header already ruled out");
300            }
301        }
302        assert!(read_capped(Some(5), Unread, 4).is_err());
303    }
304
305    #[test]
306    fn a_body_that_outgrows_the_cap_is_refused() {
307        // No content-length, or one that understates the body.
308        assert!(read_capped(None, &b"abcde"[..], 4).is_err());
309        assert!(read_capped(Some(1), &b"abcde"[..], 4).is_err());
310    }
311
312    #[test]
313    fn a_body_that_is_not_utf8_is_refused() {
314        assert!(read_capped(None, &[0xff, 0xfe][..], 4).is_err());
315    }
316}