use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::io::Write;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use bytes::Bytes;
use mime::Mime;
use quick_xml::events::Event;
use roxmltree::Node;
use crate::model::InputFile;
use crate::{Error, Result};
const XOP_INCLUDE_NS: &str = "http://www.w3.org/2004/08/xop/include";
const MAX_PART_HEADERS: usize = 32;
const MAX_PART_HEADER_BYTES: usize = 16 * 1024;
const MAX_CONTENT_ID_BYTES: usize = 2 * 1024;
const MAX_INPUT_FILES: usize = 4;
const MAX_INPUT_FILE_BYTES: usize = 16 * 1024 * 1024;
const MAX_TOTAL_INPUT_FILE_BYTES: usize = 32 * 1024 * 1024;
pub(crate) struct OutgoingRequest {
pub(crate) body: Vec<u8>,
pub(crate) content_type: String,
}
pub(crate) fn attachment_content_id(index: usize) -> String {
format!("attachment-{index}@dmvs.invalid")
}
pub(crate) fn write_xop_include(
writer: &mut super::soap::XmlWriter,
index: usize,
) -> super::soap::XmlResult {
let mut include = quick_xml::events::BytesStart::new("xop:Include");
include.push_attribute(("xmlns:xop", XOP_INCLUDE_NS));
include.push_attribute((
"href",
format!("cid:{}", attachment_content_id(index)).as_str(),
));
writer.write_event(Event::Empty(include))?;
Ok(())
}
pub(crate) fn encode_multipart(
xml: Vec<u8>,
files: &[InputFile],
max_request_bytes: usize,
) -> Result<OutgoingRequest> {
if xml.len() > max_request_bytes {
return Err(super::soap::request_too_large(max_request_bytes));
}
if files.is_empty() {
return Ok(OutgoingRequest {
body: xml,
content_type: "text/xml; charset=utf-8".into(),
});
}
if files.len() > MAX_INPUT_FILES {
return Err(Error::invalid_input(
"files",
"at most four supporting files are permitted per request",
));
}
let mut total = 0_usize;
for file in files {
file.validate()?;
if file.content.len() > MAX_INPUT_FILE_BYTES {
return Err(Error::invalid_input(
"file.content",
"a supporting file exceeds the 16 MiB input limit",
));
}
total = total.saturating_add(file.content.len());
}
if total > MAX_TOTAL_INPUT_FILE_BYTES {
return Err(Error::invalid_input(
"files",
"supporting files exceed the aggregate 32 MiB input limit",
));
}
let boundary = format!("dmvs-{}", uuid::Uuid::new_v4().simple());
let root_header = format!(
"--{boundary}\r\nContent-Type: application/xop+xml; charset=utf-8; type=\"text/xml\"\r\nContent-Transfer-Encoding: 8bit\r\nContent-ID: <root@dmvs.invalid>\r\n\r\n"
);
let attachment_headers: Vec<_> = files
.iter()
.enumerate()
.map(|(index, _)| {
format!(
"\r\n--{boundary}\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <{}>\r\n\r\n",
attachment_content_id(index)
)
})
.collect();
let closing = format!("\r\n--{boundary}--\r\n");
let mut encoded_len = xml.len();
account_request_bytes(&mut encoded_len, root_header.len(), max_request_bytes)?;
for (header, file) in attachment_headers.iter().zip(files) {
account_request_bytes(&mut encoded_len, header.len(), max_request_bytes)?;
account_request_bytes(&mut encoded_len, file.content.len(), max_request_bytes)?;
}
account_request_bytes(&mut encoded_len, closing.len(), max_request_bytes)?;
let mut body = super::soap::CappedWriter::new(max_request_bytes);
write_request_bytes(&mut body, root_header.as_bytes(), max_request_bytes)?;
write_request_bytes(&mut body, &xml, max_request_bytes)?;
for (header, file) in attachment_headers.iter().zip(files) {
write_request_bytes(&mut body, header.as_bytes(), max_request_bytes)?;
write_request_bytes(&mut body, &file.content, max_request_bytes)?;
}
write_request_bytes(&mut body, closing.as_bytes(), max_request_bytes)?;
let body = body.into_inner();
debug_assert_eq!(body.len(), encoded_len);
if body.len() > max_request_bytes {
return Err(super::soap::request_too_large(max_request_bytes));
}
Ok(OutgoingRequest {
body,
content_type: format!(
"multipart/related; boundary=\"{boundary}\"; type=\"application/xop+xml\"; start=\"<root@dmvs.invalid>\"; start-info=\"text/xml\""
),
})
}
fn account_request_bytes(total: &mut usize, additional: usize, limit: usize) -> Result<()> {
*total = total
.checked_add(additional)
.filter(|total| *total <= limit)
.ok_or_else(|| super::soap::request_too_large(limit))?;
Ok(())
}
fn write_request_bytes(
writer: &mut super::soap::CappedWriter,
bytes: &[u8],
limit: usize,
) -> Result<()> {
writer.write_all(bytes).map_err(|error| {
if error.kind() == std::io::ErrorKind::FileTooLarge {
super::soap::request_too_large(limit)
} else {
Error::invalid_input("request", "could not allocate the encoded request buffer")
}
})
}
#[derive(Clone, Copy)]
pub(crate) struct MimeLimits {
pub(crate) max_parts: usize,
pub(crate) max_decoded_bytes: usize,
pub(crate) max_total_decoded_bytes: usize,
}
pub(crate) struct SoapBody<'a> {
pub(crate) xml: &'a [u8],
pub(crate) attachments: Attachments<'a>,
}
impl<'a> SoapBody<'a> {
pub(crate) fn parse(
bytes: &'a [u8],
content_type: Option<&str>,
limits: MimeLimits,
) -> Result<Self> {
let content_type = content_type
.ok_or_else(|| Error::invalid_response("SOAP Content-Type is missing"))?
.trim()
.parse::<Mime>()
.map_err(|_| Error::invalid_response("invalid SOAP Content-Type"))?;
if content_type.essence_str() == "text/xml" {
return Ok(Self {
xml: bytes,
attachments: Attachments::inline(limits),
});
}
if content_type.type_() != mime::MULTIPART || content_type.subtype().as_str() != "related" {
return Err(Error::invalid_response(
"SOAP response must be text/xml or multipart/related",
));
}
Self::parse_multipart(bytes, &content_type, limits)
}
fn parse_multipart(bytes: &'a [u8], content_type: &Mime, limits: MimeLimits) -> Result<Self> {
let boundary = content_type
.get_param("boundary")
.map(|value| value.as_str())
.ok_or_else(|| Error::invalid_response("multipart boundary is missing"))?;
if boundary.is_empty()
|| boundary.len() > 70
|| !boundary.is_ascii()
|| boundary.bytes().any(|byte| byte == b'\r' || byte == b'\n')
{
return Err(Error::invalid_response("invalid multipart boundary"));
}
let start = content_type
.get_param("start")
.map(|value| normalize_content_id(value.as_str()))
.transpose()?;
let declared_root_type = content_type.get_param("type");
let parts = parse_multipart(bytes, boundary, limits.max_parts)?;
let root_index = match start {
Some(start) => parts
.iter()
.position(|part| part.content_id.as_deref() == Some(start.as_str()))
.ok_or_else(|| {
Error::invalid_response("multipart start does not identify a MIME part")
})?,
None => 0,
};
let root = &parts[root_index];
if !is_soap_xml(root.content_type.as_ref()) {
return Err(Error::invalid_response(
"multipart start part is not a SOAP XML document",
));
}
if let Some(declared) = declared_root_type
&& root
.content_type
.as_ref()
.is_none_or(|actual| actual.essence_str() != declared.as_str())
{
return Err(Error::invalid_response(
"multipart type parameter does not match its start part",
));
}
require_text_transfer_encoding(root.content_transfer_encoding.as_deref())?;
let xml = root.body;
let attachments = parts
.into_iter()
.enumerate()
.filter(|(index, _)| *index != root_index)
.map(|(_, part)| part)
.collect();
Ok(Self {
xml,
attachments: Attachments {
parts: attachments,
limits,
allow_xop: true,
used: RefCell::new(HashSet::new()),
total_decoded: Cell::new(0),
},
})
}
}
pub(crate) struct Attachments<'a> {
parts: Vec<MimePart<'a>>,
limits: MimeLimits,
allow_xop: bool,
used: RefCell<HashSet<usize>>,
total_decoded: Cell<usize>,
}
impl Attachments<'_> {
pub(crate) fn inline(limits: MimeLimits) -> Self {
Self {
parts: Vec::new(),
limits,
allow_xop: false,
used: RefCell::new(HashSet::new()),
total_decoded: Cell::new(0),
}
}
pub(crate) fn decode(&self, node: Node<'_, '_>) -> Result<Bytes> {
let mut elements = node.children().filter(|child| child.is_element());
if let Some(include) = elements.next() {
if elements.next().is_some()
|| include.tag_name().namespace() != Some(XOP_INCLUDE_NS)
|| include.tag_name().name() != "Include"
|| !self.allow_xop
|| node
.children()
.filter(|child| child.is_text())
.any(|text| text.text().is_some_and(|text| !text.trim().is_empty()))
|| include.children().any(|child| {
child.is_element()
|| (child.is_text()
&& child.text().is_some_and(|text| !text.trim().is_empty()))
})
{
return Err(Error::invalid_response(
"binary element has an invalid XOP structure",
));
}
let href = include
.attribute("href")
.ok_or_else(|| Error::invalid_response("XOP Include href is missing"))?;
if include.attributes().count() != 1 {
return Err(Error::invalid_response(
"XOP Include has unsupported attributes",
));
}
return self.decode_attachment(&parse_cid(href)?);
}
let content = super::soap::simple_content(node, "Obsah")?;
self.account_and_decode_inline(&content)
}
fn decode_attachment(&self, content_id: &str) -> Result<Bytes> {
let index = self
.parts
.iter()
.position(|part| part.content_id.as_deref() == Some(content_id))
.ok_or_else(|| {
Error::invalid_response("XOP reference has no matching MIME attachment")
})?;
if !self.used.borrow_mut().insert(index) {
return Err(Error::invalid_response(
"one MIME attachment is referenced more than once",
));
}
let attachment = &self.parts[index];
if !matches!(
attachment.content_transfer_encoding.as_deref(),
None | Some("binary")
) {
return Err(Error::invalid_response(
"MTOM attachment must use binary content transfer encoding",
));
}
self.check_decoded_len(attachment.body.len())?;
Ok(Bytes::copy_from_slice(attachment.body))
}
fn account_and_decode_inline(&self, content: &str) -> Result<Bytes> {
let mut encoded_length = 0_usize;
let mut last = [0_u8; 2];
for byte in content.bytes().filter(|byte| !byte.is_ascii_whitespace()) {
encoded_length = encoded_length
.checked_add(1)
.ok_or_else(|| Error::invalid_response("invalid inline base64 length"))?;
last = [last[1], byte];
}
if encoded_length == 0 {
self.check_decoded_len(0)?;
return Ok(Bytes::new());
}
if !encoded_length.is_multiple_of(4) {
return Err(Error::invalid_response("malformed inline base64"));
}
let padding = if last == *b"==" {
2
} else if last[1] == b'=' {
1
} else {
0
};
let decoded_length = (encoded_length / 4)
.checked_mul(3)
.and_then(|length| length.checked_sub(padding))
.ok_or_else(|| Error::invalid_response("invalid inline base64 length"))?;
self.check_decoded_len(decoded_length)?;
let encoded: Vec<_> = content
.bytes()
.filter(|byte| !byte.is_ascii_whitespace())
.collect();
let decoded = BASE64_STANDARD
.decode(encoded)
.map_err(|_| Error::invalid_response("malformed inline base64"))?;
if decoded.len() != decoded_length {
return Err(Error::invalid_response("malformed inline base64"));
}
Ok(Bytes::from(decoded))
}
fn check_decoded_len(&self, len: usize) -> Result<()> {
if len > self.limits.max_decoded_bytes {
return Err(Error::ResponseTooLarge {
limit: self.limits.max_decoded_bytes,
});
}
let total = self
.total_decoded
.get()
.checked_add(len)
.ok_or(Error::ResponseTooLarge {
limit: self.limits.max_total_decoded_bytes,
})?;
if total > self.limits.max_total_decoded_bytes {
return Err(Error::ResponseTooLarge {
limit: self.limits.max_total_decoded_bytes,
});
}
self.total_decoded.set(total);
Ok(())
}
pub(crate) fn finish(&self) -> Result<()> {
if self.used.borrow().len() == self.parts.len() {
Ok(())
} else {
Err(Error::invalid_response(
"multipart response contains unrelated or unreferenced parts",
))
}
}
}
fn is_soap_xml(content_type: Option<&Mime>) -> bool {
content_type.is_some_and(|content_type| {
matches!(
content_type.essence_str(),
"text/xml" | "application/xop+xml" | "application/soap+xml"
)
})
}
fn require_text_transfer_encoding(encoding: Option<&str>) -> Result<()> {
if matches!(
encoding,
None | Some("7bit") | Some("8bit") | Some("binary")
) {
Ok(())
} else {
Err(Error::invalid_response(
"SOAP MIME part has an unsupported transfer encoding",
))
}
}
fn parse_cid(href: &str) -> Result<String> {
let href = href.trim();
let Some(cid) = href
.get(..4)
.filter(|scheme| scheme.eq_ignore_ascii_case("cid:"))
.and_then(|_| href.get(4..))
else {
return Err(Error::invalid_response(
"XOP Include href must use the cid scheme",
));
};
if cid.is_empty() || cid.len() > MAX_CONTENT_ID_BYTES {
return Err(Error::invalid_response("invalid XOP content ID"));
}
let raw = cid.as_bytes();
for index in 0..raw.len() {
if raw[index] == b'%'
&& (index + 2 >= raw.len()
|| !raw[index + 1].is_ascii_hexdigit()
|| !raw[index + 2].is_ascii_hexdigit())
{
return Err(Error::invalid_response("invalid XOP content ID escaping"));
}
}
let decoded = percent_encoding::percent_decode_str(cid)
.decode_utf8()
.map_err(|_| Error::invalid_response("XOP content ID is not valid UTF-8"))?;
if decoded.is_empty()
|| decoded.len() > MAX_CONTENT_ID_BYTES
|| decoded.chars().any(char::is_control)
|| decoded.bytes().any(|byte| byte.is_ascii_whitespace())
{
return Err(Error::invalid_response("invalid XOP content ID"));
}
Ok(decoded.into_owned())
}
struct MimePart<'a> {
content_id: Option<String>,
content_type: Option<Mime>,
content_transfer_encoding: Option<String>,
body: &'a [u8],
}
fn parse_multipart<'a>(
bytes: &'a [u8],
boundary: &str,
max_parts: usize,
) -> Result<Vec<MimePart<'a>>> {
let mut marker = Vec::with_capacity(boundary.len() + 2);
marker.extend_from_slice(b"--");
marker.extend_from_slice(boundary.as_bytes());
let first = find_marker(bytes, &marker, 0)
.ok_or_else(|| Error::invalid_response("multipart opening boundary is missing"))?;
let mut cursor = first + marker.len();
let mut parts = Vec::new();
let mut content_ids = HashSet::new();
loop {
if bytes.get(cursor..cursor + 2) == Some(b"--") {
cursor += 2;
while matches!(bytes.get(cursor), Some(b' ' | b'\t')) {
cursor += 1;
}
if cursor != bytes.len() && bytes.get(cursor..cursor + 2) != Some(b"\r\n") {
return Err(Error::invalid_response(
"malformed multipart closing boundary",
));
}
if parts.is_empty() {
return Err(Error::invalid_response("multipart response has no parts"));
}
return Ok(parts);
}
if bytes.get(cursor..cursor + 2) != Some(b"\r\n") {
return Err(Error::invalid_response("malformed multipart boundary"));
}
let header_start = cursor + 2;
let header_end_relative = find_subslice(&bytes[header_start..], b"\r\n\r\n")
.ok_or_else(|| Error::invalid_response("truncated MIME part headers"))?;
let header_end = header_start + header_end_relative;
if header_end - header_start > MAX_PART_HEADER_BYTES {
return Err(Error::invalid_response("MIME part headers are too large"));
}
let body_start = header_end + 4;
let next_marker = find_marker(bytes, &marker, body_start)
.ok_or_else(|| Error::invalid_response("multipart closing boundary is missing"))?;
let body_end = if next_marker == body_start {
body_start
} else {
next_marker
.checked_sub(2)
.ok_or_else(|| Error::invalid_response("malformed multipart part boundary"))?
};
if next_marker != body_start && bytes.get(body_end..next_marker) != Some(b"\r\n") {
return Err(Error::invalid_response("malformed multipart part boundary"));
}
let part = parse_part(
&bytes[header_start..header_end],
&bytes[body_start..body_end],
)?;
if let Some(content_id) = &part.content_id
&& !content_ids.insert(content_id.clone())
{
return Err(Error::invalid_response("duplicate MIME Content-ID"));
}
if parts.len() >= max_parts {
return Err(Error::invalid_response("too many MIME parts"));
}
parts.push(part);
cursor = next_marker + marker.len();
}
}
fn find_marker(haystack: &[u8], marker: &[u8], start: usize) -> Option<usize> {
let mut search_start = start;
while let Some(relative) = find_subslice(&haystack[search_start..], marker) {
let position = search_start + relative;
let begins_line = position == 0
|| (position >= 2 && haystack.get(position - 2..position) == Some(b"\r\n"));
let after = position + marker.len();
let valid_suffix = haystack.get(after..after + 2) == Some(b"\r\n")
|| haystack.get(after..after + 2) == Some(b"--");
if begins_line && valid_suffix {
return Some(position);
}
search_start = position.checked_add(1)?;
if search_start >= haystack.len() {
break;
}
}
None
}
fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || needle.len() > haystack.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn parse_part_content_type(value: &str) -> Result<Mime> {
value
.parse::<Mime>()
.or_else(|_| {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.parse::<Mime>()
})
.map_err(|_| Error::invalid_response("invalid MIME part Content-Type"))
}
fn parse_part<'a>(headers: &[u8], body: &'a [u8]) -> Result<MimePart<'a>> {
let headers = std::str::from_utf8(headers)
.map_err(|_| Error::invalid_response("MIME part headers are not UTF-8"))?;
let mut content_id = None;
let mut content_type = None;
let mut content_transfer_encoding = None;
let mut count = 0;
for line in headers.split("\r\n") {
count += 1;
if count > MAX_PART_HEADERS {
return Err(Error::invalid_response("too many MIME part headers"));
}
if line.starts_with([' ', '\t']) {
return Err(Error::invalid_response(
"folded MIME part headers are not supported",
));
}
let (name, value) = line
.split_once(':')
.ok_or_else(|| Error::invalid_response("malformed MIME part header"))?;
let value = value.trim();
if name.eq_ignore_ascii_case("Content-ID") {
if content_id.is_some() {
return Err(Error::invalid_response("duplicate MIME Content-ID header"));
}
content_id = Some(normalize_content_id(value)?);
} else if name.eq_ignore_ascii_case("Content-Type") {
if content_type.is_some() {
return Err(Error::invalid_response(
"duplicate MIME Content-Type header",
));
}
content_type = Some(parse_part_content_type(value)?);
} else if name.eq_ignore_ascii_case("Content-Transfer-Encoding") {
if content_transfer_encoding.is_some() {
return Err(Error::invalid_response(
"duplicate MIME transfer-encoding header",
));
}
content_transfer_encoding = Some(value.to_ascii_lowercase());
}
}
Ok(MimePart {
content_id,
content_type,
content_transfer_encoding,
body,
})
}
fn normalize_content_id(value: &str) -> Result<String> {
let value = value.trim();
let value = if value.starts_with('<') || value.ends_with('>') {
if !(value.starts_with('<') && value.ends_with('>')) || value.len() < 3 {
return Err(Error::invalid_response("invalid MIME Content-ID"));
}
&value[1..value.len() - 1]
} else {
value
};
if value.is_empty()
|| value.len() > MAX_CONTENT_ID_BYTES
|| value.bytes().any(|byte| byte.is_ascii_whitespace())
{
return Err(Error::invalid_response("invalid MIME Content-ID"));
}
Ok(value.to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
const LIMITS: MimeLimits = MimeLimits {
max_parts: 4,
max_decoded_bytes: 1024,
max_total_decoded_bytes: 2048,
};
fn multipart(root_xml: &str, attachment_id: &str, attachment: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.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");
bytes.extend_from_slice(root_xml.as_bytes());
bytes.extend_from_slice(b"\r\n--dmvs-boundary\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <");
bytes.extend_from_slice(attachment_id.as_bytes());
bytes.extend_from_slice(b">\r\n\r\n");
bytes.extend_from_slice(attachment);
bytes.extend_from_slice(b"\r\n--dmvs-boundary--\r\n");
bytes
}
fn decode_xop(root_xml: &str) -> Result<Bytes> {
let bytes = multipart(root_xml, "file@dmvs", b"content");
let body = SoapBody::parse(
&bytes,
Some(
r#"multipart/related; boundary="dmvs-boundary"; type="application/xop+xml"; start="<root@dmvs>""#,
),
LIMITS,
)?;
let document = roxmltree::Document::parse(std::str::from_utf8(body.xml).unwrap()).unwrap();
body.attachments.decode(document.root_element())
}
#[test]
fn resolves_binary_xop_and_enforces_reference_accounting() {
let xml = r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs"/></Obsah>"#;
let bytes = multipart(xml, "file@dmvs", b"secret\x00bytes");
let body = SoapBody::parse(
&bytes,
Some(r#"multipart/related; boundary="dmvs-boundary"; type="application/xop+xml"; start="<root@dmvs>""#),
LIMITS,
)
.unwrap();
let document = roxmltree::Document::parse(std::str::from_utf8(body.xml).unwrap()).unwrap();
assert_eq!(
body.attachments.decode(document.root_element()).unwrap(),
Bytes::from_static(b"secret\x00bytes")
);
body.attachments.finish().unwrap();
}
#[test]
fn tolerates_invalid_mime_parameters_only_with_a_valid_essence() {
assert_eq!(
parse_part_content_type("application/xml; charset=application/octet-stream")
.unwrap()
.essence_str(),
"application/xml"
);
assert!(parse_part_content_type("not a mime; charset=application/octet-stream").is_err());
let xml = r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs"/></Obsah>"#;
let mut bytes = multipart(xml, "file@dmvs", b"content");
let original = b"Content-Type: application/octet-stream\r\n";
let position = find_subslice(&bytes, original).unwrap();
bytes.splice(
position..position + original.len(),
b"Content-Type: application/xml; charset=application/octet-stream\r\n"
.iter()
.copied(),
);
let body = SoapBody::parse(
&bytes,
Some(r#"multipart/related; boundary="dmvs-boundary"; type="application/xop+xml"; start="<root@dmvs>""#),
LIMITS,
)
.unwrap();
let document = roxmltree::Document::parse(std::str::from_utf8(body.xml).unwrap()).unwrap();
assert_eq!(
body.attachments.decode(document.root_element()).unwrap(),
Bytes::from_static(b"content")
);
body.attachments.finish().unwrap();
}
#[test]
fn xop_include_is_schema_empty_but_permits_whitespace() {
let whitespace = concat!(
r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs">"#,
" \r\n\t ",
"</xop:Include></Obsah>"
);
assert_eq!(
decode_xop(whitespace).unwrap(),
Bytes::from_static(b"content")
);
for xml in [
r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs">not empty</xop:Include></Obsah>"#,
r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs"><child/></xop:Include></Obsah>"#,
r#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:file%40dmvs"><xop:Include href="cid:file%40dmvs"/></xop:Include></Obsah>"#,
] {
assert!(matches!(
decode_xop(xml),
Err(Error::InvalidResponse { .. })
));
}
}
#[test]
fn outgoing_multipart_includes_soap_11_media_type_metadata() {
let file = InputFile::new("evidence.txt", Bytes::from_static(b"synthetic")).unwrap();
let encoded =
encode_multipart(b"<synthetic/>".to_vec(), std::slice::from_ref(&file), 4096).unwrap();
let content_type = encoded.content_type.parse::<Mime>().unwrap();
assert_eq!(
content_type.get_param("type").unwrap().as_str(),
"application/xop+xml"
);
assert_eq!(
content_type.get_param("start-info").unwrap().as_str(),
"text/xml"
);
assert_eq!(
content_type.get_param("start").unwrap().as_str(),
"<root@dmvs.invalid>"
);
let boundary = content_type.get_param("boundary").unwrap().as_str();
let body = String::from_utf8(encoded.body).unwrap();
assert!(body.starts_with(&format!(
"--{boundary}\r\nContent-Type: application/xop+xml; charset=utf-8; type=\"text/xml\"\r\nContent-Transfer-Encoding: 8bit\r\nContent-ID: <root@dmvs.invalid>\r\n\r\n"
)));
}
#[test]
fn outgoing_multipart_enforces_the_exact_total_request_limit() {
let file = InputFile::new("evidence.txt", Bytes::from_static(b"synthetic")).unwrap();
let xml = b"<synthetic/>".to_vec();
let encoded = encode_multipart(xml.clone(), std::slice::from_ref(&file), 4096).unwrap();
let limit = encoded.body.len();
let exact = encode_multipart(xml.clone(), std::slice::from_ref(&file), limit).unwrap();
assert_eq!(exact.body.len(), limit);
let error = encode_multipart(xml.clone(), std::slice::from_ref(&file), limit - 1)
.map(|_| ())
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "max_request_bytes",
..
}
));
let error = encode_multipart(
xml.clone(),
std::slice::from_ref(&file),
xml.len() + file.content.len(),
)
.map(|_| ())
.unwrap_err();
assert!(matches!(
error,
Error::InvalidInput {
field: "max_request_bytes",
..
}
));
}
#[test]
fn permits_a_first_root_part_without_content_id() {
let bytes = multipart("<Obsah>QUJD</Obsah>", "file@dmvs", b"content");
let mut root_only = Vec::new();
let root_end = find_subslice(&bytes, b"\r\n--dmvs-boundary").unwrap();
root_only.extend_from_slice(&bytes[..root_end]);
root_only.extend_from_slice(b"\r\n--dmvs-boundary--\r\n");
let root_only = root_only
.windows(b"Content-ID: <root@dmvs>\r\n".len())
.position(|window| window == b"Content-ID: <root@dmvs>\r\n")
.map(|position| {
let mut bytes = Vec::new();
bytes.extend_from_slice(&root_only[..position]);
bytes.extend_from_slice(
&root_only[position + b"Content-ID: <root@dmvs>\r\n".len()..],
);
bytes
})
.unwrap();
let body = SoapBody::parse(
&root_only,
Some("multipart/related; boundary=dmvs-boundary; type=\"application/xop+xml\""),
LIMITS,
)
.unwrap();
assert!(body.attachments.parts.is_empty());
body.attachments.finish().unwrap();
}
#[test]
fn inline_base64_is_bounded_and_xop_requires_multipart() {
let inline = SoapBody::parse(b"<Obsah>QUJD</Obsah>", Some("text/xml"), LIMITS).unwrap();
let document =
roxmltree::Document::parse(std::str::from_utf8(inline.xml).unwrap()).unwrap();
assert_eq!(
inline.attachments.decode(document.root_element()).unwrap(),
Bytes::from_static(b"ABC")
);
let xop = SoapBody::parse(
br#"<Obsah xmlns:xop="http://www.w3.org/2004/08/xop/include"><xop:Include href="cid:no@dmvs"/></Obsah>"#,
Some("text/xml"),
LIMITS,
)
.unwrap();
let document = roxmltree::Document::parse(std::str::from_utf8(xop.xml).unwrap()).unwrap();
assert!(xop.attachments.decode(document.root_element()).is_err());
}
#[test]
fn xop_content_ids_percent_decode_and_reject_bad_escapes() {
assert_eq!(parse_cid("cid:name%40example").unwrap(), "name@example");
assert_eq!(parse_cid("cid:name%25example").unwrap(), "name%example");
assert!(parse_cid("cid:bad%2").is_err());
assert!(parse_cid("cid:bad%GG").is_err());
assert!(parse_cid("https://example.invalid/file").is_err());
}
#[test]
fn rejects_unreferenced_parts_and_decoded_overflow() {
let bytes = multipart("<Obsah>QUJD</Obsah>", "unreferenced@dmvs", b"other");
let body = SoapBody::parse(
&bytes,
Some(r#"multipart/related; boundary=dmvs-boundary; start="<root@dmvs>""#),
LIMITS,
)
.unwrap();
let document = roxmltree::Document::parse(std::str::from_utf8(body.xml).unwrap()).unwrap();
body.attachments.decode(document.root_element()).unwrap();
assert!(body.attachments.finish().is_err());
let small = MimeLimits {
max_decoded_bytes: 2,
..LIMITS
};
let inline = SoapBody::parse(b"<Obsah>QUJD</Obsah>", Some("text/xml"), small).unwrap();
let document =
roxmltree::Document::parse(std::str::from_utf8(inline.xml).unwrap()).unwrap();
assert!(matches!(
inline.attachments.decode(document.root_element()),
Err(Error::ResponseTooLarge { limit: 2 })
));
}
}