pdf-engine 1.0.0-beta.6

Unified PDF rendering engine — page rendering, text extraction, thumbnails.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Resource limits for PDF processing.
//!
//! These limits protect against adversarial inputs that could cause OOM, stack overflow,
//! CPU exhaustion, or zip bombs. All limits are enforced with clean error returns — no panics.
//!
//! # Default limits
//!
//! The defaults cover 99.9% of real-world PDFs while providing strong safety guarantees:
//!
//! | Resource | Default |
//! |---|---|
//! | PDF file size | 500 MB |
//! | Single decompressed stream | 256 MB |
//! | Total memory per document | 1 GB |
//! | Object reference depth | 100 levels |
//! | Content stream operators | 10,000,000 |
//! | Image pixel count | 256 megapixels (16384×16384) |
//! | XFA template nesting depth | 50 levels |
//! | FormCalc recursion depth | 200 levels |

/// Resource limits for a single PDF processing operation.
///
/// Construct via [`ProcessingLimits::default()`] for standard limits,
/// or use the builder methods to customize for your use case.
///
/// # Examples
///
/// ```rust
/// use pdf_engine::limits::ProcessingLimits;
///
/// // Default limits (recommended for server-side processing):
/// let limits = ProcessingLimits::default();
///
/// // Stricter limits for WASM/browser context:
/// let wasm_limits = ProcessingLimits::wasm();
///
/// // Custom limits:
/// let custom = ProcessingLimits::default()
///     .max_file_bytes(100 * 1024 * 1024)   // 100 MB
///     .max_stream_bytes(64 * 1024 * 1024);  // 64 MB per stream
/// ```
#[derive(Debug, Clone)]
pub struct ProcessingLimits {
    /// Maximum PDF file size in bytes. Default: 500 MB.
    pub max_file_bytes: u64,
    /// Maximum decompressed size of any single stream. Default: 256 MB.
    /// Prevents zip bombs via FlateDecode or LZWDecode.
    pub max_stream_bytes: u64,
    /// Maximum total memory allocated per document. Default: 1 GB.
    pub max_total_memory_bytes: u64,
    /// Maximum object reference depth (prevents stack overflow on recursive refs). Default: 100.
    pub max_object_depth: u32,
    /// Maximum content stream operators per page. Default: 10,000,000.
    pub max_operator_count: u64,
    /// Maximum pixel count per image (width × height). Default: 268,435,456 (16384²).
    pub max_image_pixels: u64,
    /// Maximum XFA template XML nesting depth. Default: 50.
    pub max_xfa_nesting_depth: u32,
    /// Maximum FormCalc recursion depth. Default: 200.
    pub max_formcalc_depth: u32,
}

impl Default for ProcessingLimits {
    fn default() -> Self {
        Self {
            max_file_bytes: 500 * 1024 * 1024,          // 500 MB
            max_stream_bytes: 256 * 1024 * 1024,        // 256 MB
            max_total_memory_bytes: 1024 * 1024 * 1024, // 1 GB
            max_object_depth: 100,
            max_operator_count: 10_000_000,
            max_image_pixels: 16384 * 16384, // 268 MP
            max_xfa_nesting_depth: 50,
            max_formcalc_depth: 200,
        }
    }
}

impl ProcessingLimits {
    /// Create a new set of limits with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Strict limits for WASM/browser contexts with limited memory.
    ///
    /// - Max file: 50 MB
    /// - Max stream: 32 MB
    /// - Max total memory: 128 MB
    /// - Image pixels: 64 MP (8192×8192)
    pub fn wasm() -> Self {
        Self {
            max_file_bytes: 50 * 1024 * 1024,          // 50 MB
            max_stream_bytes: 32 * 1024 * 1024,        // 32 MB
            max_total_memory_bytes: 128 * 1024 * 1024, // 128 MB
            max_object_depth: 50,
            max_operator_count: 1_000_000,
            max_image_pixels: 8192 * 8192, // 64 MP
            max_xfa_nesting_depth: 30,
            max_formcalc_depth: 100,
        }
    }

    /// Unlimited: no resource limits (use only in trusted environments).
    pub fn unlimited() -> Self {
        Self {
            max_file_bytes: u64::MAX,
            max_stream_bytes: u64::MAX,
            max_total_memory_bytes: u64::MAX,
            max_object_depth: u32::MAX,
            max_operator_count: u64::MAX,
            max_image_pixels: u64::MAX,
            max_xfa_nesting_depth: u32::MAX,
            max_formcalc_depth: u32::MAX,
        }
    }

    /// Set maximum PDF file size.
    pub fn max_file_bytes(mut self, bytes: u64) -> Self {
        self.max_file_bytes = bytes;
        self
    }

    /// Set maximum decompressed stream size.
    pub fn max_stream_bytes(mut self, bytes: u64) -> Self {
        self.max_stream_bytes = bytes;
        self
    }

