revenant-sign-core 3.0.5

Cross-platform client library for ARX CoSign / DocuSign Signature Appliance electronic signatures via the OASIS DSS SOAP API
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Read-only PDF structure access, backed by `lopdf`.
//!
//! Opens a PDF purely to read structure -- page object numbers and dimensions,
//! the trailer `/Size`, `/Info` and `/ID` carry-forward entries, and per-object
//! entry enumeration for building page/catalog overrides. It never writes; the
//! actual signed output is assembled as raw bytes in [`super::incremental`].
//!
//! All `lopdf` types are contained here so the rest of the `pdf` module depends
//! on plain data (numbers, strings, [`PageInfo`]) rather than a specific PDF
//! library -- if the backing library ever changes, only this file moves.

use lopdf::{Dictionary, Document, Object, ObjectId};

use crate::{Result, RevenantError};

/// Maximum `/Parent` walk depth when resolving inherited page attributes.
/// A page tree deeper than this is almost certainly malformed or cyclic.
const MAX_PARENT_DEPTH: usize = 64;

/// `/SigFlags` bits to OR into an AcroForm when adding a signature field:
/// bit 1 = SignaturesExist, bit 2 = AppendOnly (ISO 32000-1 Table 219).
const SIG_FLAGS_SIGNED_APPEND: i64 = 1 | 2;

/// An indirect-object reference: object number and generation. Displays as the
/// PDF `"N G R"` reference syntax.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ObjRef {
    pub num: u32,
    pub gen: u16,
}

impl ObjRef {
    /// Construct a reference from an object number and generation.
    #[must_use]
    pub fn new(num: u32, gen: u16) -> Self {
        Self { num, gen }
    }
}

impl std::fmt::Display for ObjRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {} R", self.num, self.gen)
    }
}

/// Structural facts about one page needed to place a signature.
#[derive(Debug, Clone, PartialEq)]
pub struct PageInfo {
    /// The page object's number (generation is assumed 0).
    pub obj_num: u32,
    /// Effective page width in PDF points (CropBox over MediaBox, rotation-aware).
    pub width: f64,
    /// Effective page height in PDF points.
    pub height: f64,
    /// Existing `/Annots` references, in order.
    pub annots: Vec<ObjRef>,
}

/// An opened PDF, queried for the structure a signature update needs.
#[derive(Debug)]
pub struct PdfReader {
    doc: Document,
}

impl PdfReader {
    /// Parse a PDF from memory.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if the bytes are not a parseable PDF.
    pub fn open(pdf_bytes: &[u8]) -> Result<Self> {
        let doc = Document::load_mem(pdf_bytes)
            .map_err(|e| RevenantError::Pdf(format!("Cannot parse PDF: {e}")))?;
        Ok(Self { doc })
    }

    /// Number of pages in the document.
    #[must_use]
    pub fn page_count(&self) -> usize {
        self.doc.get_pages().len()
    }

    /// Whether the PDF declares document encryption (`/Encrypt` in the trailer).
    ///
    /// An encrypted source cannot receive a correct incremental-update
    /// signature: the appended objects would have to be encrypted with the
    /// document key and the `/Encrypt` reference carried into the new trailer.
    /// Signing one regardless yields a structurally inconsistent file whose
    /// original content is unreadable, so the embedded-signing path rejects it
    /// up front (fail-loud) rather than emitting a corrupt "signed" document.
    ///
    /// Two lopdf signals are combined because either alone is insufficient:
    /// `is_encrypted()` reports a trailer that still carries `/Encrypt` (a
    /// document lopdf did not decrypt -- e.g. a non-empty user password);
    /// `was_encrypted()` reports one lopdf transparently decrypted on load (the
    /// common empty-user-password case), which strips `/Encrypt` from the
    /// in-memory trailer. A trailer check alone would wrongly pass the latter and
    /// append plaintext objects onto still-encrypted original bytes.
    #[must_use]
    pub fn is_encrypted(&self) -> bool {
        self.doc.is_encrypted() || self.doc.was_encrypted()
    }

