Skip to main content

sheetkit_core/workbook/
budget.rs

1use crate::error::{Error, Result};
2use crate::resource::{
3    ResourceCategory, ResourceDimension, ResourceLimitError, ResourceOperation, ResourceStage,
4};
5
6const MIB: u64 = 1024 * 1024;
7
8/// Finite limits applied to one workbook-open operation.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct OpenLimits {
11    /// Maximum bytes in the outer ZIP or container input.
12    pub outer_input_bytes: u64,
13    /// Maximum central-directory entry count.
14    pub archive_entries: u64,
15    /// Maximum size declared by one archive entry.
16    pub entry_declared_bytes: u64,
17    /// Maximum bytes actually read from one archive entry.
18    pub entry_actual_bytes: u64,
19    /// Maximum sum of archive entry declared sizes.
20    pub aggregate_declared_bytes: u64,
21    /// Maximum cumulative bytes actually read from archive entries.
22    pub aggregate_actual_bytes: u64,
23    /// Maximum uncompressed-to-compressed ratio for one entry.
24    pub compression_ratio: u64,
25    /// Decompressed entry size at or below which the ratio is not enforced.
26    /// Above it, the ratio applies to the whole entry. Non-empty entries with
27    /// zero compressed bytes are always rejected. `0` enforces every entry.
28    pub compression_ratio_floor_bytes: u64,
29    /// Maximum bytes actually read from one XML part.
30    pub xml_bytes: u64,
31    /// Maximum raw package bytes retained by the resulting workbook.
32    pub retained_package_bytes: u64,
33}
34
35impl Default for OpenLimits {
36    fn default() -> Self {
37        Self {
38            outer_input_bytes: 128 * MIB,
39            archive_entries: 4_096,
40            entry_declared_bytes: 256 * MIB,
41            entry_actual_bytes: 256 * MIB,
42            aggregate_declared_bytes: 512 * MIB,
43            aggregate_actual_bytes: 512 * MIB,
44            compression_ratio: 100,
45            compression_ratio_floor_bytes: 8 * MIB,
46            xml_bytes: 256 * MIB,
47            retained_package_bytes: 512 * MIB,
48        }
49    }
50}
51
52impl OpenLimits {
53    /// Largest supported finite values. These ceilings cannot be disabled.
54    pub const fn hard_ceiling() -> Self {
55        Self {
56            outer_input_bytes: 2 * 1024 * MIB,
57            archive_entries: 65_536,
58            entry_declared_bytes: 1024 * MIB,
59            entry_actual_bytes: 1024 * MIB,
60            aggregate_declared_bytes: 4 * 1024 * MIB,
61            aggregate_actual_bytes: 4 * 1024 * MIB,
62            compression_ratio: 1_000,
63            compression_ratio_floor_bytes: 1024 * MIB,
64            xml_bytes: 1024 * MIB,
65            retained_package_bytes: 2 * 1024 * MIB,
66        }
67    }
68
69    pub(crate) fn validate(self) -> Result<Self> {
70        let ceiling = Self::hard_ceiling();
71        // The floor only relaxes enforcement, so zero (strictest) is allowed.
72        if self.compression_ratio_floor_bytes > ceiling.compression_ratio_floor_bytes {
73            return Err(limit_error(
74                ResourceDimension::CompressionRatioFloorBytes,
75                ceiling.compression_ratio_floor_bytes,
76                self.compression_ratio_floor_bytes,
77                ResourceStage::Validate,
78            ));
79        }
80        for (dimension, value, maximum) in [
81            (
82                ResourceDimension::InputBytes,
83                self.outer_input_bytes,
84                ceiling.outer_input_bytes,
85            ),
86            (
87                ResourceDimension::EntryCount,
88                self.archive_entries,
89                ceiling.archive_entries,
90            ),
91            (
92                ResourceDimension::EntryDeclaredBytes,
93                self.entry_declared_bytes,
94                ceiling.entry_declared_bytes,
95            ),
96            (
97                ResourceDimension::EntryActualBytes,
98                self.entry_actual_bytes,
99                ceiling.entry_actual_bytes,
100            ),
101            (
102                ResourceDimension::AggregateDeclaredBytes,
103                self.aggregate_declared_bytes,
104                ceiling.aggregate_declared_bytes,
105            ),
106            (
107                ResourceDimension::AggregateActualBytes,
108                self.aggregate_actual_bytes,
109                ceiling.aggregate_actual_bytes,
110            ),
111            (
112                ResourceDimension::CompressionRatio,
113                self.compression_ratio,
114                ceiling.compression_ratio,
115            ),
116            (
117                ResourceDimension::XmlBytes,
118                self.xml_bytes,
119                ceiling.xml_bytes,
120            ),
121            (
122                ResourceDimension::RetainedBytes,
123                self.retained_package_bytes,
124                ceiling.retained_package_bytes,
125            ),
126        ] {
127            if value == 0 || value > maximum {
128                return Err(limit_error(
129                    dimension,
130                    maximum,
131                    value.max(maximum.saturating_add(1)),
132                    ResourceStage::Validate,
133                ));
134            }
135        }
136        Ok(self)
137    }
138}
139
140pub(crate) struct OpenBudget {
141    limits: OpenLimits,
142    aggregate_declared: u64,
143    aggregate_actual: u64,
144    retained: u64,
145    violation: Option<ResourceLimitError>,
146    integrity_violation: Option<String>,
147}
148
149impl OpenBudget {
150    pub(crate) fn new(limits: OpenLimits) -> Result<Self> {
151        Ok(Self {
152            limits: limits.validate()?,
153            aggregate_declared: 0,
154            aggregate_actual: 0,
155            retained: 0,
156            violation: None,
157            integrity_violation: None,
158        })
159    }
160
161    #[cfg(feature = "encryption")]
162    pub(crate) const fn limits(&self) -> OpenLimits {
163        self.limits
164    }
165
166    pub(crate) fn check_outer_input(&self, observed: u64) -> Result<()> {
167        check(
168            ResourceDimension::InputBytes,
169            self.limits.outer_input_bytes,
170            observed,
171            ResourceStage::Inspect,
172        )
173    }
174
175    pub(crate) fn charge_retained(&mut self, amount: u64) -> Result<()> {
176        let observed = checked_total(self.retained, amount);
177        check(
178            ResourceDimension::RetainedBytes,
179            self.limits.retained_package_bytes,
180            observed,
181            ResourceStage::Read,
182        )?;
183        self.retained = observed;
184        Ok(())
185    }
186
187    pub(crate) fn preflight_entry(&mut self, declared: u64, compressed: u64) -> Result<()> {
188        check(
189            ResourceDimension::EntryDeclaredBytes,
190            self.limits.entry_declared_bytes,
191            declared,
192            ResourceStage::Inspect,
193        )?;
194        let aggregate = checked_total(self.aggregate_declared, declared);
195        check(
196            ResourceDimension::AggregateDeclaredBytes,
197            self.limits.aggregate_declared_bytes,
198            aggregate,
199            ResourceStage::Inspect,
200        )?;
201        check_ratio(declared, compressed, self.limits, ResourceStage::Inspect)?;
202        self.aggregate_declared = aggregate;
203        Ok(())
204    }
205
206    pub(crate) fn charge_actual(
207        &mut self,
208        entry_total: u64,
209        amount: u64,
210        compressed: u64,
211        xml: bool,
212    ) -> Result<u64> {
213        let entry_observed = checked_total(entry_total, amount);
214        check(
215            ResourceDimension::EntryActualBytes,
216            self.limits.entry_actual_bytes,
217            entry_observed,
218            ResourceStage::Read,
219        )?;
220        if xml {
221            check(
222                ResourceDimension::XmlBytes,
223                self.limits.xml_bytes,
224                entry_observed,
225                ResourceStage::Read,
226            )?;
227        }
228        check_ratio(entry_observed, compressed, self.limits, ResourceStage::Read)?;
229        let aggregate = checked_total(self.aggregate_actual, amount);
230        check(
231            ResourceDimension::AggregateActualBytes,
232            self.limits.aggregate_actual_bytes,
233            aggregate,
234            ResourceStage::Read,
235        )?;
236        self.aggregate_actual = aggregate;
237        Ok(entry_observed)
238    }
239
240    pub(crate) fn record_violation(&mut self, error: Error) {
241        if self.violation.is_none() {
242            if let Error::ResourceLimitExceeded(metadata) = error {
243                self.violation = Some(metadata);
244            }
245        }
246    }
247
248    /// Record the first archive integrity failure observed while reading.
249    pub(crate) fn record_integrity_violation(&mut self, message: String) {
250        if self.integrity_violation.is_none() {
251            self.integrity_violation = Some(message);
252        }
253    }
254
255    /// Return the first recorded resource or integrity failure, if any.
256    pub(crate) fn pending_error(&self) -> Option<Error> {
257        if let Some(metadata) = self.violation {
258            return Some(Error::ResourceLimitExceeded(metadata));
259        }
260        self.integrity_violation
261            .as_ref()
262            .map(|message| Error::Zip(message.clone()))
263    }
264}
265
266fn checked_total(current: u64, amount: u64) -> u64 {
267    let (total, overflowed) = current.overflowing_add(amount);
268    if overflowed {
269        u64::MAX
270    } else {
271        total
272    }
273}
274
275fn check(
276    dimension: ResourceDimension,
277    limit: u64,
278    observed: u64,
279    stage: ResourceStage,
280) -> Result<()> {
281    if observed > limit {
282        return Err(limit_error(dimension, limit, observed, stage));
283    }
284    Ok(())
285}
286
287/// Enforce the per-entry ratio once `actual` exceeds the configured floor.
288/// A non-empty entry with zero compressed bytes is rejected regardless.
289fn check_ratio(
290    actual: u64,
291    compressed: u64,
292    limits: OpenLimits,
293    stage: ResourceStage,
294) -> Result<()> {
295    if compressed != 0 && actual <= limits.compression_ratio_floor_bytes {
296        return Ok(());
297    }
298    let observed = if actual == 0 {
299        0
300    } else if compressed == 0 {
301        u64::MAX
302    } else {
303        actual.div_ceil(compressed)
304    };
305    check(
306        ResourceDimension::CompressionRatio,
307        limits.compression_ratio,
308        observed,
309        stage,
310    )
311}
312
313pub(crate) fn limit_error(
314    dimension: ResourceDimension,
315    limit: u64,
316    observed: u64,
317    stage: ResourceStage,
318) -> Error {
319    match ResourceLimitError::exceeded(
320        ResourceOperation::WorkbookOpen,
321        if dimension == ResourceDimension::XmlBytes {
322            ResourceCategory::Xml
323        } else {
324            ResourceCategory::Archive
325        },
326        dimension,
327        limit,
328        observed,
329        Some(stage),
330    ) {
331        Some(metadata) => Error::ResourceLimitExceeded(metadata),
332        None => Error::Internal("invalid workbook resource limit state".to_string()),
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    #[test]
341    fn exact_limit_is_accepted_and_one_over_is_rejected() {
342        let mut budget = OpenBudget::new(OpenLimits {
343            entry_actual_bytes: 8,
344            ..OpenLimits::default()
345        })
346        .unwrap();
347        assert_eq!(budget.charge_actual(0, 8, 8, false).unwrap(), 8);
348        let error = budget.charge_actual(8, 1, 8, false).unwrap_err();
349        assert_eq!(
350            error.resource_metadata().unwrap().dimension(),
351            ResourceDimension::EntryActualBytes
352        );
353    }
354
355    #[test]
356    fn checked_aggregate_overflow_fails_closed() {
357        let mut budget = OpenBudget::new(OpenLimits::hard_ceiling()).unwrap();
358        budget.aggregate_actual = u64::MAX - 1;
359        let error = budget.charge_actual(0, 2, 2, false).unwrap_err();
360        assert_eq!(error.resource_metadata().unwrap().observed(), u64::MAX);
361    }
362
363    #[test]
364    fn non_empty_zero_compressed_entry_has_unbounded_ratio() {
365        let mut budget = OpenBudget::new(OpenLimits::default()).unwrap();
366        let error = budget.preflight_entry(1, 0).unwrap_err();
367        assert_eq!(
368            error.resource_metadata().unwrap().dimension(),
369            ResourceDimension::CompressionRatio
370        );
371    }
372
373    #[test]
374    fn retained_and_ratio_boundaries_are_inclusive() {
375        let mut budget = OpenBudget::new(OpenLimits {
376            retained_package_bytes: 8,
377            compression_ratio: 4,
378            compression_ratio_floor_bytes: 0,
379            ..OpenLimits::default()
380        })
381        .unwrap();
382        budget.charge_retained(8).unwrap();
383        assert_eq!(budget.charge_actual(0, 8, 2, false).unwrap(), 8);
384
385        let retained = budget.charge_retained(1).unwrap_err();
386        assert_eq!(
387            retained.resource_metadata().unwrap().dimension(),
388            ResourceDimension::RetainedBytes
389        );
390        let ratio = budget.charge_actual(0, 9, 2, false).unwrap_err();
391        assert_eq!(
392            ratio.resource_metadata().unwrap().dimension(),
393            ResourceDimension::CompressionRatio
394        );
395    }
396
397    #[test]
398    fn ratio_floor_is_inclusive_and_zero_compressed_ignores_it() {
399        let limits = OpenLimits {
400            compression_ratio: 4,
401            compression_ratio_floor_bytes: 64,
402            ..OpenLimits::default()
403        };
404        let mut budget = OpenBudget::new(limits).unwrap();
405        budget.preflight_entry(64, 1).unwrap();
406        assert_eq!(budget.charge_actual(0, 64, 1, false).unwrap(), 64);
407        let above = budget.charge_actual(64, 1, 1, false).unwrap_err();
408        assert_eq!(
409            above.resource_metadata().unwrap().observed(),
410            65,
411            "ratio covers the whole entry, not only bytes past the floor"
412        );
413        let mut budget = OpenBudget::new(limits).unwrap();
414        let declared = budget.preflight_entry(65, 1).unwrap_err();
415        assert_eq!(
416            declared.resource_metadata().unwrap().dimension(),
417            ResourceDimension::CompressionRatio
418        );
419        let zero = budget.preflight_entry(1, 0).unwrap_err();
420        assert_eq!(zero.resource_metadata().unwrap().observed(), u64::MAX);
421    }
422
423    #[test]
424    fn aggregate_actual_is_cumulative_across_entry_reads() {
425        let mut budget = OpenBudget::new(OpenLimits {
426            aggregate_actual_bytes: 8,
427            ..OpenLimits::default()
428        })
429        .unwrap();
430        budget.charge_actual(0, 4, 4, false).unwrap();
431        budget.charge_actual(0, 4, 4, false).unwrap();
432        let error = budget.charge_actual(0, 1, 1, false).unwrap_err();
433        assert_eq!(
434            error.resource_metadata().unwrap().dimension(),
435            ResourceDimension::AggregateActualBytes
436        );
437    }
438}