flpdf 0.8.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Typed permission configuration for writer-side `/Encrypt` `/P` encoding.
//!
//! qpdf correspondence: `QPDF_encryption.cc` permission projection and `/P` encoding.
//!
//! [`Permissions`] is the read-only view of an already-encrypted document's
//! `/P` bitfield, with one accessor per capability bit. This module also owns
//! the writer-side counterpart: a typed
//! configuration that callers populate and then encode into the `/P`
//! bitfield via [`PermissionsConfig::to_p_bits`], which the various
//! `/Encrypt` dictionary builders in the encryption Standard handler consume.
//!
//! The reader and writer projections are intentionally separate so the read
//! path cannot accidentally widen its `/P` interpretation when the writer
//! gains new options.

/// Standard security handler permission bits read from an encrypted
/// document's `/P` entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Permissions {
    raw: i32,
}

impl Permissions {
    pub(crate) fn new(raw: i32) -> Self {
        Self { raw }
    }

    /// Raw signed `/P` value.
    pub fn raw(self) -> i32 {
        self.raw
    }

    /// Print the document, possibly at degraded quality if high-quality printing is denied.
    pub fn can_print(self) -> bool {
        self.has_bit(0x0004)
    }

    /// Modify document contents by operations other than controlled form/annotation edits.
    pub fn can_modify(self) -> bool {
        self.has_bit(0x0008)
    }

    /// Copy or otherwise extract text and graphics.
    pub fn can_copy(self) -> bool {
        self.has_bit(0x0010)
    }

    /// Add or modify annotations and interactive form fields.
    pub fn can_annotate(self) -> bool {
        self.has_bit(0x0020)
    }

    /// Fill in existing interactive form fields.
    pub fn can_fill_forms(self) -> bool {
        self.has_bit(0x0100)
    }

    /// Extract text and graphics for accessibility purposes.
    pub fn can_extract_for_accessibility(self) -> bool {
        self.has_bit(0x0200)
    }

    /// Assemble the document by inserting, rotating, or deleting pages/bookmarks.
    pub fn can_assemble(self) -> bool {
        self.has_bit(0x0400)
    }

    /// Print the document at high quality.
    pub fn can_print_high_quality(self) -> bool {
        self.has_bit(0x0800)
    }

    fn has_bit(self, bit: u32) -> bool {
        (self.raw as u32) & bit != 0
    }
}

/// Print-permission level (PDF 1.7 §7.6.3.2 Table 22, bits 3 and 12).
///
/// Encoded as two separate bits in `/P`: bit 3 grants any printing, and
/// bit 12 (R≥3 only) grants high-quality printing. The three meaningful
/// combinations are:
///
/// | Variant | Bit 3 | Bit 12 | Reader behavior                          |
/// |---------|-------|--------|------------------------------------------|
/// | `None`  | 0     | 0      | Printing denied                          |
/// | `Low`   | 1     | 0      | Print allowed at degraded resolution     |
/// | `High`  | 1     | 1      | Print allowed at full quality            |
///
/// `(bit3=0, bit12=1)` is ignored by readers (bit 12 only takes effect when
/// bit 3 is also set), so [`PermissionsConfig::from_p_bits`] decodes it as
/// [`PrintPermission::None`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PrintPermission {
    /// Printing denied (bit 3 cleared).
    None,
    /// Print allowed at degraded resolution (bit 3 set, bit 12 cleared).
    Low,
    /// Print allowed at full quality (bits 3 and 12 set). The default.
    #[default]
    High,
}

/// Typed `/P` permission configuration for the Standard handler's R=2
/// writer path.
///
/// qpdf keeps R=2's four permission inputs separate from its R>=3
/// configuration (`QPDFWriter::setR2EncryptionParametersInsecure`,
/// `libqpdf/QPDFWriter.cc:337-360`). R=2 uses bits 3 through 6 only; the
/// R>=3 fields for form filling, accessibility, assembly, and high-quality
/// printing do not exist in this revision's writer contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct R2PermissionsConfig {
    /// Bit 3 — allow printing.
    pub print: bool,
    /// Bit 4 — allow document modification.
    pub modify: bool,
    /// Bit 5 — allow extraction.
    pub extract: bool,
    /// Bit 6 — allow annotation changes.
    pub annotate: bool,
}

impl Default for R2PermissionsConfig {
    fn default() -> Self {
        Self {
            print: true,
            modify: true,
            extract: true,
            annotate: true,
        }
    }
}