    /// The `/Size` value from the trailer (highest object number + 1).
    ///
    /// Uses `lopdf`, which resolves cross-reference streams, incremental
    /// updates, and hybrid-reference files -- a plain regex over the bytes
    /// fails when a large xref-stream `/Size` is followed by a smaller
    /// traditional trailer.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if `/Size` is missing or not an integer.
    pub fn size(&self) -> Result<i64> {
        self.doc
            .trailer
            .get(b"Size")
            .and_then(Object::as_i64)
            .map_err(|e| {
                RevenantError::Pdf(format!("Cannot determine /Size from PDF trailer: {e}"))
            })
    }

    /// Trailer entries to carry forward into the incremental update's trailer
    /// (`/Info` and `/ID`), each as a raw `"  /Key value"` line.
    ///
    /// Per ISO 32000-1 S7.5.6 an incremental trailer must repeat the previous
    /// trailer's entries (except `/Prev` and `/Size`, which are updated). This
    /// reads `lopdf`'s resolved trailer uniformly, which is correct for both
    /// traditional and cross-reference-stream trailers.
    #[must_use]
    pub fn trailer_carry_forward(&self) -> Vec<String> {
        let mut out = Vec::new();
        if let Ok(Object::Reference(id)) = self.doc.trailer.get(b"Info") {
            out.push(format!("/Info {} {} R", id.0, id.1));
        }
        if let Ok(id_obj) = self.doc.trailer.get(b"ID") {
            let mut buf = Vec::new();
            write_id_forcing_hex(id_obj, &mut buf);
            // Forcing the hex form guarantees ASCII output, so this conversion is
            // lossless -- a literal /ID carrying raw bytes would otherwise be
            // corrupted by String::from_utf8_lossy.
            if let Ok(id_str) = String::from_utf8(buf) {
                out.push(format!("/ID {id_str}"));
            }
        }
        out
    }

    /// Read structural facts about the page at a 0-based index.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if the index is out of range, the page or
    /// its box cannot be read, or an existing annotation is not an indirect
    /// reference.
    pub fn page_info(&self, page_index: usize) -> Result<PageInfo> {
        let pages = self.doc.get_pages();
        // get_pages() is keyed 1-based.
        let page_number = u32::try_from(page_index)
            .ok()
            .and_then(|i| i.checked_add(1))
            .ok_or_else(|| RevenantError::Pdf(format!("Page index {page_index} too large")))?;
        let page_id = *pages.get(&page_number).ok_or_else(|| {
            RevenantError::Pdf(format!(
                "Page {page_index} out of range (PDF has {} page(s), 0-based).",
                pages.len()
            ))
        })?;

        let (width, height) = self.page_dimensions(page_id)?;
        let annots = self.page_annots(page_id)?;

        Ok(PageInfo {
            obj_num: page_id.0,
            width,
            height,
            annots,
        })
    }

    /// Effective (width, height): CropBox if present else MediaBox, with the
    /// page's `/Rotate` (90/270 swap) applied.
    fn page_dimensions(&self, page_id: ObjectId) -> Result<(f64, f64)> {
        let box_obj = self
            .get_inherited(page_id, b"CropBox")
            .or_else(|| self.get_inherited(page_id, b"MediaBox"))
            .ok_or_else(|| {
                RevenantError::Pdf(format!("Page {} has no MediaBox or CropBox", page_id.0))
            })?;

        let [x0, y0, x1, y1] = self.array_f64_4(box_obj)?;
        let mut w = (x1 - x0).abs();
        let mut h = (y1 - y0).abs();

        if let Some(rotate_obj) = self.get_inherited(page_id, b"Rotate") {
            let rotate = rotate_obj.as_i64().unwrap_or(0).rem_euclid(360);
            if rotate == 90 || rotate == 270 {
                std::mem::swap(&mut w, &mut h);
            }
        }
        Ok((w, h))
    }

    /// Existing `/Annots` references on a page, in order.
    fn page_annots(&self, page_id: ObjectId) -> Result<Vec<ObjRef>> {
        let page = self
            .doc
            .get_dictionary(page_id)
            .map_err(|e| RevenantError::Pdf(format!("Cannot read page object: {e}")))?;
        let Ok(annots_obj) = page.get(b"Annots") else {
            return Ok(Vec::new());
        };
        // /Annots may itself be an indirect reference to the array.
        let annots_obj = self.deref(annots_obj);
        let Ok(array) = annots_obj.as_array() else {
            return Ok(Vec::new());
        };

        let mut refs = Vec::with_capacity(array.len());
        for elem in array {
            let id = elem.as_reference().map_err(|_| {
                RevenantError::Pdf(
                    "Existing annotation is inline, not an indirect reference; \
                     cannot carry it forward."
                        .to_owned(),
                )
            })?;
            refs.push(ObjRef::new(id.0, id.1));
        }
        Ok(refs)
    }

