//! Release downloads are separate from package validation and installation. use reqwest::{blocking::Client, Url}; use serde_json::Value; use std::{io::Read, time::Duration}; use crate::error::Result; const MAX_METADATA: usize = 2 * 1024 * 1024; const MAX_ARCHIVE: usize = 100 * 1024 * 1024; #[derive(Debug)] pub struct Repository { pub url: Url, pub api: Url, } fn web_url(input: &str) -> Result { let url = Url::parse(input).map_err(|_| "Enter a complete HTTP or HTTPS link.")?; if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() { return Err("Use an HTTP or HTTPS link without credentials or a fragment.".into()); } Ok(url) } impl Repository { pub fn parse(input: &str, tag: &str) -> Result { let mut url = web_url(input.trim())?; if url.query().is_some() { return Err("Use a repository link without a query.".into()); } let path = url .path() .trim_end_matches('/') .trim_end_matches(".git") .to_owned(); let parts: Vec<_> = path.trim_start_matches('/').split('/').collect(); if parts.len() != 2 || parts.iter().any(|part| { part.is_empty() || *part == "." || *part == ".." || !part .bytes() .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) }) { return Err( "Use the repository root link, such as https://host/owner/repository.".into(), ); } url.set_path(&path); let mut api = url.clone(); api.set_path("/"); { let mut segments = api .path_segments_mut() .map_err(|_| "Invalid repository link.")?; segments.clear(); segments .extend(["api", "v1", "repos"]) .extend(&parts) .push("releases"); let tag = tag.trim(); if tag.is_empty() { segments.push("latest"); } else { if tag.len() > 200 || tag.chars().any(char::is_control) || matches!(tag, "." | "..") { return Err("Enter a release tag with at most 200 characters.".into()); } segments.push("tags"); segments.push(tag); } } Ok(Self { url, api }) } } pub struct Download { pub bytes: Vec, pub source: String, } fn read_limited(reader: impl Read, limit: usize) -> Result> { crate::fsutil::read_to_limit(reader, limit as u64) .map_err(|_| "The download was interrupted. Try again.")? .ok_or_else(|| "The download exceeds its size limit.".into()) } // Send credentials only to the release API's origin, including after redirects. fn get( client: &Client, start: Url, auth_origin: &Url, authorization: Option<&str>, limit: usize, ) -> Result> { let mut url = start; let started = std::time::Instant::now(); for _ in 0..=5 { let remaining = Duration::from_secs(60) .checked_sub(started.elapsed()) .filter(|remaining| !remaining.is_zero()) .ok_or("The download timed out. Try again.")?; let mut request = client.get(url.clone()).timeout(remaining); if url.origin() == auth_origin.origin() { if let Some(value) = authorization { request = request.header(reqwest::header::AUTHORIZATION, value); } } let response = request .send() .map_err(|_| "Cannot reach the release server. Check the link and connection.")?; if response.status().is_redirection() { let location = response .headers() .get(reqwest::header::LOCATION) .and_then(|value| value.to_str().ok()) .ok_or("The server returned an invalid redirect.")?; let next = url .join(location) .map_err(|_| "The server returned an invalid redirect.")?; web_url(next.as_str())?; if url.scheme() == "https" && next.scheme() != "https" { return Err("The server redirected a secure link to HTTP.".into()); } url = next; continue; } if !response.status().is_success() { return Err(match response.status().as_u16() { 401 | 403 => "Access denied. Check the token and repository read access.".into(), 404 => "Release not found. Check the repository, release tag, and token for private access.".into(), 429 => "The server request limit was reached. Try again later.".into(), code => format!("The release server returned HTTP {code}.").into(), }); } if response .content_length() .is_some_and(|size| size > limit as u64) { return Err("The download exceeds its size limit.".into()); } return read_limited(response, limit); } Err("The server returned too many redirects.".into()) } fn asset(metadata: &Value) -> Result<(String, Url)> { if metadata["draft"].as_bool() == Some(true) { return Err("Publish the release before installing its plugin.".into()); } let tag = metadata["tag_name"] .as_str() .filter(|tag| !tag.is_empty()) .ok_or("The release has no tag.")?; let assets = &metadata["assets"]; let zips: Vec<_> = assets .as_array() .ok_or("The release has no attached plugin ZIP.")? .iter() .filter(|item| { item["name"] .as_str() .is_some_and(|name| name.to_ascii_lowercase().ends_with(".zip")) }) .collect(); if zips.len() != 1 { return Err( "The release must contain exactly one plugin ZIP. Source archives do not count.".into(), ); } let item = zips[0]; let link = item["browser_download_url"] .as_str() .ok_or("The plugin ZIP has no download link.")?; if item["size"] .as_u64() .is_some_and(|size| size > MAX_ARCHIVE as u64) { return Err("The archive exceeds 100 MiB.".into()); } Ok((tag.to_owned(), web_url(link)?)) } pub fn download(repository: &Repository, token: Option<&str>) -> Result { let authorization = token .filter(|value| !value.is_empty()) .map(|value| format!("token {value}")); download_authorized(repository, authorization.as_deref()) } fn download_authorized(repository: &Repository, authorization: Option<&str>) -> Result { let client = Client::builder() .user_agent("RuneStone-plugin-installer/0.1") .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(60)) .redirect(reqwest::redirect::Policy::none()) .build() .map_err(|_| "Cannot start the download client.")?; let metadata = get( &client, repository.api.clone(), &repository.api, authorization, MAX_METADATA, )?; let metadata: Value = serde_json::from_slice(&metadata) .map_err(|_| "The server did not return release metadata.")?; let (tag, url) = asset(&metadata)?; if repository.url.scheme() == "https" && url.scheme() != "https" { return Err("The plugin ZIP must use HTTPS for this repository.".into()); } let bytes = get( &client, url.clone(), &repository.api, authorization, MAX_ARCHIVE, )?; // Query parameters can contain temporary download credentials. let mut display = url; display.set_query(None); Ok(Download { bytes, source: format!("{} @ {}\n{}", repository.url, tag, display), }) } #[cfg(test)] pub(crate) mod tests { use super::*; use serde_json::json; use std::{io::Write, net::TcpListener, thread, time::Instant}; pub fn server(responses: Vec<(String, Vec)>) -> (String, thread::JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); let handle = thread::spawn(move || { let mut requests = Vec::new(); for (headers, body) in responses { let start = Instant::now(); let mut stream = loop { match listener.accept() { Ok((stream, _)) => break stream, Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && start.elapsed() < Duration::from_secs(15) => { thread::sleep(Duration::from_millis(10)) } Err(error) => panic!("Test server did not receive a request: {error}"), } }; stream.set_nonblocking(false).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut request = Vec::new(); while !request.ends_with(b"\r\n\r\n") { let mut byte = [0]; stream.read_exact(&mut byte).unwrap(); request.push(byte[0]); assert!(request.len() < 16384); } requests.push(String::from_utf8(request).unwrap()); write!( stream, "HTTP/1.1 {headers}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() ) .unwrap(); stream.write_all(&body).unwrap(); } requests }); (base, handle) } #[test] fn network_errors_limits_and_redirect_credentials() { let client = Client::builder() .redirect(reqwest::redirect::Policy::none()) .build() .unwrap(); let (target, target_server) = server(vec![("200 OK".into(), b"zip".to_vec())]); let (origin, origin_server) = server(vec![( format!("302 Found\r\nLocation: {target}/download"), vec![], )]); let url = Url::parse(&origin).unwrap(); assert_eq!( get(&client, url.clone(), &url, Some("token secret"), 10).unwrap(), b"zip" ); assert!(origin_server.join().unwrap()[0].contains("authorization: token secret")); assert!(!target_server.join().unwrap()[0] .to_lowercase() .contains("authorization:")); for (status, body, limit, message) in [ ("404 Not Found", vec![], 100, "Release not found"), ("403 Forbidden", vec![], 100, "Access denied"), ("200 OK", b"12345".to_vec(), 4, "size limit"), ( "302 Found\r\nLocation: file:///secret", vec![], 100, "HTTP or HTTPS", ), ] { let (base, handle) = server(vec![(status.into(), body)]); let url = Url::parse(&base).unwrap(); assert!(get(&client, url.clone(), &url, None, limit) .unwrap_err() .to_string() .contains(message)); handle.join().unwrap(); } } #[test] fn repository_routes_and_tags() { let cases = [ ( "https://git.example/owner/demo.git/", "", "https://git.example/api/v1/repos/owner/demo/releases/latest", ), ( "http://localhost:6610/group/demo", "trial/1", "http://localhost:6610/api/v1/repos/group/demo/releases/tags/trial%2F1", ), ]; for (url, tag, expected) in cases { assert_eq!(Repository::parse(url, tag).unwrap().api.as_str(), expected); } for bad in [ "file:///tmp/plugin", "git@example:owner/demo", "https://user:secret@example/a/b", "https://example/a/b?token=secret", "https://example/a/b/tree/main", "https://example/a/b#main", ] { assert!(Repository::parse(bad, "").is_err(), "{bad}"); } } #[test] fn release_assets_are_explicit_and_unambiguous() { let zip = json!({"name":"org.test.demo-1.0.0.zip", "browser_download_url":"https://example/demo.zip"}); assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone()]})).is_ok()); assert!(asset( &json!({"tag_name":"v1", "zipball_url":"https://example/source.zip", "assets":[]}) ) .is_err()); assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone(),zip.clone()]})).is_err()); assert!(asset(&json!({"tag_name":"v1", "draft":true, "assets":[zip]})).is_err()); assert!(read_limited(&b"12345"[..], 4).is_err()); assert_eq!(read_limited(&b"1234"[..], 4).unwrap(), b"1234"); } }