mod codelists;
mod datasets;
mod inquiries;
mod lifecycle;
mod registry;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use futures_util::StreamExt;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use secrecy::{ExposeSecret, SecretString};
use tokio::sync::Semaphore;
use crate::error::{Error, Result};
use crate::model::{CorrelationId, InputFile, Response, SubjectId};
use crate::wire::mtom::{Attachments, MimeLimits, SoapBody};
use crate::wire::soap::{self, Operation, XmlLimits, XmlResult};
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_MAX_RESPONSE_BYTES: usize = 256 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Environment {
Integration,
Production,
}
impl Environment {
fn base_url(self) -> &'static str {
match self {
Self::Integration => "https://dmvs-i.cuzk.gov.cz:8443/api/ws/v1",
Self::Production => "https://dmvs.cuzk.gov.cz:8443/api/ws/v1",
}
}
}
#[derive(Clone)]
pub struct TlsIdentity {
combined_pem: SecretString,
}
impl TlsIdentity {
pub fn from_pem(certificate_chain: impl AsRef<str>, private_key: impl AsRef<str>) -> Self {
let combined = format!(
"{}\n{}\n",
certificate_chain.as_ref().trim(),
private_key.as_ref().trim()
);
Self {
combined_pem: SecretString::new(combined.into_boxed_str()),
}
}
pub fn from_combined_pem(pem: impl Into<String>) -> Self {
Self {
combined_pem: SecretString::new(pem.into().into_boxed_str()),
}
}
}
impl fmt::Debug for TlsIdentity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("TlsIdentity([REDACTED])")
}
}
#[derive(Clone)]
pub struct Client {
inner: Arc<ClientInner>,
}
struct ClientInner {
http: reqwest::Client,
environment: Environment,
subject_id: SubjectId,
base_url: String,
max_request_bytes: usize,
max_response_bytes: usize,
xml_limits: XmlLimits,
mime_limits: MimeLimits,
permits: Semaphore,
}
impl fmt::Debug for Client {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Client")
.field("environment", &self.inner.environment)
.field("base_url", &self.inner.base_url)
.field("max_request_bytes", &self.inner.max_request_bytes)
.field("max_response_bytes", &self.inner.max_response_bytes)
.field("tls_identity", &"[REDACTED]")
.finish_non_exhaustive()
}
}
pub struct ClientBuilder {
environment: Environment,
identity: Option<TlsIdentity>,
subject_id: Option<SubjectId>,
connect_timeout: Duration,
timeout: Duration,
max_request_bytes: usize,
max_response_bytes: usize,
max_xml_nodes: u32,
max_xml_depth: u32,
max_mime_parts: usize,
max_decoded_file_bytes: usize,
max_total_decoded_file_bytes: usize,
max_concurrency: usize,
#[cfg(test)]
test_base_url: Option<String>,
}
impl Client {
pub fn builder(environment: Environment) -> ClientBuilder {
ClientBuilder {
environment,
identity: None,
subject_id: None,
connect_timeout: DEFAULT_CONNECT_TIMEOUT,
timeout: DEFAULT_TIMEOUT,
max_request_bytes: soap::DEFAULT_MAX_REQUEST_BYTES,
max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
max_xml_nodes: 2_000_000,
max_xml_depth: 256,
max_mime_parts: 32,
max_decoded_file_bytes: DEFAULT_MAX_RESPONSE_BYTES,
max_total_decoded_file_bytes: DEFAULT_MAX_RESPONSE_BYTES,
max_concurrency: 1,
#[cfg(test)]
test_base_url: None,
}
}
pub fn environment(&self) -> Environment {
self.inner.environment
}
pub fn subject_id(&self) -> &SubjectId {
&self.inner.subject_id
}
pub(crate) async fn execute<T>(
&self,
operation: Operation,
correlation_id: CorrelationId,
write_request: impl FnOnce(&mut soap::XmlWriter) -> XmlResult,
decode_response: impl FnOnce(Option<roxmltree::Node<'_, '_>>) -> Result<T>,
) -> Result<Response<T>> {
self.execute_with_files(operation, correlation_id, write_request, |data, _| {
decode_response(data)
})
.await
}
pub(crate) async fn execute_with_files<T>(
&self,
operation: Operation,
correlation_id: CorrelationId,
write_request: impl FnOnce(&mut soap::XmlWriter) -> XmlResult,
decode_response: impl FnOnce(Option<roxmltree::Node<'_, '_>>, &Attachments<'_>) -> Result<T>,
) -> Result<Response<T>> {
let request = soap::request_with_limit(
operation,
correlation_id,
self.inner.max_request_bytes,
write_request,
)?;
self.execute_encoded(
operation,
correlation_id,
request,
"text/xml; charset=utf-8",
decode_response,
)
.await
}
pub(crate) async fn execute_submission<T>(
&self,
operation: Operation,
correlation_id: CorrelationId,
files: &[InputFile],
write_request: impl FnOnce(&mut soap::XmlWriter) -> XmlResult,
decode_response: impl FnOnce(Option<roxmltree::Node<'_, '_>>) -> Result<T>,
) -> Result<Response<T>> {
let xml = soap::request_with_limit(
operation,
correlation_id,
self.inner.max_request_bytes,
write_request,
)?;
let request =
super::wire::mtom::encode_multipart(xml, files, self.inner.max_request_bytes)?;
self.execute_encoded(
operation,
correlation_id,
request.body,
&request.content_type,
|data, _| decode_response(data),
)
.await
.map_err(|error| match error {
Error::Transport(_)
| Error::Http { .. }
| Error::ResponseTooLarge { .. }
| Error::InvalidResponse { .. }
| Error::IntegrityMismatch
| Error::Download { .. } => Error::SubmissionUncertain {
source: Box::new(error),
},
other => other,
})
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(
name = "dmvs.request",
level = "debug",
skip_all,
fields(operation = operation.action, endpoint = operation.service.path(), environment = ?self.inner.environment)
)
)]
async fn execute_encoded<T>(
&self,
operation: Operation,
correlation_id: CorrelationId,
request: Vec<u8>,
request_content_type: &str,
decode_response: impl FnOnce(Option<roxmltree::Node<'_, '_>>, &Attachments<'_>) -> Result<T>,
) -> Result<Response<T>> {
let permit = self
.inner
.permits
.acquire()
.await
.map_err(|_| Error::invalid_input("concurrency", "request limiter is closed"))?;
let url = format!("{}/{}", self.inner.base_url, operation.service.path());
let response = self
.inner
.http
.post(url)
.header(CONTENT_TYPE, request_content_type)
.header(ACCEPT, "text/xml, multipart/related")
.header("SOAPAction", format!("\"{}\"", operation.action))
.body(request)
.send()
.await
.map_err(Error::Transport)?;
let status = response.status();
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
return Err(Error::Authentication {
status: status.as_u16(),
});
}
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let body = read_bounded(response, self.inner.max_response_bytes).await?;
#[cfg(feature = "tracing")]
tracing::debug!(
http_status = status.as_u16(),
response_bytes = body.len(),
"DMVS response received"
);
let decoded = SoapBody::parse(&body, content_type.as_deref(), self.inner.mime_limits)
.and_then(|body| {
soap::decode_with_attachments(
body.xml,
&body.attachments,
operation,
correlation_id,
self.inner.xml_limits,
decode_response,
)
});
let result = if status.is_success() {
decoded
} else {
match decoded {
Err(error @ (Error::SoapFault { .. } | Error::Service(_))) => Err(error),
_ => Err(Error::Http {
status: status.as_u16(),
}),
}
};
drop(permit);
result
}
#[cfg(test)]
pub(crate) fn test_client(base_url: String) -> Self {
let key = rcgen::KeyPair::generate().unwrap();
let params = rcgen::CertificateParams::new(vec!["localhost".to_owned()]).unwrap();
let certificate = params.self_signed(&key).unwrap();
ClientBuilder {
test_base_url: Some(base_url),
..Client::builder(Environment::Integration)
}
.identity(TlsIdentity::from_pem(
certificate.pem(),
key.serialize_pem(),
))
.subject_id(SubjectId::new("requester-id").unwrap())
.build()
.unwrap()
}
}
impl ClientBuilder {
pub fn identity(mut self, identity: TlsIdentity) -> Self {
self.identity = Some(identity);
self
}
pub fn subject_id(mut self, subject_id: SubjectId) -> Self {
self.subject_id = Some(subject_id);
self
}
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_request_bytes(mut self, limit: usize) -> Self {
self.max_request_bytes = limit;
self
}
pub fn max_response_bytes(mut self, limit: usize) -> Self {
self.max_response_bytes = limit;
self
}
pub fn max_xml_nodes(mut self, limit: u32) -> Self {
self.max_xml_nodes = limit;
self
}
pub fn max_xml_depth(mut self, limit: u32) -> Self {
self.max_xml_depth = limit;
self
}
pub fn max_mime_parts(mut self, limit: usize) -> Self {
self.max_mime_parts = limit;
self
}
pub fn max_decoded_file_bytes(mut self, limit: usize) -> Self {
self.max_decoded_file_bytes = limit;
self
}
pub fn max_total_decoded_file_bytes(mut self, limit: usize) -> Self {
self.max_total_decoded_file_bytes = limit;
self
}
pub fn max_concurrency(mut self, limit: usize) -> Self {
self.max_concurrency = limit;
self
}
pub fn build(self) -> Result<Client> {
let identity = self
.identity
.ok_or_else(|| Error::invalid_input("identity", "a TLS identity is required"))?;
let subject_id = self
.subject_id
.ok_or_else(|| Error::invalid_input("subject_id", "a subject ID is required"))?;
for (field, invalid) in [
("connect_timeout", self.connect_timeout.is_zero()),
("request_timeout", self.timeout.is_zero()),
("max_request_bytes", self.max_request_bytes == 0),
("max_response_bytes", self.max_response_bytes == 0),
("max_xml_nodes", self.max_xml_nodes == 0),
("max_xml_depth", self.max_xml_depth == 0),
("max_mime_parts", self.max_mime_parts == 0),
("max_decoded_file_bytes", self.max_decoded_file_bytes == 0),
(
"max_total_decoded_file_bytes",
self.max_total_decoded_file_bytes == 0,
),
("max_concurrency", self.max_concurrency == 0),
] {
if invalid {
return Err(Error::invalid_input(
field,
"value must be greater than zero",
));
}
}
#[cfg(test)]
let (base_url, https_only) = match self.test_base_url {
Some(url) => (url, false),
None => (self.environment.base_url().to_owned(), true),
};
#[cfg(not(test))]
let (base_url, https_only) = (self.environment.base_url().to_owned(), true);
if self.max_concurrency > Semaphore::MAX_PERMITS {
return Err(Error::invalid_input(
"max_concurrency",
format!("value must not exceed {}", Semaphore::MAX_PERMITS),
));
}
let identity = reqwest::Identity::from_pem(
identity.combined_pem.expose_secret().as_bytes(),
)
.map_err(|_| Error::TlsIdentity {
message: "expected a supported PEM certificate chain and private key".to_owned(),
})?;
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.https_only(https_only)
.connect_timeout(self.connect_timeout)
.timeout(self.timeout)
.identity(identity)
.user_agent(concat!("dmvs/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(Error::Transport)?;
Ok(Client {
inner: Arc::new(ClientInner {
http,
environment: self.environment,
subject_id,
base_url: base_url.trim_end_matches('/').to_owned(),
max_request_bytes: self.max_request_bytes,
max_response_bytes: self.max_response_bytes,
xml_limits: XmlLimits {
max_nodes: self.max_xml_nodes,
max_depth: self.max_xml_depth,
},
mime_limits: MimeLimits {
max_parts: self.max_mime_parts,
max_decoded_bytes: self.max_decoded_file_bytes,
max_total_decoded_bytes: self.max_total_decoded_file_bytes,
},
permits: Semaphore::new(self.max_concurrency),
}),
})
}
}
async fn read_bounded(response: reqwest::Response, limit: usize) -> Result<Bytes> {
if response
.content_length()
.is_some_and(|length| length > limit as u64)
{
return Err(Error::ResponseTooLarge { limit });
}
let mut stream = response.bytes_stream();
let mut body = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(Error::Transport)?;
if body.len().saturating_add(chunk.len()) > limit {
return Err(Error::ResponseTooLarge { limit });
}
body.extend_from_slice(&chunk);
}
Ok(Bytes::from(body))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn environment_has_fixed_https_endpoints() {
assert!(
Environment::Integration
.base_url()
.starts_with("https://dmvs-i.cuzk.gov.cz")
);
assert!(
Environment::Production
.base_url()
.starts_with("https://dmvs.cuzk.gov.cz")
);
}
#[test]
fn identity_and_configuration_are_validated_without_network() {
let error = Client::builder(Environment::Integration)
.build()
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "identity",
..
}
));
let identity = TlsIdentity::from_pem("not a certificate", "not a key");
assert_eq!(format!("{identity:?}"), "TlsIdentity([REDACTED])");
let error = Client::builder(Environment::Production)
.identity(identity.clone())
.build()
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "subject_id",
..
}
));
let error = Client::builder(Environment::Production)
.identity(identity.clone())
.subject_id(SubjectId::new("subject").unwrap())
.max_request_bytes(0)
.build()
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "max_request_bytes",
..
}
));
let error = Client::builder(Environment::Production)
.identity(identity.clone())
.subject_id(SubjectId::new("subject").unwrap())
.max_concurrency(usize::MAX)
.build()
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "max_concurrency",
..
}
));
let error = Client::builder(Environment::Production)
.identity(identity)
.subject_id(SubjectId::new("subject").unwrap())
.build()
.unwrap_err();
assert!(matches!(error, Error::TlsIdentity { .. }));
}
#[test]
fn generated_test_identity_builds_a_client() {
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_RSA_SHA256).unwrap();
let key_pem = key.serialize_pem();
assert!(key_pem.starts_with("-----BEGIN PRIVATE KEY-----"));
let params = rcgen::CertificateParams::new(vec!["localhost".to_owned()]).unwrap();
let certificate = params.self_signed(&key).unwrap();
let client = Client::builder(Environment::Integration)
.identity(TlsIdentity::from_pem(
certificate.pem(),
key.serialize_pem(),
))
.subject_id(SubjectId::new("subject").unwrap())
.build()
.unwrap();
assert_eq!(client.environment(), Environment::Integration);
assert_eq!(client.subject_id().as_str(), "subject");
}
}