1use 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
34pub const NUGET_ID: &str = "gitpoulpi";
36
37pub const MANIFEST_FILE: &str = "latest.json";
39
40pub const CHOCOLATEY_COMMUNITY_FEED: &str = "https://community.chocolatey.org/api/v2/";
42
43pub const MAX_V2_PAGES: usize = 5;
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum SourceSpec {
49 GitHubReleases {
51 api_base: String,
53 repo: String,
55 token: Option<String>,
56 },
57 NuGet { feed: String },
59 Manifest { url: String },
61 None,
63}
64
65impl SourceSpec {
66 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 mirror()
100 } else {
101 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#[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 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(), ¶ms.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 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 ¶ms.keys,
185 )
186 .map_err(|e| Error::Decode(format!("the manifest is not trusted: {e}")))?;
187 vec![manifest_release(url, &manifest, ¶ms.target)?]
188 }
189 };
190 Ok(newest_after_pinned(
191 &releases,
192 ¶ms.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
214async 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
236async 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
271fn 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
335fn 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
361fn 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("<", "<")
379 .replace(">", ">")
380 .replace(""", "\"")
381 .replace("'", "'")
382 .replace("&", "&")
383}
384
385#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
389pub struct Manifest {
390 pub version: String,
391 #[serde(default)]
392 pub notes: String,
393 #[serde(default)]
395 pub assets: BTreeMap<String, String>,
396}
397
398impl Manifest {
399 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 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 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/"), ¶ms("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 ¶ms("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, ¶ms("1.0.0")).unwrap();
565 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'&$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, ¶ms("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 "& 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, ¶ms("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, ¶ms("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 ¶ms("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 ¶ms("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, ¶ms("1.0.0"))).unwrap_err();
707 assert!(matches!(err, Error::Decode(_)), "{err:?}");
708 err.to_string()
709 };
710 let unsigned = RecordedTransport::new().on("latest.json", 200, &body);
712 assert!(refused(&unsigned).contains("signature"));
713 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 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 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, ¶ms("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, ¶ms("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 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}