Skip to main content

camel_processor/data_format/
xml.rs

1use camel_api::body::Body;
2use camel_api::data_format::DataFormat;
3use camel_api::error::CamelError;
4use camel_api::xml_convert::{json_to_xml, xml_to_json_with_depth_limit};
5use serde::Deserialize;
6
7fn default_max_depth() -> usize {
8    camel_api::xml_convert::DEFAULT_MAX_XML_DEPTH
9}
10
11/// Configuration for [`XmlDataFormat`]. All fields have hardened defaults;
12/// setting a non-default value is the per-item explicit choice per ADR-0033.
13#[derive(Debug, Clone, Deserialize)]
14#[serde(deny_unknown_fields)]
15pub struct XmlConfig {
16    /// Maximum XML nesting depth accepted by `unmarshal` (DoS cap).
17    /// Default 100. Inert during `marshal`.
18    #[serde(default = "default_max_depth")]
19    pub max_depth: usize,
20}
21
22impl Default for XmlConfig {
23    fn default() -> Self {
24        Self {
25            max_depth: default_max_depth(),
26        }
27    }
28}
29
30#[derive(Debug, Clone, Default)]
31pub struct XmlDataFormat {
32    config: XmlConfig,
33}
34
35impl XmlDataFormat {
36    pub fn new(config: XmlConfig) -> Self {
37        Self { config }
38    }
39}
40
41impl DataFormat for XmlDataFormat {
42    fn name(&self) -> &str {
43        "xml"
44    }
45
46    /// Marshal a body into XML.
47    ///
48    /// `Body::Json` is serialized to XML text. `Body::Xml` and valid-UTF-8
49    /// `Body::Bytes` are already-serialized XML and pass through unchanged;
50    /// invalid UTF-8 fails closed. There is no content sniffing, no
51    /// well-formedness re-parse, and no re-encoding. UTF-8-only mirrors the
52    /// REST XML charset gate.
53    fn marshal(&self, body: Body) -> Result<Body, CamelError> {
54        match body {
55            Body::Json(v) => {
56                let xml = json_to_xml(&v)?;
57                Ok(Body::Text(xml))
58            }
59            Body::Text(_) => Ok(body),
60            Body::Stream(_) => Err(CamelError::TypeConversionFailed(
61                "cannot marshal Body::Stream — add 'stream_cache' or 'convert_body_to' before this step".to_string(),
62            )),
63            Body::Bytes(b) => {
64                if let Err(e) = std::str::from_utf8(&b) {
65                    return Err(CamelError::TypeConversionFailed(format!(
66                        "XmlDataFormat::marshal: Body::Bytes is not valid UTF-8 (first invalid byte offset {})",
67                        e.valid_up_to()
68                    )));
69                }
70                Ok(Body::Bytes(b))
71            }
72            Body::Xml(s) => Ok(Body::Xml(s)),
73            // Empty-body operations (e.g. REST 204) must not fail marshalling;
74            // matches JsonDataFormat, which passes Body::Empty through.
75            Body::Empty => Ok(Body::Empty),
76            _ => Err(CamelError::TypeConversionFailed(
77                "XmlDataFormat::marshal does not support this body type".to_string(),
78            )),
79        }
80    }
81
82    fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
83        match body {
84            Body::Json(_) => Ok(body),
85            Body::Text(s) => {
86                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
87                Ok(Body::Json(v))
88            }
89            Body::Bytes(b) => {
90                let s = String::from_utf8(b.to_vec()).map_err(|e| {
91                    CamelError::TypeConversionFailed(format!(
92                        "cannot unmarshal Body::Bytes as XML: {e}"
93                    ))
94                })?;
95                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
96                Ok(Body::Json(v))
97            }
98            Body::Xml(s) => {
99                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
100                Ok(Body::Json(v))
101            }
102            Body::Stream(_) => Err(CamelError::TypeConversionFailed(
103                "cannot unmarshal Body::Stream directly — use UnmarshalService which auto-materializes"
104                    .to_string(),
105            )),
106            Body::Empty => Err(CamelError::TypeConversionFailed(
107                "XmlDataFormat::unmarshal only supports Body::Json, Body::Text, Body::Bytes, and Body::Xml"
108                    .to_string(),
109            )),
110            _ => Err(CamelError::TypeConversionFailed(
111                "XmlDataFormat::unmarshal does not support this body type".to_string(),
112            )),
113        }
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use bytes::Bytes;
121    use serde_json::json;
122
123    #[test]
124    fn test_name() {
125        assert_eq!(XmlDataFormat::default().name(), "xml");
126    }
127
128    #[test]
129    fn test_unmarshal_text_to_json() {
130        let body = Body::Text("<root><child>value</child></root>".to_string());
131        let result = XmlDataFormat::default().unmarshal(body).unwrap();
132        match result {
133            Body::Json(v) => assert_eq!(v["root"]["child"], json!("value")),
134            _ => panic!("expected Body::Json"),
135        }
136    }
137
138    #[test]
139    fn test_unmarshal_bytes_to_json() {
140        let body = Body::Bytes(Bytes::from_static(b"<root/>"));
141        let result = XmlDataFormat::default().unmarshal(body).unwrap();
142        match result {
143            Body::Json(v) => assert_eq!(v["root"], serde_json::Value::Null),
144            _ => panic!("expected Body::Json"),
145        }
146    }
147
148    #[test]
149    fn test_unmarshal_xml_body_to_json() {
150        let body = Body::Xml("<root><a>1</a></root>".to_string());
151        let result = XmlDataFormat::default().unmarshal(body).unwrap();
152        match result {
153            Body::Json(v) => assert_eq!(v["root"]["a"], json!("1")),
154            _ => panic!("expected Body::Json"),
155        }
156    }
157
158    #[test]
159    fn test_unmarshal_invalid_xml() {
160        let body = Body::Text("not xml".to_string());
161        let result = XmlDataFormat::default().unmarshal(body);
162        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
163    }
164
165    #[test]
166    fn test_unmarshal_json_noop() {
167        let body = Body::Json(json!({"x": 1}));
168        let result = XmlDataFormat::default().unmarshal(body).unwrap();
169        assert!(matches!(result, Body::Json(_)));
170    }
171
172    #[test]
173    fn test_unmarshal_empty_returns_error() {
174        let body = Body::Empty;
175        let result = XmlDataFormat::default().unmarshal(body);
176        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
177    }
178
179    #[test]
180    fn test_marshal_json_to_text() {
181        let body = Body::Json(json!({"root": {"name": "Alice"}}));
182        let result = XmlDataFormat::default().marshal(body).unwrap();
183        match result {
184            Body::Text(s) => {
185                assert!(s.contains("<root>"));
186                assert!(s.contains("<name>Alice</name>"));
187            }
188            _ => panic!("expected Body::Text"),
189        }
190    }
191
192    #[test]
193    fn test_marshal_text_noop() {
194        let body = Body::Text("already text".to_string());
195        let result = XmlDataFormat::default().marshal(body).unwrap();
196        assert_eq!(result, Body::Text("already text".to_string()));
197    }
198
199    #[test]
200    fn marshal_empty_is_noop() {
201        let result = XmlDataFormat::default().marshal(Body::Empty).unwrap();
202        assert_eq!(result, Body::Empty);
203    }
204
205    #[test]
206    fn unmarshal_empty_fails_closed() {
207        let result = XmlDataFormat::default().unmarshal(Body::Empty);
208        match result {
209            Err(CamelError::TypeConversionFailed(msg)) => {
210                assert!(
211                    msg.contains("XmlDataFormat::unmarshal"),
212                    "message should name the format: {msg}"
213                );
214            }
215            other => panic!("expected TypeConversionFailed, got {other:?}"),
216        }
217    }
218
219    #[test]
220    fn unmarshal_truncated_fails() {
221        let result = XmlDataFormat::default().unmarshal(Body::Text("<user><name>".to_string()));
222        match result {
223            Err(CamelError::TypeConversionFailed(msg)) => {
224                assert!(
225                    msg.contains("unexpected end of XML input"),
226                    "message should name truncated input: {msg}"
227                );
228            }
229            other => panic!("expected TypeConversionFailed, got {other:?}"),
230        }
231    }
232
233    #[test]
234    fn marshal_output_has_no_declaration() {
235        let body = Body::Json(json!({"user": {"name": "kenny"}}));
236        let result = XmlDataFormat::default().marshal(body).unwrap();
237        assert_eq!(
238            result,
239            Body::Text("<user><name>kenny</name></user>".to_string())
240        );
241    }
242
243    #[test]
244    fn marshal_multi_key_object_fails() {
245        let body = Body::Json(json!({"a": 1, "b": 2}));
246        match XmlDataFormat::default().marshal(body) {
247            Err(CamelError::TypeConversionFailed(msg)) => {
248                assert!(
249                    msg.contains("exactly one root element"),
250                    "message should explain root requirement: {msg}"
251                );
252            }
253            other => panic!("expected TypeConversionFailed, got {other:?}"),
254        }
255    }
256
257    #[test]
258    fn marshal_top_level_array_fails() {
259        let body = Body::Json(json!([{"a": 1}]));
260        let result = XmlDataFormat::default().marshal(body);
261        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
262    }
263
264    #[test]
265    fn marshal_top_level_scalar_fails() {
266        let body = Body::Json(json!("hello"));
267        let result = XmlDataFormat::default().marshal(body);
268        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
269    }
270
271    #[test]
272    fn unmarshal_leaf_text_is_string() {
273        let result = XmlDataFormat::default()
274            .unmarshal(Body::Text("<n>42</n>".to_string()))
275            .unwrap();
276        assert_eq!(result, Body::Json(json!({"n": "42"})));
277    }
278
279    #[test]
280    fn unmarshal_drops_xmlns_declarations() {
281        let xml = r#"<r xmlns="urn:x" xmlns:p="urn:p"><child>v</child></r>"#;
282        let result = XmlDataFormat::default()
283            .unmarshal(Body::Text(xml.to_string()))
284            .unwrap();
285        assert_eq!(result, Body::Json(json!({"r": {"child": "v"}})));
286    }
287
288    #[test]
289    fn unmarshal_empty_element_is_null() {
290        let result = XmlDataFormat::default()
291            .unmarshal(Body::Text("<r><empty/></r>".to_string()))
292            .unwrap();
293        assert_eq!(result, Body::Json(json!({"r": {"empty": null}})));
294    }
295
296    #[test]
297    fn unmarshal_doctype_entity_ref_fails_closed() {
298        let xml = r#"<!DOCTYPE foo [<!ENTITY x "BOOM">]><foo>&x;</foo>"#;
299        match XmlDataFormat::default().unmarshal(Body::Text(xml.to_string())) {
300            Err(CamelError::TypeConversionFailed(msg)) => {
301                assert!(
302                    msg.contains("unrecognized entity"),
303                    "custom entity should fail closed: {msg}"
304                );
305            }
306            other => panic!("expected TypeConversionFailed, got {other:?}"),
307        }
308    }
309
310    #[test]
311    fn unmarshal_doctype_without_entity_ok() {
312        let result = XmlDataFormat::default()
313            .unmarshal(Body::Text("<!DOCTYPE foo><foo>v</foo>".to_string()))
314            .unwrap();
315        assert_eq!(result, Body::Json(json!({"foo": "v"})));
316    }
317
318    #[test]
319    fn marshal_xml_body_passes_through() {
320        let body = Body::Xml("<user><name>kenny</name></user>".to_string());
321        let result = XmlDataFormat::default().marshal(body).unwrap();
322        assert_eq!(
323            result,
324            Body::Xml("<user><name>kenny</name></user>".to_string())
325        );
326    }
327
328    #[test]
329    fn marshal_valid_utf8_bytes_passes_through() {
330        let body = Body::Bytes(Bytes::from_static(b"<user/>"));
331        let result = XmlDataFormat::default().marshal(body).unwrap();
332        match result {
333            Body::Bytes(b) => assert_eq!(b, Bytes::from_static(b"<user/>")),
334            other => panic!("expected Body::Bytes, got {other:?}"),
335        }
336    }
337
338    #[test]
339    fn marshal_invalid_utf8_bytes_fails_naming_body_bytes() {
340        let body = Body::Bytes(Bytes::from_static(&[0xFF, 0xFE]));
341        match XmlDataFormat::default().marshal(body) {
342            Err(CamelError::TypeConversionFailed(msg)) => {
343                assert!(
344                    msg.contains("Body::Bytes"),
345                    "should name the variant: {msg}"
346                );
347                assert!(msg.contains("UTF-8"), "should name the charset: {msg}");
348                assert!(msg.contains('0'), "should name the invalid offset: {msg}");
349            }
350            other => panic!("expected TypeConversionFailed, got {other:?}"),
351        }
352    }
353
354    #[test]
355    fn marshal_stream_still_fails_closed() {
356        use camel_api::body::{StreamBody, StreamMetadata};
357        use std::sync::Arc;
358        use tokio::sync::Mutex;
359
360        let body = Body::Stream(StreamBody {
361            stream: Arc::new(Mutex::new(Some(Box::pin(futures::stream::empty())))),
362            metadata: StreamMetadata::default(),
363        });
364        match XmlDataFormat::default().marshal(body) {
365            Err(CamelError::TypeConversionFailed(msg)) => {
366                assert!(
367                    msg.contains("stream_cache"),
368                    "message should point at stream_cache: {msg}"
369                );
370            }
371            other => panic!("expected TypeConversionFailed, got {other:?}"),
372        }
373    }
374
375    #[test]
376    fn test_unmarshal_with_raised_max_depth() {
377        let mut xml = String::new();
378        for _ in 0..150 {
379            xml.push_str("<a>");
380        }
381        xml.push('1');
382        for _ in 0..150 {
383            xml.push_str("</a>");
384        }
385        // Default depth (100) rejects 150 nesting; raised cap accepts it.
386        let body = Body::Text(xml);
387        let df = XmlDataFormat::new(XmlConfig { max_depth: 200 });
388        let result = df.unmarshal(body);
389        assert!(
390            result.is_ok(),
391            "should accept depth 150 under raised cap 200"
392        );
393    }
394}