    /// Build a raw override of a PDF object with one entry replaced/added.
    ///
    /// Enumerates every entry of object `obj_num` (generation 0), skipping
    /// `skip_key`, re-serializes each value, appends `new_entry`, and returns
    /// the complete `N 0 obj ... endobj` definition as bytes. Indirect
    /// references are preserved as references (not inlined); this is valid PDF
    /// and avoids duplicating the referenced objects into the override.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if the object is missing or is not a
    /// dictionary.
    pub fn object_override(
        &self,
        obj_num: u32,
        skip_key: &str,
        new_entry: &str,
    ) -> Result<Vec<u8>> {
        let obj = self
            .doc
            .get_object((obj_num, 0))
            .map_err(|e| RevenantError::Pdf(format!("Cannot read object {obj_num}: {e}")))?;
        let dict = obj.as_dict().map_err(|e| {
            RevenantError::Pdf(format!("Object {obj_num} is not a dictionary: {e}"))
        })?;

        let skip = skip_key.strip_prefix('/').unwrap_or(skip_key).as_bytes();

        let mut out = Vec::new();
        out.extend_from_slice(format!("{obj_num} 0 obj\n<<\n").as_bytes());
        for (key, value) in dict {
            if key.as_slice() == skip {
                continue;
            }
            out.extend_from_slice(b"  ");
            write_name(key, &mut out);
            out.push(b' ');
            write_object(value, &mut out);
            out.push(b'\n');
        }
        out.extend_from_slice(new_entry.as_bytes());
        out.push(b'\n');
        out.extend_from_slice(b">>\nendobj\n");
        Ok(out)
    }

    /// Build a raw catalog override that installs the signature field into the
    /// document's AcroForm, **merging** with any AcroForm the document already
    /// has instead of replacing it.
    ///
    /// A signing tool must not destroy an existing form. Overwriting `/AcroForm`
    /// wholesale orphans every existing field -- and, when re-signing, the prior
    /// signature's field -- so a reader reports the earlier form/signature as
    /// removed. This preserves the existing `/Fields` (appending the new one),
    /// keeps ancillary keys (`/DR`, `/DA`, `/NeedAppearances`, `/CO`, ...), and
    /// OR-s the append-only / signatures-exist bits into `/SigFlags`.
    ///
    /// With no existing AcroForm it emits the minimal `<< /Fields [N 0 R]
    /// /SigFlags 3 >>`, matching the fresh-form case.
    ///
    /// # Errors
    ///
    /// Returns [`RevenantError::Pdf`] if the catalog object is missing or is not
    /// a dictionary.
    pub fn catalog_override_with_sig_field(
        &self,
        root_obj_num: u32,
        new_field_obj_num: u32,
    ) -> Result<Vec<u8>> {
        let obj = self
            .doc
            .get_object((root_obj_num, 0))
            .map_err(|e| RevenantError::Pdf(format!("Cannot read catalog {root_obj_num}: {e}")))?;
        let dict = obj.as_dict().map_err(|e| {
            RevenantError::Pdf(format!("Catalog {root_obj_num} is not a dictionary: {e}"))
        })?;

        let mut out = Vec::new();
        out.extend_from_slice(format!("{root_obj_num} 0 obj\n<<\n").as_bytes());
        for (key, value) in dict {
            if key.as_slice() == b"AcroForm" {
                continue;
            }
            out.extend_from_slice(b"  ");
            write_name(key, &mut out);
            out.push(b' ');
            write_object(value, &mut out);
            out.push(b'\n');
        }
        out.extend_from_slice(b"  /AcroForm << ");
        self.write_merged_acroform_body(dict.get(b"AcroForm").ok(), new_field_obj_num, &mut out);
        out.extend_from_slice(b">>\n>>\nendobj\n");
        Ok(out)
    }