    /// Set maximum total memory per document.
    pub fn max_total_memory_bytes(mut self, bytes: u64) -> Self {
        self.max_total_memory_bytes = bytes;
        self
    }

    /// Set maximum object reference depth.
    pub fn max_object_depth(mut self, depth: u32) -> Self {
        self.max_object_depth = depth;
        self
    }

    /// Set maximum content stream operator count.
    pub fn max_operator_count(mut self, count: u64) -> Self {
        self.max_operator_count = count;
        self
    }

    /// Set maximum image pixel count (width × height).
    pub fn max_image_pixels(mut self, pixels: u64) -> Self {
        self.max_image_pixels = pixels;
        self
    }

    /// Set maximum XFA template nesting depth.
    pub fn max_xfa_nesting_depth(mut self, depth: u32) -> Self {
        self.max_xfa_nesting_depth = depth;
        self
    }

    /// Set maximum FormCalc recursion depth.
    pub fn max_formcalc_depth(mut self, depth: u32) -> Self {
        self.max_formcalc_depth = depth;
        self
    }

    /// Check if a file size is within limits. Returns `Err` with a descriptive message if exceeded.
    pub fn check_file_size(&self, bytes: u64) -> Result<(), LimitError> {
        if bytes > self.max_file_bytes {
            Err(LimitError::FileTooLarge {
                actual_bytes: bytes,
                limit_bytes: self.max_file_bytes,
            })
        } else {
            Ok(())
        }
    }

    /// Check if a decompressed stream size is within limits.
    pub fn check_stream_size(&self, bytes: u64) -> Result<(), LimitError> {
        if bytes > self.max_stream_bytes {
            Err(LimitError::StreamTooLarge {
                actual_bytes: bytes,
                limit_bytes: self.max_stream_bytes,
            })
        } else {
            Ok(())
        }
    }

    /// Check if image dimensions are within limits.
    pub fn check_image_pixels(&self, width: u64, height: u64) -> Result<(), LimitError> {
        let pixels = width.saturating_mul(height);
        if pixels > self.max_image_pixels {
            Err(LimitError::ImageTooLarge {
                width,
                height,
                pixels,
                limit_pixels: self.max_image_pixels,
            })
        } else {
            Ok(())
        }
    }

    /// Check if an object depth is within limits.
    pub fn check_object_depth(&self, depth: u32) -> Result<(), LimitError> {
        if depth > self.max_object_depth {
            Err(LimitError::ObjectDepthExceeded {
                depth,
                limit: self.max_object_depth,
            })
        } else {
            Ok(())
        }
    }
}

/// Error returned when a configured resource limit is exceeded.
///
/// A `LimitError` is a hard stop on the current operation — the caller
/// should either raise the relevant cap on the [`ProcessingLimits`] used
/// to construct the engine, or refuse the input. All variants carry both
/// the observed value and the limit so callers can produce useful error
/// messages without re-running detection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LimitError {
    /// PDF file size exceeded [`ProcessingLimits::max_file_bytes`].
    /// Defends against trivially-DoS-ing the parser with an oversized
    /// input.
    FileTooLarge {
        /// Observed file size in bytes.
        actual_bytes: u64,
        /// Configured maximum file size in bytes.
        limit_bytes: u64,
    },
    /// A decompressed stream exceeded
    /// [`ProcessingLimits::max_stream_bytes`]. Defends against
    /// "decompression bomb" inputs (Flate, LZW, ASCII85) that expand
    /// far beyond their compressed footprint.
    StreamTooLarge {
        /// Observed decompressed stream size in bytes.
        actual_bytes: u64,
        /// Configured maximum stream size in bytes.
        limit_bytes: u64,
    },
    /// An image XObject exceeded [`ProcessingLimits::max_image_pixels`].
    /// `pixels = width * height` regardless of color depth. Guards the
    /// memory used by rasterization and color-space conversion.
    ImageTooLarge {
        /// Observed image width in pixels.
        width: u64,
        /// Observed image height in pixels.
        height: u64,
        /// Observed total pixel count (`width * height`).
        pixels: u64,
        /// Configured maximum pixel count.
        limit_pixels: u64,
    },
    /// Indirect-object reference chain exceeded
    /// [`ProcessingLimits::max_object_depth`]. Defends against cyclic or
    /// pathologically nested object graphs that would otherwise blow
    /// the parser stack.
    ObjectDepthExceeded {
        /// Observed reference-chain depth.
        depth: u32,
        /// Configured maximum reference-chain depth.
        limit: u32,
    },
    /// Content-stream operator count exceeded
    /// [`ProcessingLimits::max_operator_count`]. Caps per-page
    /// rendering work so a billion no-op operators can't pin a CPU.
    TooManyOperators {
        /// Observed operator count.
        count: u64,
        /// Configured maximum operator count.
        limit: u64,
    },
    /// XFA template subform nesting exceeded
    /// [`ProcessingLimits::max_xfa_nesting_depth`]. Defends the XFA
    /// layout engine against pathologically nested templates.
    XfaNestingTooDeep {
        /// Observed XFA subform nesting depth.
        depth: u32,
        /// Configured maximum nesting depth.
        limit: u32,
    },
    /// FormCalc expression recursion exceeded
    /// [`ProcessingLimits::max_formcalc_depth`]. Stops infinite or
    /// deeply mutually-recursive expressions from blowing the FormCalc
    /// interpreter stack.
    FormCalcRecursionTooDeep {
        /// Observed recursion depth.
        depth: u32,
        /// Configured maximum recursion depth.
        limit: u32,
    },
}

