Skip to main content

jubarte_dom/
limits.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#![cfg_attr(
6    not(test),
7    deny(clippy::indexing_slicing, clippy::arithmetic_side_effects)
8)]
9
10//! Input resource budgets and refusal error types shared by XML parsing,
11//! ZIP package admission and the comparer.
12
13use std::fmt;
14
15/// Resource budgets. The defaults are a product policy, not a proof against
16/// every denial of service.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct InputLimits {
19    /// Size of the ZIP file itself.
20    pub max_compressed_bytes: u64,
21    /// ZIP entries, directories included.
22    pub max_entries: usize,
23    /// Inflated size of any one entry.
24    pub max_part_bytes: u64,
25    /// Inflated size of all entries together.
26    pub max_uncompressed_bytes: u64,
27    /// Element nesting in any XML part.
28    pub max_xml_depth: usize,
29    /// Attributes per element, including namespace declarations.
30    pub max_element_attributes: usize,
31    /// UTF-8 bytes in a qualified attribute name.
32    pub max_attribute_name_bytes: usize,
33    /// Bytes in a raw or decoded attribute value.
34    pub max_attribute_value_bytes: usize,
35    /// Bytes in a complete start tag, including syntax and delimiters.
36    pub max_start_tag_bytes: usize,
37    /// XML element start tags in all the package's XML parts together.
38    /// Memory follows the element count, not the bytes: a few hundred KB of
39    /// zipped one-run paragraphs is millions of DOM nodes and several GB
40    /// once parsed and laid out (#2014).
41    pub max_xml_elements: u64,
42    /// Characters of text plus elements in one side of a comparison: its
43    /// body and notes together, or one header or footer. `compare` turns
44    /// every character into an atom of 2-4 KB, so 1 MiB of text peaked at
45    /// 2.1-3.9 GB and B1's 66 MiB of spaces passed 6 GB (word_exp
46    /// cmp_scale, 2026-10-31). Only the comparer reads it.
47    pub max_story_units: u64,
48}
49
50impl Default for InputLimits {
51    fn default() -> Self {
52        const MIB: u64 = 1024 * 1024;
53        Self {
54            max_compressed_bytes: 64 * MIB,
55            max_entries: 10_000,
56            max_part_bytes: 64 * MIB,
57            max_uncompressed_bytes: 256 * MIB,
58            max_xml_depth: 256,
59            max_element_attributes: crate::xmllinq::parse::MAX_ELEMENT_ATTRIBUTES,
60            max_attribute_name_bytes: crate::xmllinq::parse::MAX_ATTRIBUTE_NAME_BYTES,
61            max_attribute_value_bytes: crate::xmllinq::parse::MAX_ATTRIBUTE_VALUE_BYTES,
62            max_start_tag_bytes: crate::xmllinq::parse::MAX_TAG_ATTRIBUTE_BYTES,
63            // The largest of 2,434 real documents (the bench corpora and
64            // tests/) holds 365,343 elements: 2,000,000 refuses none of them
65            // and bounds `read` near 3 GB: E5, just under it, peaked at
66            // 2.2 GB with page markers and 2.9 GB without (#2014).
67            max_xml_elements: 2_000_000,
68            max_story_units: 2_000_000,
69        }
70    }
71}
72
73impl InputLimits {
74    /// The redline comparer's budget: the same entry and depth caps as
75    /// [`Self::default`], with room for the embedded media legal corpora
76    /// carry (512 MiB per file and per part, 2 GiB inflated in all). Hosts
77    /// that know their documents set `WmlComparerSettings::input_limits`
78    /// tighter.
79    #[must_use]
80    pub const fn compare() -> Self {
81        const MIB: u64 = 1024 * 1024;
82        Self {
83            max_compressed_bytes: 512 * MIB,
84            max_entries: 10_000,
85            max_part_bytes: 512 * MIB,
86            max_uncompressed_bytes: 2048 * MIB,
87            max_xml_depth: 256,
88            max_element_attributes: crate::xmllinq::parse::MAX_ELEMENT_ATTRIBUTES,
89            max_attribute_name_bytes: crate::xmllinq::parse::MAX_ATTRIBUTE_NAME_BYTES,
90            max_attribute_value_bytes: crate::xmllinq::parse::MAX_ATTRIBUTE_VALUE_BYTES,
91            max_start_tag_bytes: crate::xmllinq::parse::MAX_TAG_ATTRIBUTE_BYTES,
92            max_xml_elements: 4_000_000,
93            // The largest of 6,645 real documents holds 925,884 (a redline;
94            // the largest original 557,534).
95            max_story_units: 2_000_000,
96        }
97    }
98}
99
100/// Field-by-field overrides of an [`InputLimits`] budget: the shape the
101/// Python and WASM bindings take as a JSON object. Every key is optional and
102/// keeps the base value when absent; an unknown key is refused, so a typo
103/// cannot silently leave a default in force.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct InputLimitOverrides {
107    /// Replaces [`InputLimits::max_compressed_bytes`].
108    pub max_compressed_bytes: Option<u64>,
109    /// Replaces [`InputLimits::max_entries`].
110    pub max_entries: Option<usize>,
111    /// Replaces [`InputLimits::max_part_bytes`].
112    pub max_part_bytes: Option<u64>,
113    /// Replaces [`InputLimits::max_uncompressed_bytes`].
114    pub max_uncompressed_bytes: Option<u64>,
115    /// Replaces [`InputLimits::max_xml_depth`].
116    pub max_xml_depth: Option<usize>,
117    /// Replaces [`InputLimits::max_element_attributes`].
118    pub max_element_attributes: Option<usize>,
119    /// Replaces [`InputLimits::max_attribute_name_bytes`].
120    pub max_attribute_name_bytes: Option<usize>,
121    /// Replaces [`InputLimits::max_attribute_value_bytes`].
122    pub max_attribute_value_bytes: Option<usize>,
123    /// Replaces [`InputLimits::max_start_tag_bytes`].
124    pub max_start_tag_bytes: Option<usize>,
125    /// Replaces [`InputLimits::max_xml_elements`].
126    pub max_xml_elements: Option<u64>,
127    /// Replaces [`InputLimits::max_story_units`].
128    pub max_story_units: Option<u64>,
129}
130
131impl InputLimitOverrides {
132    /// Parse a JSON object such as `{"max_part_bytes": 67108864}`.
133    ///
134    /// # Errors
135    ///
136    /// `invalid input limits: ...` for malformed JSON, an unknown key, or a
137    /// value that is not a non-negative integer in range.
138    pub fn from_json(json: &str) -> Result<Self, String> {
139        serde_json::from_str(json).map_err(|e| format!("invalid input limits: {e}"))
140    }
141
142    /// `base` with every given key replaced.
143    #[must_use]
144    pub fn apply(self, base: InputLimits) -> InputLimits {
145        InputLimits {
146            max_compressed_bytes: self
147                .max_compressed_bytes
148                .unwrap_or(base.max_compressed_bytes),
149            max_entries: self.max_entries.unwrap_or(base.max_entries),
150            max_part_bytes: self.max_part_bytes.unwrap_or(base.max_part_bytes),
151            max_uncompressed_bytes: self
152                .max_uncompressed_bytes
153                .unwrap_or(base.max_uncompressed_bytes),
154            max_xml_depth: self.max_xml_depth.unwrap_or(base.max_xml_depth),
155            max_element_attributes: self
156                .max_element_attributes
157                .unwrap_or(base.max_element_attributes),
158            max_attribute_name_bytes: self
159                .max_attribute_name_bytes
160                .unwrap_or(base.max_attribute_name_bytes),
161            max_attribute_value_bytes: self
162                .max_attribute_value_bytes
163                .unwrap_or(base.max_attribute_value_bytes),
164            max_start_tag_bytes: self.max_start_tag_bytes.unwrap_or(base.max_start_tag_bytes),
165            max_xml_elements: self.max_xml_elements.unwrap_or(base.max_xml_elements),
166            max_story_units: self.max_story_units.unwrap_or(base.max_story_units),
167        }
168    }
169}
170
171/// Why a package was refused.
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum AdmissionErrorKind {
174    /// A budget in [`InputLimits`] was exceeded (`INPUT_LIMIT`).
175    InputLimit,
176    /// Two entries name the same part (`DUPLICATE_PART`).
177    DuplicatePart,
178    /// Not a WordprocessingML package, an unsafe part name, encryption or an
179    /// unsupported compression method (`UNSUPPORTED_PACKAGE`).
180    UnsupportedPackage,
181    /// Not a readable ZIP, or an entry fails its CRC (`INVALID_PACKAGE`).
182    InvalidPackage,
183    /// A ZIP local file header disagrees with the central directory
184    /// (`ZIP_HEADER_MISMATCH`): a dual-header ("zip cloaking",
185    /// GHSA-m665-v7pm-7grj) package whose two headers describe different
186    /// entries. Every reader here trusts the central directory; a tool
187    /// scanning local headers would see another package, so admission
188    /// refuses the file instead of picking a side.
189    ZipHeaderMismatch,
190    /// An XML part is malformed or nests too deep (`INVALID_XML`).
191    InvalidXml,
192    /// A Word 97-2003 `.doc`, or an encrypted document of any Word version:
193    /// an OLE compound file, which only Word reads (`LEGACY_DOC`).
194    LegacyDocument,
195}
196
197impl AdmissionErrorKind {
198    /// The stable error code agents and bindings see.
199    #[must_use]
200    pub const fn code(self) -> &'static str {
201        match self {
202            Self::InputLimit => "INPUT_LIMIT",
203            Self::DuplicatePart => "DUPLICATE_PART",
204            Self::UnsupportedPackage => "UNSUPPORTED_PACKAGE",
205            Self::InvalidPackage => "INVALID_PACKAGE",
206            Self::ZipHeaderMismatch => "ZIP_HEADER_MISMATCH",
207            Self::InvalidXml => "INVALID_XML",
208            Self::LegacyDocument => "LEGACY_DOC",
209        }
210    }
211
212    /// Every kind, in code order.
213    pub const ALL: [Self; 7] = [
214        Self::InputLimit,
215        Self::DuplicatePart,
216        Self::UnsupportedPackage,
217        Self::InvalidPackage,
218        Self::ZipHeaderMismatch,
219        Self::InvalidXml,
220        Self::LegacyDocument,
221    ];
222}
223
224/// A refused package: the kind and what exactly was refused.
225#[derive(Clone, Debug, PartialEq, Eq)]
226pub struct AdmissionError {
227    /// The error class.
228    pub kind: AdmissionErrorKind,
229    /// Human-readable detail, naming the entry when there is one.
230    pub message: String,
231}
232
233impl AdmissionError {
234    #[doc(hidden)]
235    pub fn new(kind: AdmissionErrorKind, message: impl Into<String>) -> Self {
236        Self {
237            kind,
238            message: message.into(),
239        }
240    }
241
242    /// The stable error code (`INPUT_LIMIT`, …).
243    #[must_use]
244    pub const fn code(&self) -> &'static str {
245        self.kind.code()
246    }
247}
248
249impl fmt::Display for AdmissionError {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        write!(f, "{}: {}", self.code(), self.message)
252    }
253}
254
255impl std::error::Error for AdmissionError {}
256
257/// A story holds markup the comparer cannot flatten into atoms: a
258/// `w:subDoc`, `w:altChunk`, `w:contentPart` or custom XML markup.
259/// Carried inside `OpcError::Io`; callers can downcast its `get_ref()`.
260#[derive(Debug)]
261pub struct UnsupportedContentError {
262    /// The story and the element, such as
263    /// `original document: Document contains subDoc`.
264    pub message: String,
265}
266
267impl fmt::Display for UnsupportedContentError {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write!(f, "{}: {}", Self::CODE, self.message)
270    }
271}
272
273impl std::error::Error for UnsupportedContentError {}
274
275impl UnsupportedContentError {
276    /// The stable error code agents and bindings see.
277    pub const CODE: &'static str = "UNSUPPORTED_CONTENT";
278}
279
280/// A refusal's message with its code first (`CODE: context: detail`): the
281/// comparer's opaque `I/O error: ` wrapper is dropped, any other context
282/// before the code (`document B: `) stays after it. `None` when no
283/// `: `-separated segment of `message` is an admission code or the
284/// comparer's `UNSUPPORTED_CONTENT`. The CLI and
285/// the bindings print refusals through it, so a code reads the same
286/// whatever wrapped it.
287#[must_use]
288pub fn code_first(message: &str) -> Option<String> {
289    let segments: Vec<&str> = message.split(": ").collect();
290    let at = segments.iter().position(|segment| {
291        *segment == UnsupportedContentError::CODE
292            || AdmissionErrorKind::ALL
293                .iter()
294                .any(|kind| kind.code() == *segment)
295    })?;
296    let (before, from) = segments.split_at(at);
297    let mut parts = from.iter().take(1).copied().collect::<Vec<_>>();
298    parts.extend(
299        before
300            .iter()
301            .copied()
302            .filter(|segment| *segment != "I/O error" && !segment.is_empty()),
303    );
304    parts.extend(from.iter().skip(1).copied());
305    Some(parts.join(": "))
306}
307
308#[cfg(test)]
309#[cfg_attr(all(coverage_nightly, test), coverage(off))]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn code_first_handles_admission_and_unsupported_content_codes() {
315        assert_eq!(
316            code_first("document B: I/O error: UNSUPPORTED_CONTENT: body: subDoc").as_deref(),
317            Some("UNSUPPORTED_CONTENT: document B: body: subDoc")
318        );
319        assert_eq!(
320            code_first("I/O error: INPUT_LIMIT: zip too big").as_deref(),
321            Some("INPUT_LIMIT: zip too big")
322        );
323        assert_eq!(code_first("plain error"), None);
324    }
325
326    #[test]
327    fn limit_overrides_replace_selected_fields_only() {
328        let base = InputLimits::default();
329        let patched = InputLimitOverrides::from_json(r#"{"max_part_bytes": 1234}"#)
330            .expect("valid overrides")
331            .apply(base);
332        assert_eq!(patched.max_part_bytes, 1234);
333        assert_eq!(patched.max_entries, base.max_entries);
334    }
335}