    /// Write the body (between `<<` and `>>`) of the merged AcroForm dictionary.
    ///
    /// `existing` is the catalog's current `/AcroForm` value, if any (an inline
    /// dict or an indirect reference -- both are handled via [`Self::deref`]).
    fn write_merged_acroform_body(
        &self,
        existing: Option<&Object>,
        new_field_obj_num: u32,
        out: &mut Vec<u8>,
    ) {
        let existing_dict = existing
            .map(|o| self.deref(o))
            .and_then(|o| o.as_dict().ok());

        let mut wrote_fields = false;
        let mut wrote_sigflags = false;
        if let Some(acroform) = existing_dict {
            for (key, value) in acroform {
                match key.as_slice() {
                    b"Fields" => {
                        self.write_merged_fields(value, new_field_obj_num, out);
                        wrote_fields = true;
                    }
                    b"SigFlags" => {
                        let flags =
                            self.deref(value).as_i64().unwrap_or(0) | SIG_FLAGS_SIGNED_APPEND;
                        out.extend_from_slice(format!("/SigFlags {flags} ").as_bytes());
                        wrote_sigflags = true;
                    }
                    _ => {
                        write_name(key, out);
                        out.push(b' ');
                        write_object(value, out);
                        out.push(b' ');
                    }
                }
            }
        }
        if !wrote_fields {
            out.extend_from_slice(format!("/Fields [{new_field_obj_num} 0 R] ").as_bytes());
        }
        if !wrote_sigflags {
            out.extend_from_slice(format!("/SigFlags {SIG_FLAGS_SIGNED_APPEND} ").as_bytes());
        }
    }

    /// Write `/Fields [ <existing...> <new> 0 R ]`, preserving the existing field
    /// references. Those objects live in the original bytes, untouched by the
    /// incremental update, so referencing them by number stays valid.
    fn write_merged_fields(
        &self,
        fields_value: &Object,
        new_field_obj_num: u32,
        out: &mut Vec<u8>,
    ) {
        out.extend_from_slice(b"/Fields [");
        if let Ok(array) = self.deref(fields_value).as_array() {
            for elem in array {
                write_object(elem, out);
                out.push(b' ');
            }
        }
        out.extend_from_slice(format!("{new_field_obj_num} 0 R] ").as_bytes());
    }

    /// Resolve `key` on `start`, walking `/Parent` for inheritable page
    /// attributes (MediaBox/CropBox/Rotate), depth-capped against cycles.
    fn get_inherited(&self, start: ObjectId, key: &[u8]) -> Option<&Object> {
        let mut current = start;
        for _ in 0..MAX_PARENT_DEPTH {
            let dict = self.doc.get_dictionary(current).ok()?;
            if let Ok(value) = dict.get(key) {
                return Some(self.deref(value));
            }
            let parent = dict.get(b"Parent").ok()?;
            current = parent.as_reference().ok()?;
        }
        None
    }

    /// Resolve an object one level if it is an indirect reference; otherwise
    /// return it unchanged.
    fn deref<'a>(&'a self, obj: &'a Object) -> &'a Object {
        self.doc
            .dereference(obj)
            .map_or(obj, |(_, resolved)| resolved)
    }

    /// Read a 4-number array (a rectangle), resolving any element references.
    fn array_f64_4(&self, obj: &Object) -> Result<[f64; 4]> {
        let array = self
            .deref(obj)
            .as_array()
            .map_err(|e| RevenantError::Pdf(format!("Page box is not an array: {e}")))?;
        if array.len() < 4 {
            return Err(RevenantError::Pdf(format!(
                "Page box has {} elements, expected 4",
                array.len()
            )));
        }
        let mut out = [0.0f64; 4];
        for (slot, elem) in out.iter_mut().zip(array.iter()) {
            *slot =
                f64::from(self.deref(elem).as_float().map_err(|e| {
                    RevenantError::Pdf(format!("Page box value is not numeric: {e}"))
                })?);
        }
        Ok(out)
    }
}

// ── Minimal PDF object serialization ────────────────────────────────────
//
// lopdf's own writer is a private module, so we serialize the handful of
// object shapes that appear as page/catalog entries ourselves. References are
// emitted as references; this is the intended, reference-preserving behavior.

