//! Forge release API and streaming, hashed asset download. use crate::Res; use crate::config::{App, Config}; use serde::Deserialize; use sha2::{Digest, Sha256}; use std::fs::{self, File}; use std::io::{Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::time::Duration; use ureq::http::Response; use ureq::{Agent, Body}; const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const API_TIMEOUT: Duration = Duration::from_secs(30); const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600); const MAX_DOWNLOAD: u64 = 1 << 30; const MAX_API_BODY: u64 = 16 << 20; #[derive(Deserialize)] struct Release { tag: String, draft: bool, prerelease: bool, assets: Vec, } /// A downloadable file attached to a release. #[derive(Deserialize)] pub struct Asset { name: String, size: u64, pub sha256: String, download_url: String, } /// Client for one forge. The token is attached only to URLs under the forge base. pub struct Forge { agent: Agent, /// Forge base URL plus a trailing slash, for the token host check. prefix: String, token: Option, } impl Forge { pub fn new(cfg: &Config) -> Forge { let agent = Agent::config_builder() .timeout_connect(Some(CONNECT_TIMEOUT)) .http_status_as_error(false) .build() .into(); Forge { agent, prefix: format!("{}/", cfg.forge), token: cfg.token.clone(), } } /// GET `url` with an overall timeout, adding the token if `url` is on the forge host. fn get(&self, url: &str, timeout: Duration) -> Res> { let mut req = self .agent .get(url) .config() .timeout_global(Some(timeout)) .build(); if let Some(token) = self .token .as_deref() .filter(|_| url.starts_with(&self.prefix)) { req = req.header("Authorization", format!("token {token}")); } req.call().map_err(|e| format!("request failed: {e}")) } /// Newest eligible release of the app's repo and its asset for this host, as `(tag, asset)`. pub fn latest(&self, app: &App) -> Res<(String, Asset)> { let url = format!("{}api/v1/repos/{}/releases", self.prefix, app.repo); let mut resp = self.get(&url, API_TIMEOUT)?; if !resp.status().is_success() { return Err(format!("releases API returned {}", resp.status())); } let releases: Vec = serde_json::from_reader(resp.body_mut().with_config().limit(MAX_API_BODY).reader()) .map_err(|e| format!("bad releases JSON: {e}"))?; let Release { tag, assets, .. } = releases .into_iter() .find(|r| !r.draft && (app.prerelease || !r.prerelease)) .ok_or("no release")?; let want = app.asset_name(); let asset = assets .into_iter() .find(|a| a.name == want) .ok_or_else(|| format!("release {tag} has no asset {want}"))?; if asset.sha256.len() != 64 || !asset .sha256 .bytes() .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { return Err(format!("asset {want} has a malformed sha256")); } Ok((tag, asset)) } /// Streams `asset` to `dest` (mode 0755, fsynced), failing on a hash mismatch or the size cap. /// On error the caller removes `dest`. pub fn download(&self, asset: &Asset, dest: &Path) -> Res<()> { if asset.size > MAX_DOWNLOAD { return Err(format!("asset {} is larger than 1 GiB", asset.name)); } let mut resp = self.get(&asset.download_url, DOWNLOAD_TIMEOUT)?; if !resp.status().is_success() { return Err(format!("download returned {}", resp.status())); } let mut body = resp.body_mut().with_config().limit(MAX_DOWNLOAD).reader(); let mut file = File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?; let mut hasher = Sha256::new(); let mut buf = vec![0u8; 64 * 1024]; loop { let n = body .read(&mut buf) .map_err(|e| format!("download failed: {e}"))?; if n == 0 { break; } hasher.update(&buf[..n]); file.write_all(&buf[..n]) .map_err(|e| format!("write {}: {e}", dest.display()))?; } file.set_permissions(fs::Permissions::from_mode(0o755)) .and_then(|()| file.sync_all()) .map_err(|e| format!("finalize {}: {e}", dest.display()))?; let got = hex::encode(hasher.finalize()); if got != asset.sha256 { return Err(format!( "sha256 mismatch for {} (expected {}, got {got})", asset.name, asset.sha256 )); } Ok(()) } }