impl R2PermissionsConfig {
    /// Encode qpdf's R=2 `/P` bitfield.
    pub fn to_p_bits(self) -> i32 {
        // qpdf's setEncryptionParameters starts with all bits set, then
        // clears the two reserved low bits and the denied capability bits.
        let mut bits = 0xFFFF_FFC0u32;
        if self.print {
            bits |= 0x004;
        }
        if self.modify {
            bits |= 0x008;
        }
        if self.extract {
            bits |= 0x010;
        }
        if self.annotate {
            bits |= 0x020;
        }
        bits as i32
    }
}

/// Typed `/P` permission configuration for the writer side of the Standard
/// security handler.
///
/// Fields correspond one-to-one to ISO 32000-1 §7.6.3.2 Table 22 bit
/// assignments for revisions ≥ 3. R=2 has a separate
/// [`R2PermissionsConfig`] because qpdf's writer exposes a separate four-bit
/// setter for that revision.
/// Encode to the `/P` integer via [`Self::to_p_bits`]; decode an
/// already-stored `/P` via [`Self::from_p_bits`].
///
/// # Bit mapping
///
/// | Field             | Bit | Mask     | Spec entry (Table 22)              |
/// |-------------------|-----|----------|------------------------------------|
/// | `print` (Low/High)| 3   | `0x004`  | Print                              |
/// | `modify_contents` | 4   | `0x008`  | Modify document contents           |
/// | `extract`         | 5   | `0x010`  | Copy text and graphics             |
/// | `annotate`        | 6   | `0x020`  | Modify annotations / fill forms    |
/// | `fill_forms`      | 9   | `0x100`  | Fill interactive form fields (R≥3) |
/// | `accessibility`   | 10  | `0x200`  | Extract for accessibility (R≥3)    |
/// | `assemble`        | 11  | `0x400`  | Assemble pages (R≥3)               |
/// | `print` (High)    | 12  | `0x800`  | Print high quality (R≥3)           |
///
/// Bits 1-2 are spec-reserved and must be 0; bits 7-8 and 13-32 are
/// spec-reserved and must be 1 for R≥3. [`Self::to_p_bits`] enforces all
/// three reserved-bit rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PermissionsConfig {
    /// Bit 3 (any print) + bit 12 (high quality print). See [`PrintPermission`].
    pub print: PrintPermission,
    /// Bit 4 — modify document contents by means other than annotation/form edits.
    pub modify_contents: bool,
    /// Bit 5 — copy text and graphics out of the document.
    pub extract: bool,
    /// Bit 6 — add / modify annotations and (for R<3) fill interactive form fields.
    pub annotate: bool,
    /// Bit 9 (R≥3) — fill existing interactive form fields. Distinct from
    /// the broader `annotate` capability above; readers honor both.
    pub fill_forms: bool,
    /// Bit 10 (R≥3) — extract text and graphics for accessibility tools.
    /// Deprecated in PDF 2.0 (accessibility is unconditionally permitted);
    /// emitted for ISO 32000-1 readers' benefit.
    pub accessibility: bool,
    /// Bit 11 (R≥3) — insert, rotate, or delete pages, and create document
    /// outline / thumbnail items.
    pub assemble: bool,
}

impl Default for PermissionsConfig {
    /// All capabilities granted (no restrictions). Encodes to `/P = -4`,
    /// the value qpdf emits when no `--print`/`--modify`/etc. flags are
    /// passed to `--encrypt`, and the value present in this project's
    /// existing encrypted test fixtures.
    fn default() -> Self {
        Self {
            print: PrintPermission::High,
            modify_contents: true,
            extract: true,
            annotate: true,
            fill_forms: true,
            accessibility: true,
            assemble: true,
        }
    }
}

impl PermissionsConfig {
    /// All capabilities denied (most restrictive). Useful as a starting
    /// point for `--encrypt --print=none --modify=none …` style invocations
    /// where the caller will then enable specific bits.
    pub fn none() -> Self {
        Self {
            print: PrintPermission::None,
            modify_contents: false,
            extract: false,
            annotate: false,
            fill_forms: false,
            accessibility: false,
            assemble: false,
        }
    }