/// Serialize a PDF name (`/Key`), escaping delimiter and non-printable bytes as
/// `#XX`, matching the PDF name-encoding rules.
fn write_name(name: &[u8], out: &mut Vec<u8>) {
    out.push(b'/');
    for &byte in name {
        if is_name_special(byte) {
            out.extend_from_slice(format!("#{byte:02X}").as_bytes());
        } else {
            out.push(byte);
        }
    }
}

fn is_name_special(byte: u8) -> bool {
    b" \t\n\r\x0C()<>[]{}/%#".contains(&byte) || !(33..=126).contains(&byte)
}

/// Serialize a single PDF object value to bytes.
fn write_object(obj: &Object, out: &mut Vec<u8>) {
    match obj {
        Object::Null => out.extend_from_slice(b"null"),
        Object::Boolean(true) => out.extend_from_slice(b"true"),
        Object::Boolean(false) => out.extend_from_slice(b"false"),
        Object::Integer(value) => out.extend_from_slice(value.to_string().as_bytes()),
        Object::Real(value) => out.extend_from_slice(format_real(*value).as_bytes()),
        Object::Name(name) => write_name(name, out),
        Object::String(text, format) => write_string(text, *format, out),
        Object::Array(array) => write_array(array, out),
        Object::Dictionary(dict) => write_dictionary(dict, out),
        Object::Reference(id) => out.extend_from_slice(format!("{} {} R", id.0, id.1).as_bytes()),
        // Streams are always indirect objects, so a stream never appears as an
        // inline entry value; if one somehow does, emit its dictionary.
        Object::Stream(stream) => write_dictionary(&stream.dict, out),
    }
}

/// Format a real number as a valid PDF number (Rust's float `Display` omits a
/// trailing `.0`, so whole values render as integers).
fn format_real(value: f32) -> String {
    format!("{value}")
}

/// Serialize a trailer `/ID` value, forcing every string element to the
/// hexadecimal `<...>` form.
///
/// `/ID` is an array of two byte strings. Emitting them as hex keeps the output
/// pure ASCII and byte-exact; a literal `(...)` string carrying raw binary bytes
/// (which `/ID` values routinely are) would otherwise be mangled when the entry
/// is folded into the trailer text. Hex and literal forms encode the same bytes,
/// so the carried-forward `/ID` stays identical to the original -- what a
/// revision-consistency check requires.
fn write_id_forcing_hex(obj: &Object, out: &mut Vec<u8>) {
    match obj {
        Object::String(text, _) => write_string(text, lopdf::StringFormat::Hexadecimal, out),
        Object::Array(array) => {
            out.push(b'[');
            for (i, elem) in array.iter().enumerate() {
                if i > 0 {
                    out.push(b' ');
                }
                write_id_forcing_hex(elem, out);
            }
            out.push(b']');
        }
        other => write_object(other, out),
    }
}

fn write_string(text: &[u8], format: lopdf::StringFormat, out: &mut Vec<u8>) {
    match format {
        lopdf::StringFormat::Literal => {
            out.push(b'(');
            for &byte in text {
                if matches!(byte, b'(' | b')' | b'\\' | b'\r') {
                    out.push(b'\\');
                }
                out.push(byte);
            }
            out.push(b')');
        }
        lopdf::StringFormat::Hexadecimal => {
            out.push(b'<');
            for &byte in text {
                out.extend_from_slice(format!("{byte:02X}").as_bytes());
            }
            out.push(b'>');
        }
    }
}

fn write_array(array: &[Object], out: &mut Vec<u8>) {
    out.push(b'[');
    for (i, elem) in array.iter().enumerate() {
        if i > 0 {
            out.push(b' ');
        }
        write_object(elem, out);
    }
    out.push(b']');
}

