Skip to main content

gitpoulpi_hosting/updates/
mod.rs

1//! Looking for a newer GitPoulpi release (the updates-and-install design,
2//! slice A).
3//!
4//! Everything here is pure except [`check`], which asks `GET
5//! /repos/<owner>/<name>/releases` through an [`HttpTransport`] (so the tests
6//! never open a socket) and [`UpdateState`], the small JSON file that keeps the
7//! last answer and the version the user chose to skip.
8//!
9//! Traps:
10//! - `/releases/latest` never returns a pre-release, so the channel cannot be
11//!   honoured through it: the list is fetched and filtered here.
12//! - Semver, not string, order: `0.10.0` is newer than `0.9.0`, and a
13//!   pre-release (`0.2.0-rc.1`) is older than its release (`0.2.0`).
14//! - The sources (GitHub, NuGet, manifest) live in [`sources`]; they all end in
15//!   [`newest_after_pinned`], so semver, channel and pin rules exist once.
16//! - A private repository answers 404 without a token; that is a normal
17//!   "no answer", never a user-facing error (the caller logs one line).
18
19pub mod notices;
20pub mod signing;
21pub mod sources;
22
23use std::cmp::Ordering;
24use std::path::Path;
25
26use crate::http::HttpTransport;
27use crate::{Error, Result};
28use gitpoulpi_config::{release, UpdateChannel};
29
30/// Env var that points the check at another API root (tests: a loopback
31/// server). Unset: `https://api.github.com`. Test builds refuse every
32/// non-loopback host anyway (`http::external_host_refusal`).
33pub const API_ENV: &str = "GITPOULPI_UPDATE_API";
34
35/// The API root the check talks to.
36pub fn api_base() -> String {
37    std::env::var(API_ENV)
38        .ok()
39        .map(|v| v.trim().trim_end_matches('/').to_string())
40        .filter(|v| !v.is_empty())
41        .unwrap_or_else(|| "https://api.github.com".to_string())
42}
43
44/// The hosts a release download may touch, the first request and every
45/// redirect: GitHub's release pages and the CDN its asset links redirect to.
46/// Anything else is refused (a tampered release JSON must not send the
47/// updater to a host of its choosing). Loopback joins them only while
48/// [`API_ENV`] is set, which is how tests point the whole flow at a fake
49/// server.
50pub const DOWNLOAD_HOSTS: &[&str] = &[
51    "github.com",
52    "api.github.com",
53    "objects.githubusercontent.com",
54    "release-assets.githubusercontent.com",
55    "github-releases.githubusercontent.com",
56];
57
58/// Whether `url` is `https` on one of the [`DOWNLOAD_HOSTS`] (or loopback
59/// while testing).
60pub fn download_host_allowed(url: &str) -> bool {
61    download_host_allowed_with(url, &[])
62}
63
64/// [`download_host_allowed`] plus `extra` hosts: the policy's `download_base`
65/// (a mirror), given as a URL or a bare host. The mirror is allowed only when
66/// the caller passes it; it is never a global. Matching is on the host alone
67/// (no suffix match: `mirror.example.evil` is not `mirror.example`) and the
68/// scheme must still be `https`.
69pub fn download_host_allowed_with(url: &str, extra: &[String]) -> bool {
70    let Some((scheme, rest)) = url.split_once("://") else {
71        return false;
72    };
73    let Some(host) = host_of_authority(rest) else {
74        return false;
75    };
76    if std::env::var_os(API_ENV).is_some_and(|v| !v.is_empty())
77        && (host == "127.0.0.1" || host == "localhost" || host == "[::1]")
78    {
79        return scheme == "http" || scheme == "https";
80    }
81    scheme == "https"
82        && (DOWNLOAD_HOSTS.contains(&host.as_str())
83            || extra.iter().any(|e| {
84                let e = e.trim();
85                let e = e.split_once("://").map_or(e, |(_, r)| r);
86                host_of_authority(e).is_some_and(|h| h == host)
87            }))
88}
89
90/// The lowercase host of `rest` (a URL without its scheme); `None` for
91/// userinfo (`https://github.com@evil/`), which hides the real host.
92fn host_of_authority(rest: &str) -> Option<String> {
93    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
94    if authority.is_empty() || authority.contains('@') {
95        return None;
96    }
97    let host = authority
98        .rsplit_once(':')
99        .filter(|(_, port)| port.chars().all(|c| c.is_ascii_digit()))
100        .map_or(authority, |(h, _)| h)
101        .to_ascii_lowercase();
102    Some(host)
103}
104
105/// A semantic version: `major.minor.patch[-pre][+build]`, a leading `v`
106/// tolerated. Build metadata is ignored, as semver says.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Version {
109    pub major: u64,
110    pub minor: u64,
111    pub patch: u64,
112    /// Dot-separated pre-release identifiers; empty for a full release.
113    pub pre: Vec<String>,
114}
115
116impl Version {
117    pub fn parse(text: &str) -> Option<Self> {
118        let text = text.trim().trim_start_matches(['v', 'V']);
119        let text = text.split('+').next()?;
120        let (core, pre) = match text.split_once('-') {
121            Some((core, pre)) => (core, Some(pre)),
122            None => (text, None),
123        };
124        let mut nums = core.split('.');
125        let major = nums.next()?.parse().ok()?;
126        let minor = nums.next()?.parse().ok()?;
127        let patch = nums.next()?.parse().ok()?;
128        if nums.next().is_some() {
129            return None;
130        }
131        let pre = match pre {
132            Some("") => return None,
133            Some(p) => p.split('.').map(str::to_string).collect(),
134            None => Vec::new(),
135        };
136        Some(Self {
137            major,
138            minor,
139            patch,
140            pre,
141        })
142    }
143
144    pub fn is_prerelease(&self) -> bool {
145        !self.pre.is_empty()
146    }
147}
148
149impl Ord for Version {
150    fn cmp(&self, other: &Self) -> Ordering {
151        (self.major, self.minor, self.patch)
152            .cmp(&(other.major, other.minor, other.patch))
153            .then_with(|| match (self.pre.is_empty(), other.pre.is_empty()) {
154                (true, true) => Ordering::Equal,
155                // A release outranks its own pre-releases.
156                (true, false) => Ordering::Greater,
157                (false, true) => Ordering::Less,
158                (false, false) => compare_pre(&self.pre, &other.pre),
159            })
160    }
161}
162
163impl PartialOrd for Version {
164    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
165        Some(self.cmp(other))
166    }
167}
168
169fn compare_pre(a: &[String], b: &[String]) -> Ordering {
170    for (x, y) in a.iter().zip(b) {
171        let ord = match (x.parse::<u64>(), y.parse::<u64>()) {
172            (Ok(x), Ok(y)) => x.cmp(&y),
173            // Numeric identifiers rank below alphanumeric ones.
174            (Ok(_), Err(_)) => Ordering::Less,
175            (Err(_), Ok(_)) => Ordering::Greater,
176            (Err(_), Err(_)) => x.cmp(y),
177        };
178        if ord != Ordering::Equal {
179            return ord;
180        }
181    }
182    a.len().cmp(&b.len())
183}
184
185/// One downloadable file of a release.
186#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
187pub struct Asset {
188    pub name: String,
189    pub url: String,
190    #[serde(default)]
191    pub size: u64,
192}
193
194/// A published release, as far as the notice needs it.
195#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
196pub struct Release {
197    pub tag: String,
198    pub version: String,
199    pub prerelease: bool,
200    /// The release body (Markdown): what the Release notes tab shows.
201    pub notes: String,
202    /// The release's page on github.com: what "Download" opens.
203    pub page_url: String,
204    /// The archive built for this target, when the release carries one.
205    pub asset: Option<Asset>,
206    /// Its `.sha256` file (used by the self-updater of slice B).
207    pub checksum: Option<Asset>,
208}
209
210#[derive(serde::Deserialize)]
211struct RawAsset {
212    name: String,
213    browser_download_url: String,
214    #[serde(default)]
215    size: u64,
216}
217
218#[derive(serde::Deserialize)]
219struct RawRelease {
220    tag_name: String,
221    #[serde(default)]
222    draft: bool,
223    #[serde(default)]
224    prerelease: bool,
225    #[serde(default)]
226    body: Option<String>,
227    #[serde(default)]
228    html_url: String,
229    #[serde(default)]
230    assets: Vec<RawAsset>,
231}
232
233/// The archive and checksum of `version` for `target` among `assets`.
234pub fn pick_assets(
235    assets: &[Asset],
236    version: &str,
237    target: &str,
238) -> (Option<Asset>, Option<Asset>) {
239    let archive = release::archive_name(version, target);
240    let checksum = format!("{archive}.sha256");
241    let find = |name: &str| assets.iter().find(|a| a.name == name).cloned();
242    (find(&archive), find(&checksum))
243}
244
245/// The version a release tag names: `releases/v0.2.0` (this repository's
246/// rule), or a bare `v0.2.0` / `0.2.0`. Any other prefix is not a release.
247pub fn version_of_tag(tag: &str) -> Option<&str> {
248    let tag = tag.trim();
249    let bare = tag.strip_prefix("releases/").unwrap_or(tag);
250    let version = bare.trim_start_matches(['v', 'V']);
251    (!version.contains('/') && Version::parse(version).is_some()).then_some(version)
252}
253
254/// Reads the `/releases` answer: drafts and tags that are not a version are
255/// dropped. `target` picks the asset.
256pub fn parse_releases(body: &str, target: &str) -> Result<Vec<Release>> {
257    let raw: Vec<RawRelease> =
258        serde_json::from_str(body).map_err(|e| Error::Decode(e.to_string()))?;
259    Ok(raw
260        .into_iter()
261        .filter(|r| !r.draft)
262        .filter_map(|r| {
263            let version = version_of_tag(&r.tag_name)?.to_string();
264            let v = Version::parse(&version)?;
265            let assets: Vec<Asset> = r
266                .assets
267                .into_iter()
268                .map(|a| Asset {
269                    name: a.name,
270                    url: a.browser_download_url,
271                    size: a.size,
272                })
273                .collect();
274            let (asset, checksum) = pick_assets(&assets, &version, target);
275            Some(Release {
276                tag: r.tag_name,
277                version,
278                prerelease: r.prerelease || v.is_prerelease(),
279                notes: r.body.unwrap_or_default(),
280                page_url: r.html_url,
281                asset,
282                checksum,
283            })
284        })
285        .collect())
286}
287
288/// The newest release allowed by `channel` that is newer than `running`;
289/// `None` when the running build is up to date (or newer: a dev build).
290pub fn newest_after(
291    releases: &[Release],
292    running: &str,
293    channel: UpdateChannel,
294) -> Option<Release> {
295    newest_after_pinned(releases, running, channel, None)
296}
297
298/// Whether `version` is at or below `pin`: `"1.4"` (or `"1"`) is any 1.4.x
299/// (any 1.x), `"1.4.2"` is at most 1.4.2. An unreadable pin allows nothing:
300/// an administrator's typo must not lift the ceiling.
301pub fn within_pin(version: &Version, pin: &str) -> bool {
302    let parts: Vec<&str> = pin
303        .trim()
304        .trim_start_matches(['v', 'V'])
305        .split('.')
306        .collect();
307    let nums: Option<Vec<u64>> = parts.iter().map(|p| p.parse().ok()).collect();
308    match nums.as_deref() {
309        Some([major]) => version.major == *major,
310        Some([major, minor]) => version.major == *major && version.minor == *minor,
311        Some([major, minor, patch]) => {
312            (version.major, version.minor, version.patch) <= (*major, *minor, *patch)
313        }
314        _ => false,
315    }
316}
317
318/// The one filter every check source ends in: allowed by `channel`, within
319/// `pin`, newer than `running`, then the highest by semver.
320pub fn newest_after_pinned(
321    releases: &[Release],
322    running: &str,
323    channel: UpdateChannel,
324    pin: Option<&str>,
325) -> Option<Release> {
326    let running = Version::parse(running)?;
327    let pin = pin.map(str::trim).filter(|p| !p.is_empty());
328    releases
329        .iter()
330        .filter(|r| channel == UpdateChannel::Prerelease || !r.prerelease)
331        .filter_map(|r| Some((Version::parse(&r.version)?, r)))
332        .filter(|(v, _)| pin.is_none_or(|p| within_pin(v, p)))
333        .filter(|(v, _)| *v > running)
334        .max_by(|a, b| a.0.cmp(&b.0))
335        .map(|(_, r)| r.clone())
336}
337
338/// What one check needs.
339#[derive(Debug, Clone, Default)]
340pub struct CheckParams {
341    /// `owner/name`.
342    pub repo: String,
343    pub running: String,
344    pub channel: UpdateChannel,
345    pub target: String,
346    /// A github.com token, when the user has one stored (a private
347    /// repository answers 404 without it).
348    pub token: Option<String>,
349    /// The administrator's ceiling: `"1.4"` = any 1.4.x, `"1.4.2"` = at most
350    /// 1.4.2 (see [`within_pin`]).
351    pub pin: Option<String>,
352    /// The release signing keys a manifest is verified against (production:
353    /// `gitpoulpi_update::signing::release_keys()`). Empty accepts nothing.
354    pub keys: Vec<signing::PublicKey>,
355    /// The policy's `download_base` mirror, where the security notices of a
356    /// source that has no release page of its own are looked for.
357    pub download_base: Option<String>,
358}
359
360/// Asks GitHub (the `base` API root) for the releases and returns the newer
361/// one, if any. Kept for the callers that predate [`sources::SourceSpec`].
362pub async fn check(
363    transport: &dyn HttpTransport,
364    base: &str,
365    params: &CheckParams,
366) -> Result<Option<Release>> {
367    sources::SourceSpec::GitHubReleases {
368        api_base: base.to_string(),
369        repo: params.repo.clone(),
370        token: params.token.clone(),
371    }
372    .check(transport, params)
373    .await
374}
375
376/// A day, in seconds: the throttle between two checks.
377pub const CHECK_INTERVAL_SECS: u64 = 24 * 60 * 60;
378
379/// What is kept between runs (`<data dir>/updates.json`): when the host was
380/// last asked, what it said, and the version the user chose to skip.
381#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
382pub struct UpdateState {
383    /// Unix seconds of the last attempt, successful or not.
384    #[serde(default)]
385    pub checked_at: u64,
386    /// The newest release found, kept for later runs: the chip needs no
387    /// request to say "available" again. Compared with the running version
388    /// every time it is read ([`UpdateState::available`]).
389    #[serde(default)]
390    pub latest: Option<Release>,
391    /// The version the user chose to skip: no chip for it, a newer one shows.
392    #[serde(default)]
393    pub skipped: Option<String>,
394    /// The security notices of the last check whose signature held (every
395    /// notice, not only the ones that name this build: the running version
396    /// is compared when they are read). Kept like `latest`, so the chip needs
397    /// no request.
398    #[serde(default)]
399    pub advisories: Vec<notices::Advisory>,
400}
401
402impl UpdateState {
403    /// Reads the file; a missing or damaged one is an empty state.
404    pub fn load(path: &Path) -> Self {
405        std::fs::read_to_string(path)
406            .ok()
407            .and_then(|raw| serde_json::from_str(&raw).ok())
408            .unwrap_or_default()
409    }
410
411    /// Writes the file, creating its folder. Best effort for the caller:
412    /// losing it only means one more check.
413    pub fn save(&self, path: &Path) -> std::io::Result<()> {
414        if let Some(parent) = path.parent() {
415            std::fs::create_dir_all(parent)?;
416        }
417        let raw = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
418        std::fs::write(path, raw)
419    }
420
421    /// Whether a check is due: never done, or a day old. `force` (the
422    /// palette's "Check for updates now") ignores the throttle.
423    pub fn due(&self, now: u64, force: bool) -> bool {
424        force || self.checked_at == 0 || now.saturating_sub(self.checked_at) >= CHECK_INTERVAL_SECS
425    }
426
427    /// The kept release when it is still newer than `running`, in `channel`,
428    /// and not the skipped one.
429    pub fn available(&self, running: &str, channel: UpdateChannel) -> Option<Release> {
430        let latest = self.latest.as_ref()?;
431        let newest = newest_after(std::slice::from_ref(latest), running, channel)?;
432        (self.skipped.as_deref() != Some(newest.version.as_str())).then_some(newest)
433    }
434
435    /// Records the security notices a check read: they replace the kept ones
436    /// only when the file was fetched and its signature held (a failed or
437    /// untrusted answer keeps what was known).
438    pub fn record_notices(&mut self, answer: Option<Result<Vec<notices::Advisory>>>) {
439        if let Some(Ok(list)) = answer {
440            self.advisories = list;
441        }
442    }
443
444    /// Records an attempt: the answer replaces the kept release only when the
445    /// host answered (a failed check keeps what was known).
446    pub fn record(&mut self, now: u64, answer: Option<Result<Option<Release>>>) {
447        self.checked_at = now;
448        if let Some(Ok(latest)) = answer {
449            self.latest = latest;
450        }
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use crate::http::RecordedTransport;
458
459    const TARGET: &str = "x86_64-unknown-linux-gnu";
460
461    fn body() -> String {
462        serde_json::json!([
463            {"tag_name": "v0.3.0-rc.1", "prerelease": true, "body": "rc notes",
464             "html_url": "https://example.test/r/v0.3.0-rc.1", "assets": []},
465            {"tag_name": "releases/v0.2.0", "prerelease": false, "body": "## 0.2.0\n- new",
466             "html_url": "https://example.test/r/v0.2.0",
467             "assets": [
468               {"name": "gitpoulpi-0.2.0-x86_64-unknown-linux-gnu.tar.gz",
469                "browser_download_url": "https://example.test/d/linux.tar.gz", "size": 10},
470               {"name": "gitpoulpi-0.2.0-x86_64-unknown-linux-gnu.tar.gz.sha256",
471                "browser_download_url": "https://example.test/d/linux.sha256", "size": 1},
472               {"name": "gitpoulpi-0.2.0-x86_64-pc-windows-msvc.zip",
473                "browser_download_url": "https://example.test/d/win.zip", "size": 10}]},
474            {"tag_name": "v0.9.0", "draft": true, "assets": []},
475            {"tag_name": "nightly", "assets": []},
476            {"tag_name": "v0.1.0", "assets": []}
477        ])
478        .to_string()
479    }
480
481    fn params(running: &str, channel: UpdateChannel) -> CheckParams {
482        CheckParams {
483            repo: "Poulpi-Lab/GitPoulpi".into(),
484            running: running.into(),
485            channel,
486            target: TARGET.into(),
487            token: None,
488            pin: None,
489            keys: Vec::new(),
490            download_base: None,
491        }
492    }
493
494    #[test]
495    fn versions_compare_as_semver_not_as_text() {
496        let v = |s: &str| Version::parse(s).unwrap();
497        assert!(v("0.10.0") > v("0.9.0"));
498        assert!(v("1.0.0") > v("0.99.99"));
499        assert!(v("0.2.0") > v("0.2.0-rc.1"), "a release beats its rc");
500        assert!(v("0.2.0-rc.2") > v("0.2.0-rc.1"));
501        assert!(v("0.2.0-rc.10") > v("0.2.0-rc.9"), "numeric identifiers");
502        assert!(v("0.2.0-rc.1") > v("0.2.0-beta.7"), "alphabetic order");
503        assert_eq!(v("v1.2.3+build5"), v("1.2.3"), "build metadata ignored");
504        assert_eq!(Version::parse("nightly"), None);
505        assert_eq!(Version::parse("1.2"), None);
506        assert_eq!(Version::parse("1.2.3.4"), None);
507        assert_eq!(Version::parse("1.2.3-"), None);
508    }
509
510    #[test]
511    fn release_tags_are_prefixed_or_bare_and_other_prefixes_are_not_releases() {
512        assert_eq!(version_of_tag("releases/v0.2.0"), Some("0.2.0"));
513        assert_eq!(version_of_tag("releases/v1.0.0-rc.1"), Some("1.0.0-rc.1"));
514        assert_eq!(version_of_tag("v0.2.0"), Some("0.2.0"));
515        assert_eq!(version_of_tag("0.2.0"), Some("0.2.0"));
516        assert_eq!(version_of_tag("checkpoints/v0.2.0"), None);
517        assert_eq!(version_of_tag("releases/nightly"), None);
518        assert_eq!(version_of_tag("nightly"), None);
519    }
520
521    #[test]
522    fn the_stable_channel_skips_prereleases_and_drafts() {
523        let releases = parse_releases(&body(), TARGET).unwrap();
524        assert_eq!(releases.len(), 3, "the draft and the non-version tag drop");
525        let stable = newest_after(&releases, "0.1.0", UpdateChannel::Stable).unwrap();
526        assert_eq!(stable.version, "0.2.0");
527        assert!(newest_after(&releases, "0.2.0", UpdateChannel::Stable).is_none());
528    }
529
530    #[test]
531    fn the_prerelease_channel_sees_release_candidates() {
532        let releases = parse_releases(&body(), TARGET).unwrap();
533        let pre = newest_after(&releases, "0.2.0", UpdateChannel::Prerelease).unwrap();
534        assert_eq!(pre.version, "0.3.0-rc.1");
535        assert!(pre.prerelease);
536        assert!(newest_after(&releases, "0.3.0", UpdateChannel::Prerelease).is_none());
537    }
538
539    #[test]
540    fn a_dev_build_ahead_of_the_latest_release_is_up_to_date() {
541        let releases = parse_releases(&body(), TARGET).unwrap();
542        assert!(newest_after(&releases, "0.5.0", UpdateChannel::Stable).is_none());
543        assert!(newest_after(&releases, "garbage", UpdateChannel::Stable).is_none());
544    }
545
546    #[test]
547    fn the_asset_is_the_archive_named_for_the_target() {
548        let linux = parse_releases(&body(), TARGET).unwrap();
549        let r = linux.iter().find(|r| r.version == "0.2.0").unwrap();
550        assert_eq!(
551            r.asset.as_ref().unwrap().url,
552            "https://example.test/d/linux.tar.gz"
553        );
554        assert!(r.checksum.as_ref().unwrap().name.ends_with(".sha256"));
555        let win = parse_releases(&body(), "x86_64-pc-windows-msvc").unwrap();
556        let r = win.iter().find(|r| r.version == "0.2.0").unwrap();
557        assert!(r.asset.as_ref().unwrap().name.ends_with(".zip"));
558        assert!(r.checksum.is_none(), "no checksum published for it");
559        let mac = parse_releases(&body(), "aarch64-apple-darwin").unwrap();
560        let r = mac.iter().find(|r| r.version == "0.2.0").unwrap();
561        assert!(
562            r.asset.is_none(),
563            "no archive for a target the release lacks"
564        );
565        assert_eq!(r.page_url, "https://example.test/r/v0.2.0");
566    }
567
568    #[test]
569    fn the_check_asks_the_releases_list_and_answers_the_newer_one() {
570        let transport =
571            RecordedTransport::new().on("/repos/Poulpi-Lab/GitPoulpi/releases", 200, &body());
572        let found = futures_block(check(
573            &transport,
574            "https://api.example.test/",
575            &CheckParams {
576                token: Some("tok".into()),
577                ..params("0.1.0", UpdateChannel::Stable)
578            },
579        ))
580        .unwrap()
581        .expect("a newer release");
582        assert_eq!(found.version, "0.2.0");
583        assert_eq!(found.notes, "## 0.2.0\n- new");
584        let seen = transport.requests();
585        assert_eq!(seen.len(), 1);
586        assert!(seen[0]
587            .url
588            .starts_with("https://api.example.test/repos/Poulpi-Lab/GitPoulpi/releases"));
589        assert!(
590            seen[0]
591                .headers
592                .iter()
593                .any(|(k, v)| k == "Authorization" && v == "Bearer tok"),
594            "{:?}",
595            seen[0].headers
596        );
597    }
598
599    #[test]
600    fn no_token_means_no_authorization_header_and_a_404_is_an_error_not_a_panic() {
601        let transport =
602            RecordedTransport::new().on("/releases", 404, "{\"message\":\"Not Found\"}");
603        let err = futures_block(check(
604            &transport,
605            "https://api.example.test",
606            &params("0.1.0", UpdateChannel::Stable),
607        ))
608        .unwrap_err();
609        assert!(err.to_string().contains("404"), "{err}");
610        assert!(transport.requests()[0]
611            .headers
612            .iter()
613            .all(|(k, _)| k != "Authorization"));
614    }
615
616    #[test]
617    fn the_check_is_due_once_a_day() {
618        let mut s = UpdateState::default();
619        assert!(s.due(1000, false), "never checked");
620        s.record(1000, None);
621        assert!(!s.due(1000 + CHECK_INTERVAL_SECS - 1, false));
622        assert!(s.due(1000 + CHECK_INTERVAL_SECS, false));
623        assert!(
624            s.due(1001, true),
625            "the palette command ignores the throttle"
626        );
627    }
628
629    #[test]
630    fn a_failed_check_keeps_the_known_release_and_still_counts_as_an_attempt() {
631        let releases = parse_releases(&body(), TARGET).unwrap();
632        let newest = newest_after(&releases, "0.1.0", UpdateChannel::Stable);
633        let mut s = UpdateState::default();
634        s.record(10, Some(Ok(newest.clone())));
635        s.record(20, Some(Err(Error::Http("offline".into()))));
636        assert_eq!(s.checked_at, 20);
637        assert_eq!(s.latest, newest);
638    }
639
640    #[test]
641    fn skipping_a_version_hides_it_but_not_a_newer_one() {
642        let releases = parse_releases(&body(), TARGET).unwrap();
643        let mut s = UpdateState {
644            latest: newest_after(&releases, "0.1.0", UpdateChannel::Stable),
645            skipped: Some("0.2.0".into()),
646            ..Default::default()
647        };
648        assert!(s.available("0.1.0", UpdateChannel::Stable).is_none());
649        s.latest.as_mut().unwrap().version = "0.2.1".into();
650        assert!(s.available("0.1.0", UpdateChannel::Stable).is_some());
651    }
652
653    #[test]
654    fn the_kept_release_stops_being_news_once_the_app_is_updated() {
655        let releases = parse_releases(&body(), TARGET).unwrap();
656        let s = UpdateState {
657            latest: newest_after(&releases, "0.1.0", UpdateChannel::Stable),
658            ..Default::default()
659        };
660        assert!(s.available("0.1.0", UpdateChannel::Stable).is_some());
661        assert!(s.available("0.2.0", UpdateChannel::Stable).is_none());
662    }
663
664    #[test]
665    fn the_state_file_round_trips_and_a_damaged_one_is_empty() {
666        let dir = tempfile::tempdir().unwrap();
667        let path = dir.path().join("sub").join("updates.json");
668        assert_eq!(UpdateState::load(&path), UpdateState::default());
669        let s = UpdateState {
670            checked_at: 42,
671            latest: None,
672            skipped: Some("0.2.0".into()),
673            advisories: vec![notices::Advisory {
674                id: "GPSA-2026-001".into(),
675                affected: "<0.3.0".into(),
676                fixed: Some("0.3.0".into()),
677                severity: "high".into(),
678                url: "https://example.test/a".into(),
679                summary: "s".into(),
680            }],
681        };
682        s.save(&path).unwrap();
683        assert_eq!(UpdateState::load(&path), s);
684        std::fs::write(&path, "{not json").unwrap();
685        assert_eq!(UpdateState::load(&path), UpdateState::default());
686    }
687
688    /// The transport is async; the tests have no runtime of their own.
689    fn futures_block<F: std::future::Future>(f: F) -> F::Output {
690        tokio::runtime::Builder::new_current_thread()
691            .build()
692            .unwrap()
693            .block_on(f)
694    }
695}
696
697#[cfg(test)]
698mod download_host_tests {
699    use super::*;
700    use crate::http::{HttpRequest, RecordedTransport};
701
702    #[test]
703    fn only_https_github_release_hosts_may_be_downloaded_from() {
704        for ok in [
705            "https://github.com/o/r/releases/download/v1/a.tar.gz",
706            "https://objects.githubusercontent.com/github-production-release-asset/1",
707            "https://release-assets.githubusercontent.com/x?sig=1",
708            "https://api.github.com/repos/o/r/releases/assets/1",
709        ] {
710            assert!(download_host_allowed(ok), "{ok}");
711        }
712        for refused in [
713            "http://github.com/o/r/a.tar.gz",
714            "https://evil.example/a.tar.gz",
715            "https://github.com.evil.example/a.tar.gz",
716            "https://github.com@evil.example/a.tar.gz",
717            "https://notgithub.com/a",
718            "https://127.0.0.1:9/a",
719            "ftp://github.com/a",
720            "github.com/a",
721        ] {
722            assert!(!download_host_allowed(refused), "{refused}");
723        }
724    }
725
726    #[tokio::test]
727    async fn the_recorded_transport_serves_files_in_chunks_and_can_be_canceled() {
728        let transport = RecordedTransport::new().on_file("/a.bin", vec![1u8; 200 * 1024]);
729        let calls = std::sync::atomic::AtomicUsize::new(0);
730        let bytes = transport
731            .download(HttpRequest::get("https://github.com/a.bin"), &|_, total| {
732                assert_eq!(total, Some(200 * 1024));
733                calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
734                true
735            })
736            .await
737            .unwrap();
738        assert_eq!(bytes.len(), 200 * 1024);
739        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 4);
740        let canceled = transport
741            .download(HttpRequest::get("https://github.com/a.bin"), &|_, _| false)
742            .await;
743        assert!(canceled.is_err());
744    }
745}