impl std::fmt::Display for LimitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::FileTooLarge {
                actual_bytes,
                limit_bytes,
            } => write!(
                f,
                "PDF file too large: {} MB (limit: {} MB)",
                actual_bytes / 1024 / 1024,
                limit_bytes / 1024 / 1024
            ),
            Self::StreamTooLarge {
                actual_bytes,
                limit_bytes,
            } => write!(
                f,
                "Decompressed stream too large: {} MB (limit: {} MB)",
                actual_bytes / 1024 / 1024,
                limit_bytes / 1024 / 1024
            ),
            Self::ImageTooLarge {
                width,
                height,
                pixels,
                limit_pixels,
            } => write!(
                f,
                "Image too large: {}×{} ({} MP, limit: {} MP)",
                width,
                height,
                pixels / 1_000_000,
                limit_pixels / 1_000_000
            ),
            Self::ObjectDepthExceeded { depth, limit } => write!(
                f,
                "Object reference depth exceeded: {} (limit: {})",
                depth, limit
            ),
            Self::TooManyOperators { count, limit } => write!(
                f,
                "Content stream has too many operators: {} (limit: {})",
                count, limit
            ),
            Self::XfaNestingTooDeep { depth, limit } => write!(
                f,
                "XFA template nesting too deep: {} (limit: {})",
                depth, limit
            ),
            Self::FormCalcRecursionTooDeep { depth, limit } => write!(
                f,
                "FormCalc recursion too deep: {} (limit: {})",
                depth, limit
            ),
        }
    }
}

impl std::error::Error for LimitError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_limits() {
        let l = ProcessingLimits::default();
        assert_eq!(l.max_file_bytes, 500 * 1024 * 1024);
        assert_eq!(l.max_stream_bytes, 256 * 1024 * 1024);
        assert_eq!(l.max_image_pixels, 16384 * 16384);
    }

    #[test]
    fn test_wasm_limits_stricter_than_default() {
        let wasm = ProcessingLimits::wasm();
        let default = ProcessingLimits::default();
        assert!(wasm.max_file_bytes < default.max_file_bytes);
        assert!(wasm.max_stream_bytes < default.max_stream_bytes);
        assert!(wasm.max_image_pixels < default.max_image_pixels);
    }

    #[test]
    fn test_file_size_check() {
        let l = ProcessingLimits::default();
        assert!(l.check_file_size(100 * 1024 * 1024).is_ok()); // 100 MB: ok
        assert!(l.check_file_size(500 * 1024 * 1024).is_ok()); // 500 MB: ok (at limit)
        assert!(l.check_file_size(501 * 1024 * 1024).is_err()); // 501 MB: exceeded
    }

    #[test]
    fn test_image_pixel_check() {
        let l = ProcessingLimits::default();
        assert!(l.check_image_pixels(1920, 1080).is_ok());
        assert!(l.check_image_pixels(16384, 16384).is_ok()); // at limit
        assert!(l.check_image_pixels(16385, 16384).is_err()); // just over
    }

    #[test]
    fn test_stream_size_check() {
        let l = ProcessingLimits::default();
        assert!(l.check_stream_size(100 * 1024 * 1024).is_ok());
        assert!(l.check_stream_size(256 * 1024 * 1024).is_ok()); // at limit
        assert!(l.check_stream_size(257 * 1024 * 1024).is_err()); // exceeded
    }

    #[test]
    fn test_builder_pattern() {
        let l = ProcessingLimits::default()
            .max_file_bytes(10 * 1024 * 1024)
            .max_stream_bytes(5 * 1024 * 1024);
        assert_eq!(l.max_file_bytes, 10 * 1024 * 1024);
        assert_eq!(l.max_stream_bytes, 5 * 1024 * 1024);
    }

    #[test]
    fn test_limit_error_display() {
        let err = LimitError::FileTooLarge {
            actual_bytes: 600 * 1024 * 1024,
            limit_bytes: 500 * 1024 * 1024,
        };
        let msg = err.to_string();
        assert!(msg.contains("600 MB"));
        assert!(msg.contains("500 MB"));
    }
}