use crate::wire::soap::XmlWriter as Writer;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use roxmltree::Node;
use crate::model::{
CodeList, CodeListAttribute, CodeListAttributeKind, CodeListAttributeReference,
CodeListDataType, CodeListInfo, CodeListItem, CodeListItemAttribute, CodeListVersionInfo,
CorrelationId, IsDmvsCertificate, JvfVersion, JvfVersionInfo, Response,
};
use crate::wire::files;
use crate::wire::mtom::Attachments;
use crate::wire::soap::{self, Operation, Service};
use crate::{Client, Error, Result};
const LIST_CODE_LISTS: Operation = Operation::new(
Service::R24a,
"vylistujCiselniky",
"VylistujCiselniky",
"VylistujCiselnikyOdpoved",
);
const READ_CODE_LIST: Operation = Operation::new(
Service::R24a,
"ctiCiselnik",
"CtiCiselnik",
"CtiCiselnikOdpoved",
);
const LIST_JVF_VERSIONS: Operation = Operation::new(
Service::R24a,
"vylistujVerzeJvf",
"VylistujVerzeJvf",
"VylistujVerzeJvfOdpoved",
);
const READ_JVF_VERSION: Operation = Operation::new(
Service::R24a,
"ctiVerziJvf",
"CtiVerziJvf",
"CtiVerziJvfOdpoved",
);
const LIST_IS_DMVS_CERTIFICATES: Operation = Operation::new(
Service::R24a,
"vylistujCertifikatyIsDmvs",
"VylistujCertifikatyIsDmvs",
"VylistujCertifikatyIsDmvsOdpoved",
);
const CODELISTS_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Ciselniky:v1";
const COMMON_JVF_NS: &str = "urn:cz:isvs:dmvs:common:schemas:Jvf:v1";
const ISDMVS_JVF_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:Jvf:v1";
const IS_DMVS_NS: &str = "urn:cz:isvs:dmvs:isdmvs:schemas:IsDmvs:v1";
impl Client {
/// Lists available central code lists through R24a `vylistujCiselniky`.
pub async fn list_code_lists(&self) -> Result<Response<Vec<CodeListInfo>>> {
self.list_code_lists_at(CorrelationId::new()).await
}
async fn list_code_lists_at(
&self,
correlation_id: CorrelationId,
) -> Result<Response<Vec<CodeListInfo>>> {
self.execute(
LIST_CODE_LISTS,
correlation_id,
|_| Ok(()),
decode_code_lists,
)
.await
}
/// Reads one code-list version through R24a `ctiCiselnik`.
///
/// If `version` is `None`, the service selects the current version. A
/// successful response without `Data` is returned as `None`.
pub async fn read_code_list(
&self,
id: &str,
version: Option<&str>,
) -> Result<Response<Option<CodeList>>> {
self.read_code_list_at(CorrelationId::new(), id, version)
.await
}
async fn read_code_list_at(
&self,
correlation_id: CorrelationId,
id: &str,
version: Option<&str>,
) -> Result<Response<Option<CodeList>>> {
self.execute(
READ_CODE_LIST,
correlation_id,
|writer| write_code_list_request(writer, id, version),
decode_code_list,
)
.await
}
/// Lists all documented JVF versions through R24a `vylistujVerzeJvf`.
pub async fn list_jvf_versions(&self) -> Result<Response<Vec<JvfVersionInfo>>> {
self.list_jvf_versions_at(CorrelationId::new()).await
}
async fn list_jvf_versions_at(
&self,
correlation_id: CorrelationId,
) -> Result<Response<Vec<JvfVersionInfo>>> {
self.execute(
LIST_JVF_VERSIONS,
correlation_id,
|_| Ok(()),
decode_jvf_versions,
)
.await
}
/// Reads a JVF version and its original file through R24a `ctiVerziJvf`.
///
/// If `version` is `None`, the service selects the current version. A
/// successful response without `Data` is returned as `None`.
pub async fn read_jvf_version(
&self,
version: Option<&str>,
) -> Result<Response<Option<JvfVersion>>> {
self.read_jvf_version_at(CorrelationId::new(), version)
.await
}
async fn read_jvf_version_at(
&self,
correlation_id: CorrelationId,
version: Option<&str>,
) -> Result<Response<Option<JvfVersion>>> {
self.execute_with_files(
READ_JVF_VERSION,
correlation_id,
|writer| write_jvf_version_request(writer, version),
decode_jvf_version,
)
.await
}
/// Lists IS DMVS authentication certificates through R24a
/// `vylistujCertifikatyIsDmvs`.
pub async fn list_is_dmvs_certificates(&self) -> Result<Response<Vec<IsDmvsCertificate>>> {
self.list_is_dmvs_certificates_at(CorrelationId::new())
.await
}
async fn list_is_dmvs_certificates_at(
&self,
correlation_id: CorrelationId,
) -> Result<Response<Vec<IsDmvsCertificate>>> {
self.execute(
LIST_IS_DMVS_CERTIFICATES,
correlation_id,
|writer| soap::empty_element(writer, "Data"),
decode_is_dmvs_certificates,
)
.await
}
}
fn write_data_with_namespace(
writer: &mut Writer,
namespace_declaration: (&str, &str),
write_contents: impl FnOnce(&mut Writer) -> soap::XmlResult,
) -> soap::XmlResult {
let mut data = BytesStart::new("Data");
data.push_attribute(namespace_declaration);
writer.write_event(Event::Start(data))?;
write_contents(writer)?;
writer.write_event(Event::End(BytesEnd::new("Data")))?;
Ok(())
}
fn write_code_list_request(
writer: &mut Writer,
id: &str,
version: Option<&str>,
) -> soap::XmlResult {
write_data_with_namespace(writer, ("xmlns:c", CODELISTS_NS), |writer| {
soap::element(writer, "Ciselnik", |writer| {
soap::text_element(writer, "c:Id", id)
})?;
if let Some(version) = version {
soap::text_element(writer, "Verze", version)?;
}
Ok(())
})
}
fn write_jvf_version_request(writer: &mut Writer, version: Option<&str>) -> soap::XmlResult {
let Some(version) = version else {
return soap::empty_element(writer, "Data");
};
write_data_with_namespace(writer, ("xmlns:j", COMMON_JVF_NS), |writer| {
soap::element(writer, "Verze", |writer| {
soap::text_element(writer, "j:Verze", version)
})
})
}
fn required_child<'a, 'input>(
node: Node<'a, 'input>,
namespace: &str,
name: &str,
) -> Result<Node<'a, 'input>> {
soap::child(node, namespace, name)?
.ok_or_else(|| Error::invalid_response(format!("required XML element {name} is missing")))
}
struct CodeListBase {
id: String,
name: String,
attributes: Vec<CodeListAttribute>,
}
fn decode_code_list_base(node: Node<'_, '_>) -> Result<CodeListBase> {
let attributes = required_child(node, CODELISTS_NS, "Atributy")?;
Ok(CodeListBase {
id: soap::required_text(node, CODELISTS_NS, "Id")?,
name: soap::required_text_or_empty(node, CODELISTS_NS, "Nazev")?,
attributes: soap::children(attributes, CODELISTS_NS, "Atribut")
.map(decode_code_list_attribute)
.collect::<Result<_>>()?,
})
}
fn decode_code_list_attribute(node: Node<'_, '_>) -> Result<CodeListAttribute> {
let plain = soap::child(node, CODELISTS_NS, "PlainAtribut")?;
let reference = soap::child(node, CODELISTS_NS, "RefAtribut")?;
let kind = match (plain, reference) {
(Some(plain), None) => CodeListAttributeKind::Plain(CodeListDataType::from_raw(
soap::required_text(plain, CODELISTS_NS, "DatovyTyp")?,
)),
(None, Some(reference)) => CodeListAttributeKind::Reference(CodeListAttributeReference {
code_list_id: soap::required_text(reference, CODELISTS_NS, "Ciselnik")?,
attribute_id: soap::required_text(reference, CODELISTS_NS, "Atribut")?,
}),
_ => {
return Err(Error::invalid_response(
"code-list attribute must contain exactly one representation",
));
}
};
Ok(CodeListAttribute {
id: soap::required_text(node, CODELISTS_NS, "Id")?,
name: soap::required_text_or_empty(node, CODELISTS_NS, "Nazev")?,
kind,
})
}
fn decode_code_list_version(node: Node<'_, '_>) -> Result<CodeListVersionInfo> {
Ok(CodeListVersionInfo {
version: soap::required_text(node, CODELISTS_NS, "Verze")?,
valid_from: soap::parse_date_time(soap::required_text(node, CODELISTS_NS, "PlatnostOd")?)?,
valid_to: soap::optional_text(node, CODELISTS_NS, "PlatnostDo")?
.map(soap::parse_date_time)
.transpose()?,
})
}
fn decode_code_list_info(node: Node<'_, '_>) -> Result<CodeListInfo> {
let base = decode_code_list_base(node)?;
let latest_version = required_child(node, CODELISTS_NS, "PosledniVerze")?;
Ok(CodeListInfo {
id: base.id,
name: base.name,
attributes: base.attributes,
latest_version: decode_code_list_version(latest_version)?,
})
}
fn decode_code_lists(data: Option<Node<'_, '_>>) -> Result<Vec<CodeListInfo>> {
let Some(data) = data else {
return Ok(Vec::new());
};
let service = Service::R24a.namespace();
let code_lists = required_child(data, service, "Ciselniky")?;
soap::children(code_lists, service, "Ciselnik")
.map(decode_code_list_info)
.collect()
}
fn decode_code_list(data: Option<Node<'_, '_>>) -> Result<Option<CodeList>> {
let Some(data) = data else {
return Ok(None);
};
let service = Service::R24a.namespace();
let info = required_child(data, service, "Ciselnik")?;
let base = decode_code_list_base(info)?;
let version = required_child(data, service, "Verze")?;
let items = required_child(data, service, "Polozky")?;
Ok(Some(CodeList {
id: base.id,
name: base.name,
attributes: base.attributes,
version: decode_code_list_version(version)?,
items: soap::children(items, service, "Polozka")
.map(decode_code_list_item)
.collect::<Result<_>>()?,
}))
}
fn decode_code_list_item(node: Node<'_, '_>) -> Result<CodeListItem> {
let attributes = required_child(node, CODELISTS_NS, "Atributy")?;
Ok(CodeListItem {
attributes: soap::children(attributes, CODELISTS_NS, "Atribut")
.map(decode_code_list_item_attribute)
.collect::<Result<_>>()?,
invalidated: soap::parse_bool(
&soap::required_text(node, CODELISTS_NS, "Zneplatneno")?,
"Zneplatneno",
)?,
})
}
fn decode_code_list_item_attribute(node: Node<'_, '_>) -> Result<CodeListItemAttribute> {
if node.children().any(|child| {
child.is_element()
|| child.is_text() && child.text().is_some_and(|text| !text.trim().is_empty())
}) {
return Err(Error::invalid_response(
"code-list item attribute must be empty",
));
}
let id = node
.attribute("id")
.ok_or_else(|| Error::invalid_response("code-list item attribute id is missing"))?;
let value = node
.attribute("hodnota")
.ok_or_else(|| Error::invalid_response("code-list item attribute value is missing"))?;
Ok(CodeListItemAttribute {
id: id.to_owned(),
value: value.to_owned(),
})
}
fn decode_jvf_version_info(version: Node<'_, '_>) -> Result<JvfVersionInfo> {
Ok(JvfVersionInfo {
version: soap::required_text(version, COMMON_JVF_NS, "Verze")?,
valid_from: soap::parse_date_time(soap::required_text(
version,
ISDMVS_JVF_NS,
"PlatnostOd",
)?)?,
valid_to: soap::optional_text(version, ISDMVS_JVF_NS, "PlatnostDo")?
.map(soap::parse_date_time)
.transpose()?,
description: soap::required_text_or_empty(version, ISDMVS_JVF_NS, "Popis")?,
})
}
fn decode_jvf_versions(data: Option<Node<'_, '_>>) -> Result<Vec<JvfVersionInfo>> {
let Some(data) = data else {
return Ok(Vec::new());
};
let service = Service::R24a.namespace();
let versions = required_child(data, service, "Verze")?;
soap::children(versions, service, "Verze")
.map(decode_jvf_version_info)
.collect()
}
fn decode_jvf_version(
data: Option<Node<'_, '_>>,
attachments: &Attachments<'_>,
) -> Result<Option<JvfVersion>> {
let Some(data) = data else {
return Ok(None);
};
let version = required_child(data, Service::R24a.namespace(), "Verze")?;
let info = decode_jvf_version_info(version)?;
let content = required_child(version, ISDMVS_JVF_NS, "Obsah")?;
Ok(Some(JvfVersion {
version: info.version,
valid_from: info.valid_from,
valid_to: info.valid_to,
description: info.description,
content: files::decode_output_file(content, attachments)?,
}))
}
fn decode_is_dmvs_certificates(data: Option<Node<'_, '_>>) -> Result<Vec<IsDmvsCertificate>> {
let Some(data) = data else {
return Ok(Vec::new());
};
let service = Service::R24a.namespace();
let certificates = required_child(data, service, "Certifikaty")?;
soap::children(certificates, service, "Certifikat")
.map(|certificate| {
Ok(IsDmvsCertificate {
usage_started_at: soap::parse_date_time(soap::required_text(
certificate,
IS_DMVS_NS,
"ZacatekPouzivani",
)?)?,
valid_from: soap::parse_date_time(soap::required_text(
certificate,
IS_DMVS_NS,
"PlatnostOd",
)?)?,
valid_to: soap::parse_date_time(soap::required_text(
certificate,
IS_DMVS_NS,
"PlatnostDo",
)?)?,
certificate_pem: soap::required_text(certificate, IS_DMVS_NS, "Certifikat")?,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use wiremock::matchers::{body_string, header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
use super::*;
use crate::wire::mtom::{MimeLimits, SoapBody};
const REQUEST_UUID: &str = "ed8af7af-5b39-4dff-96ab-7561214336f1";
const RESPONSE_UUID: &str = "c5f073e9-d3e9-4845-aae0-de3ef42357be";
const JVF_BYTES: &[u8] = b"synthetic JVF\0content";
fn limits() -> soap::XmlLimits {
soap::XmlLimits {
max_nodes: 65_536,
max_depth: 128,
}
}
fn operation_response(operation: Operation, data: Option<&str>) -> String {
let data = data
.map(|data| format!("<r:Data>{data}</r:Data>"))
.unwrap_or_default();
format!(
"<s:Envelope xmlns:s=\"{}\" xmlns:r=\"{}\" xmlns:m=\"{}\" xmlns:c=\"{CODELISTS_NS}\" xmlns:cj=\"{COMMON_JVF_NS}\" xmlns:ij=\"{ISDMVS_JVF_NS}\" xmlns:is=\"{IS_DMVS_NS}\" xmlns:f=\"{}\" xmlns:xop=\"http://www.w3.org/2004/08/xop/include\"><s:Body><r:{}><m:Hlavicka><m:UidOdpovedi>{RESPONSE_UUID}</m:UidOdpovedi><m:Vysledek stav=\"OK\"><m:UidZadosti>{REQUEST_UUID}</m:UidZadosti><m:Hlaseni><m:Hlaseni kod=\"1000\" typ=\"Informace\"><m:Zprava>Synthetic success</m:Zprava></m:Hlaseni></m:Hlaseni></m:Vysledek></m:Hlavicka>{data}</r:{}></s:Body></s:Envelope>",
soap::SOAP_11_NS,
Service::R24a.namespace(),
soap::MESSAGES_NS,
files::FILES_NS,
operation.response,
operation.response,
)
}
fn decode_jvf_body(
bytes: &[u8],
content_type: Option<&str>,
) -> Result<Response<Option<JvfVersion>>> {
let body = SoapBody::parse(
bytes,
content_type,
MimeLimits {
max_parts: 4,
max_decoded_bytes: 1024,
max_total_decoded_bytes: 2048,
},
)?;
soap::decode_with_attachments(
body.xml,
&body.attachments,
READ_JVF_VERSION,
REQUEST_UUID.parse().unwrap(),
limits(),
decode_jvf_version,
)
}
fn jvf_data(content: &str) -> String {
format!(
"<r:Verze><cj:Verze>1.0.0</cj:Verze><ij:PlatnostOd>2022-01-01T00:00:00.000+01:00</ij:PlatnostOd><ij:PlatnostDo>2022-04-20T23:59:59.000+02:00</ij:PlatnostDo><ij:Popis>Synthetic JVF version</ij:Popis><ij:Obsah><f:Obsah>{content}</f:Obsah><f:Nazev>jvf-1.0.0.zip</f:Nazev><f:Velikost>{}</f:Velikost><f:KontrolniSoucet>synthetic-checksum</f:KontrolniSoucet></ij:Obsah></r:Verze>",
JVF_BYTES.len(),
)
}
fn code_list_info() -> &'static str {
"<r:Ciselniky><r:Ciselnik><c:Id>CS_SYNTHETIC</c:Id><c:Nazev>Synthetic code list</c:Nazev><c:Atributy><c:Atribut><c:Id>CODE</c:Id><c:Nazev>Code</c:Nazev><c:PlainAtribut><c:DatovyTyp>String</c:DatovyTyp></c:PlainAtribut></c:Atribut><c:Atribut><c:Id>VALID_FROM</c:Id><c:Nazev>Valid from</c:Nazev><c:PlainAtribut><c:DatovyTyp>FutureDateTime</c:DatovyTyp></c:PlainAtribut></c:Atribut><c:Atribut><c:Id>OWNER</c:Id><c:Nazev>Owner</c:Nazev><c:RefAtribut><c:Ciselnik>CS_OWNER</c:Ciselnik><c:Atribut>ID</c:Atribut></c:RefAtribut></c:Atribut></c:Atributy><c:PosledniVerze><c:Verze>1.2.0</c:Verze><c:PlatnostOd>2024-01-01T00:00:00+01:00</c:PlatnostOd><c:PlatnostDo>2024-12-31T23:59:59+01:00</c:PlatnostDo></c:PosledniVerze></r:Ciselnik></r:Ciselniky>"
}
async fn expect_exchange(
server: &MockServer,
operation: Operation,
request: Vec<u8>,
response: String,
) {
Mock::given(method("POST"))
.and(path("/R24aCteniCiselniku"))
.and(header("SOAPAction", format!("\"{}\"", operation.action)))
.and(header("Content-Type", "text/xml; charset=utf-8"))
.and(body_string(String::from_utf8(request).unwrap()))
.respond_with(
ResponseTemplate::new(200).set_body_raw(response, "text/xml; charset=utf-8"),
)
.expect(1)
.mount(server)
.await;
}
fn response() -> String {
format!(
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"{}\"><SOAP-ENV:Body><ns5:VylistujVerzeJvfOdpoved xmlns:ns5=\"{}\" xmlns:ns3=\"{}\" xmlns:ns21=\"{COMMON_JVF_NS}\" xmlns:ns22=\"{ISDMVS_JVF_NS}\"><ns3:Hlavicka><ns3:UidOdpovedi>{RESPONSE_UUID}</ns3:UidOdpovedi><ns3:Vysledek stav=\"OK\"><ns3:UidZadosti>{REQUEST_UUID}</ns3:UidZadosti><ns3:Hlaseni><ns3:Hlaseni kod=\"1000\" typ=\"Informace\"><ns3:Zprava>Požadovaná akce byla úspěšně provedena</ns3:Zprava></ns3:Hlaseni></ns3:Hlaseni></ns3:Vysledek></ns3:Hlavicka><ns5:Data><ns5:Verze><ns5:Verze><ns21:Verze>1.0.0</ns21:Verze><ns22:PlatnostOd>2022-01-01T00:00:00.000+01:00</ns22:PlatnostOd><ns22:PlatnostDo>2022-04-20T23:59:59.000+02:00</ns22:PlatnostDo><ns22:Popis>Popis verze 1.0.0</ns22:Popis></ns5:Verze><ns5:Verze><ns21:Verze>1.0.1</ns21:Verze><ns22:PlatnostOd>2022-04-21T00:00:00.000+02:00</ns22:PlatnostOd><ns22:Popis>Popis verze 1.0.1</ns22:Popis></ns5:Verze></ns5:Verze></ns5:Data></ns5:VylistujVerzeJvfOdpoved></SOAP-ENV:Body></SOAP-ENV:Envelope>",
soap::SOAP_11_NS,
Service::R24a.namespace(),
soap::MESSAGES_NS,
)
}
#[test]
fn parses_official_version_example() {
let response = soap::decode(
response().as_bytes(),
LIST_JVF_VERSIONS,
REQUEST_UUID.parse().unwrap(),
soap::XmlLimits {
max_nodes: 65_536,
max_depth: 128,
},
decode_jvf_versions,
)
.unwrap();
assert_eq!(response.value.len(), 2);
assert_eq!(response.value[0].version, "1.0.0");
assert!(response.value[0].valid_from.timestamp().is_some());
assert_eq!(
response.value[0].valid_to.as_ref().unwrap().as_str(),
"2022-04-20T23:59:59.000+02:00"
);
assert!(response.value[1].valid_to.is_none());
assert_eq!(response.metadata.messages.len(), 1);
}
#[test]
fn accepts_empty_jvf_descriptions_for_list_and_detail() {
let listed = response().replace(
"<ns22:Popis>Popis verze 1.0.0</ns22:Popis>",
"<ns22:Popis/>",
);
let response = soap::decode(
listed.as_bytes(),
LIST_JVF_VERSIONS,
REQUEST_UUID.parse().unwrap(),
limits(),
decode_jvf_versions,
)
.unwrap();
assert_eq!(response.value[0].description, "");
let detail = jvf_data(&BASE64_STANDARD.encode(JVF_BYTES)).replace(
"<ij:Popis>Synthetic JVF version</ij:Popis>",
"<ij:Popis></ij:Popis>",
);
let xml = operation_response(READ_JVF_VERSION, Some(&detail));
let response = decode_jvf_body(xml.as_bytes(), Some("text/xml")).unwrap();
let version = response.value.unwrap();
assert_eq!(version.description, "");
assert_eq!(version.content.bytes().as_ref(), JVF_BYTES);
}
#[tokio::test]
async fn executes_exact_http_and_soap_contract() {
let server = MockServer::start().await;
let id: CorrelationId = REQUEST_UUID.parse().unwrap();
let request = soap::request(LIST_JVF_VERSIONS, id, |_| Ok(())).unwrap();
Mock::given(method("POST"))
.and(path("/R24aCteniCiselniku"))
.and(header("SOAPAction", "\"vylistujVerzeJvf\""))
.and(header("Content-Type", "text/xml; charset=utf-8"))
.and(body_string(String::from_utf8(request).unwrap()))
.respond_with(
ResponseTemplate::new(200).set_body_raw(response(), "text/xml; charset=utf-8"),
)
.expect(1)
.mount(&server)
.await;
let client = Client::test_client(server.uri());
let response = client.list_jvf_versions_at(id).await.unwrap();
assert_eq!(response.value.len(), 2);
assert_eq!(response.metadata.request_id, id);
}
#[test]
fn writes_all_r24a_request_data_shapes() {
let id: CorrelationId = REQUEST_UUID.parse().unwrap();
let list = soap::request(LIST_CODE_LISTS, id, |_| Ok(())).unwrap();
assert!(!String::from_utf8(list).unwrap().contains("<Data"));
let without_version = soap::request(READ_CODE_LIST, id, |writer| {
write_code_list_request(writer, "CS_SYNTHETIC", None)
})
.unwrap();
assert!(
String::from_utf8(without_version)
.unwrap()
.contains("<Data xmlns:c=\"urn:cz:isvs:dmvs:isdmvs:schemas:Ciselniky:v1\"><Ciselnik><c:Id>CS_SYNTHETIC</c:Id></Ciselnik></Data>")
);
let with_version = soap::request(READ_CODE_LIST, id, |writer| {
write_code_list_request(writer, "CS_SYNTHETIC", Some("1.2.0"))
})
.unwrap();
assert!(
String::from_utf8(with_version)
.unwrap()
.contains("<Data xmlns:c=\"urn:cz:isvs:dmvs:isdmvs:schemas:Ciselniky:v1\"><Ciselnik><c:Id>CS_SYNTHETIC</c:Id></Ciselnik><Verze>1.2.0</Verze></Data>")
);
let current_jvf = soap::request(READ_JVF_VERSION, id, |writer| {
write_jvf_version_request(writer, None)
})
.unwrap();
assert!(String::from_utf8(current_jvf).unwrap().contains("<Data/>"));
let selected_jvf = soap::request(READ_JVF_VERSION, id, |writer| {
write_jvf_version_request(writer, Some("1.0.0"))
})
.unwrap();
assert!(
String::from_utf8(selected_jvf)
.unwrap()
.contains("<Data xmlns:j=\"urn:cz:isvs:dmvs:common:schemas:Jvf:v1\"><Verze><j:Verze>1.0.0</j:Verze></Verze></Data>")
);
let certificates = soap::request(LIST_IS_DMVS_CERTIFICATES, id, |writer| {
soap::empty_element(writer, "Data")
})
.unwrap();
assert!(String::from_utf8(certificates).unwrap().contains("<Data/>"));
}
#[test]
fn parses_code_list_discovery_with_references_and_unknown_data_types() {
let xml = operation_response(LIST_CODE_LISTS, Some(code_list_info()));
let response = soap::decode(
xml.as_bytes(),
LIST_CODE_LISTS,
REQUEST_UUID.parse().unwrap(),
limits(),
decode_code_lists,
)
.unwrap();
assert_eq!(response.value.len(), 1);
let code_list = &response.value[0];
assert_eq!(code_list.id, "CS_SYNTHETIC");
assert_eq!(code_list.name, "Synthetic code list");
assert_eq!(code_list.attributes.len(), 3);
assert_eq!(
code_list.attributes[0].kind,
CodeListAttributeKind::Plain(CodeListDataType::String)
);
assert_eq!(
code_list.attributes[1].kind,
CodeListAttributeKind::Plain(CodeListDataType::Other("FutureDateTime".into()))
);
match &code_list.attributes[1].kind {
CodeListAttributeKind::Plain(data_type) => {
assert_eq!(data_type.as_str(), "FutureDateTime");
}
other => panic!("expected plain attribute, got {other:?}"),
}
assert_eq!(
code_list.attributes[2].kind,
CodeListAttributeKind::Reference(CodeListAttributeReference {
code_list_id: "CS_OWNER".into(),
attribute_id: "ID".into(),
})
);
assert_eq!(code_list.latest_version.version, "1.2.0");
assert_eq!(
code_list.latest_version.valid_to.as_ref().unwrap().as_str(),
"2024-12-31T23:59:59+01:00"
);
assert_eq!(CodeListDataType::from_raw("Number").as_str(), "Number");
assert_eq!(CodeListDataType::from_raw("Boolean").as_str(), "Boolean");
assert_eq!(CodeListDataType::from_raw("Date").as_str(), "Date");
}
#[test]
fn parses_selected_code_list_items_and_boolean_lexemes() {
let data = "<r:Ciselnik><c:Id>CS_SYNTHETIC</c:Id><c:Nazev>Synthetic code list</c:Nazev><c:Atributy><c:Atribut><c:Id>CODE</c:Id><c:Nazev>Code</c:Nazev><c:PlainAtribut><c:DatovyTyp>String</c:DatovyTyp></c:PlainAtribut></c:Atribut></c:Atributy></r:Ciselnik><r:Verze><c:Verze>1.2.0</c:Verze><c:PlatnostOd>2024-01-01T00:00:00+01:00</c:PlatnostOd></r:Verze><r:Polozky><r:Polozka><c:Atributy><c:Atribut id=\"CODE\" hodnota=\"A&B\"/><c:Atribut id=\"EMPTY\" hodnota=\"\"/></c:Atributy><c:Zneplatneno>0</c:Zneplatneno></r:Polozka><r:Polozka><c:Atributy/><c:Zneplatneno>true</c:Zneplatneno></r:Polozka></r:Polozky>";
let xml = operation_response(READ_CODE_LIST, Some(data));
let response = soap::decode(
xml.as_bytes(),
READ_CODE_LIST,
REQUEST_UUID.parse().unwrap(),
limits(),
decode_code_list,
)
.unwrap();
let code_list = response.value.unwrap();
assert_eq!(code_list.id, "CS_SYNTHETIC");
assert_eq!(code_list.version.version, "1.2.0");
assert!(code_list.version.valid_to.is_none());
assert_eq!(code_list.items.len(), 2);
assert!(!code_list.items[0].invalidated);
assert_eq!(code_list.items[0].attributes[0].id, "CODE");
assert_eq!(code_list.items[0].attributes[0].value, "A&B");
assert_eq!(code_list.items[0].attributes[1].value, "");
assert!(code_list.items[1].invalidated);
assert!(code_list.items[1].attributes.is_empty());
}
#[test]
fn parses_synthetic_is_dmvs_certificate_without_exposing_it_in_debug() {
const PEM: &str = "-----BEGIN CERTIFICATE-----\nU1lOVEhFVElDLUNFUlRJRklDQVRFCg==\n-----END CERTIFICATE-----";
let data = format!(
"<r:Certifikaty><r:Certifikat><is:ZacatekPouzivani>2024-02-01T08:00:00+01:00</is:ZacatekPouzivani><is:PlatnostOd>2024-01-01T00:00:00+01:00</is:PlatnostOd><is:PlatnostDo>2027-01-01T00:00:00+01:00</is:PlatnostDo><is:Certifikat>{PEM}</is:Certifikat></r:Certifikat></r:Certifikaty>"
);
let xml = operation_response(LIST_IS_DMVS_CERTIFICATES, Some(&data));
let response = soap::decode(
xml.as_bytes(),
LIST_IS_DMVS_CERTIFICATES,
REQUEST_UUID.parse().unwrap(),
limits(),
decode_is_dmvs_certificates,
)
.unwrap();
assert_eq!(response.value.len(), 1);
let certificate = &response.value[0];
assert_eq!(certificate.certificate_pem, PEM);
assert_eq!(
certificate.usage_started_at.as_str(),
"2024-02-01T08:00:00+01:00"
);
assert_eq!(certificate.valid_to.as_str(), "2027-01-01T00:00:00+01:00");
assert!(!format!("{certificate:?}").contains("BEGIN CERTIFICATE"));
}
#[test]
fn absent_data_maps_to_empty_lists_or_missing_single_values() {
let id = REQUEST_UUID.parse().unwrap();
let code_lists = operation_response(LIST_CODE_LISTS, None);
assert!(
soap::decode(
code_lists.as_bytes(),
LIST_CODE_LISTS,
id,
limits(),
decode_code_lists,
)
.unwrap()
.value
.is_empty()
);
let jvf_versions = operation_response(LIST_JVF_VERSIONS, None);
assert!(
soap::decode(
jvf_versions.as_bytes(),
LIST_JVF_VERSIONS,
id,
limits(),
decode_jvf_versions,
)
.unwrap()
.value
.is_empty()
);
let certificates = operation_response(LIST_IS_DMVS_CERTIFICATES, None);
assert!(
soap::decode(
certificates.as_bytes(),
LIST_IS_DMVS_CERTIFICATES,
id,
limits(),
decode_is_dmvs_certificates,
)
.unwrap()
.value
.is_empty()
);
let code_list = operation_response(READ_CODE_LIST, None);
assert!(
soap::decode(
code_list.as_bytes(),
READ_CODE_LIST,
id,
limits(),
decode_code_list,
)
.unwrap()
.value
.is_none()
);
let jvf_version = operation_response(READ_JVF_VERSION, None);
assert!(
decode_jvf_body(jvf_version.as_bytes(), Some("text/xml"))
.unwrap()
.value
.is_none()
);
}
#[tokio::test]
async fn executes_all_new_r24a_operations_with_exact_requests() {
let server = MockServer::start().await;
let id: CorrelationId = REQUEST_UUID.parse().unwrap();
let request = soap::request(LIST_CODE_LISTS, id, |_| Ok(())).unwrap();
expect_exchange(
&server,
LIST_CODE_LISTS,
request,
operation_response(LIST_CODE_LISTS, Some("<r:Ciselniky/>")),
)
.await;
let request = soap::request(READ_CODE_LIST, id, |writer| {
write_code_list_request(writer, "CS_SYNTHETIC", Some("1.2.0"))
})
.unwrap();
expect_exchange(
&server,
READ_CODE_LIST,
request,
operation_response(READ_CODE_LIST, None),
)
.await;
let request = soap::request(READ_JVF_VERSION, id, |writer| {
write_jvf_version_request(writer, Some("1.0.0"))
})
.unwrap();
expect_exchange(
&server,
READ_JVF_VERSION,
request,
operation_response(READ_JVF_VERSION, None),
)
.await;
let request = soap::request(LIST_IS_DMVS_CERTIFICATES, id, |writer| {
soap::empty_element(writer, "Data")
})
.unwrap();
expect_exchange(
&server,
LIST_IS_DMVS_CERTIFICATES,
request,
operation_response(LIST_IS_DMVS_CERTIFICATES, Some("<r:Certifikaty/>")),
)
.await;
let client = Client::test_client(server.uri());
assert!(
client
.list_code_lists_at(id)
.await
.unwrap()
.value
.is_empty()
);
assert!(
client
.read_code_list_at(id, "CS_SYNTHETIC", Some("1.2.0"))
.await
.unwrap()
.value
.is_none()
);
assert!(
client
.read_jvf_version_at(id, Some("1.0.0"))
.await
.unwrap()
.value
.is_none()
);
let certificates = client.list_is_dmvs_certificates_at(id).await.unwrap();
assert!(certificates.value.is_empty());
assert_eq!(certificates.metadata.request_id, id);
}
#[test]
fn decodes_inline_and_mtom_jvf_files() {
let inline_data = jvf_data(&BASE64_STANDARD.encode(JVF_BYTES));
let inline_xml = operation_response(READ_JVF_VERSION, Some(&inline_data));
let inline = decode_jvf_body(inline_xml.as_bytes(), Some("text/xml"))
.unwrap()
.value
.unwrap();
assert_eq!(inline.version, "1.0.0");
assert_eq!(inline.content.bytes().as_ref(), JVF_BYTES);
assert_eq!(inline.content.metadata.name, "jvf-1.0.0.zip");
assert_eq!(inline.content.metadata.size, JVF_BYTES.len() as u64);
assert_eq!(
inline.content.metadata.checksum.as_str(),
"synthetic-checksum"
);
let mtom_data = jvf_data("<xop:Include href=\"cid:jvf%40dmvs\"/>");
let mtom_xml = operation_response(READ_JVF_VERSION, Some(&mtom_data));
let mut multipart = Vec::new();
multipart.extend_from_slice(b"--dmvs-boundary\r\nContent-Type: application/xop+xml; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\nContent-ID: <root@dmvs>\r\n\r\n");
multipart.extend_from_slice(mtom_xml.as_bytes());
multipart.extend_from_slice(b"\r\n--dmvs-boundary\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <jvf@dmvs>\r\n\r\n");
multipart.extend_from_slice(JVF_BYTES);
multipart.extend_from_slice(b"\r\n--dmvs-boundary--\r\n");
let mtom = decode_jvf_body(
&multipart,
Some(
"multipart/related; boundary=dmvs-boundary; type=\"application/xop+xml\"; start=\"<root@dmvs>\"",
),
)
.unwrap()
.value
.unwrap();
assert_eq!(mtom.content.bytes().as_ref(), JVF_BYTES);
assert_eq!(
mtom.valid_to.as_ref().unwrap().as_str(),
"2022-04-20T23:59:59.000+02:00"
);
}
#[test]
fn rejects_ambiguous_attributes_and_non_empty_item_attributes() {
let attribute_xml = format!(
"<c:Atribut xmlns:c=\"{CODELISTS_NS}\"><c:Id>A</c:Id><c:Nazev>A</c:Nazev><c:PlainAtribut><c:DatovyTyp>String</c:DatovyTyp></c:PlainAtribut><c:RefAtribut><c:Ciselnik>B</c:Ciselnik><c:Atribut>C</c:Atribut></c:RefAtribut></c:Atribut>"
);
let attribute = roxmltree::Document::parse(&attribute_xml).unwrap();
assert!(decode_code_list_attribute(attribute.root_element()).is_err());
let item_attribute_xml = format!(
"<c:Atribut xmlns:c=\"{CODELISTS_NS}\" id=\"A\" hodnota=\"B\">unexpected</c:Atribut>"
);
let item_attribute = roxmltree::Document::parse(&item_attribute_xml).unwrap();
assert!(decode_code_list_item_attribute(item_attribute.root_element()).is_err());
}
}