    /// Encode this configuration into the signed 32-bit `/P` value per
    /// ISO 32000-1 §7.6.3.2 Table 22 (R≥3 format).
    ///
    /// Bits 1-2 are left at 0; bits 7-8 and bits 13-32 are set to 1 per
    /// the reserved-bit rules. The two-bit print encoding is:
    ///
    /// - `PrintPermission::None`:  bit 3 = 0, bit 12 = 0
    /// - `PrintPermission::Low`:   bit 3 = 1, bit 12 = 0
    /// - `PrintPermission::High`:  bit 3 = 1, bit 12 = 1
    ///
    /// The result is typically negative because the reserved bits 13-32
    /// include the sign bit (bit 31).
    pub fn to_p_bits(&self) -> i32 {
        let mut bits: u32 = 0;

        // Bits 1-2: reserved, must be 0 (already 0).
        // Bit 3 (0x004): any print permission.
        if self.print != PrintPermission::None {
            bits |= 0x004;
        }
        // Bit 4 (0x008): modify_contents.
        if self.modify_contents {
            bits |= 0x008;
        }
        // Bit 5 (0x010): extract.
        if self.extract {
            bits |= 0x010;
        }
        // Bit 6 (0x020): annotate.
        if self.annotate {
            bits |= 0x020;
        }
        // Bits 7-8 (0x040, 0x080): reserved, must be 1 for R≥3.
        bits |= 0x040 | 0x080;
        // Bit 9 (0x100): fill_forms (R≥3).
        if self.fill_forms {
            bits |= 0x100;
        }
        // Bit 10 (0x200): accessibility (R≥3).
        if self.accessibility {
            bits |= 0x200;
        }
        // Bit 11 (0x400): assemble (R≥3).
        if self.assemble {
            bits |= 0x400;
        }
        // Bit 12 (0x800): print_high_quality — only meaningful when bit 3 is set.
        if self.print == PrintPermission::High {
            bits |= 0x800;
        }
        // Bits 13-32: reserved, must be 1 for R≥3.
        bits |= 0xFFFF_F000;

        bits as i32
    }

