Skip to main content

xml_sec/c14n/
mod.rs

1//! XML Canonicalization (C14N).
2//!
3//! Implements:
4//! - [Canonical XML 1.0](https://www.w3.org/TR/xml-c14n/) (inclusive)
5//! - [Canonical XML 1.1](https://www.w3.org/TR/xml-c14n11/) (inclusive; xml:id non-inheritance and xml:base fixup)
6//! - [Exclusive XML Canonicalization 1.0](https://www.w3.org/TR/xml-exc-c14n/) (exclusive)
7//!
8//! # Example
9//!
10//! ```
11//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
12//! use xml_sec::c14n::{C14nAlgorithm, C14nMode, canonicalize_xml};
13//!
14//! let xml = b"<root b=\"2\" a=\"1\"><empty/></root>";
15//! let algo = C14nAlgorithm::new(C14nMode::Inclusive1_0, false);
16//! let canonical = canonicalize_xml(xml, &algo)?;
17//! assert_eq!(
18//!     String::from_utf8(canonical)?,
19//!     "<root a=\"1\" b=\"2\"><empty></empty></root>"
20//! );
21//! # Ok(())
22//! # }
23//! ```
24
25mod escape;
26mod ns_common;
27pub(crate) mod ns_exclusive;
28pub(crate) mod ns_inclusive;
29pub(crate) mod prefix;
30pub(crate) mod serialize;
31pub(crate) mod xml_base;
32
33use std::collections::HashSet;
34
35use roxmltree::{Document, Node, NodeId};
36
37use ns_exclusive::ExclusiveNsRenderer;
38use ns_inclusive::InclusiveNsRenderer;
39#[cfg(any(feature = "xmldsig", test))]
40use serialize::CanonicalOutputLimitExceeded;
41#[cfg(any(feature = "xmldsig", test))]
42use serialize::serialize_canonical_visible_with_positions_bounded;
43use serialize::{
44    C14nConfig, CanonicalOutputOptions, serialize_canonical_visible_with_position_bounded,
45    serialize_canonical_visible_with_position_with_xml_base_budget,
46};
47
48/// C14N algorithm mode (without the comments flag).
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum C14nMode {
51    /// Inclusive C14N 1.0 — all in-scope namespaces rendered.
52    Inclusive1_0,
53    /// Inclusive C14N 1.1 — like 1.0 with xml:id non-inheritance and xml:base fixup.
54    Inclusive1_1,
55    /// Exclusive C14N 1.0 — only visibly-utilized namespaces rendered.
56    Exclusive1_0,
57}
58
59/// Full C14N algorithm identifier.
60///
61/// Constructed from algorithm URIs found in `<CanonicalizationMethod>` or
62/// `<Transform>` elements.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct C14nAlgorithm {
65    mode: C14nMode,
66    with_comments: bool,
67    /// For Exclusive C14N: prefixes forced via InclusiveNamespaces PrefixList.
68    /// `"#default"` is normalized to `""` (empty string) by `with_prefix_list()`.
69    inclusive_prefixes: HashSet<String>,
70}
71
72impl C14nAlgorithm {
73    /// The canonicalization mode.
74    pub fn mode(&self) -> C14nMode {
75        self.mode
76    }
77
78    /// Whether comment nodes are preserved.
79    pub fn with_comments(&self) -> bool {
80        self.with_comments
81    }
82
83    /// Prefixes forced via InclusiveNamespaces PrefixList (exclusive C14N).
84    pub fn inclusive_prefixes(&self) -> &HashSet<String> {
85        &self.inclusive_prefixes
86    }
87
88    /// Create a new algorithm with the given mode and comments flag.
89    pub fn new(mode: C14nMode, with_comments: bool) -> Self {
90        Self {
91            mode,
92            with_comments,
93            inclusive_prefixes: HashSet::new(),
94        }
95    }
96
97    /// Parse from an algorithm URI. Returns `None` for unrecognized URIs.
98    pub fn from_uri(uri: &str) -> Option<Self> {
99        let (mode, with_comments) = match uri {
100            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" => (C14nMode::Inclusive1_0, false),
101            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" => {
102                (C14nMode::Inclusive1_0, true)
103            }
104            "http://www.w3.org/2006/12/xml-c14n11" => (C14nMode::Inclusive1_1, false),
105            "http://www.w3.org/2006/12/xml-c14n11#WithComments" => (C14nMode::Inclusive1_1, true),
106            "http://www.w3.org/2001/10/xml-exc-c14n#" => (C14nMode::Exclusive1_0, false),
107            "http://www.w3.org/2001/10/xml-exc-c14n#WithComments" => (C14nMode::Exclusive1_0, true),
108            _ => return None,
109        };
110        Some(Self {
111            mode,
112            with_comments,
113            inclusive_prefixes: HashSet::new(),
114        })
115    }
116
117    /// Set the InclusiveNamespaces PrefixList (exclusive C14N only).
118    /// `"#default"` is normalized to empty string `""`.
119    ///
120    /// Only meaningful for [`C14nMode::Exclusive1_0`]. For inclusive modes,
121    /// the prefix list is ignored during canonicalization.
122    pub fn with_prefix_list(mut self, prefix_list: &str) -> Self {
123        self.inclusive_prefixes = prefix_list
124            .split_whitespace()
125            .map(|p| {
126                if p == "#default" {
127                    String::new()
128                } else {
129                    p.to_string()
130                }
131            })
132            .collect();
133        self
134    }
135
136    /// Get the algorithm URI for this configuration.
137    pub fn uri(&self) -> &'static str {
138        match (self.mode, self.with_comments) {
139            (C14nMode::Inclusive1_0, false) => "http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
140            (C14nMode::Inclusive1_0, true) => {
141                "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
142            }
143            (C14nMode::Inclusive1_1, false) => "http://www.w3.org/2006/12/xml-c14n11",
144            (C14nMode::Inclusive1_1, true) => "http://www.w3.org/2006/12/xml-c14n11#WithComments",
145            (C14nMode::Exclusive1_0, false) => "http://www.w3.org/2001/10/xml-exc-c14n#",
146            (C14nMode::Exclusive1_0, true) => "http://www.w3.org/2001/10/xml-exc-c14n#WithComments",
147        }
148    }
149}
150
151/// Error type for C14N operations.
152#[derive(Debug, thiserror::Error)]
153pub enum C14nError {
154    /// XML parsing error.
155    #[error("XML parse error: {0}")]
156    Parse(String),
157    /// Invalid node reference.
158    #[error("invalid node reference")]
159    InvalidNode,
160    /// Algorithm not yet implemented.
161    #[error("unsupported algorithm: {0}")]
162    UnsupportedAlgorithm(String),
163    /// The inherited `xml:base` chain exceeds the configured component limit.
164    #[error("XML Base resolution exceeds maximum of {max} inherited components: got {actual}")]
165    XmlBaseComponentsTooLarge {
166        /// Configured maximum inherited components.
167        max: usize,
168        /// Number of inherited components encountered.
169        actual: usize,
170    },
171    /// Cumulative `xml:base` resolution work exceeds the configured byte limit.
172    #[error("XML Base resolution exceeds maximum of {max_bytes} bytes: got at least {actual}")]
173    XmlBaseResolutionTooLarge {
174        /// Configured maximum cumulative bytes.
175        max_bytes: usize,
176        /// Minimum cumulative byte count that exceeded the maximum.
177        actual: usize,
178    },
179    /// I/O error.
180    #[error("I/O error: {0}")]
181    Io(#[from] std::io::Error),
182}
183
184#[cfg(any(feature = "xmldsig", test))]
185pub(crate) fn is_output_limit_error(error: &C14nError) -> bool {
186    matches!(
187        error,
188        C14nError::Io(error)
189            if error
190                .get_ref()
191                .is_some_and(|source| source.is::<CanonicalOutputLimitExceeded>())
192    )
193}
194
195/// Visibility contract for canonicalizing a precise XPath node-set.
196///
197/// XPath can select attributes and namespace nodes independently from their
198/// owner element. The public closure API predates that requirement and treats
199/// both categories as visible whenever their owner is visible; XMLDSig uses
200/// this richer crate-private contract for standards-compliant subsets.
201pub(crate) trait NodeVisibility {
202    fn contains_node(&self, node: Node<'_, '_>) -> bool;
203
204    fn contains_attribute(
205        &self,
206        owner: Node<'_, '_>,
207        namespace: Option<&str>,
208        local_name: &str,
209    ) -> bool;
210
211    fn contains_namespace(&self, owner: Node<'_, '_>, prefix: &str, uri: &str) -> bool;
212}
213
214struct ClosureVisibility<'a> {
215    predicate: &'a dyn Fn(Node<'_, '_>) -> bool,
216}
217
218impl NodeVisibility for ClosureVisibility<'_> {
219    fn contains_node(&self, node: Node<'_, '_>) -> bool {
220        (self.predicate)(node)
221    }
222
223    fn contains_attribute(
224        &self,
225        owner: Node<'_, '_>,
226        _namespace: Option<&str>,
227        _local_name: &str,
228    ) -> bool {
229        (self.predicate)(owner)
230    }
231
232    fn contains_namespace(&self, owner: Node<'_, '_>, _prefix: &str, _uri: &str) -> bool {
233        (self.predicate)(owner)
234    }
235}
236
237/// Canonicalize an XML document or document subset.
238///
239/// - `doc`: parsed roxmltree document (read-only DOM).
240/// - `node_set`: optional predicate controlling which nodes appear in output.
241///   `None` means the entire document.
242/// - `algo`: algorithm parameters (mode, comments, prefix list).
243/// - `output`: byte buffer receiving canonical XML.
244pub fn canonicalize(
245    doc: &Document,
246    node_set: Option<&dyn Fn(Node) -> bool>,
247    algo: &C14nAlgorithm,
248    output: &mut Vec<u8>,
249) -> Result<(), C14nError> {
250    let visibility = node_set.map(|predicate| ClosureVisibility { predicate });
251    canonicalize_with_visibility(
252        doc,
253        visibility
254            .as_ref()
255            .map(|visibility| visibility as &dyn NodeVisibility),
256        algo,
257        output,
258    )
259}
260
261#[cfg(any(feature = "xmldsig", test))]
262/// Canonicalize through the closure visibility API while enforcing both the
263/// output ceiling and the caller's operation-wide XML Base work budget.
264pub(crate) fn canonicalize_bounded_with_xml_base_budget(
265    doc: &Document,
266    node_set: Option<&dyn Fn(Node) -> bool>,
267    algo: &C14nAlgorithm,
268    max_output_bytes: usize,
269    xml_base_resolution: &xml_base::XmlBaseResolutionBudget,
270    output: &mut Vec<u8>,
271) -> Result<(), C14nError> {
272    let visibility = node_set.map(|predicate| ClosureVisibility { predicate });
273    canonicalize_with_visibility_and_position_bounded_with_xml_base_budget(
274        doc,
275        visibility
276            .as_ref()
277            .map(|visibility| visibility as &dyn NodeVisibility),
278        algo,
279        None,
280        max_output_bytes,
281        xml_base_resolution,
282        output,
283    )?;
284    Ok(())
285}
286
287pub(crate) fn canonicalize_with_visibility(
288    doc: &Document,
289    visibility: Option<&dyn NodeVisibility>,
290    algo: &C14nAlgorithm,
291    output: &mut Vec<u8>,
292) -> Result<(), C14nError> {
293    canonicalize_with_visibility_and_position(doc, visibility, algo, None, output)?;
294    Ok(())
295}
296
297pub(crate) fn canonicalize_with_visibility_and_position(
298    doc: &Document,
299    visibility: Option<&dyn NodeVisibility>,
300    algo: &C14nAlgorithm,
301    tracked_element: Option<NodeId>,
302    output: &mut Vec<u8>,
303) -> Result<Option<usize>, C14nError> {
304    canonicalize_with_visibility_and_position_impl(
305        doc,
306        visibility,
307        algo,
308        tracked_element,
309        None,
310        None,
311        output,
312    )
313}
314
315#[cfg(test)]
316pub(crate) fn canonicalize_with_visibility_and_position_bounded(
317    doc: &Document,
318    visibility: Option<&dyn NodeVisibility>,
319    algo: &C14nAlgorithm,
320    tracked_element: Option<NodeId>,
321    max_output_bytes: usize,
322    output: &mut Vec<u8>,
323) -> Result<Option<usize>, C14nError> {
324    canonicalize_with_visibility_and_position_impl(
325        doc,
326        visibility,
327        algo,
328        tracked_element,
329        Some(max_output_bytes),
330        None,
331        output,
332    )
333}
334
335#[cfg(any(feature = "xmldsig", test))]
336pub(crate) fn canonicalize_with_visibility_and_position_bounded_with_xml_base_budget(
337    doc: &Document,
338    visibility: Option<&dyn NodeVisibility>,
339    algo: &C14nAlgorithm,
340    tracked_element: Option<NodeId>,
341    max_output_bytes: usize,
342    xml_base_resolution: &xml_base::XmlBaseResolutionBudget,
343    output: &mut Vec<u8>,
344) -> Result<Option<usize>, C14nError> {
345    canonicalize_with_visibility_and_position_impl(
346        doc,
347        visibility,
348        algo,
349        tracked_element,
350        Some(max_output_bytes),
351        Some(xml_base_resolution),
352        output,
353    )
354}
355
356#[cfg(any(feature = "xmldsig", test))]
357pub(crate) fn canonicalize_with_visibility_and_positions_bounded_with_xml_base_budget(
358    doc: &Document,
359    visibility: Option<&dyn NodeVisibility>,
360    algo: &C14nAlgorithm,
361    tracked_elements: &[NodeId],
362    max_output_bytes: usize,
363    xml_base_resolution: &xml_base::XmlBaseResolutionBudget,
364    output: &mut Vec<u8>,
365) -> Result<Vec<(NodeId, usize)>, C14nError> {
366    let config = C14nConfig {
367        inherit_xml_attrs: !matches!(algo.mode, C14nMode::Exclusive1_0),
368        fixup_xml_base: matches!(algo.mode, C14nMode::Inclusive1_1),
369    };
370    let inclusive = InclusiveNsRenderer;
371    let exclusive = ExclusiveNsRenderer::new(&algo.inclusive_prefixes);
372    let renderer: &dyn serialize::NsRenderer = match algo.mode {
373        C14nMode::Inclusive1_0 | C14nMode::Inclusive1_1 => &inclusive,
374        C14nMode::Exclusive1_0 => &exclusive,
375    };
376    serialize_canonical_visible_with_positions_bounded(
377        doc,
378        visibility,
379        algo.with_comments,
380        renderer,
381        config,
382        CanonicalOutputOptions::bounded_many(
383            tracked_elements,
384            max_output_bytes,
385            xml_base_resolution,
386        ),
387        output,
388    )
389}
390
391fn canonicalize_with_visibility_and_position_impl(
392    doc: &Document,
393    visibility: Option<&dyn NodeVisibility>,
394    algo: &C14nAlgorithm,
395    tracked_element: Option<NodeId>,
396    max_output_bytes: Option<usize>,
397    xml_base_resolution: Option<&xml_base::XmlBaseResolutionBudget>,
398    output: &mut Vec<u8>,
399) -> Result<Option<usize>, C14nError> {
400    let default_xml_base_resolution = xml_base::XmlBaseResolutionBudget::default();
401    let xml_base_resolution = xml_base_resolution.unwrap_or(&default_xml_base_resolution);
402    // inherit_xml_attrs: Inclusive C14N inherits xml:* attrs from ancestors
403    // per §2.4. Exclusive C14N explicitly omits this per Exc-C14N §3.
404    // fixup_xml_base: C14N 1.1 resolves relative xml:base URIs via RFC 3986.
405    match algo.mode {
406        C14nMode::Inclusive1_0 => {
407            let renderer = InclusiveNsRenderer;
408            let config = C14nConfig {
409                inherit_xml_attrs: true,
410                fixup_xml_base: false,
411            };
412            serialize_canonical_visible_with_position_dispatch(
413                doc,
414                visibility,
415                algo.with_comments,
416                &renderer,
417                config,
418                tracked_element,
419                max_output_bytes,
420                xml_base_resolution,
421                output,
422            )
423        }
424        C14nMode::Inclusive1_1 => {
425            let renderer = InclusiveNsRenderer;
426            let config = C14nConfig {
427                inherit_xml_attrs: true,
428                fixup_xml_base: true,
429            };
430            serialize_canonical_visible_with_position_dispatch(
431                doc,
432                visibility,
433                algo.with_comments,
434                &renderer,
435                config,
436                tracked_element,
437                max_output_bytes,
438                xml_base_resolution,
439                output,
440            )
441        }
442        C14nMode::Exclusive1_0 => {
443            let renderer = ExclusiveNsRenderer::new(&algo.inclusive_prefixes);
444            let config = C14nConfig {
445                inherit_xml_attrs: false,
446                fixup_xml_base: false,
447            };
448            serialize_canonical_visible_with_position_dispatch(
449                doc,
450                visibility,
451                algo.with_comments,
452                &renderer,
453                config,
454                tracked_element,
455                max_output_bytes,
456                xml_base_resolution,
457                output,
458            )
459        }
460    }
461}
462
463#[allow(clippy::too_many_arguments)]
464fn serialize_canonical_visible_with_position_dispatch(
465    doc: &Document,
466    visibility: Option<&dyn NodeVisibility>,
467    with_comments: bool,
468    renderer: &dyn serialize::NsRenderer,
469    config: C14nConfig,
470    tracked_element: Option<NodeId>,
471    max_output_bytes: Option<usize>,
472    xml_base_resolution: &xml_base::XmlBaseResolutionBudget,
473    output: &mut Vec<u8>,
474) -> Result<Option<usize>, C14nError> {
475    match max_output_bytes {
476        Some(max_output_bytes) => serialize_canonical_visible_with_position_bounded(
477            doc,
478            visibility,
479            with_comments,
480            renderer,
481            config,
482            CanonicalOutputOptions::bounded(tracked_element, max_output_bytes, xml_base_resolution),
483            output,
484        ),
485        None => serialize_canonical_visible_with_position_with_xml_base_budget(
486            doc,
487            visibility,
488            with_comments,
489            renderer,
490            config,
491            tracked_element,
492            xml_base_resolution,
493            output,
494        ),
495    }
496}
497
498/// Convenience: parse XML bytes and canonicalize the whole document.
499///
500/// Input must be valid UTF-8 (XML 1.0 documents are UTF-8 or declare their
501/// encoding; roxmltree only accepts UTF-8). DTDs and external entity resolution
502/// are disabled, and the library's absolute XML byte, node, and depth ceilings apply.
503/// Returns `C14nError::Parse` for invalid UTF-8, malformed XML, or exceeded
504/// input ceilings.
505pub fn canonicalize_xml(xml: &[u8], algo: &C14nAlgorithm) -> Result<Vec<u8>, C14nError> {
506    if xml.len() > crate::hard_limits::XML_DOCUMENT_BYTE_CEILING {
507        return Err(C14nError::Parse(format!(
508            "input exceeds maximum XML document size of {} bytes: got {}",
509            crate::hard_limits::XML_DOCUMENT_BYTE_CEILING,
510            xml.len()
511        )));
512    }
513    let xml_str =
514        std::str::from_utf8(xml).map_err(|e| C14nError::Parse(format!("invalid UTF-8: {e}")))?;
515    let document = crate::document::parse_borrowed_with_settings_and_budget(
516        xml_str,
517        crate::document::DocumentParseSettings::default(),
518        None,
519    )
520    .map_err(|error| C14nError::Parse(error.to_string()))?;
521    let mut output = Vec::new();
522    canonicalize(&document, None, algo, &mut output)?;
523    Ok(output)
524}
525
526/// Canonicalize a retained owned document without reparsing it.
527pub fn canonicalize_document(
528    document: &crate::XmlDocument,
529    algo: &C14nAlgorithm,
530) -> Result<Vec<u8>, C14nError> {
531    let mut output = Vec::new();
532    document.with_view(|view| canonicalize(view.document(), None, algo, &mut output))?;
533    Ok(output)
534}
535
536#[cfg(test)]
537#[allow(clippy::unwrap_used)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn from_uri_roundtrip() {
543        let uris = [
544            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
545            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments",
546            "http://www.w3.org/2006/12/xml-c14n11",
547            "http://www.w3.org/2006/12/xml-c14n11#WithComments",
548            "http://www.w3.org/2001/10/xml-exc-c14n#",
549            "http://www.w3.org/2001/10/xml-exc-c14n#WithComments",
550        ];
551        for uri in uris {
552            let algo = C14nAlgorithm::from_uri(uri).expect(uri);
553            assert_eq!(algo.uri(), uri);
554        }
555    }
556
557    #[test]
558    fn unknown_uri_returns_none() {
559        assert!(C14nAlgorithm::from_uri("http://example.com/unknown").is_none());
560    }
561
562    #[test]
563    fn prefix_list_parsing() {
564        let algo = C14nAlgorithm::new(C14nMode::Exclusive1_0, false)
565            .with_prefix_list("foo bar #default baz");
566        assert!(algo.inclusive_prefixes.contains("foo"));
567        assert!(algo.inclusive_prefixes.contains("bar"));
568        assert!(algo.inclusive_prefixes.contains("baz"));
569        assert!(algo.inclusive_prefixes.contains("")); // #default → ""
570        assert_eq!(algo.inclusive_prefixes.len(), 4);
571    }
572
573    #[test]
574    fn canonicalize_xml_basic() {
575        let xml = b"<root b=\"2\" a=\"1\"><empty/></root>";
576        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_0, false);
577        let result = canonicalize_xml(xml, &algo).expect("c14n");
578        assert_eq!(
579            String::from_utf8(result).expect("utf8"),
580            r#"<root a="1" b="2"><empty></empty></root>"#
581        );
582    }
583
584    #[test]
585    fn canonicalize_xml_rejects_input_above_the_document_byte_ceiling_before_parsing() {
586        // The convenience parser accepts untrusted bytes, so allocation bounds
587        // must apply before UTF-8 or XML parsing can inspect the payload.
588        let xml = vec![b' '; crate::hard_limits::XML_DOCUMENT_BYTE_CEILING + 1];
589        let error = match canonicalize_xml(&xml, &C14nAlgorithm::new(C14nMode::Inclusive1_0, false))
590        {
591            Err(error) => error,
592            Ok(_) => panic!("oversized canonicalization input must be rejected"),
593        };
594        assert!(matches!(
595            error,
596            C14nError::Parse(message)
597                if message.contains("exceeds maximum XML document size")
598        ));
599    }
600
601    #[test]
602    fn canonicalize_xml_rejects_input_above_the_document_node_ceiling() {
603        // A compact document can otherwise force an effectively unbounded
604        // parser-node allocation despite staying below the byte ceiling.
605        let children = "<n/>".repeat(crate::hard_limits::XML_DOCUMENT_NODE_CEILING as usize);
606        let xml = format!("<root>{children}</root>");
607        let error = match canonicalize_xml(
608            xml.as_bytes(),
609            &C14nAlgorithm::new(C14nMode::Inclusive1_0, false),
610        ) {
611            Err(error) => error,
612            Ok(_) => panic!("excessive canonicalization nodes must be rejected"),
613        };
614        assert!(matches!(
615            error,
616            C14nError::Parse(message) if message.contains("nodes limit reached")
617        ));
618    }
619
620    #[test]
621    fn canonicalize_xml_rejects_input_above_the_document_depth_ceiling() {
622        // The convenience parser is a public untrusted-input boundary, so the
623        // absolute depth ceiling must apply before recursive C14N traversal.
624        let depth = crate::hard_limits::XML_DOCUMENT_DEPTH_CEILING + 1;
625        let xml = format!("{}{}", "<n>".repeat(depth), "</n>".repeat(depth));
626
627        let error = canonicalize_xml(
628            xml.as_bytes(),
629            &C14nAlgorithm::new(C14nMode::Inclusive1_0, false),
630        )
631        .expect_err("over-depth canonicalization input must be rejected");
632
633        assert!(matches!(
634            error,
635            C14nError::Parse(message) if message.contains("maximum element depth")
636        ));
637    }
638
639    #[test]
640    fn canonicalize_xml_does_not_enable_dtd_or_external_entity_resolution() {
641        // Whole-document C14N is a convenience API, not an implicit opt-in to
642        // DTD parsing or external resource access.
643        let xml = br#"<!DOCTYPE root [<!ENTITY value 'expanded'>]><root>&value;</root>"#;
644        let error = canonicalize_xml(xml, &C14nAlgorithm::new(C14nMode::Inclusive1_0, false))
645            .expect_err("DTD input must remain disabled");
646        assert!(matches!(
647            error,
648            C14nError::Parse(message) if message.contains("DTD detected")
649        ));
650    }
651
652    #[test]
653    fn c14n_1_1_basic() {
654        // C14N 1.1 serialization is identical to 1.0 for full documents.
655        let xml = b"<root b=\"2\" a=\"1\"><empty/></root>";
656        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
657        let result = canonicalize_xml(xml, &algo).expect("c14n 1.1");
658        assert_eq!(
659            String::from_utf8(result).expect("utf8"),
660            r#"<root a="1" b="2"><empty></empty></root>"#
661        );
662    }
663
664    #[test]
665    fn c14n_1_1_with_comments() {
666        let xml = b"<root><!-- comment -->text</root>";
667        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_1, true);
668        let result = canonicalize_xml(xml, &algo).expect("c14n 1.1 with comments");
669        assert_eq!(
670            String::from_utf8(result).expect("utf8"),
671            "<root><!-- comment -->text</root>"
672        );
673    }
674
675    #[test]
676    fn c14n_1_1_without_comments() {
677        let xml = b"<root><!-- comment -->text</root>";
678        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
679        let result = canonicalize_xml(xml, &algo).expect("c14n 1.1 without comments");
680        assert_eq!(
681            String::from_utf8(result).expect("utf8"),
682            "<root>text</root>"
683        );
684    }
685
686    #[test]
687    fn c14n_1_1_namespaces() {
688        // C14N 1.1 renders all in-scope namespaces like 1.0.
689        let xml = b"<root xmlns:a=\"http://a\" xmlns:b=\"http://b\"><child/></root>";
690        let algo_10 = C14nAlgorithm::new(C14nMode::Inclusive1_0, false);
691        let algo_11 = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
692        let result_10 = canonicalize_xml(xml, &algo_10).expect("1.0");
693        let result_11 = canonicalize_xml(xml, &algo_11).expect("1.1");
694        // For full documents, 1.0 and 1.1 produce identical output.
695        assert_eq!(result_10, result_11);
696    }
697
698    #[test]
699    fn c14n_1_1_xml_id_is_not_inherited_in_subset() {
700        // C14N 1.1 explicitly excludes xml:id from simple inheritable
701        // attributes, so omitting its owner must also omit the attribute.
702        use roxmltree::Document;
703        use std::collections::HashSet;
704
705        let xml = r#"<root xml:id="r1"><child>text</child></root>"#;
706        let doc = Document::parse(xml).expect("parse");
707        let child = doc.root_element().first_element_child().expect("child");
708
709        // Build subset: child + its descendants, excluding root
710        let mut ids = HashSet::new();
711        let mut stack = vec![child];
712        while let Some(n) = stack.pop() {
713            ids.insert(n.id());
714            for c in n.children() {
715                stack.push(c);
716            }
717        }
718        let pred = move |n: roxmltree::Node| ids.contains(&n.id());
719
720        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
721        let mut out = Vec::new();
722        canonicalize(&doc, Some(&pred), &algo, &mut out).expect("c14n 1.1 subset");
723        let result = String::from_utf8(out).expect("utf8");
724
725        assert!(
726            !result.contains(r#"xml:id="r1""#),
727            "xml:id must not be inherited in C14N 1.1 subset; got: {result}"
728        );
729    }
730
731    #[test]
732    fn c14n_1_0_xml_id_is_inherited_in_subset() {
733        // C14N 1.0 predates the C14N 1.1 xml:id exception, so xml:id follows
734        // the general xml:* apex inheritance rule in a document subset.
735        use roxmltree::Document;
736        use std::collections::HashSet;
737
738        let xml = r#"<root xml:id="r1"><child>text</child></root>"#;
739        let doc = Document::parse(xml).expect("parse");
740        let child = doc.root_element().first_element_child().expect("child");
741        let ids = child
742            .descendants()
743            .map(|node| node.id())
744            .collect::<HashSet<_>>();
745        let pred = move |node: roxmltree::Node| ids.contains(&node.id());
746
747        let algo = C14nAlgorithm::new(C14nMode::Inclusive1_0, false);
748        let mut out = Vec::new();
749        canonicalize(&doc, Some(&pred), &algo, &mut out).expect("c14n 1.0 subset");
750
751        assert_eq!(
752            String::from_utf8(out).expect("utf8"),
753            r#"<child xml:id="r1">text</child>"#
754        );
755    }
756
757    #[test]
758    fn bounded_canonicalization_stops_before_exceeding_the_limit() {
759        // XMLDSig applies a signature-wide output ceiling. The serializer must
760        // stop at that ceiling instead of allocating the complete hostile value
761        // and rejecting it only after serialization has finished.
762        let xml = format!("<root>{}</root>", "x".repeat(4_096));
763        let document = Document::parse(&xml).expect("fixed XML must parse");
764        let algorithm = C14nAlgorithm::new(C14nMode::Inclusive1_0, false);
765        let mut output = Vec::new();
766
767        let error = canonicalize_with_visibility_and_position_bounded(
768            &document,
769            None,
770            &algorithm,
771            None,
772            64,
773            &mut output,
774        )
775        .expect_err("canonicalization must stop at the caller's byte ceiling");
776
777        assert!(is_output_limit_error(&error));
778        assert!(
779            output.len() <= 64,
780            "bounded output grew to {} bytes",
781            output.len()
782        );
783    }
784
785    #[test]
786    fn c14n_1_1_bounds_inherited_xml_base_components() {
787        // C14N 1.1 subset fixup walks ancestors outside the selected node set.
788        // Bounding that walk prevents deeply nested xml:base chains from
789        // multiplying URI-resolution work during canonicalization.
790        let mut xml = String::new();
791        for _ in 0..=crate::hard_limits::XML_BASE_COMPONENT_CEILING {
792            xml.push_str(r#"<n xml:base="segment/">"#);
793        }
794        xml.push_str("<leaf/>");
795        for _ in 0..=crate::hard_limits::XML_BASE_COMPONENT_CEILING {
796            xml.push_str("</n>");
797        }
798        let document = Document::parse(&xml).expect("fixed XML must parse");
799        let leaf = document
800            .descendants()
801            .find(|node| node.has_tag_name("leaf"))
802            .expect("leaf");
803        let visible = |node: Node<'_, '_>| node == leaf;
804        let algorithm = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
805        let mut output = Vec::new();
806
807        let error = canonicalize_with_visibility(
808            &document,
809            Some(&ClosureVisibility {
810                predicate: &visible,
811            }),
812            &algorithm,
813            &mut output,
814        )
815        .expect_err("C14N must reject an overlong inherited xml:base chain");
816
817        assert!(
818            error.to_string().contains("XML Base"),
819            "unexpected C14N error: {error}"
820        );
821    }
822
823    #[test]
824    fn unbounded_output_preserves_the_callers_xml_base_budget() {
825        // Output capacity and XML Base work are independent limits. Omitting
826        // an output ceiling must not replace the caller's XML Base policy.
827        let document = Document::parse(
828            r#"<root xml:base="one/"><parent xml:base="two/"><leaf/></parent></root>"#,
829        )
830        .unwrap();
831        let leaf = document
832            .descendants()
833            .find(|node| node.has_tag_name("leaf"))
834            .unwrap();
835        let visible = |node: Node<'_, '_>| node == leaf;
836        let budget = xml_base::XmlBaseResolutionBudget::with_limits(1, usize::MAX);
837        let algorithm = C14nAlgorithm::new(C14nMode::Inclusive1_1, false);
838        let mut output = Vec::new();
839
840        let error = canonicalize_with_visibility_and_position_impl(
841            &document,
842            Some(&ClosureVisibility {
843                predicate: &visible,
844            }),
845            &algorithm,
846            None,
847            None,
848            Some(&budget),
849            &mut output,
850        )
851        .expect_err("the caller's component ceiling must survive unbounded dispatch");
852
853        assert!(matches!(
854            error,
855            C14nError::XmlBaseComponentsTooLarge { max: 1, actual: 2 }
856        ));
857    }
858}