//! Registry HTTP transport seam. //! //! [`RegistryHttp`] is the test seam; [`ReqwestRegistryHttp`] is the production //! transport for package registries and deps.dev. The retry helpers use the //! reference-side policy: four attempts, sleeping 1s/2s/4s between retryable //! responses (429 and 5xx gateway/service errors) and transport failures. //! //! `download_limited` additionally enforces a byte cap while streaming, so a //! registry cannot exhaust memory. A cap rejection is a typed //! [`DownloadTooLarge`] error and is never retried. //! //! Non-success statuses surface as [`HttpStatusError`], which preserves the //! `Retry-After` and rate-limit headers so per-host governors (`host`) can //! back off. Error text never includes URL userinfo, query strings, or //! fragments. use std::fmt; use std::time::{Duration, UNIX_EPOCH}; use anyhow::{Context, Result, anyhow}; use async_trait::async_trait; use futures::StreamExt; use serde_json::Value; pub const USER_AGENT: &str = "vuln-notif/1.0 (+https://github.com/scanoss/purl2cpe)"; pub const HTTP_TIMEOUT: Duration = Duration::from_secs(60); pub const RETRY_DELAYS: [Duration; 3] = [ Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4), ]; /// A byte-cap rejection. Match with `anyhow::Error::downcast_ref`; size-cap /// failures are never retried. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DownloadTooLarge { pub url: String, pub limit: u64, /// Known size: the declared Content-Length, or the downloaded byte count /// for the defaulted `download` fallback. pub size: Option, } impl fmt::Display for DownloadTooLarge { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self.size { Some(size) => write!( formatter, "artifact {} is {size} bytes, over the {}-byte limit", redact_url(&self.url), self.limit ), None => write!( formatter, "artifact {} exceeds the {}-byte limit", redact_url(&self.url), self.limit ), } } } impl std::error::Error for DownloadTooLarge {} /// A non-success HTTP status with the rate-limit headers that came with it. /// /// `url` is already redacted: userinfo, query, and fragment are removed before /// the value is stored, so the error can be logged safely. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HttpStatusError { pub status: u16, pub url: String, pub retry_after: Option, pub rate_limit_remaining: Option, pub rate_limit_reset: Option, } impl HttpStatusError { pub fn new(status: u16, url: &str) -> Self { Self { status, url: redact_url(url), retry_after: None, rate_limit_remaining: None, rate_limit_reset: None, } } /// Delay implied by rate-limit signals, or `None` when this response is /// not a rate-limit response. /// /// A 429 always backs off (one second without `Retry-After`). A 403 backs /// off only when it carries `Retry-After` or exhausted/`reset` rate-limit /// headers; a plain authorization 403 returns `None`. pub fn rate_limit_delay(&self, now_unix: f64) -> Option { let seconds = match self.status { 429 => self .retry_after .as_deref() .and_then(|value| parse_retry_after(value, now_unix)) .unwrap_or(1.0), 403 => { if let Some(seconds) = self .retry_after .as_deref() .and_then(|value| parse_retry_after(value, now_unix)) { seconds } else if self.rate_limit_remaining == Some(0) || self.rate_limit_reset.is_some() { self.rate_limit_reset.map_or(1.0, |reset| { let reset = reset as f64; if reset > now_unix { reset - now_unix } else { reset } }) } else { return None; } } _ => return None, }; Some(Duration::from_secs_f64(seconds.max(0.0))) } } impl fmt::Display for HttpStatusError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "HTTP {} for {}", self.status, self.url) } } impl std::error::Error for HttpStatusError {} /// Parse `Retry-After`: a numeric number of seconds first, else an HTTP date. pub fn parse_retry_after(value: &str, now_unix: f64) -> Option { let value = value.trim(); if let Ok(seconds) = value.parse::() { return Some(seconds.max(0.0)); } let retry_at = httpdate::parse_http_date(value).ok()?; let retry_at = retry_at .duration_since(UNIX_EPOCH) .map(|d| d.as_secs_f64()) .unwrap_or(0.0); Some((retry_at - now_unix).max(0.0)) } /// Strip URL userinfo, query, and fragment before a URL is shown in an error. /// /// Scheme, host, port, and path are kept; nothing else is needed to identify /// the failing request and everything else can carry credentials. pub fn redact_url(url: &str) -> String { let url = url.split('#').next().unwrap_or(url); let url = url.split('?').next().unwrap_or(url); match url.split_once("://") { Some((scheme, rest)) => { let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let authority = &rest[..end]; let host = authority .rsplit_once('@') .map_or(authority, |(_, host)| host); format!("{scheme}://{host}{}", &rest[end..]) } None => url.to_owned(), } } #[async_trait] pub trait RegistryHttp: Send + Sync { async fn get_json(&self, url: &str) -> Result; /// GET with request headers. Defaulted so existing fakes keep compiling; /// the default ignores the headers. [`ReqwestRegistryHttp`] sends them. /// /// Headers carry credentials (for example a Gitee bearer token); this /// method never logs them and callers must not either. async fn get_json_with_headers( &self, url: &str, _headers: &[(String, String)], ) -> Result { self.get_json(url).await } async fn get_text(&self, url: &str) -> Result; async fn head_size(&self, url: &str) -> Result; /// Fetch the whole artifact. Only used for hashing and size. async fn download(&self, url: &str) -> Result>; /// Fetch an artifact with a hard byte cap. /// /// Defaulted so existing fakes keep compiling: the fallback downloads in /// full and then checks the size. [`ReqwestRegistryHttp`] streams instead /// and rejects from `Content-Length` before reading any body. async fn download_limited(&self, url: &str, max_bytes: u64) -> Result> { let bytes = self.download(url).await?; if bytes.len() as u64 > max_bytes { return Err(DownloadTooLarge { url: url.to_owned(), limit: max_bytes, size: Some(bytes.len() as u64), } .into()); } Ok(bytes) } /// POST a JSON body and decode a JSON response. /// /// Unsupported by default so fakes that only serve GET requests keep /// compiling; [`ReqwestRegistryHttp`] implements it with the same retry /// policy as [`RegistryHttp::get_json`]. async fn post_json(&self, url: &str, _body: &Value) -> Result { Err(anyhow!("POST {url} is not supported by this transport")) } } pub struct ReqwestRegistryHttp { client: reqwest::Client, } impl ReqwestRegistryHttp { pub fn new() -> Result { let client = reqwest::Client::builder() .timeout(HTTP_TIMEOUT) .user_agent(USER_AGENT) .redirect(reqwest::redirect::Policy::limited(10)) .build() .context("build registry HTTP client")?; Ok(Self { client }) } pub fn with_client(client: reqwest::Client) -> Self { Self { client } } async fn get_response(&self, url: &str) -> Result { self.send_with_retry(url, || self.client.get(url)).await } async fn get_response_with_headers( &self, url: &str, headers: &[(String, String)], ) -> Result { self.send_with_retry(url, || { let mut request = self.client.get(url); for (name, value) in headers { request = request.header(name.as_str(), value.as_str()); } request }) .await } async fn post_response(&self, url: &str, body: &Value) -> Result { self.send_with_retry(url, || self.client.post(url).json(body)) .await } async fn send_with_retry(&self, url: &str, build: F) -> Result where F: Fn() -> reqwest::RequestBuilder, { let mut last_error: Option = None; for attempt in 0..=RETRY_DELAYS.len() { if attempt > 0 { tokio::time::sleep(RETRY_DELAYS[attempt - 1]).await; } match build().send().await { Ok(response) => { let status = response.status(); if status == reqwest::StatusCode::OK { return Ok(response); } let error = status_error(status, url, response.headers()); if retryable(status) { last_error = Some(error); continue; } return Err(error); } Err(error) => { last_error = Some(anyhow!( "request failed for {}: {}", redact_url(url), error.without_url() )); } } } Err(last_error.unwrap_or_else(|| anyhow!("request failed for {}", redact_url(url)))) } /// Download with retries, an early `Content-Length` rejection, and a /// streaming cap. Size-cap rejections return immediately. async fn fetch_bytes(&self, url: &str, max_bytes: u64) -> Result> { let mut last_error: Option = None; for attempt in 0..=RETRY_DELAYS.len() { if attempt > 0 { tokio::time::sleep(RETRY_DELAYS[attempt - 1]).await; } match self.client.get(url).send().await { Ok(response) => { let status = response.status(); if status != reqwest::StatusCode::OK { let error = status_error(status, url, response.headers()); if retryable(status) { last_error = Some(error); continue; } return Err(error); } if let Some(size) = response .content_length() .or_else(|| header_content_length(&response)) && size > max_bytes { return Err(DownloadTooLarge { url: url.to_owned(), limit: max_bytes, size: Some(size), } .into()); } match read_capped(response, url, max_bytes).await { Ok(bytes) => return Ok(bytes), Err(error) if error.downcast_ref::().is_some() => { return Err(error); } Err(error) => last_error = Some(error), } } Err(error) => { last_error = Some(anyhow!( "request failed for {}: {}", redact_url(url), error.without_url() )) } } } Err(last_error.unwrap_or_else(|| anyhow!("request failed for {}", redact_url(url)))) } } fn retryable(status: reqwest::StatusCode) -> bool { matches!(status.as_u16(), 429 | 500 | 502 | 503 | 504) } fn status_error( status: reqwest::StatusCode, url: &str, headers: &reqwest::header::HeaderMap, ) -> anyhow::Error { let mut error = HttpStatusError::new(status.as_u16(), url); error.retry_after = header_value(headers, &["retry-after"]); error.rate_limit_remaining = header_value(headers, &["x-ratelimit-remaining", "ratelimit-remaining"]) .and_then(|value| value.parse().ok()); error.rate_limit_reset = header_value(headers, &["x-ratelimit-reset", "ratelimit-reset"]) .and_then(|value| value.parse().ok()); error.into() } fn header_value(headers: &reqwest::header::HeaderMap, names: &[&str]) -> Option { names.iter().find_map(|name| { headers .get(*name) .and_then(|value| value.to_str().ok()) .map(str::to_owned) }) } fn header_content_length(response: &reqwest::Response) -> Option { response .headers() .get(reqwest::header::CONTENT_LENGTH) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()) } async fn read_capped(response: reqwest::Response, url: &str, max_bytes: u64) -> Result> { let mut bytes = Vec::new(); let mut stream = response.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(|error| { anyhow!( "read body from {}: {}", redact_url(url), error.without_url() ) })?; if bytes.len() as u64 + chunk.len() as u64 > max_bytes { return Err(DownloadTooLarge { url: url.to_owned(), limit: max_bytes, size: None, } .into()); } bytes.extend_from_slice(&chunk); } Ok(bytes) } #[async_trait] impl RegistryHttp for ReqwestRegistryHttp { async fn get_json(&self, url: &str) -> Result { let response = self.get_response(url).await?; response.json::().await.map_err(|error| { anyhow!( "decode JSON from {}: {}", redact_url(url), error.without_url() ) }) } async fn get_json_with_headers( &self, url: &str, headers: &[(String, String)], ) -> Result { let response = self.get_response_with_headers(url, headers).await?; response.json::().await.map_err(|error| { anyhow!( "decode JSON from {}: {}", redact_url(url), error.without_url() ) }) } async fn get_text(&self, url: &str) -> Result { let response = self.get_response(url).await?; response.text().await.map_err(|error| { anyhow!( "read text from {}: {}", redact_url(url), error.without_url() ) }) } async fn head_size(&self, url: &str) -> Result { let response = self.send_with_retry(url, || self.client.head(url)).await?; let raw = response .headers() .get(reqwest::header::CONTENT_LENGTH) .and_then(|value| value.to_str().ok()) .unwrap_or("0"); raw.parse::() .with_context(|| format!("invalid Content-Length {raw:?} from {}", redact_url(url))) } async fn download(&self, url: &str) -> Result> { self.fetch_bytes(url, u64::MAX).await } async fn download_limited(&self, url: &str, max_bytes: u64) -> Result> { self.fetch_bytes(url, max_bytes).await } async fn post_json(&self, url: &str, body: &Value) -> Result { let response = self.post_response(url, body).await?; response.json::().await.map_err(|error| { anyhow!( "decode JSON from {}: {}", redact_url(url), error.without_url() ) }) } }