Skip to main content

gitpoulpi_hosting/updates/
sources.rs

1//! Where an update check asks (the install-channels design, section 1.5).
2//!
3//! A [`SourceSpec`] is a plain value the caller builds from the install
4//! channel and the policy; [`SourceSpec::check`] runs it through an
5//! [`HttpTransport`] (tests use a fake, never a socket). Every source ends in
6//! [`newest_after_pinned`], so semver, channel and pin filtering live once.
7//!
8//! Traps:
9//! - NuGet ids are lowercase in the v3 `index.json` path; the feed's own
10//!   casing (`GitPoulpi`) 404s on several servers.
11//! - A v3 feed URL ends in `.json`; anything else is a v2 (OData/Atom) root.
12//!   The v2 answer is pages of `<entry>` with a `rel="next"` link, followed
13//!   up to [`MAX_V2_PAGES`] times.
14//! - NuGet versions may carry a fourth part (`1.4.2.0`); a zero one is
15//!   dropped, a non-zero one is not a version this app can order, so it is
16//!   skipped.
17//! - Release notes are never taken from NuGet or the manifest's host
18//!   beyond what the manifest says; the panel falls back to the compiled-in
19//!   CHANGELOG.
20//! - The manifest names assets without URLs: they are siblings of the
21//!   manifest file, which is what "a mirror only copies files" means.
22
23use std::collections::BTreeMap;
24
25use async_trait::async_trait;
26
27use super::{
28    newest_after_pinned, parse_releases, pick_assets, signing, Asset, CheckParams, Release, Version,
29};
30use crate::http::{HttpRequest, HttpTransport};
31use crate::{Error, Result};
32use gitpoulpi_config::release;
33
34/// The package id on NuGet and Chocolatey feeds.
35pub const NUGET_ID: &str = "gitpoulpi";
36
37/// The manifest's file name (its signature is `latest.json.minisig`).
38pub const MANIFEST_FILE: &str = "latest.json";
39
40/// Chocolatey's community feed (a v2 root).
41pub const CHOCOLATEY_COMMUNITY_FEED: &str = "https://community.chocolatey.org/api/v2/";
42
43/// Pages of a v2 answer followed before giving up (the feed is small).
44pub const MAX_V2_PAGES: usize = 5;
45
46/// Which source answers the check.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum SourceSpec {
49    /// The GitHub (or GitHub Enterprise Server) releases API.
50    GitHubReleases {
51        /// `https://api.github.com`, or a GHES `https://host/api/v3`.
52        api_base: String,
53        /// `owner/name`.
54        repo: String,
55        token: Option<String>,
56    },
57    /// A NuGet v3 service index (`.../index.json`) or a v2 root.
58    NuGet { feed: String },
59    /// A static `latest.json`.
60    Manifest { url: String },
61    /// Never asks anyone (a managed deployment).
62    None,
63}
64
65impl SourceSpec {
66    /// Where the signed security notices are for this source, or `None` when
67    /// nothing may be asked (the `None` source; a NuGet feed of the
68    /// organization's own, which is not a reason to contact GitHub; a GitHub
69    /// Enterprise Server, whose host is not a release host).
70    ///
71    /// - GitHub: `<web>/<repo>/releases/latest/download/security.json`.
72    /// - A manifest mirror: `security.json` next to the manifest.
73    /// - NuGet: from GitHub when the feed is the public one; otherwise from
74    ///   the policy's `download_base` mirror when there is one.
75    pub fn notices_url(&self, repo: &str, download_base: Option<&str>) -> Option<String> {
76        let github = |web: &str| {
77            format!(
78                "{}/{}/releases/latest/download/{}",
79                web.trim_end_matches('/'),
80                repo.trim_matches('/'),
81                super::notices::FILE
82            )
83        };
84        let mirror = || {
85            download_base
86                .map(str::trim)
87                .filter(|b| !b.is_empty())
88                .map(|b| format!("{}/{}", b.trim_end_matches('/'), super::notices::FILE))
89        };
90        match self {
91            SourceSpec::None => None,
92            SourceSpec::GitHubReleases { api_base, .. } => {
93                let api = api_base.trim_end_matches('/');
94                if api == "https://api.github.com" {
95                    Some(github("https://github.com"))
96                } else if api.ends_with("/api/v3") {
97                    // Enterprise Server: not a release host, so only a
98                    // mirror the policy names can serve the notices.
99                    mirror()
100                } else {
101                    // The test override (`GITPOULPI_UPDATE_API`): a fake
102                    // server serves the web side of the release too.
103                    Some(github(api))
104                }
105            }
106            SourceSpec::Manifest { url } => {
107                let dir = url
108                    .split(['?', '#'])
109                    .next()
110                    .unwrap_or(url)
111                    .rsplit_once('/')
112                    .map_or("", |(d, _)| d);
113                Some(format!("{dir}/{}", super::notices::FILE))
114            }
115            SourceSpec::NuGet { feed } => {
116                if feed.trim().starts_with(CHOCOLATEY_COMMUNITY_FEED)
117                    || feed.contains("api.nuget.org")
118                {
119                    Some(github("https://github.com"))
120                } else {
121                    mirror()
122                }
123            }
124        }
125    }
126}
127
128/// One way of finding the newest release.
129#[async_trait]
130pub trait CheckSource: Send + Sync {
131    async fn latest(
132        &self,
133        transport: &dyn HttpTransport,
134        params: &CheckParams,
135    ) -> Result<Option<Release>>;
136}
137
138impl SourceSpec {
139    /// Asks the source for the newest release newer than `params.running`.
140    pub async fn check(
141        &self,
142        transport: &dyn HttpTransport,
143        params: &CheckParams,
144    ) -> Result<Option<Release>> {
145        self.latest(transport, params).await
146    }
147}
148
149#[async_trait]
150impl CheckSource for SourceSpec {
151    async fn latest(
152        &self,
153        transport: &dyn HttpTransport,
154        params: &CheckParams,
155    ) -> Result<Option<Release>> {
156        let releases = match self {
157            SourceSpec::None => return Ok(None),
158            SourceSpec::GitHubReleases {
159                api_base,
160                repo,
161                token,
162            } => {
163                github_releases(transport, api_base, repo, token.as_deref(), &params.target).await?
164            }
165            SourceSpec::NuGet { feed } => nuget_releases(transport, feed).await?,
166            SourceSpec::Manifest { url } => {
167                let body = get(transport, url, "the update manifest", &[]).await?;
168                let manifest = parse_manifest(&body)?;
169                // The hashes inside are only as good as the file: a mirror
170                // must copy `latest.json.minisig` next to it.
171                let sig = get(
172                    transport,
173                    &format!("{url}.minisig"),
174                    "the update manifest's signature",
175                    &[],
176                )
177                .await
178                .map_err(|e| Error::Decode(format!("the manifest has no signature: {e}")))?;
179                signing::verify(
180                    body.as_bytes(),
181                    &sig,
182                    MANIFEST_FILE,
183                    manifest.version.trim().trim_start_matches(['v', 'V']),
184                    &params.keys,
185                )
186                .map_err(|e| Error::Decode(format!("the manifest is not trusted: {e}")))?;
187                vec![manifest_release(url, &manifest, &params.target)?]
188            }
189        };
190        Ok(newest_after_pinned(
191            &releases,
192            &params.running,
193            params.channel,
194            params.pin.as_deref(),
195        ))
196    }
197}
198
199async fn get(
200    transport: &dyn HttpTransport,
201    url: &str,
202    what: &str,
203    headers: &[(&str, String)],
204) -> Result<String> {
205    let mut request = HttpRequest::get(url);
206    for (k, v) in headers {
207        request = request.header(*k, v.clone());
208    }
209    let response = transport.send(request).await?;
210    response.error_for_status(what)?;
211    Ok(response.body)
212}
213
214// ---- GitHub ----------------------------------------------------------
215
216async fn github_releases(
217    transport: &dyn HttpTransport,
218    api_base: &str,
219    repo: &str,
220    token: Option<&str>,
221    target: &str,
222) -> Result<Vec<Release>> {
223    let url = format!(
224        "{}/repos/{}/releases?per_page=30",
225        api_base.trim_end_matches('/'),
226        repo.trim_matches('/')
227    );
228    let mut headers = vec![("Accept", "application/vnd.github+json".to_string())];
229    if let Some(token) = token.map(str::trim).filter(|t| !t.is_empty()) {
230        headers.push(("Authorization", format!("Bearer {token}")));
231    }
232    let body = get(transport, &url, "the update check", &headers).await?;
233    parse_releases(&body, target)
234}
235
236// ---- NuGet -----------------------------------------------------------
237
238async fn nuget_releases(transport: &dyn HttpTransport, feed: &str) -> Result<Vec<Release>> {
239    let feed = feed.trim();
240    let versions = if feed
241        .split(['?', '#'])
242        .next()
243        .unwrap_or("")
244        .ends_with(".json")
245    {
246        nuget_v3_versions(transport, feed).await?
247    } else {
248        nuget_v2_versions(transport, feed).await?
249    };
250    let page_base = feed
251        .starts_with(CHOCOLATEY_COMMUNITY_FEED)
252        .then_some("https://community.chocolatey.org/packages/gitpoulpi");
253    Ok(versions
254        .into_iter()
255        .filter_map(|raw| {
256            let version = normalize_nuget_version(&raw)?;
257            let v = Version::parse(&version)?;
258            Some(Release {
259                tag: version.clone(),
260                prerelease: v.is_prerelease(),
261                notes: String::new(),
262                page_url: page_base.map_or_else(String::new, |b| format!("{b}/{version}")),
263                asset: None,
264                checksum: None,
265                version,
266            })
267        })
268        .collect())
269}
270
271/// `1.4.2.0` -> `1.4.2`; a non-zero fourth part cannot be ordered here.
272fn normalize_nuget_version(raw: &str) -> Option<String> {
273    let raw = raw.trim();
274    let (core, rest) = match raw.find(['-', '+']) {
275        Some(i) => raw.split_at(i),
276        None => (raw, ""),
277    };
278    let mut parts: Vec<&str> = core.split('.').collect();
279    if parts.len() == 4 {
280        if parts[3] != "0" {
281            return None;
282        }
283        parts.pop();
284    }
285    while parts.len() < 3 && !parts.is_empty() {
286        parts.push("0");
287    }
288    Some(format!("{}{rest}", parts.join(".")))
289}
290
291async fn nuget_v3_versions(transport: &dyn HttpTransport, index_url: &str) -> Result<Vec<String>> {
292    let body = get(transport, index_url, "the NuGet service index", &[]).await?;
293    let index: serde_json::Value =
294        serde_json::from_str(&body).map_err(|e| Error::Decode(e.to_string()))?;
295    let base = index["resources"]
296        .as_array()
297        .into_iter()
298        .flatten()
299        .find(|r| {
300            r["@type"]
301                .as_str()
302                .is_some_and(|t| t.starts_with("PackageBaseAddress"))
303        })
304        .and_then(|r| r["@id"].as_str())
305        .ok_or_else(|| Error::Decode("the NuGet index has no PackageBaseAddress".into()))?;
306    let url = format!("{}/{NUGET_ID}/index.json", base.trim_end_matches('/'));
307    let body = get(transport, &url, "the NuGet version list", &[]).await?;
308    let list: serde_json::Value =
309        serde_json::from_str(&body).map_err(|e| Error::Decode(e.to_string()))?;
310    Ok(list["versions"]
311        .as_array()
312        .into_iter()
313        .flatten()
314        .filter_map(|v| v.as_str().map(str::to_string))
315        .collect())
316}
317
318async fn nuget_v2_versions(transport: &dyn HttpTransport, root: &str) -> Result<Vec<String>> {
319    let mut url = format!(
320        "{}/FindPackagesById()?id='{NUGET_ID}'",
321        root.trim_end_matches('/')
322    );
323    let mut versions = Vec::new();
324    for _ in 0..MAX_V2_PAGES {
325        let body = get(transport, &url, "the NuGet feed", &[]).await?;
326        versions.extend(atom_versions(&body));
327        match atom_next_link(&body) {
328            Some(next) if next != url => url = next,
329            _ => break,
330        }
331    }
332    Ok(versions)
333}
334
335/// The text of every `<d:Version>` element of an Atom/OData answer. A plain
336/// scan, not an XML parser: the shape is fixed by the OData v2 contract, and
337/// `<d:NormalizedVersion>` / `<d:VersionDownloadCount>` must not match.
338fn atom_versions(body: &str) -> Vec<String> {
339    const OPEN: &str = "<d:Version";
340    let mut out = Vec::new();
341    let mut rest = body;
342    while let Some(i) = rest.find(OPEN) {
343        rest = &rest[i + OPEN.len()..];
344        if !rest.starts_with(['>', ' ', '/']) {
345            continue;
346        }
347        let Some(gt) = rest.find('>') else { break };
348        if rest[..gt].ends_with('/') {
349            continue;
350        }
351        let after = &rest[gt + 1..];
352        let Some(end) = after.find("</d:Version>") else {
353            break;
354        };
355        out.push(unescape(after[..end].trim()));
356        rest = &after[end..];
357    }
358    out
359}
360
361/// The `href` of `<link rel="next" href="..."/>`, if the answer is paged.
362fn atom_next_link(body: &str) -> Option<String> {
363    let mut rest = body;
364    while let Some(i) = rest.find("<link") {
365        let tail = &rest[i..];
366        let end = tail.find('>')?;
367        let tag = &tail[..end];
368        if tag.contains("rel=\"next\"") {
369            let href = tag.split("href=\"").nth(1)?.split('"').next()?;
370            return Some(unescape(href));
371        }
372        rest = &tail[end..];
373    }
374    None
375}
376
377fn unescape(s: &str) -> String {
378    s.replace("&lt;", "<")
379        .replace("&gt;", ">")
380        .replace("&quot;", "\"")
381        .replace("&apos;", "'")
382        .replace("&amp;", "&")
383}
384
385// ---- Manifest --------------------------------------------------------
386
387/// The static `latest.json` a release attaches.
388#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
389pub struct Manifest {
390    pub version: String,
391    #[serde(default)]
392    pub notes: String,
393    /// File name -> SHA-256 (lowercase hex).
394    #[serde(default)]
395    pub assets: BTreeMap<String, String>,
396}
397
398impl Manifest {
399    /// The SHA-256 the manifest states for `name`.
400    pub fn sha256_of(&self, name: &str) -> Option<&str> {
401        self.assets.get(name).map(String::as_str)
402    }
403}
404
405pub fn parse_manifest(body: &str) -> Result<Manifest> {
406    serde_json::from_str(body).map_err(|e| Error::Decode(e.to_string()))
407}
408
409fn manifest_release(url: &str, manifest: &Manifest, target: &str) -> Result<Release> {
410    let version = manifest.version.trim().trim_start_matches(['v', 'V']);
411    let v = Version::parse(version)
412        .ok_or_else(|| Error::Decode(format!("the manifest version {version:?} is not semver")))?;
413    let dir = url
414        .split(['?', '#'])
415        .next()
416        .unwrap_or(url)
417        .rsplit_once('/')
418        .map_or("", |(d, _)| d);
419    let archive = release::archive_name(version, target);
420    let sibling = |name: &str| Asset {
421        name: name.to_string(),
422        url: format!("{dir}/{name}"),
423        size: 0,
424    };
425    // The archive and its `.sha256` sit next to the manifest, like on the
426    // release page; only archives the manifest lists count.
427    let listed: Vec<Asset> = manifest.assets.keys().map(|n| sibling(n)).collect();
428    let (asset, mut checksum) = pick_assets(&listed, version, target);
429    if asset.is_some() && checksum.is_none() {
430        checksum = Some(sibling(&format!("{archive}.sha256")));
431    }
432    Ok(Release {
433        tag: version.to_string(),
434        version: version.to_string(),
435        prerelease: v.is_prerelease(),
436        notes: manifest.notes.clone(),
437        page_url: String::new(),
438        asset,
439        checksum,
440    })
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::http::RecordedTransport;
447    use crate::updates::{download_host_allowed, download_host_allowed_with};
448    use gitpoulpi_config::UpdateChannel;
449    use gitpoulpi_testkit::signing::TestSigner;
450
451    const TARGET: &str = "x86_64-unknown-linux-gnu";
452
453    fn signer() -> &'static TestSigner {
454        static SIGNER: std::sync::OnceLock<TestSigner> = std::sync::OnceLock::new();
455        SIGNER.get_or_init(TestSigner::new)
456    }
457
458    /// `body` served as `latest.json` with a signature for `version`.
459    fn signed_manifest(body: &str, version: &str) -> RecordedTransport {
460        RecordedTransport::new()
461            .on(
462                "latest.json.minisig",
463                200,
464                &signer().sign(MANIFEST_FILE, version, body.as_bytes()),
465            )
466            .on("latest.json", 200, body)
467    }
468
469    fn block<F: std::future::Future>(f: F) -> F::Output {
470        tokio::runtime::Builder::new_current_thread()
471            .build()
472            .unwrap()
473            .block_on(f)
474    }
475
476    fn params(running: &str) -> CheckParams {
477        CheckParams {
478            repo: "Poulpi-Lab/GitPoulpi".into(),
479            running: running.into(),
480            channel: UpdateChannel::Stable,
481            target: TARGET.into(),
482            keys: vec![signing::parse_key(&signer().public_key_text()).unwrap()],
483            ..Default::default()
484        }
485    }
486
487    fn run(t: &RecordedTransport, spec: &SourceSpec, p: &CheckParams) -> Option<Release> {
488        block(spec.check(t, p)).unwrap()
489    }
490
491    fn github_body() -> String {
492        serde_json::json!([
493            {"tag_name": "v1.5.0", "prerelease": false, "body": "five", "html_url": "u5", "assets": []},
494            {"tag_name": "v1.4.9", "prerelease": false, "body": "four nine", "html_url": "u49", "assets": []},
495            {"tag_name": "v1.4.2", "prerelease": false, "body": "four two", "html_url": "u42", "assets": []},
496            {"tag_name": "v1.6.0-rc.1", "prerelease": true, "body": "rc", "html_url": "u6", "assets": []}
497        ])
498        .to_string()
499    }
500
501    fn github(api_base: &str) -> SourceSpec {
502        SourceSpec::GitHubReleases {
503            api_base: api_base.into(),
504            repo: "Poulpi-Lab/GitPoulpi".into(),
505            token: Some("tok".into()),
506        }
507    }
508
509    #[test]
510    fn github_asks_the_releases_list_with_the_token() {
511        let t = RecordedTransport::new().on(
512            "/repos/Poulpi-Lab/GitPoulpi/releases",
513            200,
514            &github_body(),
515        );
516        let found = run(&t, &github("https://api.github.com/"), &params("1.0.0")).unwrap();
517        assert_eq!(found.version, "1.5.0");
518        let seen = t.requests();
519        assert!(seen[0]
520            .url
521            .starts_with("https://api.github.com/repos/Poulpi-Lab/GitPoulpi/releases"));
522        assert!(seen[0]
523            .headers
524            .iter()
525            .any(|(k, v)| k == "Authorization" && v == "Bearer tok"));
526    }
527
528    #[test]
529    fn github_enterprise_uses_its_own_api_base() {
530        let t = RecordedTransport::new().on("/api/v3/repos/", 200, &github_body());
531        let found = run(
532            &t,
533            &github("https://ghe.corp.example/api/v3"),
534            &params("1.0.0"),
535        )
536        .unwrap();
537        assert_eq!(found.version, "1.5.0");
538        assert!(t.requests()[0]
539            .url
540            .starts_with("https://ghe.corp.example/api/v3/repos/Poulpi-Lab/GitPoulpi/releases"));
541    }
542
543    const V3_INDEX: &str = r#"{"version":"3.0.0","resources":[
544        {"@id":"https://feed.example/query","@type":"SearchQueryService"},
545        {"@id":"https://feed.example/flat/","@type":"PackageBaseAddress/3.0.0"}]}"#;
546    const V3_VERSIONS: &str =
547        r#"{"versions":["1.3.0","1.4.2","1.4.9","1.5.0","1.6.0-rc.1","1.7.0.0","1.8.0.3"]}"#;
548
549    fn nuget_v3() -> (RecordedTransport, SourceSpec) {
550        let t = RecordedTransport::new()
551            .on("/flat/gitpoulpi/index.json", 200, V3_VERSIONS)
552            .on("/v3/index.json", 200, V3_INDEX);
553        (
554            t,
555            SourceSpec::NuGet {
556                feed: "https://feed.example/v3/index.json".into(),
557            },
558        )
559    }
560
561    #[test]
562    fn nuget_v3_follows_the_service_index_to_the_lowercase_id_list() {
563        let (t, spec) = nuget_v3();
564        let found = run(&t, &spec, &params("1.0.0")).unwrap();
565        // 1.8.0.3 has a non-zero fourth part and is skipped; 1.7.0.0 is 1.7.0.
566        assert_eq!(found.version, "1.7.0");
567        assert!(!found.prerelease);
568        let urls: Vec<String> = t.requests().into_iter().map(|r| r.url).collect();
569        assert_eq!(
570            urls,
571            [
572                "https://feed.example/v3/index.json",
573                "https://feed.example/flat/gitpoulpi/index.json"
574            ]
575        );
576        let pre = CheckParams {
577            channel: UpdateChannel::Prerelease,
578            running: "1.7.0".into(),
579            ..params("1.7.0")
580        };
581        assert!(
582            run(&t, &spec, &pre).is_none(),
583            "1.6.0-rc.1 is older than 1.7.0"
584        );
585    }
586
587    fn atom(versions: &[&str], next: Option<&str>) -> String {
588        let entries: String = versions
589            .iter()
590            .map(|v| {
591                format!(
592                    "<entry><title type=\"text\">gitpoulpi</title><m:properties>\
593                     <d:Version>{v}</d:Version><d:NormalizedVersion>{v}</d:NormalizedVersion>\
594                     <d:VersionDownloadCount m:type=\"Edm.Int32\">3</d:VersionDownloadCount>\
595                     </m:properties></entry>"
596                )
597            })
598            .collect();
599        let link = next
600            .map(|n| format!("<link rel=\"next\" href=\"{n}\" />"))
601            .unwrap_or_default();
602        format!("<?xml version=\"1.0\"?><feed xmlns:d=\"x\">{entries}{link}</feed>")
603    }
604
605    #[test]
606    fn nuget_v2_reads_atom_entries_and_follows_the_next_page() {
607        let page2 = atom(&["1.5.0"], None);
608        let page1 = atom(
609            &["1.3.0", "1.4.2"],
610            Some("https://feed.example/api/v2/FindPackagesById()?id='gitpoulpi'&amp;$skip=2"),
611        );
612        let t = RecordedTransport::new().on("$skip=2", 200, &page2).on(
613            "FindPackagesById()?id='gitpoulpi'",
614            200,
615            &page1,
616        );
617        let spec = SourceSpec::NuGet {
618            feed: "https://feed.example/api/v2/".into(),
619        };
620        let found = run(&t, &spec, &params("1.0.0")).unwrap();
621        assert_eq!(found.version, "1.5.0");
622        assert_eq!(t.requests().len(), 2);
623        assert!(
624            t.requests()[1].url.contains("&$skip=2"),
625            "&amp; is unescaped"
626        );
627    }
628
629    #[test]
630    fn the_chocolatey_community_feed_links_its_package_page() {
631        let t = RecordedTransport::new().on("FindPackagesById", 200, &atom(&["2.0.0"], None));
632        let spec = SourceSpec::NuGet {
633            feed: CHOCOLATEY_COMMUNITY_FEED.into(),
634        };
635        let found = run(&t, &spec, &params("1.0.0")).unwrap();
636        assert_eq!(
637            found.page_url,
638            "https://community.chocolatey.org/packages/gitpoulpi/2.0.0"
639        );
640        assert!(t.requests()[0]
641            .url
642            .starts_with("https://community.chocolatey.org/api/v2/FindPackagesById()"));
643    }
644
645    #[test]
646    fn a_v3_index_without_package_base_address_is_a_decode_error() {
647        let t = RecordedTransport::new().on("/index.json", 200, r#"{"resources":[]}"#);
648        let spec = SourceSpec::NuGet {
649            feed: "https://feed.example/index.json".into(),
650        };
651        assert!(block(spec.check(&t, &params("1.0.0"))).is_err());
652    }
653
654    fn manifest_body() -> String {
655        serde_json::json!({
656            "version": "1.4.2",
657            "notes": "## 1.4.2\n- fix",
658            "assets": {
659                "gitpoulpi-1.4.2-x86_64-unknown-linux-gnu.tar.gz": "ab12",
660                "gitpoulpi-1.4.2-x86_64-pc-windows-msvc.zip": "cd34"
661            }
662        })
663        .to_string()
664    }
665
666    #[test]
667    fn the_manifest_names_the_archive_beside_itself() {
668        let url = "https://mirror.example/gitpoulpi/latest.json";
669        let t = signed_manifest(&manifest_body(), "1.4.2");
670        let found = run(
671            &t,
672            &SourceSpec::Manifest { url: url.into() },
673            &params("1.0.0"),
674        )
675        .unwrap();
676        assert_eq!(found.version, "1.4.2");
677        assert_eq!(found.notes, "## 1.4.2\n- fix");
678        assert_eq!(
679            found.asset.unwrap().url,
680            "https://mirror.example/gitpoulpi/gitpoulpi-1.4.2-x86_64-unknown-linux-gnu.tar.gz"
681        );
682        assert_eq!(
683            found.checksum.unwrap().url,
684            "https://mirror.example/gitpoulpi/gitpoulpi-1.4.2-x86_64-unknown-linux-gnu.tar.gz.sha256"
685        );
686        assert_eq!(
687            parse_manifest(&manifest_body())
688                .unwrap()
689                .sha256_of("gitpoulpi-1.4.2-x86_64-pc-windows-msvc.zip"),
690            Some("cd34")
691        );
692        let none = run(
693            &t,
694            &SourceSpec::Manifest { url: url.into() },
695            &params("1.4.2"),
696        );
697        assert!(none.is_none(), "up to date");
698    }
699
700    #[test]
701    fn a_manifest_without_a_valid_signature_is_never_trusted() {
702        let url = "https://mirror.example/gitpoulpi/latest.json";
703        let spec = SourceSpec::Manifest { url: url.into() };
704        let body = manifest_body();
705        let refused = |t: &RecordedTransport| {
706            let err = block(spec.check(t, &params("1.0.0"))).unwrap_err();
707            assert!(matches!(err, Error::Decode(_)), "{err:?}");
708            err.to_string()
709        };
710        // No signature file (the mirror copied only the manifest).
711        let unsigned = RecordedTransport::new().on("latest.json", 200, &body);
712        assert!(refused(&unsigned).contains("signature"));
713        // A signature for another version, another file and another key.
714        assert!(refused(&signed_manifest(&body, "1.4.1")).contains("not trusted"));
715        let other_file = RecordedTransport::new()
716            .on(
717                "latest.json.minisig",
718                200,
719                &signer().sign("security.json", "1.4.2", body.as_bytes()),
720            )
721            .on("latest.json", 200, &body);
722        assert!(refused(&other_file).contains("not trusted"));
723        let stranger = TestSigner::new();
724        let foreign = RecordedTransport::new()
725            .on(
726                "latest.json.minisig",
727                200,
728                &stranger.sign(MANIFEST_FILE, "1.4.2", body.as_bytes()),
729            )
730            .on("latest.json", 200, &body);
731        assert!(refused(&foreign).contains("not trusted"));
732        // A signed manifest edited afterwards (a different hash inside).
733        let edited = body.replace("ab12", "ffff");
734        let tampered = RecordedTransport::new()
735            .on(
736                "latest.json.minisig",
737                200,
738                &signer().sign(MANIFEST_FILE, "1.4.2", body.as_bytes()),
739            )
740            .on("latest.json", 200, &edited);
741        assert!(refused(&tampered).contains("not trusted"));
742        // No key compiled in accepts nothing.
743        let t = signed_manifest(&body, "1.4.2");
744        let no_keys = CheckParams {
745            keys: Vec::new(),
746            ..params("1.0.0")
747        };
748        assert!(block(spec.check(&t, &no_keys)).is_err());
749    }
750
751    #[test]
752    fn notices_are_asked_where_the_source_publishes_them() {
753        let notices = |spec: &SourceSpec, base: Option<&str>| spec.notices_url("o/r", base);
754        assert_eq!(
755            notices(&github("https://api.github.com"), None).as_deref(),
756            Some("https://github.com/o/r/releases/latest/download/security.json")
757        );
758        assert_eq!(
759            notices(&github("https://ghe.corp.example/api/v3"), None),
760            None,
761            "an Enterprise Server is not a release host"
762        );
763        assert_eq!(
764            notices(
765                &github("https://ghe.corp.example/api/v3"),
766                Some("https://mirror.example/gp/")
767            )
768            .as_deref(),
769            Some("https://mirror.example/gp/security.json")
770        );
771        let manifest = SourceSpec::Manifest {
772            url: "https://mirror.example/gp/latest.json".into(),
773        };
774        assert_eq!(
775            notices(&manifest, None).as_deref(),
776            Some("https://mirror.example/gp/security.json")
777        );
778        let public = SourceSpec::NuGet {
779            feed: CHOCOLATEY_COMMUNITY_FEED.into(),
780        };
781        assert_eq!(
782            notices(&public, None).as_deref(),
783            Some("https://github.com/o/r/releases/latest/download/security.json")
784        );
785        let internal = SourceSpec::NuGet {
786            feed: "https://nuget.corp.example/v3/index.json".into(),
787        };
788        assert_eq!(notices(&internal, None), None);
789        assert_eq!(notices(&SourceSpec::None, Some("https://m.example")), None);
790    }
791
792    #[test]
793    fn a_manifest_without_a_semver_version_is_an_error() {
794        let t = signed_manifest(r#"{"version":"nightly"}"#, "nightly");
795        let spec = SourceSpec::Manifest {
796            url: "https://m.example/latest.json".into(),
797        };
798        assert!(block(spec.check(&t, &params("1.0.0"))).is_err());
799    }
800
801    #[test]
802    fn the_none_source_never_touches_the_network() {
803        let t = RecordedTransport::new();
804        assert!(run(&t, &SourceSpec::None, &params("0.0.1")).is_none());
805        assert!(t.requests().is_empty());
806    }
807
808    #[test]
809    fn the_pin_applies_to_every_source() {
810        let pinned = |pin: &str| CheckParams {
811            pin: Some(pin.into()),
812            ..params("1.0.0")
813        };
814        let t = RecordedTransport::new().on("/releases", 200, &github_body());
815        let gh = github("https://api.github.com");
816        assert_eq!(run(&t, &gh, &pinned("1.4")).unwrap().version, "1.4.9");
817        assert_eq!(run(&t, &gh, &pinned("1.4.2")).unwrap().version, "1.4.2");
818        assert_eq!(run(&t, &gh, &pinned("1")).unwrap().version, "1.5.0");
819        assert!(
820            run(&t, &gh, &pinned("1.4.2-bad")).is_none(),
821            "a bad pin offers nothing"
822        );
823        assert!(run(&t, &gh, &pinned("0.9")).is_none());
824        let (t3, nuget) = nuget_v3();
825        assert_eq!(run(&t3, &nuget, &pinned("1.4")).unwrap().version, "1.4.9");
826        let tm = signed_manifest(&manifest_body(), "1.4.2");
827        let man = SourceSpec::Manifest {
828            url: "https://m.example/latest.json".into(),
829        };
830        assert!(run(&tm, &man, &pinned("1.3")).is_none());
831        assert_eq!(run(&tm, &man, &pinned("1.4")).unwrap().version, "1.4.2");
832    }
833
834    #[test]
835    fn a_mirror_host_is_allowed_only_when_the_policy_gives_it() {
836        let url = "https://mirror.example/gitpoulpi/a.tar.gz";
837        let base = ["https://mirror.example/gitpoulpi/".to_string()];
838        assert!(!download_host_allowed(url));
839        assert!(!download_host_allowed_with(url, &[]));
840        assert!(download_host_allowed_with(url, &base));
841        assert!(download_host_allowed_with(
842            url,
843            &["mirror.example".to_string()]
844        ));
845        // the built-in hosts stay allowed, and the mirror grants nothing more
846        assert!(download_host_allowed_with("https://github.com/a", &base));
847        assert!(!download_host_allowed_with(
848            "https://other.example/a",
849            &base
850        ));
851        assert!(!download_host_allowed_with(
852            "https://mirror.example.evil/a",
853            &base
854        ));
855        assert!(!download_host_allowed_with(
856            "https://mirror.example@evil.example/a",
857            &base
858        ));
859        assert!(
860            !download_host_allowed_with("http://mirror.example/a", &base),
861            "https only"
862        );
863    }
864}