fn write_dictionary(dict: &Dictionary, out: &mut Vec<u8>) {
    out.extend_from_slice(b"<< ");
    for (key, value) in dict {
        write_name(key, out);
        out.push(b' ');
        write_object(value, out);
        out.push(b' ');
    }
    out.extend_from_slice(b">>");
}

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

    const BLANK_LETTER: &[u8] = include_bytes!("testdata/blank_letter.pdf");
    const TWO_PAGE_A4: &[u8] = include_bytes!("testdata/two_page_a4.pdf");
    const XREF_STREAM: &[u8] = include_bytes!("testdata/blank_letter_xref_stream.pdf");
    const ENCRYPTED: &[u8] = include_bytes!("testdata/encrypted.pdf");
    // AES-256 with an empty user password: lopdf decrypts it transparently on
    // load and strips /Encrypt from the in-memory trailer, so a trailer-only
    // check would miss it. `was_encrypted()` is what catches this case.
    const ENCRYPTED_EMPTY_PW: &[u8] = include_bytes!("testdata/encrypted_empty_password.pdf");

    #[test]
    fn detects_encryption() {
        // An encrypted PDF whose trailer still carries /Encrypt must be flagged:
        // signing it would silently corrupt the document.
        let r = PdfReader::open(ENCRYPTED).unwrap();
        assert!(r.is_encrypted());
        // A plain PDF is not flagged.
        assert!(!PdfReader::open(BLANK_LETTER).unwrap().is_encrypted());
    }

    #[test]
    fn detects_empty_password_encryption() {
        // Regression: an empty-user-password document is decrypted on load, which
        // clears /Encrypt from the in-memory trailer. A trailer-only guard would
        // wrongly pass it and the signer would append plaintext objects onto
        // still-encrypted bytes, producing a file no reader can open. The guard
        // must still reject it (via was_encrypted()).
        let r = PdfReader::open(ENCRYPTED_EMPTY_PW).unwrap();
        assert!(r.is_encrypted());
    }

    #[test]
    fn id_carried_forward_as_hex_preserves_binary() {
        // A literal /ID string carrying raw (non-UTF-8) bytes must survive the
        // carry-forward; forcing hex keeps the bytes exact and the output ASCII.
        let id = Object::Array(vec![
            Object::String(vec![0x00, 0xFF, 0x41, 0x9A], lopdf::StringFormat::Literal),
            Object::String(vec![0xDE, 0xAD], lopdf::StringFormat::Hexadecimal),
        ]);
        let mut buf = Vec::new();
        write_id_forcing_hex(&id, &mut buf);
        let text = String::from_utf8(buf).expect("forced-hex /ID output must be ASCII");
        assert_eq!(text, "[<00FF419A> <DEAD>]");
    }

    #[test]
    fn reads_single_letter_page() {
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        assert_eq!(r.page_count(), 1);
        let info = r.page_info(0).unwrap();
        assert!((info.width - 612.0).abs() < 1e-6, "width {}", info.width);
        assert!((info.height - 792.0).abs() < 1e-6, "height {}", info.height);
        assert!(info.annots.is_empty());
        assert!(info.obj_num > 0);
    }

    #[test]
    fn reads_two_a4_pages() {
        let r = PdfReader::open(TWO_PAGE_A4).unwrap();
        assert_eq!(r.page_count(), 2);
        let p1 = r.page_info(0).unwrap();
        let p2 = r.page_info(1).unwrap();
        assert!((p1.width - 595.0).abs() < 1e-6);
        assert!((p1.height - 842.0).abs() < 1e-6);
        assert!((p2.height - 842.0).abs() < 1e-6);
        assert_ne!(p1.obj_num, p2.obj_num);
    }

    #[test]
    fn out_of_range_page_errors() {
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        assert!(r.page_info(1).is_err());
    }

    #[test]
    fn size_matches_object_count() {
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        // A blank single-page PDF has at least catalog + pages + page.
        assert!(r.size().unwrap() >= 4);
    }

    #[test]
    fn xref_stream_pdf_reads() {
        let r = PdfReader::open(XREF_STREAM).unwrap();
        assert_eq!(r.page_count(), 1);
        let info = r.page_info(0).unwrap();
        assert!((info.width - 612.0).abs() < 1e-6);
        assert!(r.size().unwrap() >= 4);
    }

    #[test]
    fn object_override_preserves_entries_and_appends() {
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        let page_num = r.page_info(0).unwrap().obj_num;
        let raw = r
            .object_override(page_num, "/Annots", "  /Annots [99 0 R]")
            .unwrap();
        let text = String::from_utf8_lossy(&raw);
        assert!(
            text.starts_with(&format!("{page_num} 0 obj\n<<\n")),
            "{text}"
        );
        assert!(text.contains("/Type /Page"), "{text}");
        assert!(text.contains("/MediaBox"), "{text}");
        assert!(text.contains("/Annots [99 0 R]"), "{text}");
        assert!(text.ends_with(">>\nendobj\n"), "{text}");
    }

    #[test]
    fn object_override_skips_named_key() {
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        let page_num = r.page_info(0).unwrap().obj_num;
        // /Type exists on the page; skipping it must drop it from the output.
        let raw = r.object_override(page_num, "/Type", "  /Extra 1").unwrap();
        let text = String::from_utf8_lossy(&raw);
        assert!(!text.contains("/Type /Page"), "{text}");
        assert!(text.contains("/Extra 1"), "{text}");
    }

    /// The object number of the catalog (`/Root`) in a PDF.
    fn root_obj_num(pdf: &[u8]) -> u32 {
        let doc = Document::load_mem(pdf).unwrap();
        doc.trailer.get(b"Root").unwrap().as_reference().unwrap().0
    }

    /// A minimal one-page PDF carrying an AcroForm with a single text field and
    /// `SigFlags` = 1. Returns `(bytes, existing_field_num, catalog_num)`.
    fn pdf_with_acroform() -> (Vec<u8>, u32, u32) {
        use lopdf::{dictionary, Object};

        let mut doc = Document::with_version("1.7");
        let page_tree_id = doc.new_object_id();
        let field_id = doc.add_object(dictionary! {
            "Type" => "Annot",
            "Subtype" => "Widget",
            "FT" => "Tx",
            "T" => Object::string_literal("existing_field"),
            "Rect" => vec![0.into(), 0.into(), 100.into(), 20.into()],
        });
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Parent" => page_tree_id,
            "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
            "Annots" => vec![Object::Reference(field_id)],
        });
        doc.objects.insert(
            page_tree_id,
            Object::Dictionary(dictionary! {
                "Type" => "Pages",
                "Kids" => vec![Object::Reference(page_id)],
                "Count" => 1,
            }),
        );
        let acroform_id = doc.add_object(dictionary! {
            "Fields" => vec![Object::Reference(field_id)],
            "SigFlags" => 1,
            "NeedAppearances" => true,
        });
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => page_tree_id,
            "AcroForm" => Object::Reference(acroform_id),
        });
        doc.trailer.set("Root", catalog_id);

        let mut buf = Vec::new();
        doc.save_to(&mut buf).expect("save fixture PDF");
        (buf, field_id.0, catalog_id.0)
    }

    #[test]
    fn catalog_override_creates_acroform_when_absent() {
        // No existing form: the minimal field-only AcroForm, byte-identical to the
        // pre-merge behavior, so plain-document signing is unchanged.
        let r = PdfReader::open(BLANK_LETTER).unwrap();
        let root = root_obj_num(BLANK_LETTER);
        let raw = r.catalog_override_with_sig_field(root, 99).unwrap();
        let text = String::from_utf8_lossy(&raw);
        assert!(
            text.contains("/AcroForm << /Fields [99 0 R] /SigFlags 3 >>"),
            "{text}"
        );
        assert!(text.contains("/Type /Catalog"), "{text}");
    }

    #[test]
    fn catalog_override_merges_existing_acroform() {
        // Regression for the form-destroying bug: signing a PDF that already has
        // an AcroForm must keep the existing fields and merge, not replace.
        let (pdf, field_num, root) = pdf_with_acroform();
        let r = PdfReader::open(&pdf).unwrap();
        let raw = r.catalog_override_with_sig_field(root, 99).unwrap();
        let text = String::from_utf8_lossy(&raw);

        assert!(text.contains("/Type /Catalog"), "{text}");
        // Existing field preserved, new field appended after it.
        assert!(
            text.contains(&format!("/Fields [{field_num} 0 R 99 0 R]")),
            "{text}"
        );
        // SigFlags 1 (SignaturesExist) OR-ed with append-only -> 3.
        assert!(text.contains("/SigFlags 3"), "{text}");
        // Ancillary AcroForm keys carried forward, not dropped.
        assert!(text.contains("/NeedAppearances true"), "{text}");
    }
}