    /// Decode a signed 32-bit `/P` value back into a typed
    /// [`PermissionsConfig`]. Reserved bits (1-2, 7-8, 13-32) are ignored,
    /// so `from_p_bits(p).to_p_bits()` will normalize a partially-conforming
    /// `/P` to the canonical R≥3 form.
    ///
    /// `(bit 3 = 0, bit 12 = 1)` decodes as [`PrintPermission::None`]
    /// (high-quality print requires any-print to take effect per spec).
    pub fn from_p_bits(bits: i32) -> Self {
        let bits = bits as u32;
        let any_print = bits & 0x004 != 0;
        let high_print = bits & 0x800 != 0;
        let print = if !any_print {
            PrintPermission::None
        } else if high_print {
            PrintPermission::High
        } else {
            PrintPermission::Low
        };
        Self {
            print,
            modify_contents: bits & 0x008 != 0,
            extract: bits & 0x010 != 0,
            annotate: bits & 0x020 != 0,
            fill_forms: bits & 0x100 != 0,
            accessibility: bits & 0x200 != 0,
            assemble: bits & 0x400 != 0,
        }
    }
}

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

    /// `PermissionsConfig::default()` (all granted) must encode to the
    /// canonical "all permissions" value `/P = -4` that qpdf emits and that
    /// this project's existing encrypted fixtures carry.
    #[test]
    fn default_config_encodes_to_minus_four() {
        assert_eq!(PermissionsConfig::default().to_p_bits(), -4);
    }

    /// And the inverse: `/P = -4` (the qpdf-canonical "all permissions"
    /// value that every fixture in `tests/fixtures/encrypted/` carries)
    /// must decode back to `PermissionsConfig::default()`. Implied by the
    /// 128-case round-trip below, asserted explicitly here to make the
    /// qpdf-parity guarantee visible at the named entry point.
    #[test]
    fn from_p_bits_decodes_qpdf_default_minus_four_to_default() {
        assert_eq!(
            PermissionsConfig::from_p_bits(-4),
            PermissionsConfig::default()
        );
    }

    /// `PermissionsConfig::none()` (all denied) leaves only the reserved
    /// bits set — bits 7-8 (= 0x0C0) and bits 13-32 (= 0xFFFF_F000). The
    /// combined u32 is `0xFFFF_F0C0`, which as i32 is `-3904`.
    #[test]
    fn none_config_encodes_only_reserved_bits() {
        let bits = PermissionsConfig::none().to_p_bits();
        assert_eq!(bits as u32, 0xFFFF_F0C0);
        assert_eq!(bits, -3904);
    }

    /// Round-trip every combination of boolean fields × every print level.
    /// 128 cases (2^7 booleans × 3 print levels) — exhaustive for the
    /// configuration space, catches any encode/decode asymmetry.
    #[test]
    fn round_trip_encode_decode_for_all_combinations() {
        let prints = [
            PrintPermission::None,
            PrintPermission::Low,
            PrintPermission::High,
        ];
        for &print in &prints {
            for modify_contents in [false, true] {
                for extract in [false, true] {
                    for annotate in [false, true] {
                        for fill_forms in [false, true] {
                            for accessibility in [false, true] {
                                for assemble in [false, true] {
                                    let original = PermissionsConfig {
                                        print,
                                        modify_contents,
                                        extract,
                                        annotate,
                                        fill_forms,
                                        accessibility,
                                        assemble,
                                    };
                                    let bits = original.to_p_bits();
                                    let decoded = PermissionsConfig::from_p_bits(bits);
                                    assert_eq!(
                                        decoded, original,
                                        "round-trip failed for {original:?} (bits = {bits} / 0x{:08X})",
                                        bits as u32,
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// `from_p_bits` must ignore reserved bits (1-2, 7-8, 13-32): two
    /// inputs that differ only in reserved-bit values must decode to the
    /// same [`PermissionsConfig`]. Verified by toggling each reserved-bit
    /// mask against the canonical "all denied" value.
    #[test]
    fn from_p_bits_ignores_reserved_bit_variations() {
        let baseline = PermissionsConfig::from_p_bits(-3904); // 0xFFFF_F0C0 (canonical none)
        let no_reserved = PermissionsConfig::from_p_bits(0); // all bits 0
        let only_bit1 = PermissionsConfig::from_p_bits(0x0000_0001);
        let only_bit2 = PermissionsConfig::from_p_bits(0x0000_0002);
        let only_reserved_hi = PermissionsConfig::from_p_bits(0xFFFF_F000u32 as i32);

        assert_eq!(baseline, no_reserved);
        assert_eq!(baseline, only_bit1);
        assert_eq!(baseline, only_bit2);
        assert_eq!(baseline, only_reserved_hi);
    }

    /// `(bit 3 = 0, bit 12 = 1)` decodes as `PrintPermission::None` per
    /// the spec's "bit 12 only takes effect when bit 3 is set" rule.
    /// Re-encoding then strips bit 12 — verifying that `to_p_bits` does
    /// not surprise callers with stale bits from a hand-crafted input.
    #[test]
    fn decode_of_high_bit_without_any_print_falls_back_to_none() {
        let bits_with_only_high = 0x800_u32 as i32; // bit 12 set, bit 3 cleared
        let decoded = PermissionsConfig::from_p_bits(bits_with_only_high);
        assert_eq!(decoded.print, PrintPermission::None);

        let re_encoded = decoded.to_p_bits();
        assert_eq!(
            re_encoded as u32 & 0x800,
            0,
            "re-encoded /P must not carry a stale bit 12 when print=None"
        );
    }

    /// PDF 1.7 §7.6.3.2 reserved-bit guarantees: every encoded `/P` from
    /// `to_p_bits` must have bits 1-2 cleared, bits 7-8 set, and bits 13-32
    /// set, regardless of which capability bits the config grants.
    #[test]
    fn to_p_bits_enforces_reserved_bit_invariants() {
        // Cover both ends of the spectrum to make sure the invariants hold
        // regardless of capability bits.
        for config in [PermissionsConfig::default(), PermissionsConfig::none()] {
            let bits = config.to_p_bits() as u32;
            assert_eq!(
                bits & 0x003,
                0,
                "bits 1-2 must be 0 (config = {config:?}, bits = 0x{bits:08X})"
            );
            assert_eq!(
                bits & 0x0C0,
                0x0C0,
                "bits 7-8 must be 1 (config = {config:?}, bits = 0x{bits:08X})"
            );
            assert_eq!(
                bits & 0xFFFF_F000,
                0xFFFF_F000,
                "bits 13-32 must be 1 (config = {config:?}, bits = 0x{bits:08X})"
            );
        }
    }

    /// PrintPermission encoding regression: each variant maps to a
    /// well-defined `/P` bit pattern. Pin the three known-good values so
    /// any later change to `to_p_bits` is caught.
    #[test]
    fn print_permission_encodes_bits_3_and_12_correctly() {
        let none = PermissionsConfig {
            print: PrintPermission::None,
            ..PermissionsConfig::none()
        };
        let low = PermissionsConfig {
            print: PrintPermission::Low,
            ..PermissionsConfig::none()
        };
        let high = PermissionsConfig {
            print: PrintPermission::High,
            ..PermissionsConfig::none()
        };
        // none: bits 3 and 12 both clear.
        assert_eq!(none.to_p_bits() as u32 & (0x004 | 0x800), 0);
        // low: bit 3 set, bit 12 clear.
        assert_eq!(low.to_p_bits() as u32 & (0x004 | 0x800), 0x004);
        // high: both bits set.
        assert_eq!(high.to_p_bits() as u32 & (0x004 | 0x800), 0x004 | 0x800);
    }

    /// PrintPermission::default() must be `High` so `PermissionsConfig::default()`
    /// (all granted) actually enables high-quality printing.
    #[test]
    fn print_permission_default_is_high() {
        assert_eq!(PrintPermission::default(), PrintPermission::High);
    }

    #[test]
    fn r2_permissions_encode_the_qpdf_four_bit_layout() {
        let permissions = R2PermissionsConfig {
            print: false,
            modify: true,
            extract: true,
            annotate: true,
        };

        assert_eq!(permissions.to_p_bits(), -8);
    }
}