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    fn marshal(&self, body: Body) -> Result<Body, CamelError> {
47        match body {
48            Body::Json(v) => {
49                let xml = json_to_xml(&v)?;
50                Ok(Body::Text(xml))
51            }
52            Body::Text(_) => Ok(body),
53            Body::Stream(_) => Err(CamelError::TypeConversionFailed(
54                "cannot marshal Body::Stream — add 'stream_cache' or 'convert_body_to' before this step".to_string(),
55            )),
56            Body::Empty | Body::Bytes(_) => Err(CamelError::TypeConversionFailed(
57                "XmlDataFormat::marshal only supports Body::Json and Body::Text".to_string(),
58            )),
59            Body::Xml(_) => Err(CamelError::TypeConversionFailed(
60                "XmlDataFormat::marshal does not accept Body::Xml — use unmarshal to convert XML to JSON"
61                    .to_string(),
62            )),
63        }
64    }
65
66    fn unmarshal(&self, body: Body) -> Result<Body, CamelError> {
67        match body {
68            Body::Json(_) => Ok(body),
69            Body::Text(s) => {
70                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
71                Ok(Body::Json(v))
72            }
73            Body::Bytes(b) => {
74                let s = String::from_utf8(b.to_vec()).map_err(|e| {
75                    CamelError::TypeConversionFailed(format!(
76                        "cannot unmarshal Body::Bytes as XML: {e}"
77                    ))
78                })?;
79                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
80                Ok(Body::Json(v))
81            }
82            Body::Xml(s) => {
83                let v = xml_to_json_with_depth_limit(&s, self.config.max_depth)?;
84                Ok(Body::Json(v))
85            }
86            Body::Stream(_) => Err(CamelError::TypeConversionFailed(
87                "cannot unmarshal Body::Stream directly — use UnmarshalService which auto-materializes"
88                    .to_string(),
89            )),
90            Body::Empty => Err(CamelError::TypeConversionFailed(
91                "XmlDataFormat::unmarshal only supports Body::Json, Body::Text, Body::Bytes, and Body::Xml"
92                    .to_string(),
93            )),
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use bytes::Bytes;
102    use serde_json::json;
103
104    #[test]
105    fn test_name() {
106        assert_eq!(XmlDataFormat::default().name(), "xml");
107    }
108
109    #[test]
110    fn test_unmarshal_text_to_json() {
111        let body = Body::Text("<root><child>value</child></root>".to_string());
112        let result = XmlDataFormat::default().unmarshal(body).unwrap();
113        match result {
114            Body::Json(v) => assert_eq!(v["root"]["child"], json!("value")),
115            _ => panic!("expected Body::Json"),
116        }
117    }
118
119    #[test]
120    fn test_unmarshal_bytes_to_json() {
121        let body = Body::Bytes(Bytes::from_static(b"<root/>"));
122        let result = XmlDataFormat::default().unmarshal(body).unwrap();
123        match result {
124            Body::Json(v) => assert_eq!(v["root"], serde_json::Value::Null),
125            _ => panic!("expected Body::Json"),
126        }
127    }
128
129    #[test]
130    fn test_unmarshal_xml_body_to_json() {
131        let body = Body::Xml("<root><a>1</a></root>".to_string());
132        let result = XmlDataFormat::default().unmarshal(body).unwrap();
133        match result {
134            Body::Json(v) => assert_eq!(v["root"]["a"], json!("1")),
135            _ => panic!("expected Body::Json"),
136        }
137    }
138
139    #[test]
140    fn test_unmarshal_invalid_xml() {
141        let body = Body::Text("not xml".to_string());
142        let result = XmlDataFormat::default().unmarshal(body);
143        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
144    }
145
146    #[test]
147    fn test_unmarshal_json_noop() {
148        let body = Body::Json(json!({"x": 1}));
149        let result = XmlDataFormat::default().unmarshal(body).unwrap();
150        assert!(matches!(result, Body::Json(_)));
151    }
152
153    #[test]
154    fn test_unmarshal_empty_returns_error() {
155        let body = Body::Empty;
156        let result = XmlDataFormat::default().unmarshal(body);
157        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
158    }
159
160    #[test]
161    fn test_marshal_json_to_text() {
162        let body = Body::Json(json!({"root": {"name": "Alice"}}));
163        let result = XmlDataFormat::default().marshal(body).unwrap();
164        match result {
165            Body::Text(s) => {
166                assert!(s.contains("<root>"));
167                assert!(s.contains("<name>Alice</name>"));
168            }
169            _ => panic!("expected Body::Text"),
170        }
171    }
172
173    #[test]
174    fn test_marshal_text_noop() {
175        let body = Body::Text("already text".to_string());
176        let result = XmlDataFormat::default().marshal(body).unwrap();
177        assert_eq!(result, Body::Text("already text".to_string()));
178    }
179
180    #[test]
181    fn test_marshal_empty_returns_error() {
182        let body = Body::Empty;
183        let result = XmlDataFormat::default().marshal(body);
184        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
185    }
186
187    #[test]
188    fn test_marshal_xml_body_rejected() {
189        let body = Body::Xml("<root/>".to_string());
190        let result = XmlDataFormat::default().marshal(body);
191        assert!(matches!(result, Err(CamelError::TypeConversionFailed(_))));
192    }
193
194    #[test]
195    fn test_unmarshal_with_raised_max_depth() {
196        let mut xml = String::new();
197        for _ in 0..150 {
198            xml.push_str("<a>");
199        }
200        xml.push('1');
201        for _ in 0..150 {
202            xml.push_str("</a>");
203        }
204        // Default depth (100) rejects 150 nesting; raised cap accepts it.
205        let body = Body::Text(xml);
206        let df = XmlDataFormat::new(XmlConfig { max_depth: 200 });
207        let result = df.unmarshal(body);
208        assert!(
209            result.is_ok(),
210            "should accept depth 150 under raised cap 200"
211        );
212    }
213}