use std::fmt;
use std::time::Duration;
use bytes::Bytes;
use futures_util::StreamExt;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use url::Url;
use crate::model::{Checksum, IntegrityStatus};
use crate::{Error, Result};
const DEFAULT_MAX_DOWNLOAD_BYTES: usize = 1024 * 1024 * 1024;
#[derive(Clone, Debug, Default)]
pub struct DownloadExpectation {
size: Option<u64>,
checksum: Option<ChecksumExpectation>,
}
#[derive(Clone, Debug)]
enum ChecksumExpectation {
Declared(Checksum),
SelectedSha256(Checksum),
}
impl DownloadExpectation {
pub fn new() -> Self {
Self::default()
}
pub fn with_size(mut self, size: u64) -> Self {
self.size = Some(size);
self
}
pub fn with_checksum(mut self, checksum: Checksum) -> Self {
self.checksum = Some(ChecksumExpectation::Declared(checksum));
self
}
pub fn with_sha256_checksum(mut self, checksum: Checksum) -> Self {
self.checksum = Some(ChecksumExpectation::SelectedSha256(checksum));
self
}
fn verify(&self, bytes: &[u8]) -> Result<IntegrityStatus> {
if self.size.is_some_and(|size| size != bytes.len() as u64) {
return Err(Error::IntegrityMismatch);
}
match &self.checksum {
Some(ChecksumExpectation::Declared(checksum)) => checksum.verify(bytes),
Some(ChecksumExpectation::SelectedSha256(checksum)) => checksum.verify_sha256(bytes),
None => Ok(IntegrityStatus::Unverified),
}
}
fn verify_streaming(&self, size: u64, digest: sha2::Sha256) -> Result<IntegrityStatus> {
use sha2::Digest as _;
if self.size.is_some_and(|expected| expected != size) {
return Err(Error::IntegrityMismatch);
}
let Some(expectation) = &self.checksum else {
return Ok(IntegrityStatus::Unverified);
};
let actual = digest
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
let expected = match expectation {
ChecksumExpectation::Declared(checksum) => match checksum.declared_algorithm() {
Some(crate::ChecksumAlgorithm::Sha256) => {
checksum.as_str().trim_start_matches("SHA-256=")
}
None => return Ok(IntegrityStatus::Unverified),
},
ChecksumExpectation::SelectedSha256(checksum) => {
let value = checksum
.as_str()
.strip_prefix("SHA-256=")
.unwrap_or(checksum.as_str());
if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(Error::invalid_input(
"download.checksum",
"explicit SHA-256 verification requires 64 hexadecimal digits",
));
}
value
}
};
if actual.eq_ignore_ascii_case(expected) {
Ok(IntegrityStatus::Verified)
} else {
Err(Error::IntegrityMismatch)
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct DownloadSummary {
pub size: u64,
pub integrity: IntegrityStatus,
}
#[derive(Clone, Eq, PartialEq)]
pub struct DownloadedDataset {
pub summary: DownloadSummary,
bytes: Bytes,
}
impl DownloadedDataset {
pub fn bytes(&self) -> &Bytes {
&self.bytes
}
pub fn into_bytes(self) -> Bytes {
self.bytes
}
}
impl fmt::Debug for DownloadedDataset {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DownloadedDataset")
.field("summary", &self.summary)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct DatasetDownloader {
http: reqwest::Client,
max_bytes: usize,
}
impl fmt::Debug for DatasetDownloader {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DatasetDownloader")
.field("max_bytes", &self.max_bytes)
.field("credentials", &"none")
.finish_non_exhaustive()
}
}
pub struct DatasetDownloaderBuilder {
connect_timeout: Duration,
timeout: Duration,
max_bytes: usize,
#[cfg(test)]
allow_http: bool,
}
impl DatasetDownloader {
pub fn builder() -> DatasetDownloaderBuilder {
DatasetDownloaderBuilder {
connect_timeout: Duration::from_secs(10),
timeout: Duration::from_secs(300),
max_bytes: DEFAULT_MAX_DOWNLOAD_BYTES,
#[cfg(test)]
allow_http: false,
}
}
pub async fn download(
&self,
url: &Url,
expectation: DownloadExpectation,
) -> Result<DownloadedDataset> {
let response = self.start(url).await?;
let mut stream = response.bytes_stream();
let mut bytes = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|_| Error::Download {
message: "dataset response stream failed".into(),
})?;
self.append_bounded(&mut bytes, &chunk)?;
}
let summary = DownloadSummary {
size: bytes.len() as u64,
integrity: expectation.verify(&bytes)?,
};
Ok(DownloadedDataset {
summary,
bytes: Bytes::from(bytes),
})
}
pub async fn download_to<W: AsyncWrite + Unpin>(
&self,
url: &Url,
expectation: DownloadExpectation,
sink: &mut W,
) -> Result<DownloadSummary> {
use sha2::{Digest as _, Sha256};
let response = self.start(url).await?;
let mut stream = response.bytes_stream();
let mut size = 0_usize;
let mut digest = Sha256::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|_| Error::Download {
message: "dataset response stream failed".into(),
})?;
if size.saturating_add(chunk.len()) > self.max_bytes {
return Err(Error::ResponseTooLarge {
limit: self.max_bytes,
});
}
sink.write_all(&chunk).await.map_err(|_| Error::Download {
message: "dataset output sink failed".into(),
})?;
digest.update(&chunk);
size += chunk.len();
}
sink.flush().await.map_err(|_| Error::Download {
message: "dataset output sink flush failed".into(),
})?;
Ok(DownloadSummary {
size: size as u64,
integrity: expectation.verify_streaming(size as u64, digest)?,
})
}
async fn start(&self, url: &Url) -> Result<reqwest::Response> {
validate_url(url)?;
let response = self
.http
.get(url.clone())
.send()
.await
.map_err(|_| Error::Download {
message: "dataset HTTP request failed".into(),
})?;
let status = response.status();
if !status.is_success() {
return Err(Error::Download {
message: format!("dataset server returned HTTP status {}", status.as_u16()),
});
}
if response
.content_length()
.is_some_and(|length| length > self.max_bytes as u64)
{
return Err(Error::ResponseTooLarge {
limit: self.max_bytes,
});
}
Ok(response)
}
fn append_bounded(&self, bytes: &mut Vec<u8>, chunk: &[u8]) -> Result<()> {
if bytes.len().saturating_add(chunk.len()) > self.max_bytes {
return Err(Error::ResponseTooLarge {
limit: self.max_bytes,
});
}
bytes.extend_from_slice(chunk);
Ok(())
}
}
impl DatasetDownloaderBuilder {
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = timeout;
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn max_bytes(mut self, limit: usize) -> Self {
self.max_bytes = limit;
self
}
pub fn build(self) -> Result<DatasetDownloader> {
if self.connect_timeout.is_zero() || self.timeout.is_zero() || self.max_bytes == 0 {
return Err(Error::invalid_input(
"download.configuration",
"timeouts and byte limit must be greater than zero",
));
}
#[cfg(test)]
let https_only = !self.allow_http;
#[cfg(not(test))]
let https_only = true;
let http = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.https_only(https_only)
.connect_timeout(self.connect_timeout)
.timeout(self.timeout)
.user_agent(concat!("dmvs-downloader/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|_| Error::Download {
message: "could not construct the HTTP client".into(),
})?;
Ok(DatasetDownloader {
http,
max_bytes: self.max_bytes,
})
}
}
fn validate_url(url: &Url) -> Result<()> {
if url.scheme() != "https" && !(cfg!(test) && url.scheme() == "http") {
return Err(Error::Download {
message: "dataset URL must use HTTPS".into(),
});
}
if url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() {
return Err(Error::Download {
message: "dataset URL needs a host and must not contain user information".into(),
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use wiremock::matchers::{method, path};
use wiremock::{Match, Mock, MockServer, Request, ResponseTemplate};
struct NoCredentials;
impl Match for NoCredentials {
fn matches(&self, request: &Request) -> bool {
!request.headers.contains_key("authorization")
&& !request.headers.contains_key("proxy-authorization")
&& !request.headers.contains_key("cookie")
}
}
use super::*;
fn downloader(max_bytes: usize) -> DatasetDownloader {
DatasetDownloaderBuilder {
allow_http: true,
..DatasetDownloader::builder()
}
.max_bytes(max_bytes)
.build()
.unwrap()
}
#[tokio::test]
async fn directly_constructed_downloads_do_not_send_credentials() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/dataset"))
.and(NoCredentials)
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"dataset"))
.expect(2)
.mount(&server)
.await;
let url = Url::parse(&format!("{}/dataset", server.uri())).unwrap();
let downloader = downloader(1024);
let downloaded = downloader
.download(&url, DownloadExpectation::new().with_size(7))
.await
.unwrap();
assert_eq!(downloaded.bytes().as_ref(), b"dataset");
assert_eq!(downloaded.summary.integrity, IntegrityStatus::Unverified);
assert!(!format!("{downloaded:?}").contains("dataset"));
let mut sink = Vec::new();
let summary = downloader
.download_to(&url, DownloadExpectation::new(), &mut sink)
.await
.unwrap();
assert_eq!(sink, b"dataset");
assert_eq!(summary.size, 7);
}
#[tokio::test]
async fn rejects_redirects_insecure_urls_and_oversized_content() {
assert!(validate_url(&Url::parse("http://example.com/private").unwrap()).is_ok());
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/redirect"))
.respond_with(ResponseTemplate::new(302).insert_header("Location", "/secret"))
.expect(1)
.mount(&server)
.await;
let url = Url::parse(&format!("{}/redirect", server.uri())).unwrap();
assert!(
downloader(100)
.download(&url, DownloadExpectation::new())
.await
.is_err()
);
let url = Url::parse(&format!("{}/large", server.uri())).unwrap();
Mock::given(method("GET"))
.and(path("/large"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"too large"))
.mount(&server)
.await;
assert!(matches!(
downloader(3)
.download(&url, DownloadExpectation::new())
.await,
Err(Error::ResponseTooLarge { limit: 3 })
));
}
#[test]
fn production_validation_is_https_only_and_rejects_userinfo() {
assert!(validate_url(&Url::parse("ftp://example.com/file").unwrap()).is_err());
assert!(validate_url(&Url::parse("https://user@example.com/file").unwrap()).is_err());
assert!(validate_url(&Url::parse("https://example.com/file").unwrap()).is_ok());
}
}