dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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;

/// Optional integrity expectations for an explicitly requested dataset download.
#[derive(Clone, Debug, Default)]
pub struct DownloadExpectation {
    size: Option<u64>,
    checksum: Option<ChecksumExpectation>,
}

#[derive(Clone, Debug)]
enum ChecksumExpectation {
    Declared(Checksum),
    SelectedSha256(Checksum),
}

impl DownloadExpectation {
    /// Creates expectations with no assumed size or checksum.
    pub fn new() -> Self {
        Self::default()
    }

    /// Requires the actual streamed byte count to equal `size`.
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = Some(size);
        self
    }

    /// Verifies an explicitly declared supported checksum, if one is present.
    pub fn with_checksum(mut self, checksum: Checksum) -> Self {
        self.checksum = Some(ChecksumExpectation::Declared(checksum));
        self
    }

    /// Explicitly verifies SHA-256, including for a bare algorithm-unspecified value.
    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)
        }
    }
}

/// Summary returned after streaming a dataset to a caller-provided sink.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct DownloadSummary {
    /// Actual streamed bytes.
    pub size: u64,
    /// Verification outcome; `Unverified` makes no integrity claim.
    pub integrity: IntegrityStatus,
}

/// A bounded, buffered dataset download.
#[derive(Clone, Eq, PartialEq)]
pub struct DownloadedDataset {
    /// Actual byte count and integrity outcome.
    pub summary: DownloadSummary,
    bytes: Bytes,
}

impl DownloadedDataset {
    /// Returns the original downloaded bytes.
    pub fn bytes(&self) -> &Bytes {
        &self.bytes
    }

    /// Consumes this download and returns its 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()
    }
}

/// Separate HTTPS downloader for URLs returned by DMVS.
///
/// It never inherits the SOAP client's mTLS identity, headers, cookies, or other
/// credentials. Ambient system proxies, redirects, and automatic retries are disabled.
#[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()
    }
}

/// Builder for [`DatasetDownloader`].
pub struct DatasetDownloaderBuilder {
    connect_timeout: Duration,
    timeout: Duration,
    max_bytes: usize,
    #[cfg(test)]
    allow_http: bool,
}

impl DatasetDownloader {
    /// Starts building a credential-free dataset downloader.
    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,
        }
    }

    /// Downloads to a bounded buffer after explicit caller initiation.
    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),
        })
    }

    /// Streams to a caller sink with a hard byte limit and optional verification.
    ///
    /// The sink may already contain bytes when an integrity or transport error is
    /// reported; callers should use temporary output and commit it after success.
    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 {
    /// Sets the connection timeout; the default is 10 seconds.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Sets the total request/streaming timeout; the default is 300 seconds.
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the maximum downloaded bytes; the default is 1 GiB.
    pub fn max_bytes(mut self, limit: usize) -> Self {
        self.max_bytes = limit;
        self
    }

    /// Builds the downloader without performing a network request.
    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());
    }
}