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///
155/// Reserved limits are part of the API now so they can be configured once, but nothing
156/// enforces them until the feature they bound lands (image decoding).
157///
158/// [ADR 0003]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0003-reader-tolerance-and-limits.md
159///
160/// Added in 0.2.0.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[expect(
163 clippy::struct_field_names,
164 reason = "the field names are the ADR's public limit names (`max_*`)"
165)]
166pub struct Limits {
167 max_nesting_depth: usize,
168 max_stream_decoded: usize,
169 max_decoded_total: usize,
170 max_filter_chain: usize,
171 max_resolve_depth: usize,
172 max_page_tree_depth: usize,
173 max_tree_depth: usize,
174 max_string_length: usize,
175 max_xref_sections: usize,
176 max_object_number: u32,
177 max_warnings: usize,
178 max_content_operators: u64,
179 max_xobject_depth: usize,
180 max_image_pixels: u64,
181 max_read_window: usize,
182}
183
184impl Default for Limits {
185 fn default() -> Self {
186 Self::new()
187 }
188}
189
190macro_rules! limit_accessors {
191 ($( $(#[$doc:meta])* $field:ident, $with:ident: $ty:ty; )*) => {
192 $(
193 $(#[$doc])*
194 #[doc = ""]
195 #[doc = "Added in 0.2.0."]
196 #[must_use]
197 pub const fn $field(&self) -> $ty {
198 self.$field
199 }
200
201 #[doc = concat!("Sets [`", stringify!($field), "`](Self::", stringify!($field), ").")]
202 #[doc = ""]
203 #[doc = "Added in 0.2.0."]
204 #[must_use]
205 pub const fn $with(mut self, value: $ty) -> Self {
206 self.$field = value;
207 self
208 }
209 )*
210 };
211}
212
213impl Limits {
214 /// The defaults from ADR 0003 (the same as [`Limits::default`], usable in `const`).
215 ///
216 /// Added in 0.2.0.
217 #[must_use]
218 pub const fn new() -> Self {
219 Self {
220 max_nesting_depth: 256,
221 max_stream_decoded: 64 * 1024 * 1024,
222 max_decoded_total: 1024 * 1024 * 1024,
223 max_filter_chain: 8,
224 max_resolve_depth: 32,
225 max_page_tree_depth: 256,
226 max_tree_depth: 64,
227 max_string_length: 16 * 1024 * 1024,
228 max_xref_sections: 4096,
229 // ISO 32000-1 Annex C: the largest object number a conforming reader must support.
230 max_object_number: 8_388_607,
231 max_warnings: 1000,
232 max_content_operators: 10_000_000,
233 max_xobject_depth: 32,
234 max_image_pixels: 1 << 28,
235 max_read_window: 256 * 1024 * 1024,
236 }
237 }
238
239 /// No limits at all, for trusted input only (Lamina PDF's own output in tests).
240 ///
241 /// Nesting is parsed recursively, so hostile input with unlimited nesting depth can
242 /// exhaust the stack: never use this for files from outside.
243 ///
244 /// Added in 0.2.0.
245 #[must_use]
246 pub const fn unlimited() -> Self {
247 Self {
248 max_nesting_depth: usize::MAX,
249 max_stream_decoded: usize::MAX,
250 max_decoded_total: usize::MAX,
251 max_filter_chain: usize::MAX,
252 max_resolve_depth: usize::MAX,
253 max_page_tree_depth: usize::MAX,
254 max_tree_depth: usize::MAX,
255 max_string_length: usize::MAX,
256 max_xref_sections: usize::MAX,
257 max_object_number: u32::MAX,
258 max_warnings: usize::MAX,
259 max_content_operators: u64::MAX,
260 max_xobject_depth: usize::MAX,
261 max_image_pixels: u64::MAX,
262 max_read_window: usize::MAX,
263 }
264 }
265
266 limit_accessors! {
267 /// Hard: array/dictionary nesting depth accepted by the parser, and the graphics states
268 /// one content stream may save with `q` in `laminapdf-content` (default 256; ADR 0023 §4).
269 max_nesting_depth, with_max_nesting_depth: usize;
270 /// Hard: bytes one stream may decode to, per filter stage (default 64 MiB).
271 max_stream_decoded, with_max_stream_decoded: usize;
272 /// Hard: bytes decoded by one top-level call (`open`, one page's content, one
273 /// `resolve` or `decode_stream`), across all streams and filter stages (default 1 GiB).
274 max_decoded_total, with_max_decoded_total: usize;
275 /// Hard: filters in one stream's `/Filter` chain (default 8).
276 max_filter_chain, with_max_filter_chain: usize;
277 /// Hard: indirect objects in flight at once while resolving a reference chain (default 32).
278 max_resolve_depth, with_max_resolve_depth: usize;
279 /// Hard: `/Kids` levels below the page-tree root (default 256). Hit inside the
280 /// tolerant page walk, the subtree is skipped with a `page-tree-node-skipped` warning,
281 /// as ADR 0003 §3 prescribes for hard limits on tolerant paths.
282 max_page_tree_depth, with_max_page_tree_depth: usize;
283 /// Hard: depth of name trees, number trees and outlines (default 64; enforced by the
284 /// typed views).
285 max_tree_depth, with_max_tree_depth: usize;
286 /// Hard: bytes in one string or name token (default 16 MiB).
287 max_string_length, with_max_string_length: usize;
288 /// Soft: `/Prev` hops in the xref chain; past it the stored xref is abandoned and
289 /// rebuilt by scanning (default 4,096).
290 max_xref_sections, with_max_xref_sections: usize;
291 /// Soft: highest object number kept; higher entries are dropped with a warning
292 /// (default 8,388,607, ISO 32000-1 Annex C).
293 max_object_number, with_max_object_number: u32;
294 /// Soft: warnings kept per document; later ones are dropped after one
295 /// `warnings-truncated` warning (default 1,000).
296 max_warnings, with_max_warnings: usize;
297 /// Hard: operators read by one content-stream interpretation (`laminapdf-content`), the
298 /// page's and every Form XObject's each time it is drawn (default 10,000,000; ADR 0023).
299 max_content_operators, with_max_content_operators: u64;
300 /// Hard: Form `XObject`s drawn at once by `laminapdf-content`; patterns and Type 3 glyphs
301 /// too once they are interpreted (default 32; ADR 0023).
302 max_xobject_depth, with_max_xobject_depth: usize;
303 /// Hard, reserved: pixels in one decoded image (default 2^28).
304 max_image_pixels, with_max_image_pixels: u64;
305 /// Hard: bytes one parse may read from a source without an in-memory slice
306 /// (`laminapdf-cos` reads such sources in windows; default 256 MiB). It bounds how far a
307 /// window grows for one object (its head, a stream's data, the search for a missing
308 /// `endstream`) and the backward walk over an object header found by repair. Past
309 /// it, the object fails with `LimitExceeded` where an in-memory parse would have read
310 /// on; a tolerant path (repair, `/Length` recovery, the xref entry check) treats the
311 /// item as unreadable instead. In-memory input is never limited by it.
312 max_read_window, with_max_read_window: usize;
313 }
314}
315
316/// The decoding budget of one top-level call: [`Limits::max_decoded_total`] bytes, spent by
317/// every filter stage of every stream the call decodes.
318///
319/// Create one per call ([`DecodeBudget::new`]) and pass it to every
320/// [`filters::decode`](crate::filters::decode) the call makes.
321///
322/// Added in 0.2.0.
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub struct DecodeBudget {
325 remaining: usize,
326}
327
328impl DecodeBudget {
329 /// A fresh budget of `limits.max_decoded_total()` bytes.
330 ///
331 /// Added in 0.2.0.
332 #[must_use]
333 pub const fn new(limits: &Limits) -> Self {
334 Self {
335 remaining: limits.max_decoded_total,
336 }
337 }
338
339 /// Bytes that may still be decoded.
340 ///
341 /// Added in 0.2.0.
342 #[must_use]
343 pub const fn remaining(&self) -> usize {
344 self.remaining
345 }
346
347 /// Records `bytes` of decoded output.
348 pub(crate) const fn spend(&mut self, bytes: usize) {
349 self.remaining = self.remaining.saturating_sub(bytes);
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn defaults_match_the_adr_table() {
359 let l = Limits::default();
360 assert_eq!(
361 [
362 l.max_nesting_depth(),
363 l.max_stream_decoded(),
364 l.max_decoded_total(),
365 l.max_filter_chain(),
366 l.max_resolve_depth(),
367 l.max_page_tree_depth(),
368 l.max_tree_depth(),
369 l.max_string_length(),
370 l.max_xref_sections(),
371 l.max_warnings(),
372 l.max_xobject_depth(),
373 l.max_read_window(),
374 ],
375 [
376 256,
377 64 << 20,
378 1 << 30,
379 8,
380 32,
381 256,
382 64,
383 16 << 20,
384 4096,
385 1000,
386 32,
387 256 << 20
388 ]
389 );
390 }
391
392 #[test]
393 fn defaults_for_wide_limits_match_the_adr_table() {
394 let l = Limits::default();
395 assert_eq!(
396 (l.max_object_number(), l.max_content_operators(), l.max_image_pixels()),
397 (8_388_607, 10_000_000, 1 << 28)
398 );
399 }
400
401 #[test]
402 fn with_builder_changes_only_its_field() {
403 let l = Limits::default().with_max_filter_chain(2);
404 assert_eq!(
405 l,
406 Limits {
407 max_filter_chain: 2,
408 ..Limits::default()
409 }
410 );
411 }
412
413 #[test]
414 fn limit_value_in_reads_the_matching_field() {
415 let l = Limits::default().with_max_string_length(7);
416 assert_eq!(Limit::StringLength.value_in(&l), 7);
417 }
418
419 #[test]
420 fn limit_names_are_distinct() {
421 let mut names: Vec<_> = Limit::ALL.iter().map(|l| l.name()).collect();
422 names.sort_unstable();
423 names.dedup();
424 assert_eq!(names.len(), Limit::ALL.len());
425 }
426}