Skip to main content

laminapdf_syntax/
limits.rs

1//! Resource limits applied while reading untrusted input ([ADR 0003] §3).
2//!
3//! Every number read from a file is attacker-controlled, so everything that can grow with the
4//! input (nesting, decoded bytes, reference chains, …) is bounded by a [`Limits`] value.
5//! **Hard** limits fail the call that hits them with [`Error::LimitExceeded`]; **soft** limits
6//! drop the item over the limit and carry on with a warning (the reader in `laminapdf-cos`
7//! raises it).
8//!
9//! [ADR 0003]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0003-reader-tolerance-and-limits.md
10//! [`Error::LimitExceeded`]: crate::Error::LimitExceeded
11
12use core::fmt;
13
14/// Which hard limit was exceeded (the `limit` of [`Error::LimitExceeded`](crate::Error::LimitExceeded)).
15///
16/// Soft limits never produce an error, so they have no variant here.
17///
18/// Added in 0.2.0.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20#[non_exhaustive]
21pub enum Limit {
22    /// [`Limits::max_nesting_depth`].
23    NestingDepth,
24    /// [`Limits::max_stream_decoded`].
25    StreamDecoded,
26    /// [`Limits::max_decoded_total`].
27    DecodedTotal,
28    /// [`Limits::max_filter_chain`].
29    FilterChain,
30    /// [`Limits::max_resolve_depth`].
31    ResolveDepth,
32    /// [`Limits::max_page_tree_depth`]. The only reader of the page tree today is
33    /// `Document::pages`, one of ADR 0003's tolerant paths: it skips a subtree past this
34    /// limit with the `page-tree-node-skipped` warning (an `Error::Strict` in strict mode)
35    /// instead of returning this error (ADR 0003 §3). No reader returns it yet:
36    /// `laminapdf-model`'s lookup of a page through its `/Parent` chain stops at the limit and
37    /// finds no page.
38    PageTreeDepth,
39    /// [`Limits::max_tree_depth`].
40    TreeDepth,
41    /// [`Limits::max_string_length`].
42    StringLength,
43    /// [`Limits::max_content_operators`].
44    ContentOperators,
45    /// [`Limits::max_xobject_depth`].
46    XObjectDepth,
47    /// [`Limits::max_image_pixels`].
48    ImagePixels,
49    /// [`Limits::max_read_window`].
50    ReadWindow,
51}
52
53impl Limit {
54    /// Every hard limit, in declaration order.
55    ///
56    /// Added in 0.2.0.
57    pub const ALL: [Self; 12] = [
58        Self::NestingDepth,
59        Self::StreamDecoded,
60        Self::DecodedTotal,
61        Self::FilterChain,
62        Self::ResolveDepth,
63        Self::PageTreeDepth,
64        Self::TreeDepth,
65        Self::StringLength,
66        Self::ContentOperators,
67        Self::XObjectDepth,
68        Self::ImagePixels,
69        Self::ReadWindow,
70    ];
71
72    /// The name of the [`Limits`] field, e.g. `"max_nesting_depth"`. Stable: part of the
73    /// public API in Rust, WASM and TypeScript (listed in `fixtures/codes.json`).
74    ///
75    /// Added in 0.2.0.
76    #[must_use]
77    pub const fn name(self) -> &'static str {
78        match self {
79            Self::NestingDepth => "max_nesting_depth",
80            Self::StreamDecoded => "max_stream_decoded",
81            Self::DecodedTotal => "max_decoded_total",
82            Self::FilterChain => "max_filter_chain",
83            Self::ResolveDepth => "max_resolve_depth",
84            Self::PageTreeDepth => "max_page_tree_depth",
85            Self::TreeDepth => "max_tree_depth",
86            Self::StringLength => "max_string_length",
87            Self::ContentOperators => "max_content_operators",
88            Self::XObjectDepth => "max_xobject_depth",
89            Self::ImagePixels => "max_image_pixels",
90            Self::ReadWindow => "max_read_window",
91        }
92    }
93
94    /// The configured value of this limit in `limits`.
95    ///
96    /// Added in 0.2.0.
97    #[must_use]
98    pub const fn value_in(self, limits: &Limits) -> u64 {
99        // `usize` is at most 64 bits on every supported target, so the casts are lossless.
100        match self {
101            Self::NestingDepth => limits.max_nesting_depth as u64,
102            Self::StreamDecoded => limits.max_stream_decoded as u64,
103            Self::DecodedTotal => limits.max_decoded_total as u64,
104            Self::FilterChain => limits.max_filter_chain as u64,
105            Self::ResolveDepth => limits.max_resolve_depth as u64,
106            Self::PageTreeDepth => limits.max_page_tree_depth as u64,
107            Self::TreeDepth => limits.max_tree_depth as u64,
108            Self::StringLength => limits.max_string_length as u64,
109            Self::ContentOperators => limits.max_content_operators,
110            Self::XObjectDepth => limits.max_xobject_depth as u64,
111            Self::ImagePixels => limits.max_image_pixels,
112            Self::ReadWindow => limits.max_read_window as u64,
113        }
114    }
115}
116
117impl fmt::Display for Limit {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.write_str(self.name())
120    }
121}
122
123/// Resource limits for reading untrusted PDF input ([ADR 0003] §3).
124///
125/// `Copy`, with private fields: read a limit with its getter and change it with the
126/// matching `with_*` builder, starting from [`Limits::default`] (or [`Limits::new`] in a
127/// `const` context):
128///
129/// ```
130/// use laminapdf_syntax::Limits;
131///
132/// const STRICTER: Limits = Limits::new().with_max_nesting_depth(64).with_max_stream_decoded(1 << 20);
133/// assert_eq!(STRICTER.max_nesting_depth(), 64);
134/// assert_eq!(Limits::default().max_nesting_depth(), 256);
135/// ```
136///
137/// | Field | Kind | Default |
138/// | --- | --- | --- |
139/// | [`max_nesting_depth`](Self::max_nesting_depth) | hard | 256 |
140/// | [`max_stream_decoded`](Self::max_stream_decoded) | hard | 64 MiB |
141/// | [`max_decoded_total`](Self::max_decoded_total) | hard | 1 GiB |
142/// | [`max_filter_chain`](Self::max_filter_chain) | hard | 8 |
143/// | [`max_resolve_depth`](Self::max_resolve_depth) | hard | 32 |
144/// | [`max_page_tree_depth`](Self::max_page_tree_depth) | hard | 256 |
145/// | [`max_tree_depth`](Self::max_tree_depth) | hard | 64 |
146/// | [`max_string_length`](Self::max_string_length) | hard | 16 MiB |
147/// | [`max_xref_sections`](Self::max_xref_sections) | soft | 4,096 |
148/// | [`max_object_number`](Self::max_object_number) | soft | 8,388,607 |
149/// | [`max_warnings`](Self::max_warnings) | soft | 1,000 |
150/// | [`max_content_operators`](Self::max_content_operators) | hard | 10,000,000 |
151/// | [`max_xobject_depth`](Self::max_xobject_depth) | hard | 32 |
152/// | [`max_image_pixels`](Self::max_image_pixels) | hard (reserved) | 2^28 |
153/// | [`max_read_window`](Self::max_read_window) | hard | 256 MiB |
154/// | [`max_script_length`](Self::max_script_length) | soft | 64 KiB |
155///
156/// Reserved limits are part of the API now so they can be configured once, but nothing
157/// enforces them until the feature they bound lands (image decoding).
158///
159/// [ADR 0003]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0003-reader-tolerance-and-limits.md
160///
161/// Added in 0.2.0.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163#[expect(
164    clippy::struct_field_names,
165    reason = "the field names are the ADR's public limit names (`max_*`)"
166)]
167pub struct Limits {
168    max_nesting_depth: usize,
169    max_stream_decoded: usize,
170    max_decoded_total: usize,
171    max_filter_chain: usize,
172    max_resolve_depth: usize,
173    max_page_tree_depth: usize,
174    max_tree_depth: usize,
175    max_string_length: usize,
176    max_xref_sections: usize,
177    max_object_number: u32,
178    max_warnings: usize,
179    max_content_operators: u64,
180    max_xobject_depth: usize,
181    max_image_pixels: u64,
182    max_read_window: usize,
183    max_script_length: usize,
184}
185
186impl Default for Limits {
187    fn default() -> Self {
188        Self::new()
189    }
190}
191
192macro_rules! limit_accessors {
193    ($( $(#[$doc:meta])* $field:ident, $with:ident: $ty:ty; )*) => {
194        $(
195            $(#[$doc])*
196            #[doc = ""]
197            #[doc = "Added in 0.2.0."]
198            #[must_use]
199            pub const fn $field(&self) -> $ty {
200                self.$field
201            }
202
203            #[doc = concat!("Sets [`", stringify!($field), "`](Self::", stringify!($field), ").")]
204            #[doc = ""]
205            #[doc = "Added in 0.2.0."]
206            #[must_use]
207            pub const fn $with(mut self, value: $ty) -> Self {
208                self.$field = value;
209                self
210            }
211        )*
212    };
213}
214
215impl Limits {
216    /// The defaults from ADR 0003 (the same as [`Limits::default`], usable in `const`).
217    ///
218    /// Added in 0.2.0.
219    #[must_use]
220    pub const fn new() -> Self {
221        Self {
222            max_nesting_depth: 256,
223            max_stream_decoded: 64 * 1024 * 1024,
224            max_decoded_total: 1024 * 1024 * 1024,
225            max_filter_chain: 8,
226            max_resolve_depth: 32,
227            max_page_tree_depth: 256,
228            max_tree_depth: 64,
229            max_string_length: 16 * 1024 * 1024,
230            max_xref_sections: 4096,
231            // ISO 32000-1 Annex C: the largest object number a conforming reader must support.
232            max_object_number: 8_388_607,
233            max_warnings: 1000,
234            max_content_operators: 10_000_000,
235            max_xobject_depth: 32,
236            max_image_pixels: 1 << 28,
237            max_read_window: 256 * 1024 * 1024,
238            // 4.6 times the longest of the external corpus's 88 scripts (14,078 bytes).
239            max_script_length: 64 * 1024,
240        }
241    }
242
243    /// No limits at all, for trusted input only (Lamina PDF's own output in tests).
244    ///
245    /// Nesting is parsed recursively, so hostile input with unlimited nesting depth can
246    /// exhaust the stack: never use this for files from outside.
247    ///
248    /// Added in 0.2.0.
249    #[must_use]
250    pub const fn unlimited() -> Self {
251        Self {
252            max_nesting_depth: usize::MAX,
253            max_stream_decoded: usize::MAX,
254            max_decoded_total: usize::MAX,
255            max_filter_chain: usize::MAX,
256            max_resolve_depth: usize::MAX,
257            max_page_tree_depth: usize::MAX,
258            max_tree_depth: usize::MAX,
259            max_string_length: usize::MAX,
260            max_xref_sections: usize::MAX,
261            max_object_number: u32::MAX,
262            max_warnings: usize::MAX,
263            max_content_operators: u64::MAX,
264            max_xobject_depth: usize::MAX,
265            max_image_pixels: u64::MAX,
266            max_read_window: usize::MAX,
267            max_script_length: usize::MAX,
268        }
269    }
270
271    limit_accessors! {
272        /// Hard: array/dictionary nesting depth accepted by the parser, and the graphics states
273        /// one content stream may save with `q` in `laminapdf-content` (default 256; ADR 0023 §4).
274        max_nesting_depth, with_max_nesting_depth: usize;
275        /// Hard: bytes one stream may decode to, per filter stage (default 64 MiB).
276        max_stream_decoded, with_max_stream_decoded: usize;
277        /// Hard: bytes decoded by one top-level call (`open`, one page's content, one
278        /// `resolve` or `decode_stream`), across all streams and filter stages (default 1 GiB).
279        max_decoded_total, with_max_decoded_total: usize;
280        /// Hard: filters in one stream's `/Filter` chain (default 8).
281        max_filter_chain, with_max_filter_chain: usize;
282        /// Hard: indirect objects in flight at once while resolving a reference chain (default 32).
283        max_resolve_depth, with_max_resolve_depth: usize;
284        /// Hard: `/Kids` levels below the page-tree root (default 256). Hit inside the
285        /// tolerant page walk, the subtree is skipped with a `page-tree-node-skipped` warning,
286        /// as ADR 0003 §3 prescribes for hard limits on tolerant paths.
287        max_page_tree_depth, with_max_page_tree_depth: usize;
288        /// Hard: depth of name trees, number trees and outlines (default 64; enforced by the
289        /// typed views).
290        max_tree_depth, with_max_tree_depth: usize;
291        /// Hard: bytes in one string or name token (default 16 MiB).
292        max_string_length, with_max_string_length: usize;
293        /// Soft: `/Prev` hops in the xref chain; past it the stored xref is abandoned and
294        /// rebuilt by scanning (default 4,096).
295        max_xref_sections, with_max_xref_sections: usize;
296        /// Soft: highest object number kept; higher entries are dropped with a warning
297        /// (default 8,388,607, ISO 32000-1 Annex C).
298        max_object_number, with_max_object_number: u32;
299        /// Soft: warnings kept per document; later ones are dropped after one
300        /// `warnings-truncated` warning (default 1,000).
301        max_warnings, with_max_warnings: usize;
302        /// Hard: operators read by one content-stream interpretation (`laminapdf-content`), the
303        /// page's and every Form XObject's each time it is drawn (default 10,000,000; ADR 0023).
304        max_content_operators, with_max_content_operators: u64;
305        /// Hard: Form `XObject`s drawn at once by `laminapdf-content`; patterns and Type 3 glyphs
306        /// too once they are interpreted (default 32; ADR 0023).
307        max_xobject_depth, with_max_xobject_depth: usize;
308        /// Hard, reserved: pixels in one decoded image (default 2^28).
309        max_image_pixels, with_max_image_pixels: u64;
310        /// Hard: bytes one parse may read from a source without an in-memory slice
311        /// (`laminapdf-cos` reads such sources in windows; default 256 MiB). It bounds how far a
312        /// window grows for one object (its head, a stream's data, the search for a missing
313        /// `endstream`) and the backward walk over an object header found by repair. Past
314        /// it, the object fails with `LimitExceeded` where an in-memory parse would have read
315        /// on; a tolerant path (repair, `/Length` recovery, the xref entry check) treats the
316        /// item as unreadable instead. In-memory input is never limited by it.
317        max_read_window, with_max_read_window: usize;
318    }
319
320    /// Soft: bytes of one script that form behaviour reads as tokens (a field's `/AA` `K`,
321    /// `F`, `V` or `C` JavaScript, ADR 0021 §2; default 64 KiB). A longer script is not
322    /// read: it counts as not handled, and the field is filled without its behaviour.
323    ///
324    /// Added in 0.6.0.
325    #[must_use]
326    pub const fn max_script_length(&self) -> usize {
327        self.max_script_length
328    }
329
330    /// Sets [`max_script_length`](Self::max_script_length).
331    ///
332    /// Added in 0.6.0.
333    #[must_use]
334    pub const fn with_max_script_length(mut self, value: usize) -> Self {
335        self.max_script_length = value;
336        self
337    }
338}
339
340/// The decoding budget of one top-level call: [`Limits::max_decoded_total`] bytes, spent by
341/// every filter stage of every stream the call decodes.
342///
343/// Create one per call ([`DecodeBudget::new`]) and pass it to every
344/// [`filters::decode`](crate::filters::decode) the call makes.
345///
346/// Added in 0.2.0.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct DecodeBudget {
349    remaining: usize,
350}
351
352impl DecodeBudget {
353    /// A fresh budget of `limits.max_decoded_total()` bytes.
354    ///
355    /// Added in 0.2.0.
356    #[must_use]
357    pub const fn new(limits: &Limits) -> Self {
358        Self {
359            remaining: limits.max_decoded_total,
360        }
361    }
362
363    /// Bytes that may still be decoded.
364    ///
365    /// Added in 0.2.0.
366    #[must_use]
367    pub const fn remaining(&self) -> usize {
368        self.remaining
369    }
370
371    /// Records `bytes` of decoded output.
372    pub(crate) const fn spend(&mut self, bytes: usize) {
373        self.remaining = self.remaining.saturating_sub(bytes);
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn defaults_match_the_adr_table() {
383        let l = Limits::default();
384        assert_eq!(
385            [
386                l.max_nesting_depth(),
387                l.max_stream_decoded(),
388                l.max_decoded_total(),
389                l.max_filter_chain(),
390                l.max_resolve_depth(),
391                l.max_page_tree_depth(),
392                l.max_tree_depth(),
393                l.max_string_length(),
394                l.max_xref_sections(),
395                l.max_warnings(),
396                l.max_xobject_depth(),
397                l.max_read_window(),
398                l.max_script_length(),
399            ],
400            [
401                256,
402                64 << 20,
403                1 << 30,
404                8,
405                32,
406                256,
407                64,
408                16 << 20,
409                4096,
410                1000,
411                32,
412                256 << 20,
413                64 << 10
414            ]
415        );
416    }
417
418    #[test]
419    fn defaults_for_wide_limits_match_the_adr_table() {
420        let l = Limits::default();
421        assert_eq!(
422            (l.max_object_number(), l.max_content_operators(), l.max_image_pixels()),
423            (8_388_607, 10_000_000, 1 << 28)
424        );
425    }
426
427    #[test]
428    fn with_builder_changes_only_its_field() {
429        let l = Limits::default().with_max_filter_chain(2);
430        assert_eq!(
431            l,
432            Limits {
433                max_filter_chain: 2,
434                ..Limits::default()
435            }
436        );
437    }
438
439    #[test]
440    fn limit_value_in_reads_the_matching_field() {
441        let l = Limits::default().with_max_string_length(7);
442        assert_eq!(Limit::StringLength.value_in(&l), 7);
443    }
444
445    #[test]
446    fn limit_names_are_distinct() {
447        let mut names: Vec<_> = Limit::ALL.iter().map(|l| l.name()).collect();
448        names.sort_unstable();
449        names.dedup();
450        assert_eq!(names.len(), Limit::ALL.len());
451    }
452}