Skip to main content

pdfcer_model/
document.rs

1//! # The Document — pdfcer's single object model (load side)
2//!
3//! Ties the layers together: retained source buffer → header probe →
4//! xref chain → eagerly parsed indirect objects → reference resolution.
5//! Spec sources: `iso32000__s__7.5.5.md` (load algorithm),
6//! `iso32000__s__7.3.10.md` (resolution semantics, dangling-ref rule),
7//! `iso32000__s__7.7.2.md` (catalog) in the PDF-spec RAG. Clause
8//! numbers are ISO 32000-1:2008.
9//!
10//! ## THE named invariant: one `Document`, both directions
11//!
12//! [`Document`] is simultaneously the parse result AND (from the first
13//! editing Pass on) the write source
14//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 3). No
15//! separate builder/generation model may ever be introduced — the
16//! audited prior art shows exactly how that bifurcation forecloses
17//! round-trip editing. Write-side machinery (dirty tracking, the
18//! §7.5.6 incremental writer) lands in the first editing Pass and
19//! operates on *this* type.
20//!
21//! ## The retained buffer
22//!
23//! The document owns the complete source bytes for its lifetime. Every
24//! file-level [`IndirectObject`] records a
25//! [`ByteSpan`](crate::span::ByteSpan) into this buffer (its full
26//! `N G obj … endobj` definition), which is what makes
27//! minimal-diff/incremental re-emission mechanical (ARCHITECTURE.md §5;
28//! `crate::span`). Memory cost is the file size — the deliberate price
29//! of the round-trip invariant, and small next to any renderer's
30//! working set.
31//!
32//! Objects that lived **inside an object stream** (§7.5.7) have no span
33//! of their own; they carry [`Provenance::ObjectStream`] instead,
34//! naming the container and index. See [`Provenance`] for why that
35//! distinction is a type and not a sentinel.
36//!
37//! ## Eager parse, strict failure (Pass 1 posture)
38//!
39//! `load`/`from_bytes` parse **every in-use object up front**; any
40//! malformed object fails the whole load with a precise error. Rationale:
41//! fail-clean over partial success (ARCHITECTURE.md §10) — a viewer
42//! that opens a file "successfully" and then errors object-by-object
43//! gives worse diagnostics than one clean refusal naming the offset.
44//! Lazy/tolerant loading (open-what-you-can) is a deliberate later
45//! feature for damaged-file recovery, driven by corpus evidence, not a
46//! default.
47//!
48//! ### Two phases, in this order (§7.5.7 + §7.5.8.3)
49//!
50//! 1. **File-level objects** — every type-1 (`InUse`) xref entry is
51//!    parsed at its offset.
52//! 2. **Compressed objects** — every type-2 (`InStream`) entry is
53//!    resolved through its container.
54//!
55//! The order is forced, not stylistic: a container object stream is
56//! itself an ordinary file-level stream object reached through a
57//! type-1 entry, so phase 2 needs phase 1 to have finished. §7.5.7
58//! guarantees this terminates at two levels — an object stream may not
59//! contain a stream, so a container can never live inside another
60//! container, and the object supplying a container's `/Length` may not
61//! be compressed either. There is no recursion to guard, only an
62//! ordering to respect.
63//!
64//! Each container is decoded **once** and cached for the duration of
65//! the load ([`ObjectStream`]); a container holding 200 objects would
66//! otherwise be inflated 200 times.
67//!
68//! ## Resolution semantics (§7.3.10, §7.5.4)
69//!
70//! [`Document::get`] / [`Document::resolve`] implement, exactly:
71//! - **dangling reference → null** ("shall not be considered an
72//!   error") — including object numbers with no xref entry at all;
73//! - **generation mismatch → null** (a stale reference; the xref
74//!   entry's generation is part of the identity);
75//! - **free entry → null** (§7.5.4 free-list mechanics — how deleted
76//!   and hybrid-hidden objects read as absent);
77//! - **reference chains are depth-guarded** ([`MAX_RESOLVE_DEPTH`],
78//!   pdfcer policy — `5 0 obj 5 0 R endobj` is legal syntax and must
79//!   not loop).
80
81use std::collections::HashMap;
82use std::collections::hash_map::Entry;
83use std::path::Path;
84
85use crate::linearization::{self, Linearization};
86use crate::object::{Dict, IndirectObject, ObjId, Object, Provenance};
87use crate::objstm::{ObjStmError, ObjectStream};
88use crate::parser::{ParseError, Parser, StreamLengthPolicy, TerminatorPolicy};
89use crate::recover::{self, RecoveryReport};
90use crate::view::DocumentView;
91use crate::xref::{self, SectionShape, XrefEntry, XrefError, XrefErrorKind, XrefTable};
92
93mod encryption_refusal;
94use crate::{PdfError, PdfVersion};
95pub use encryption_refusal::EncryptedRefusal;
96
97/// Maximum reference-chain hops [`Document::resolve`] follows before
98/// declaring a cycle and yielding null.
99///
100/// pdfcer policy (ARCHITECTURE.md §10): the spec permits
101/// reference-to-reference chains and does not bound them; legitimate
102/// files use at most a handful of hops. Null (not an error) on
103/// exhaustion keeps the §7.3.10 "references never hard-fail" posture
104/// consistent even for hostile cycles.
105pub const MAX_RESOLVE_DEPTH: usize = 32;
106
107/// Errors from loading a document.
108#[derive(Debug, thiserror::Error)]
109#[non_exhaustive]
110pub enum DocError {
111    /// File I/O failed.
112    #[error("I/O error reading PDF: {0}")]
113    Io(#[from] std::io::Error),
114    /// The document is encrypted with a configuration pdfcer will not decrypt
115    /// (§7.6). The inner error names *which* configuration and why — an
116    /// unimplemented cipher, an unsourced algorithm, a different security
117    /// handler, or a document no conforming reader may open at all.
118    ///
119    /// Those are four different facts with four different next actions, which
120    /// is why this is not one flat "encrypted files are unsupported".
121    #[error("{0}")]
122    Encryption(#[from] crate::crypto::EncryptionUnsupported),
123    /// The document is encrypted with a configuration pdfcer **can** decrypt,
124    /// but no password opened it.
125    ///
126    /// §7.6.3.1 requires trying the empty user password first and silently, so
127    /// reaching this error means the empty password was already tried and
128    /// failed: the document genuinely has a non-empty user password. The
129    /// caller should prompt and retry with
130    /// [`Document::from_bytes_with_password`].
131    ///
132    /// **N6**: ISO 32000-1 states no error model here at all — no retry limit,
133    /// no reporting requirement, nothing about distinguishing a wrong password
134    /// from a malformed one. All of that is pdfcer policy.
135    #[error("this document is password-protected; supply the user or owner password")]
136    PasswordRequired,
137    /// Nothing authenticated, **and** the supplied password contains
138    /// characters `/R` 5's password preprocessing may have changed before
139    /// hashing — so "wrong password" is not the only explanation.
140    ///
141    /// The Adobe supplement's step 1 applies **SASLprep** (RFC 4013) with the
142    /// Normalize and BIDI options before the UTF-8 conversion. pdfcer
143    /// implements the UTF-8 conversion and the 127-byte truncation exactly and
144    /// does **not** implement SASLprep; neither RFC is staged in the project's
145    /// spec corpus, and a stringprep dependency was not taken for a read-only
146    /// increment.
147    ///
148    /// For an all-ASCII password SASLprep is the identity, so this error can
149    /// never arise from one. pdfcer still *attempts* a non-ASCII password —
150    /// SASLprep is the identity for much more than ASCII, and getting it wrong
151    /// cannot open a document with a wrong key, only fail to open one with the
152    /// right password. This variant exists so that failure does not
153    /// masquerade as [`Self::PasswordRequired`]'s "you typed it wrong", which
154    /// would send the operator to re-check a password that was correct.
155    ///
156    /// Reported only at `/R` 5. Password encoding below that is PDFDocEncoding
157    /// (**T8**), a different unimplemented question.
158    #[error(
159        "this document is password-protected; the password supplied contains non-ASCII characters, \
160         and pdfcer does not apply the RFC 4013 (SASLprep) normalisation that /R 5 specifies before \
161         hashing — so a correct password can be rejected here"
162    )]
163    PasswordRequiresNormalisation,
164    /// Authentication failed at handler revision **6** (AES-256 hardened),
165    /// where the failure is **not** unambiguously "wrong password" (`Pass
166    /// 5.4`).
167    ///
168    /// `/R` 6's key derivation (Algorithm 2.B) contains a genuine spec
169    /// ambiguity — **A13**, the loop-exit test, which is internally
170    /// inconsistent between steps (e) and (f) and produces a different digest
171    /// (hence a different key, hence a failed authentication) depending on the
172    /// reading. pdfcer defaults to the reading pypdf and Acrobat write
173    /// ([`crate::crypto::r6::A13Reading::PerformThenTest`]); a document written
174    /// by an implementation that took the other reading would fail here with a
175    /// correct password. This variant names A13 so that failure is not
176    /// reported as "you typed it wrong" (`R169`: a spec ambiguity is disclosed,
177    /// never silently resolved). Raised only at `/R` 6.
178    #[error(
179        "this document is password-protected (AES-256 /R 6); authentication failed. If the password is correct, the cause may be ambiguity A13 in ISO 32000-2 Algorithm 2.B's loop-exit test -- pdfcer uses the reading pypdf and Acrobat write, and a file written under the other reading would not open"
180    )]
181    PasswordRequiredR6,
182    /// The `%PDF-` header probe failed — not a PDF.
183    #[error(transparent)]
184    Header(PdfError),
185    /// The cross-reference machinery failed — a damaged/unreadable
186    /// xref chain, or the deliberate `/Encrypt` capability-gap refusal
187    /// (`XrefErrorKind::EncryptionUnsupported`).
188    #[error(transparent)]
189    Xref(#[from] XrefError),
190    /// An indirect object at an xref-declared offset failed to parse.
191    #[error("object {id} (xref offset {offset}): {source}")]
192    BadObject {
193        /// The object the xref table pointed at.
194        id: ObjId,
195        /// The offset the xref entry gave.
196        offset: u64,
197        /// The underlying structural error.
198        source: ParseError,
199    },
200    /// The object parsed at an offset doesn't match the xref entry
201    /// that pointed there (wrong number or generation) — the table and
202    /// body disagree; strict Pass 1 refuses rather than guessing which
203    /// is right.
204    #[error("object at xref offset {offset} declares {found}, xref expected {expected}")]
205    ObjectIdMismatch {
206        /// What the xref entry promised.
207        expected: ObjId,
208        /// What the bytes at the offset declared.
209        found: ObjId,
210        /// The offset in question.
211        offset: u64,
212    },
213    /// A type-2 cross-reference entry (§7.5.8.3) named an object stream
214    /// that is not present as a loadable file-level object.
215    ///
216    /// §7.5.7: "there shall be an entry for it in a cross-reference
217    /// table or cross-reference stream" — so a missing container means
218    /// the file's own xref contradicts itself.
219    #[error("object {num} is compressed in object stream {container}, which is not present")]
220    ObjectStreamMissing {
221        /// The container the type-2 entry named (generation always 0).
222        container: ObjId,
223        /// The object that was to be read from it.
224        num: u32,
225    },
226    /// An object stream (§7.5.7) could not be decoded or read.
227    #[error("object stream {container}: {source}")]
228    ObjectStream {
229        /// The container object stream.
230        container: ObjId,
231        /// What went wrong inside it.
232        source: ObjStmError,
233    },
234    /// The object number stored in an object stream's pair table
235    /// disagrees with the object number its type-2 cross-reference
236    /// entry promised — the xref and the container contradict each
237    /// other, and the strict loader refuses rather than picking one
238    /// (the same posture as [`DocError::ObjectIdMismatch`] for
239    /// file-level objects).
240    #[error(
241        "object stream {container} index {index} holds object {found}, xref expected object {expected}"
242    )]
243    ObjectStreamIdMismatch {
244        /// The container object stream.
245        container: ObjId,
246        /// The index within it that was read.
247        index: u32,
248        /// The object number the type-2 entry promised.
249        expected: u32,
250        /// The object number the pair table actually stored.
251        found: u32,
252    },
253    /// The trailer has no usable `/Root` (Table 15 requires it; a
254    /// conformant update trailer always repeats it — see the RAG's
255    /// gotcha on why fallback-to-older-trailers is a repair heuristic,
256    /// not Pass 1 behavior).
257    #[error("trailer /Root missing or not a reference to a dictionary")]
258    NoCatalog,
259    /// Cross-reference **recovery** (decision 013) was attempted after the
260    /// strict load failed, but could not produce a document — no
261    /// confirmable objects, no `/Catalog`, or the entry cap. A named
262    /// fail-clean refusal, never a partial/garbage document. (An encrypted
263    /// recovered file is refused as [`XrefErrorKind::EncryptionUnsupported`]
264    /// via [`DocError::Xref`] instead, matching the clean-path capability
265    /// gap.)
266    ///
267    /// [`XrefErrorKind::EncryptionUnsupported`]: crate::xref::XrefErrorKind::EncryptionUnsupported
268    #[error("cross-reference recovery failed: {0}")]
269    Recovery(#[from] crate::recover::RecoverError),
270}
271
272/// A loaded PDF document: retained bytes + parsed structure.
273///
274/// See the module docs for the three design commitments this type
275/// embodies (one model, retained buffer, strict eager load).
276#[derive(Debug)]
277pub struct Document {
278    /// The complete, untouched source bytes (the provenance substrate —
279    /// every span in `objects` indexes into this).
280    buf: Vec<u8>,
281    /// Header-declared version (`%PDF-M.N`). Catalog `/Version`
282    /// override (§7.5.5) is reconciled by [`Document::version`].
283    header_version: PdfVersion,
284    /// Merged, `/Size`-filtered cross-reference table.
285    xref: XrefTable,
286    /// The newest trailer dictionary.
287    trailer: Dict,
288    /// Every in-use object, parsed. Keyed by full `(num, generation)`
289    /// identity.
290    objects: HashMap<ObjId, IndirectObject>,
291    /// The byte offset this file's own `startxref` names — the value an
292    /// appended update's `/Prev` must carry (§7.5.6). Retained at load
293    /// because it is not recoverable from the merged view.
294    base_startxref: u64,
295    /// The physical form of the newest cross-reference section, so a
296    /// save can match it instead of normalizing (R33).
297    section_shape: SectionShape,
298    /// Annex F linearization state, detected at load (R36).
299    linearization: Linearization,
300    /// Highest object number the cross-reference chain mentions, before
301    /// the `/Size` filter — the number a writer must allocate above.
302    highest_object_number: u32,
303    /// How many cross-reference entries `/Size` suppressed.
304    suppressed_by_size: usize,
305    /// Which objects a hybrid-reference file hides, and whether pdfcer could
306    /// tell (`Pass 281.0`). Default (empty, readable) for every non-hybrid
307    /// file and for a recovered base, where the concept does not apply.
308    hybrid: crate::xref::HybridPartition,
309    /// Every contradiction pdfcer met while loading and decided rather than
310    /// refused (`Pass 283.0`). Empty for a file that says nothing twice.
311    anomalies: Vec<LoadAnomaly>,
312    /// `Some` when this document was loaded via **cross-reference
313    /// recovery** (decision 013): the stored xref could not be parsed and
314    /// the table was rebuilt by scanning. The writer reads this to force a
315    /// full rewrite and refuse incremental save (the recovered-base rule);
316    /// the CLI/GUI read it to disclose. `None` for every cleanly-loaded
317    /// file — recovery lives entirely on the strict-load error path, so a
318    /// clean file's flow never sets it.
319    recovery: Option<RecoveryReport>,
320    /// `Some` when this document was loaded from an **encrypted** file and
321    /// successfully decrypted (§7.6, [`crate::crypto`]).
322    ///
323    /// Holds the configuration, which password opened it, and — privately —
324    /// what an incremental save needs to append under the same handler: the
325    /// file key and the source bytes as they were before decryption.
326    encryption: Option<DocumentEncryption>,
327}
328
329/// What a successfully-decrypted document was protected with.
330///
331/// Reported so the shells can tell the operator the document is encrypted,
332/// which cipher, and what the author's permissions ask for. It is a
333/// **disclosure**, not a gate: §7.6.3.1 states plainly that "there is nothing
334/// inherent in PDF encryption that enforces the document permissions", so
335/// anywhere pdfcer chooses to act on a permission bit it must say so (rule 4).
336/// What decrypts a document on load: a password to authenticate, or an
337/// already-recovered key carried from the document a save descends from.
338#[derive(Clone, Copy)]
339enum Credential<'a> {
340    Password(Option<&'a [u8]>),
341    Reuse(&'a DocumentEncryption),
342}
343
344#[derive(Debug, Clone)]
345pub struct DocumentEncryption {
346    /// The parsed `/Encrypt` dictionary.
347    pub config: crate::crypto::EncryptionConfig,
348    /// Which password opened it. [`AuthKind::EmptyUser`] is the no-prompt
349    /// case — the document had an empty user password, which every
350    /// conforming reader tries silently before prompting.
351    ///
352    /// [`AuthKind::EmptyUser`]: crate::crypto::AuthKind::EmptyUser
353    pub auth: crate::crypto::AuthKind,
354    /// The Algorithm 3.13 `/Perms` verdict — **the only integrity check in
355    /// PDF encryption**, and a `should`, not a `shall`.
356    ///
357    /// [`PermsCheck::NotApplicable`] for every `/R` ≤ 4 document, where the
358    /// entry does not exist. That is the *ordinary* answer, not a failed
359    /// check, and a front end must not render it as one.
360    ///
361    /// # Why it is here rather than acted on
362    ///
363    /// `/Perms` holds an encrypted copy of `/P` and `/EncryptMetadata`. The
364    /// plaintext copies sit in the `/Encrypt` dictionary where anyone can edit
365    /// them, with no integrity protection anywhere else in clause 7.6
366    /// (**N7**). So a disagreement is the one signal PDF gives that a
367    /// document's stated permissions are not the ones its encryptor recorded —
368    /// and no clause says what to do about it.
369    ///
370    /// pdfcer reports it and **prefers neither value**:
371    /// [`EncryptionConfig::permissions`] keeps returning the dictionary's
372    /// `/P`, because that is what the file declares and what every other
373    /// viewer shows, and this field carries the disagreement beside it.
374    /// Silently substituting the decrypted copy would be pdfcer deciding, on an
375    /// inference, what the operator is told — the exact shape project rule 4
376    /// forbids. Refusing the document would reject files nothing else objects
377    /// to, on the strength of a check the standard declines to require. See
378    /// [`PermsCheck`]'s own docs (**T27**).
379    ///
380    /// [`PermsCheck`]: crate::crypto::PermsCheck
381    /// [`PermsCheck::NotApplicable`]: crate::crypto::PermsCheck::NotApplicable
382    /// [`EncryptionConfig::permissions`]: crate::crypto::EncryptionConfig::permissions
383    pub perms: crate::crypto::PermsCheck,
384    /// The recovered file key. Private: [`crate::writer::save_incremental`]
385    /// encrypts appended objects with it (§7.6.2), so a save needs no second
386    /// password prompt. Its `Debug` never prints the key.
387    key: crate::crypto::FileKey,
388    /// The object number of an indirect `/Encrypt` dictionary (`None` when it
389    /// is direct in the trailer).
390    encrypt_dict_id: Option<u32>,
391    /// The file's bytes before decryption. Decryption rewrites stream data in
392    /// the document's buffer, so an append must start from these instead.
393    ciphertext: std::sync::Arc<[u8]>,
394    /// Whether an append may keep an RC4 handler; see [`Document::set_rc4_append`].
395    rc4_append: crate::writer::Rc4Append,
396}
397
398impl DocumentEncryption {
399    /// The recovered file key an append encrypts under.
400    pub(crate) fn file_key(&self) -> &crate::crypto::FileKey {
401        &self.key
402    }
403
404    /// An indirect `/Encrypt` dictionary's object number; an append leaves it in clear.
405    pub(crate) fn encrypt_dict_id(&self) -> Option<u32> {
406        self.encrypt_dict_id
407    }
408
409    /// The source bytes as stored on disk — ciphertext wherever the file
410    /// encrypted something.
411    pub(crate) fn ciphertext(&self) -> &[u8] {
412        &self.ciphertext
413    }
414
415    /// Whether an incremental save can append under this document's key.
416    /// `false` for an RC4 document unless [`Document::set_rc4_append`] opted
417    /// in: pdfcer never chooses RC4 (decision 190), so
418    /// [`crate::writer::save_incremental`] refuses it with
419    /// [`crate::writer::WriteError::Rc4AppendRefused`].
420    #[must_use]
421    pub fn appendable(&self) -> bool {
422        !self.uses_rc4() || self.rc4_append == crate::writer::Rc4Append::Preserve
423    }
424
425    /// Whether strings or streams are encrypted with RC4 (`/V` 1–2, or a
426    /// `/V` 4 crypt filter with `/CFM /V2`; ISO 32000-2 §7.6.2).
427    #[must_use]
428    pub fn uses_rc4(&self) -> bool {
429        use crate::crypto::Cipher;
430        [self.key.string_cipher(), self.key.stream_cipher()].contains(&Cipher::Rc4)
431    }
432
433    /// The RC4 append policy in force; [`Rc4Append::Refuse`] unless
434    /// [`Document::set_rc4_append`] changed it.
435    ///
436    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
437    #[must_use]
438    pub fn rc4_append(&self) -> crate::writer::Rc4Append {
439        self.rc4_append
440    }
441
442    /// Whether `bit` lets the operator who opened the document do what it
443    /// governs (ISO 32000-2 Table 22). The owner password grants everything;
444    /// a user (or empty-user) open is held to the declared `/P`. A bit the
445    /// document's revision does not define is not granted.
446    #[must_use]
447    pub fn grants(&self, bit: crate::crypto::PermissionBit) -> bool {
448        self.auth == crate::crypto::AuthKind::Owner
449            || self.config.permissions().granted(bit) == Some(true)
450    }
451}
452
453impl Document {
454    /// Load a document from a file on disk.
455    ///
456    /// # Errors
457    ///
458    /// [`DocError`] — I/O, header, xref, or object-level failure; every
459    /// variant carries the offending offset/object for diagnostics.
460    pub fn load(path: &Path) -> Result<Self, DocError> {
461        Self::from_bytes(std::fs::read(path)?)
462    }
463
464    /// Load a document from disk, supplying a password for an encrypted file.
465    ///
466    /// `password` is `None` to mean "no password known" — which is **not** the
467    /// same as an empty password. §7.6.3.1 requires a reader to try the empty
468    /// user password first and silently in *either* case, so `None` still
469    /// opens a permissions-only document with no prompt; what `None` means is
470    /// that if that fails, there is nothing else to try and the load returns
471    /// [`DocError::PasswordRequired`].
472    ///
473    /// Either the user or the owner password opens the document
474    /// (§7.6.3.1). Which one it was is reported by
475    /// [`Document::encryption`].
476    ///
477    /// # Errors
478    ///
479    /// [`DocError`] — as [`Document::load`], plus [`DocError::Encryption`] for
480    /// a configuration pdfcer will not decrypt and
481    /// [`DocError::PasswordRequired`] when no supplied password authenticated.
482    pub fn load_with_password(path: &Path, password: Option<&[u8]>) -> Result<Self, DocError> {
483        Self::from_bytes_with_password(std::fs::read(path)?, password)
484    }
485
486    /// Load a document from disk under explicit [`LoadOptions`] — the
487    /// path-shaped twin of [`Document::from_bytes_with_options`].
488    ///
489    /// # Why this exists as well as the bytes form
490    ///
491    /// `Pass 283.0` gave the loader a tolerant posture and gave the operator
492    /// the other choice, but shipped the choice on the **bytes** entry point
493    /// only. Every shell that opens a document opens a **file** — the GUI's
494    /// open-file action, the CLI's path argument — so taking the alternative
495    /// reading meant re-implementing [`Document::load`]'s `std::fs::read`
496    /// at each call site. An intervention route the intended caller can only
497    /// reach by rewriting the route beside it is not offered, it is merely
498    /// present.
499    ///
500    /// The operator's ruling this discharges: *"if the user can intervene in
501    /// a decision that should always be an option along with them not having
502    /// to intervene."* Re-loading the same path under
503    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]
504    /// is the whole intervention; see [`Document::load_anomalies`] for how a
505    /// shell learns there was a decision to intervene in.
506    ///
507    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]: LoadOptions::with_duplicate_keys
508    ///
509    /// # Examples
510    ///
511    /// ```no_run
512    /// use std::path::Path;
513    /// use pdfcer_model::document::{Document, LoadOptions};
514    /// use pdfcer_model::parser::DuplicateKeyPolicy;
515    ///
516    /// let path = Path::new("drawing.pdf");
517    /// let doc = Document::load(path)?;
518    /// if !doc.load_anomalies().is_empty() {
519    ///     // Offer the operator the other reading; nothing forces them to take it.
520    ///     let other = Document::load_with_options(
521    ///         path,
522    ///         None,
523    ///         LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst),
524    ///     )?;
525    ///     let _ = other;
526    /// }
527    /// # Ok::<(), pdfcer_model::document::DocError>(())
528    /// ```
529    ///
530    /// # Errors
531    ///
532    /// [`DocError`] — as [`Document::load_with_password`]. Under
533    /// [`LoadOptions::strict()`] this refuses every malformation `Pass 283.0`
534    /// taught the loader to decide.
535    pub fn load_with_options(
536        path: &Path,
537        password: Option<&[u8]>,
538        options: LoadOptions,
539    ) -> Result<Self, DocError> {
540        Self::from_bytes_with_options(std::fs::read(path)?, password, options)
541    }
542
543    /// Load a document from bytes (takes ownership — the buffer is
544    /// retained for the document's lifetime; see module docs).
545    ///
546    /// # Errors
547    ///
548    /// [`DocError`] — see [`Document::load`].
549    pub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError> {
550        Self::from_bytes_with_password(buf, None)
551    }
552
553    /// Load a COS-family file whose header is NOT `%PDF-` — a `%PPKLITE-`
554    /// address book or a `%FDF-` file — reusing the exact tokenizer, classic-
555    /// xref parser and object assembly the strict PDF path uses (`Pass 10.2`).
556    ///
557    /// `markers` are the accepted first-line tokens (e.g. `[b"%PPKLITE-"]`).
558    /// Only the STRICT path runs: there is no rebuild-by-scan recovery (these
559    /// files are written by Acrobat and well-formed; a malformed one is an
560    /// error, not a file to guess at) and no password (a trust store carries no
561    /// `/Encrypt`). The result is an ordinary [`Document`] — `get`, `trailer`,
562    /// `resolve` and the [`crate::graph::ObjectGraph`] impl all work — so a
563    /// reader (e.g. [`crate::trust_store`]) walks it with the normal object
564    /// model instead of a bespoke parser.
565    ///
566    /// # Errors
567    ///
568    /// [`DocError::Header`] if none of `markers` matches; [`DocError::Xref`] if
569    /// the cross-reference chain does not parse; other [`DocError`] object-level
570    /// failures as [`from_bytes_with_password`](Self::from_bytes_with_password).
571    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
572    pub fn from_cos_bytes(buf: Vec<u8>, markers: &[&[u8]]) -> Result<Self, DocError> {
573        let header_version = crate::probe_cos_header(&buf, markers).map_err(DocError::Header)?;
574        let loaded = xref::load_xref_chain(&buf).map_err(DocError::Xref)?;
575        let hybrid = loaded.hybrid_partition();
576        Self::assemble(
577            buf,
578            header_version,
579            loaded.table,
580            loaded.trailer,
581            loaded.startxref,
582            loaded.newest_shape,
583            loaded.highest_object_number,
584            loaded.suppressed_by_size,
585            hybrid,
586            None,
587            Credential::Password(None),
588            LoadOptions::default(),
589        )
590    }
591
592    /// Load a document from bytes, supplying a password for an encrypted file.
593    ///
594    /// See [`Document::load_with_password`] for what `None` means (it is not
595    /// the empty password).
596    ///
597    /// # Errors
598    ///
599    /// [`DocError`] — see [`Document::load_with_password`].
600    pub fn from_bytes_with_password(
601        buf: Vec<u8>,
602        password: Option<&[u8]>,
603    ) -> Result<Self, DocError> {
604        Self::from_bytes_with_options(buf, password, LoadOptions::default())
605    }
606
607    /// Load a document, choosing how its self-contradictions are decided
608    /// (`Pass 283.0`).
609    ///
610    /// The intervention half of the operator's ruling: a shell that has shown
611    /// the operator what pdfcer chose (via [`Document::load_anomalies`]) and
612    /// been told to take the other value re-loads the same bytes through here.
613    /// Everything else is identical to [`Document::from_bytes_with_password`],
614    /// which is this with the defaults.
615    ///
616    /// # Errors
617    ///
618    /// [`DocError`] — see [`Document::load_with_password`].
619    pub fn from_bytes_with_options(
620        buf: Vec<u8>,
621        password: Option<&[u8]>,
622        options: LoadOptions,
623    ) -> Result<Self, DocError> {
624        Self::from_bytes_inner(buf, Credential::Password(password), options)
625    }
626
627    /// Load `buf` — bytes produced by saving this document incrementally —
628    /// decrypting under this document's file key and access, with no
629    /// password. An unencrypted document loads `buf` like
630    /// [`Document::from_bytes`].
631    ///
632    /// The contract is that `buf` keeps this document's `/Encrypt` and
633    /// `/ID[0]` (an incremental save carries both, ISO 32000-2 §7.6.3); bytes
634    /// from anywhere else decrypt to noise.
635    ///
636    /// # Errors
637    ///
638    /// [`DocError`] — see [`Document::load`].
639    pub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError> {
640        let credential = match &self.encryption {
641            Some(e) => Credential::Reuse(e),
642            None => Credential::Password(None),
643        };
644        Self::from_bytes_inner(buf, credential, LoadOptions::default())
645    }
646
647    fn from_bytes_inner(
648        buf: Vec<u8>,
649        credential: Credential<'_>,
650        options: LoadOptions,
651    ) -> Result<Self, DocError> {
652        // 1. Header (§7.5.2 via the Pass 0 probe).
653        match crate::probe_header(&buf) {
654            // Header OK: try the strict §7.5.5 cross-reference load.
655            Ok(header_version) => match xref::load_xref_chain(&buf) {
656                Ok(loaded) => {
657                    let hybrid = loaded.hybrid_partition();
658                    Self::assemble(
659                        buf,
660                        header_version,
661                        loaded.table,
662                        loaded.trailer,
663                        loaded.startxref,
664                        loaded.newest_shape,
665                        loaded.highest_object_number,
666                        loaded.suppressed_by_size,
667                        hybrid,
668                        None,
669                        credential,
670                        options,
671                    )
672                }
673                // The strict path failed. Decision 013: attempt
674                // rebuild-by-scan recovery, but ONLY on the specific
675                // failure kinds that mean the cross-reference machinery is
676                // unparseable — never on the deliberate `/Encrypt`
677                // capability gap, and never on a future unknown kind
678                // (`recovery_reason_for` returns `None` for both).
679                Err(e) => match recover::recovery_reason_for(&e.kind) {
680                    None => Err(DocError::Xref(e)),
681                    Some(reason) => match recover::recover(&buf, reason) {
682                        Ok(rec) => Self::assemble_recovered(buf, Some(header_version), rec),
683                        // A broken-xref-AND-encrypted file fails clean for
684                        // the RIGHT reason (§7.6), not as a recovery error.
685                        Err(recover::RecoverError::Encrypted) => Err(DocError::Xref(XrefError {
686                            offset: 0,
687                            kind: XrefErrorKind::EncryptionUnsupported,
688                        })),
689                        Err(other) => Err(DocError::Recovery(other)),
690                    },
691                },
692            },
693            // Header probe failed ("not a PDF", offset-start, leading junk).
694            // Rebuild-by-scan is header-independent (absolute offsets), so
695            // it also opens an offset-start file (decision 007 §10 item 6).
696            // Attempt recovery, but succeed ONLY if the scan finds objects
697            // AND a `/Catalog`; otherwise the ORIGINAL header error stands
698            // ("not a PDF").
699            Err(header_err) => match recover::recover(&buf, recover::RecoveryReason::MissingHeader)
700            {
701                Ok(rec) => Self::assemble_recovered(buf, None, rec),
702                Err(_) => Err(DocError::Header(header_err)),
703            },
704        }
705    }
706
707    /// Assemble a [`Document`] from a cross-reference view (table plus
708    /// trailer plus physical facts), running the §7.5.7 two-phase eager
709    /// parse. Shared by the strict load path and the recovery path so the
710    /// object-parse, object-stream resolution, and linearization detection
711    /// are written exactly once.
712    ///
713    /// `recovery` is `Some` only on the rebuild-by-scan path; the writer
714    /// and front ends read it (decision 013).
715    #[allow(clippy::too_many_arguments)] // a private assembly seam; the
716    // alternative (a builder struct) buys nothing for two call sites.
717    fn assemble(
718        mut buf: Vec<u8>,
719        header_version: PdfVersion,
720        table: XrefTable,
721        trailer: Dict,
722        base_startxref: u64,
723        section_shape: SectionShape,
724        highest_object_number: u32,
725        suppressed_by_size: usize,
726        hybrid: crate::xref::HybridPartition,
727        recovery: Option<RecoveryReport>,
728        credential: Credential<'_>,
729        options: LoadOptions,
730    ) -> Result<Self, DocError> {
731        // Phase 1. Eagerly parse every file-level in-use object. Strict on
732        // the clean path; on the recovery path the SAME `/Length`-vs-
733        // `endstream` leniency `crate::recover`'s confirmation step used
734        // must apply here too, or an object recovery accepted would be
735        // rejected on re-parse and cost the whole document (the exact
736        // failure this policy exists to close). Free entries resolve to
737        // null, not to bytes; type-2 entries wait for phase 2 (module docs).
738        // THE CLEAN PATH IS LENIENT TOO SINCE `Pass 283.0`, and the
739        // comment above used to say the opposite.
740        //
741        // `RecoverFromEndstream` re-derives an extent ONLY when the stored
742        // `/Length` cannot be used — absent, non-integer, unresolvable, past
743        // the end of the buffer, or not landing on `endstream`. A usable
744        // `/Length` is still believed, so this changes behaviour for exactly
745        // one class of file: the ones that previously FAILED.
746        //
747        // The operator's ruling: *"we should be making pdfcer so that it opens
748        // pdfs that have errors, and have a way that it manages those errors
749        // such that they aren't fatal."* Losing a 46 KB drawing over a
750        // `/Metadata` stream that omits `/Length` — which is what happened, on
751        // the very next object after the duplicate key that motivated this
752        // Pass — is the failure that ruling names.
753        //
754        // Every recovery is recorded as a `LoadAnomaly` and disclosed. A
755        // caller that wants the old refusal has `LoadOptions`.
756        let length_policy = if recovery.is_some() {
757            StreamLengthPolicy::RecoverFromEndstream
758        } else {
759            options.stream_lengths
760        };
761        // The missing-`endobj` leniency travels with the length leniency,
762        // and for exactly the same stated reason: an object `recover`'s
763        // confirmation step accepted must not be rejected on re-parse
764        // here, or the recovery costs the whole document.
765        let terminator_policy = if recovery.is_some() {
766            TerminatorPolicy::RecoverAtNextHeader
767        } else {
768            options.terminators
769        };
770        let mut anomalies: Vec<LoadAnomaly> = Vec::new();
771        let mut objects: HashMap<ObjId, IndirectObject> = HashMap::new();
772        let mut compressed: Vec<(u32, u32, u32)> = Vec::new();
773        for (num, entry) in table.iter() {
774            match entry {
775                XrefEntry::InUse { offset, generation } => {
776                    let id = ObjId::new(num, generation);
777                    let parsed = parse_object_at(
778                        &buf,
779                        &table,
780                        offset,
781                        length_policy,
782                        terminator_policy,
783                        // THE LOADER OPTS IN; the parser's own default stays
784                        // strict. A duplicate key is a malformed ENTRY in an
785                        // otherwise sound file, and refusing the object cost an
786                        // operator a whole 46 KB drawing every other reader
787                        // opens. Which value wins is the caller's to override
788                        // (`LoadOptions`), and either way it is recorded.
789                        options.duplicate_keys,
790                    );
791                    // ONE UNREADABLE OBJECT NO LONGER COSTS THE DOCUMENT.
792                    //
793                    // §7.3.10 already says what a reference to an object that
794                    // is not there means: it "shall be treated as a reference
795                    // to the null object", and "shall not be considered an
796                    // error". An object whose bytes will not parse IS
797                    // undefined as far as every consumer is concerned, so
798                    // omitting it produces a document the standard describes
799                    // rather than one pdfcer invented.
800                    //
801                    // Under `strict` this is still the refusal it always was.
802                    let (io, repairs) = match parsed {
803                        Ok(pair) => pair,
804                        Err(source) => {
805                            if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
806                                return Err(DocError::BadObject { id, offset, source });
807                            }
808                            anomalies.push(LoadAnomaly::ObjectUnreadable {
809                                object: id,
810                                reason: source.to_string(),
811                            });
812                            continue;
813                        }
814                    };
815                    if repairs.stream_lengths > 0 {
816                        anomalies.push(LoadAnomaly::StreamLengthRecovered { object: id });
817                    }
818                    if repairs.missing_endobj > 0 {
819                        anomalies.push(LoadAnomaly::MissingEndobjRecovered { object: id });
820                    }
821                    anomalies.extend(repairs.duplicate_keys.into_iter().map(|rec| {
822                        LoadAnomaly::DuplicateDictKey {
823                            object: Some(id),
824                            key: rec.key,
825                            kept: rec.kept,
826                            discarded: rec.discarded,
827                        }
828                    }));
829                    if io.id != id {
830                        // The table and the body disagree about which object
831                        // lives here. Neither is more authoritative than the
832                        // other, so pdfcer does not pick: the object the table
833                        // promised is treated as undefined (§7.3.10), which is
834                        // the same answer as "the table pointed at nothing".
835                        if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
836                            return Err(DocError::ObjectIdMismatch {
837                                expected: id,
838                                found: io.id,
839                                offset,
840                            });
841                        }
842                        anomalies.push(LoadAnomaly::ObjectUnreadable {
843                            object: id,
844                            reason: format!(
845                                "the cross-reference table points at offset {offset}, where the file declares {} instead",
846                                io.id
847                            ),
848                        });
849                        continue;
850                    }
851                    objects.insert(id, io);
852                }
853                XrefEntry::InStream { stream_num, index } => {
854                    compressed.push((num, stream_num, index));
855                }
856                // `XrefEntry` is #[non_exhaustive] (§7.5.8.3 reserves
857                // future types); an entry kind this build does not know
858                // resolves to null, which is exactly what the spec
859                // prescribes for unknown types.
860                _ => {}
861            }
862        }
863
864        // Phase 1.5. Decrypt (7.6), if the trailer says so.
865        //
866        // The position of this step is load-bearing, not stylistic. It runs
867        // AFTER phase 1 -- which needs only spans and `/Length`, both of which
868        // are plaintext integers -- and BEFORE phase 2, which inflates object
869        // streams. Decrypting here makes every object stream's data plaintext
870        // by the time phase 2 reads it, and the objects phase 2 parses out of
871        // that data are then correctly left alone: strings inside an object
872        // stream are NOT separately encrypted (TRAP T4). Moving this after
873        // phase 2 would re-apply Algorithm 1 per contained object and corrupt
874        // every string in every modern file.
875        let encryption = Self::decrypt_in_place(&mut buf, &trailer, &mut objects, credential)?;
876
877        // Phase 2. Resolve compressed objects through their containers,
878        // decoding each container at most once. Deterministic order so
879        // that a file with several broken containers always reports the
880        // same one (`iter()` over a HashMap is not ordered).
881        compressed.sort_unstable();
882        Self::load_compressed(
883            &buf,
884            &compressed,
885            &mut objects,
886            options.unreadable_objects,
887            &mut anomalies,
888        )?;
889
890        // Annex F detection runs on the raw buffer and needs no xref
891        // (F.3.3: the parameter dictionary's values are all direct and
892        // it is unreferenced from the document graph), but it is done
893        // here rather than in `load_xref_chain` because it is a
894        // property of the *file*, not of its cross-reference machinery.
895        let linearization = linearization::detect(&buf);
896
897        Ok(Self {
898            buf,
899            header_version,
900            xref: table,
901            trailer,
902            objects,
903            base_startxref,
904            section_shape,
905            linearization,
906            highest_object_number,
907            suppressed_by_size,
908            hybrid,
909            anomalies,
910            recovery,
911            encryption,
912        })
913    }
914
915    /// Authenticate and decrypt the loaded objects in place (7.6).
916    ///
917    /// Returns `Ok(None)` for an unencrypted document -- the overwhelmingly
918    /// common case, and a single `contains_key` away.
919    ///
920    /// # What "in place" means, and its consequence for saving
921    ///
922    /// **Stream data is decrypted in the retained buffer.** RC4 is a stream
923    /// cipher and preserves length exactly, so the plaintext fits precisely
924    /// where the ciphertext was and every span, `/Length` and provenance
925    /// record stays true. That is what lets this increment land without
926    /// touching [`Stream`](crate::object::Stream), which holds a span rather
927    /// than owning bytes. AES will not have that property -- its plaintext is
928    /// shorter than its ciphertext -- so the AES increment has to solve a
929    /// problem this one did not.
930    ///
931    /// **Strings are decrypted in the parsed objects**, because
932    /// [`Object::String`] owns its bytes and a decrypted string cannot
933    /// generally be re-escaped into the same number of source bytes.
934    ///
935    /// So after this runs, the buffer and the parsed objects **disagree**:
936    /// streams are plaintext in both, strings are plaintext only in the
937    /// objects. That is why a full rewrite refuses a decrypted document (its
938    /// verbatim copies would put plaintext under `/Encrypt`), and why the
939    /// pre-decryption bytes are kept: an incremental save appends to them,
940    /// encrypting only what it writes.
941    ///
942    /// # Errors
943    ///
944    /// [`DocError::Encryption`] for a configuration pdfcer will not decrypt;
945    /// [`DocError::PasswordRequired`] when nothing authenticated.
946    fn decrypt_in_place(
947        buf: &mut [u8],
948        trailer: &Dict,
949        objects: &mut HashMap<ObjId, IndirectObject>,
950        credential: Credential<'_>,
951    ) -> Result<Option<DocumentEncryption>, DocError> {
952        use crate::crypto::{EncryptionConfig, EncryptionUnsupported, apply};
953
954        let Some(entry) = trailer.get(b"Encrypt") else {
955            return Ok(None);
956        };
957
958        // The `/Encrypt` dictionary is usually direct in the trailer, but may
959        // be indirect. If it is, its object number must be remembered: its
960        // `/O` and `/U` are the INPUTS to the key derivation, so decrypting
961        // them with a key derived from themselves would authenticate
962        // successfully and then produce a document of noise (E2/E3).
963        let (encrypt_dict, encrypt_dict_id) = match entry {
964            Object::Dict(d) => (d.clone(), None),
965            Object::Reference(id) => match objects.get(id).map(|o| &o.value) {
966                Some(Object::Dict(d)) => (d.clone(), Some(id.num)),
967                _ => {
968                    return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
969                        "/Encrypt names an object that is not a dictionary",
970                    )));
971                }
972            },
973            _ => {
974                return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
975                    "/Encrypt is neither a dictionary nor a reference",
976                )));
977            }
978        };
979
980        // Resolution for indirect `/O`, `/U` and `/CF` entries. Snapshotting
981        // the values a closure needs is simpler than fighting the borrow
982        // checker over `objects`, which is about to be mutated.
983        let snapshot: HashMap<ObjId, Object> = objects
984            .iter()
985            .map(|(id, io)| (*id, io.value.clone()))
986            .collect();
987        let resolve = move |id: ObjId| snapshot.get(&id).cloned();
988
989        let config = EncryptionConfig::parse(&encrypt_dict, &resolve)?;
990
991        // Algorithm 2 step (e) and Algorithm 5 step (c) hash `/ID[0]`.
992        // 7.6.1 E1: trailer `/ID` strings are never encrypted and are direct
993        // objects, so this reads them as-is. A file with no `/ID` hashes
994        // nothing there, which an empty slice expresses exactly -- the
995        // algorithm has no branch for "no ID" (SPEC AMBIGUITY A4).
996        let id0: Vec<u8> = match trailer.get(b"ID") {
997            Some(Object::Array(items)) => match items.first() {
998                Some(Object::String(s)) => s.clone(),
999                _ => Vec::new(),
1000            },
1001            _ => Vec::new(),
1002        };
1003
1004        let authenticated = match credential {
1005            Credential::Password(password) => config.authenticate(password, &id0),
1006            Credential::Reuse(e) => Some((e.key.clone(), e.auth)),
1007        };
1008        let Some((key, auth)) = authenticated else {
1009            // A failed authentication is normally just a wrong password. At
1010            // `/R` 5 with a non-ASCII password it is ambiguous, because the
1011            // SASLprep step pdfcer does not implement may have been the thing
1012            // that mattered -- and telling the operator "wrong password" for a
1013            // password that was right sends them to re-check the one thing
1014            // that is not the problem.
1015            return Err(match credential {
1016                Credential::Password(Some(pw)) if config.password_may_need_normalisation(pw) => {
1017                    DocError::PasswordRequiresNormalisation
1018                }
1019                // At /R 6 a failure is not unambiguously "wrong password": the
1020                // A13 loop-exit ambiguity can reject a correct password for a
1021                // file written under the other reading. Name it (Pass 5.4).
1022                _ if config.revision == 6 => DocError::PasswordRequiredR6,
1023                _ => DocError::PasswordRequired,
1024            });
1025        };
1026
1027        // Algorithm 3.13, run once, immediately after the key is recovered and
1028        // before a single object is decrypted -- the check needs nothing but
1029        // the key, and running it here means the verdict is available to the
1030        // shells for the whole life of the document rather than being
1031        // recomputed on demand from state they would have to keep.
1032        let perms = config.check_perms(&key);
1033        let ciphertext: std::sync::Arc<[u8]> = std::sync::Arc::from(&*buf);
1034
1035        // Decrypt every file-level object. Order within the map does not
1036        // matter: each object's key depends only on its own identity
1037        // (Algorithm 1), never on another object's contents.
1038        for (id, obj) in objects.iter_mut() {
1039            if apply::skip(obj, encrypt_dict_id, config.encrypt_metadata).is_some() {
1040                continue;
1041            }
1042            if key.streams_encrypted()
1043                && let Object::Stream(stream) = &mut obj.value
1044            {
1045                let span = stream.data_span;
1046                let end = span.start.saturating_add(span.len);
1047                // Checked access, not an in-bounds proof: `data_span` comes
1048                // from a `/Length` in an untrusted file, and a stream whose
1049                // declared length runs past the buffer is a real thing a
1050                // malformed (or deliberately hostile) document contains. A
1051                // span that does not fit is left alone -- the object then
1052                // fails to decode later, with an error about the object, which
1053                // is the honest place for it.
1054                if let Some(cipher_text) = buf.get(span.start..end) {
1055                    let plain = key.decrypt_stream(*id, cipher_text);
1056                    // ** The plaintext may be SHORTER than the ciphertext. **
1057                    //
1058                    // Increment 1 asserted the opposite here -- `RC4 must
1059                    // preserve length` -- and guarded the copy on
1060                    // `plain.len() == span.len`. That was true and correct for
1061                    // RC4, and it is the R186 shape: a guard keyed on a
1062                    // property that quietly stopped holding. Under `/AESV2`
1063                    // the ciphertext carries a 16-byte IV plus padding (T5), so
1064                    // the equality is ALWAYS false, the copy would ALWAYS be
1065                    // skipped, and every stream in an AES document would stay
1066                    // ciphertext -- with no test red and no error raised.
1067                    //
1068                    // Shorter is the easy direction: the plaintext still fits
1069                    // at `span.start`, so only the recorded length changes.
1070                    // Nothing re-reads the dictionary's `/Length` after parse
1071                    // (it is consumed once, at parser.rs's stream read), and
1072                    // `data_span` is what every downstream reader actually
1073                    // slices -- content.rs, attachments.rs, the object-stream
1074                    // path, edit.rs. So shortening the span is sufficient and
1075                    // `Stream` needs no new field.
1076                    if plain.len() <= span.len
1077                        && let Some(slot) = buf.get_mut(span.start..span.start + plain.len())
1078                    {
1079                        slot.copy_from_slice(&plain);
1080                        stream.data_span.len = plain.len();
1081                    }
1082                    // A plaintext LONGER than its ciphertext is impossible for
1083                    // both implemented ciphers, so there is no branch for it:
1084                    // it would have to overwrite the following object, and
1085                    // silently declining is the only safe response.
1086                }
1087            }
1088            if key.strings_encrypted() {
1089                apply::decrypt_strings(&mut obj.value, *id, &key);
1090            }
1091        }
1092
1093        Ok(Some(DocumentEncryption {
1094            config,
1095            auth,
1096            perms,
1097            key,
1098            encrypt_dict_id,
1099            ciphertext,
1100            rc4_append: crate::writer::Rc4Append::Refuse,
1101        }))
1102    }
1103
1104    /// How this document was encrypted, if it was -- `None` for a plain file.
1105    ///
1106    /// A **disclosure**, not a gate. See [`DocumentEncryption`].
1107    #[must_use]
1108    pub fn encryption(&self) -> Option<&DocumentEncryption> {
1109        self.encryption.as_ref()
1110    }
1111
1112    /// Choose whether an incremental save of an RC4-encrypted document keeps
1113    /// its RC4 handler ([`Rc4Append::Preserve`]) or is refused
1114    /// ([`Rc4Append::Refuse`], the default). No effect on a plain or AES
1115    /// document.
1116    ///
1117    /// Preserve keeps existing signatures valid, at a cost the save reports
1118    /// in [`SaveReport::rc4_keystream_reused`]: an edited object rewritten
1119    /// under its old number and generation is encrypted with the same RC4
1120    /// keystream as its previous revision. Decision 190.
1121    ///
1122    /// [`Rc4Append::Preserve`]: crate::writer::Rc4Append::Preserve
1123    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
1124    /// [`SaveReport::rc4_keystream_reused`]: crate::writer::SaveReport::rc4_keystream_reused
1125    pub fn set_rc4_append(&mut self, policy: crate::writer::Rc4Append) {
1126        if let Some(enc) = self.encryption.as_mut() {
1127            enc.rc4_append = policy;
1128        }
1129    }
1130
1131    /// Drop this document's encryption, in memory, without re-parsing.
1132    ///
1133    /// Load already decrypted every object's strings (in the parsed values) and
1134    /// every stream's data (in the retained buffer) — see
1135    /// [`Document::decrypt_in_place`]. So a document that WAS encrypted is,
1136    /// object-for-object, already a plaintext document; the only things still
1137    /// asserting encryption are the [`encryption`](Self::encryption) field and
1138    /// the trailer's `/Encrypt` reference. Clearing both is all that
1139    /// "remove encryption" needs at the model level — the writer then emits
1140    /// plaintext because the bytes it re-serialises already are.
1141    ///
1142    /// `Pass 5.4`: used by `pdfcer_core::EditSession::remove_encryption` and
1143    /// `pdfcer_core::EditSession::set_permissions` (which re-keys, so it first
1144    /// clears the old state, then the writer freshly encrypts).
1145    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
1146    pub fn clear_encryption(&mut self) {
1147        self.encryption = None;
1148        self.trailer.remove(b"Encrypt");
1149    }
1150
1151    /// Assemble a [`Document`] from a [`recover::RecoveredXref`].
1152    ///
1153    /// The recovered document is fixed into the shape a save must take
1154    /// (decision 013 §3.3.4, the recovered-base rule): its section shape is
1155    /// a plain classic table (`xref_stm: None`) so a full rewrite emits a
1156    /// fresh valid classic cross-reference, and `base_startxref` is 0
1157    /// because incremental append onto a broken base is refused by the
1158    /// writer. `/Size` suppression is 0 — recovery's synthesized `/Size`
1159    /// already covers every recovered object.
1160    ///
1161    /// `header_override` is the header-probe version when the header parsed
1162    /// (the xref-failure path); `None` on the header-failure path, where
1163    /// the recovery's own whole-buffer version scan is authoritative.
1164    fn assemble_recovered(
1165        buf: Vec<u8>,
1166        header_override: Option<PdfVersion>,
1167        rec: recover::RecoveredXref,
1168    ) -> Result<Self, DocError> {
1169        let version = header_override.unwrap_or(rec.version);
1170        Self::assemble(
1171            buf,
1172            version,
1173            rec.table,
1174            rec.trailer,
1175            0,
1176            SectionShape::Classic { xref_stm: None },
1177            rec.highest_object_number,
1178            0,
1179            // A recovered base is rebuilt by scanning object headers, and the
1180            // scan sees every object equally — the §7.5.8.4 partition is not
1181            // recoverable from it, and `SectionShape::Classic { xref_stm: None }`
1182            // above already says the output is not hybrid. Default, not a
1183            // guess.
1184            crate::xref::HybridPartition::default(),
1185            Some(rec.report),
1186            // The recovery path never carries a password: `recover` refuses an
1187            // encrypted file outright (`RecoverError::Encrypted`), because
1188            // rebuild-by-scan looks for `N G obj` headers in bytes that would
1189            // be ciphertext. So a recovered document is never encrypted, and
1190            // threading a password here would be dead weight that read as
1191            // support.
1192            Credential::Password(None),
1193            LoadOptions::default(),
1194        )
1195    }
1196
1197    /// Load phase 2: resolve every type-2 (`InStream`) cross-reference
1198    /// entry through its object stream, inserting the parsed objects
1199    /// into `objects`.
1200    ///
1201    /// `compressed` is `(object number, container object number, index
1202    /// within container)`, sorted. Containers are looked up in
1203    /// `objects` — which is why this runs strictly after phase 1 (module
1204    /// docs) — decoded once, and cached for the rest of the load.
1205    ///
1206    /// Every compressed object is inserted with generation **0**:
1207    /// §7.5.7 fixes the generation of a compressed object at zero, and a
1208    /// type-2 entry carries no generation field to disagree with.
1209    fn load_compressed(
1210        buf: &[u8],
1211        compressed: &[(u32, u32, u32)],
1212        objects: &mut HashMap<ObjId, IndirectObject>,
1213        policy: UnreadableObjectPolicy,
1214        anomalies: &mut Vec<LoadAnomaly>,
1215    ) -> Result<(), DocError> {
1216        let mut cache: HashMap<u32, ObjectStream> = HashMap::new();
1217
1218        // A COMPRESSED OBJECT THAT CANNOT BE READ IS UNDEFINED, NOT FATAL
1219        // — the same §7.3.10 reading the file-level loop applies, and for the
1220        // same reason: five of this function's refusals were "one object is
1221        // broken, so you get no document."
1222        //
1223        // Each is recorded with the object it cost and why. Under `strict`
1224        // every one is still the error it was.
1225        macro_rules! give_up_on {
1226            ($num:expr, $reason:expr, $err:expr) => {{
1227                if policy == UnreadableObjectPolicy::Refuse {
1228                    return Err($err);
1229                }
1230                anomalies.push(LoadAnomaly::ObjectUnreadable {
1231                    object: ObjId::new($num, 0),
1232                    reason: $reason,
1233                });
1234                continue;
1235            }};
1236        }
1237
1238        for &(num, stream_num, index) in compressed {
1239            // §7.5.7: "The generation number of an object stream and of
1240            // any compressed object shall be zero."
1241            let container = ObjId::new(stream_num, 0);
1242
1243            let objstm = match cache.entry(stream_num) {
1244                Entry::Occupied(slot) => slot.into_mut(),
1245                Entry::Vacant(slot) => {
1246                    let Some(io) = objects.get(&container) else {
1247                        give_up_on!(
1248                            num,
1249                            format!("its object stream {container} is not in the file"),
1250                            DocError::ObjectStreamMissing { container, num }
1251                        )
1252                    };
1253                    let Object::Stream(stream) = &io.value else {
1254                        give_up_on!(
1255                            num,
1256                            format!(
1257                                "object {container} is named as its container but is not a stream"
1258                            ),
1259                            DocError::ObjectStream {
1260                                container,
1261                                source: ObjStmError::NotAStream,
1262                            }
1263                        )
1264                    };
1265                    let Some(raw) = stream.data_span.slice(buf) else {
1266                        give_up_on!(
1267                            num,
1268                            format!("its object stream {container} declares data outside the file"),
1269                            DocError::ObjectStream {
1270                                container,
1271                                source: ObjStmError::DataOutOfRange,
1272                            }
1273                        )
1274                    };
1275                    match ObjectStream::parse(&stream.dict, raw) {
1276                        Ok(parsed) => slot.insert(parsed),
1277                        Err(source) => give_up_on!(
1278                            num,
1279                            format!("its object stream {container} could not be decoded: {source}"),
1280                            DocError::ObjectStream { container, source }
1281                        ),
1282                    }
1283                }
1284            };
1285
1286            let idx = usize::try_from(index).unwrap_or(usize::MAX);
1287            let (found, value) = match objstm.object_at(idx) {
1288                Ok(pair) => pair,
1289                Err(source) => give_up_on!(
1290                    num,
1291                    format!(
1292                        "index {index} of object stream {container} could not be read: {source}"
1293                    ),
1294                    DocError::ObjectStream { container, source }
1295                ),
1296            };
1297            if found != num {
1298                give_up_on!(
1299                    num,
1300                    format!(
1301                        "object stream {container} stores object {found} at index {index}, where the cross-reference table promised {num}"
1302                    ),
1303                    DocError::ObjectStreamIdMismatch {
1304                        container,
1305                        index,
1306                        expected: num,
1307                        found,
1308                    }
1309                )
1310            }
1311
1312            let id = ObjId::new(num, 0);
1313            objects.insert(
1314                id,
1315                IndirectObject {
1316                    id,
1317                    value,
1318                    provenance: Provenance::ObjectStream { container, index },
1319                },
1320            );
1321        }
1322        Ok(())
1323    }
1324
1325    /// The retained source bytes (the coordinate system every span in
1326    /// this document indexes into).
1327    #[must_use]
1328    pub fn bytes(&self) -> &[u8] {
1329        &self.buf
1330    }
1331
1332    /// A read view of this document for the rasterizer, the vector object
1333    /// model and `pageops` — the file exactly as loaded.
1334    ///
1335    /// The mirror of `EditSession::view`,
1336    /// and the reason every read path can take one parameter type
1337    /// ([`DocumentView`]) instead of two overloads. A `Document` has no
1338    /// overlay and no staging buffer, so its view carries a
1339    /// [`StreamSource::Contiguous`](crate::view::StreamSource::Contiguous)
1340    /// over [`Document::bytes`] — meaning "render the file as it is on
1341    /// disk", which is exactly what `pdfcer` and the round-trip tools
1342    /// want — and why `pdfcer-render`'s `&Document` back-compat wrappers can
1343    /// build one implicitly without changing any caller's behaviour.
1344    ///
1345    /// Cheap: two borrows plus a version probe. Building one per call is
1346    /// the intended usage; there is nothing to cache.
1347    ///
1348    /// # Examples
1349    ///
1350    /// ```
1351    /// use pdfcer_model::document::Document;
1352    /// use pdfcer_model::graph::ObjectGraph;
1353    ///
1354    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1355    /// let doc = Document::from_bytes(
1356    ///     include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
1357    /// )?;
1358    /// let view = doc.view();
1359    /// assert_eq!(view.version(), doc.version());
1360    /// assert_eq!(view.catalog_id(), doc.catalog_id());
1361    /// # Ok(())
1362    /// # }
1363    /// ```
1364    #[must_use]
1365    pub fn view(&self) -> DocumentView<'_> {
1366        DocumentView::new(self, self.bytes(), self.version())
1367    }
1368
1369    /// The newest trailer dictionary (§7.5.5 Table 15).
1370    #[must_use]
1371    pub const fn trailer(&self) -> &Dict {
1372        &self.trailer
1373    }
1374
1375    /// The merged cross-reference table.
1376    #[must_use]
1377    pub const fn xref(&self) -> &XrefTable {
1378        &self.xref
1379    }
1380
1381    /// The document's effective version: the header's `%PDF-M.N`,
1382    /// upgraded by the catalog's `/Version` name if present and higher
1383    /// (§7.5.5: version = max of the two; the catalog entry exists so
1384    /// an incremental update can raise the version without touching
1385    /// byte 0).
1386    #[must_use]
1387    pub fn version(&self) -> PdfVersion {
1388        let catalog_version = self
1389            .catalog()
1390            .ok()
1391            .and_then(|cat| cat.get(b"Version"))
1392            .and_then(Object::as_name)
1393            .and_then(|n| parse_version_name(n.as_bytes()));
1394        match catalog_version {
1395            Some(v) if v > self.header_version => v,
1396            _ => self.header_version,
1397        }
1398    }
1399
1400    /// Look up an indirect object by full identity, applying the
1401    /// §7.3.10/§7.5.4 rules (module docs): dangling, stale-generation,
1402    /// and free all yield `None` here — callers wanting the null-object
1403    /// semantics use [`Document::resolve`], which maps `None` to
1404    /// [`Object::Null`].
1405    #[must_use]
1406    pub fn get(&self, id: ObjId) -> Option<&IndirectObject> {
1407        self.objects.get(&id)
1408    }
1409
1410    /// Resolve `obj` to a non-reference value: follow reference chains
1411    /// (depth-guarded), mapping every unresolvable case to the null
1412    /// object per §7.3.10. Non-reference objects return themselves.
1413    #[must_use]
1414    pub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
1415        const NULL: &Object = &Object::Null;
1416        let mut current = obj;
1417        for _ in 0..MAX_RESOLVE_DEPTH {
1418            match current {
1419                Object::Reference(id) => match self.get(*id) {
1420                    Some(io) => current = &io.value,
1421                    None => return NULL,
1422                },
1423                other => return other,
1424            }
1425        }
1426        // Chain too deep / cyclic: null, not an error (module docs).
1427        NULL
1428    }
1429
1430    /// The document catalog (§7.7.2) — the dictionary the trailer's
1431    /// required `/Root` reference points at.
1432    ///
1433    /// # Errors
1434    ///
1435    /// [`DocError::NoCatalog`] if `/Root` is missing, not a reference,
1436    /// or doesn't resolve to a dictionary.
1437    pub fn catalog(&self) -> Result<&Dict, DocError> {
1438        self.trailer
1439            .get(b"Root")
1440            .map(|root| self.resolve(root))
1441            .and_then(Object::as_dict)
1442            .ok_or(DocError::NoCatalog)
1443    }
1444
1445    /// Number of parsed (in-use) objects.
1446    #[must_use]
1447    pub fn object_count(&self) -> usize {
1448        self.objects.len()
1449    }
1450
1451    /// Iterate all parsed indirect objects (unordered).
1452    pub fn objects(&self) -> impl Iterator<Item = &IndirectObject> {
1453        self.objects.values()
1454    }
1455
1456    /// The byte offset this file's own `startxref` names (§7.5.5).
1457    ///
1458    /// This is the value an appended update's `/Prev` must carry —
1459    /// §7.5.6: *"a `Prev` entry giving the location of the previous
1460    /// cross-reference section"*, which is the section `startxref`
1461    /// currently points at. Taking the base trailer's own `/Prev`
1462    /// instead is the classic off-by-one-revision bug: it would skip a
1463    /// revision and silently resurrect superseded objects.
1464    #[must_use]
1465    pub const fn base_startxref(&self) -> u64 {
1466        self.base_startxref
1467    }
1468
1469    /// The physical form of the newest cross-reference section.
1470    ///
1471    /// The writer matches this rather than choosing (R33): emitting a
1472    /// cross-reference stream where the base file had a classic table
1473    /// silently raises a PDF 1.4 document's effective version to 1.5.
1474    /// §7.5.6 does not require the match — that is a recorded spec
1475    /// silence — which is exactly why pdfcer imposes it.
1476    #[must_use]
1477    pub const fn section_shape(&self) -> SectionShape {
1478        self.section_shape
1479    }
1480
1481    /// Whether this file is a §7.5.8.4 **hybrid-reference** file: a
1482    /// classic cross-reference section whose trailer carries
1483    /// `/XRefStm`.
1484    ///
1485    /// Hybrid files are readable by pre-1.5 readers *and* carry the
1486    /// PDF 1.5 features those readers cannot see. Incremental save
1487    /// preserves that duality (form A: a classic update section
1488    /// carrying `/XRefStm` forward); a full rewrite cannot, and refuses
1489    /// by name rather than flattening it.
1490    #[must_use]
1491    pub const fn is_hybrid(&self) -> bool {
1492        matches!(
1493            self.section_shape,
1494            SectionShape::Classic { xref_stm: Some(_) }
1495        )
1496    }
1497
1498    /// Every contradiction this file contained that pdfcer **decided rather
1499    /// than refused** (`Pass 283.0`).
1500    ///
1501    /// # The three obligations this satisfies at once
1502    ///
1503    /// The operator's ruling: *"we should be making pdfcer so that it opens
1504    /// pdfs that have errors, and have a way that it manages those errors such
1505    /// that they aren't fatal, and if the user can intervene in a decision that
1506    /// should always be an option along with them not having to intervene."*
1507    ///
1508    /// - **Not fatal** — the document is loaded; this list is a report about
1509    ///   it, not a gate in front of it.
1510    /// - **Intervention possible** — each entry names what pdfcer chose *and
1511    ///   what it chose between*, which is what a shell needs to offer the
1512    ///   alternative. Re-load through [`Document::from_bytes_with_options`]
1513    ///   with the other policy to take it.
1514    /// - **Intervention optional** — a caller that never reads this gets a
1515    ///   working document with pdfcer's documented default.
1516    ///
1517    /// Empty for a file that contains no contradiction, which is the
1518    /// overwhelming majority. A non-empty list is not a warning that anything
1519    /// is *wrong with pdfcer's output* — it is the file saying two things.
1520    #[must_use]
1521    pub fn load_anomalies(&self) -> &[LoadAnomaly] {
1522        &self.anomalies
1523    }
1524
1525    /// This file's §7.5.8.4 partition — which objects it **hides** behind
1526    /// `/XRefStm`, and whether pdfcer could read the stream that says so
1527    /// (`Pass 281.0`).
1528    ///
1529    /// # Why a writer needs it, and why re-deriving it would be wrong
1530    ///
1531    /// §7.5.8.4 describes a three-part unit a writer creates "at the same
1532    /// time": a main classic table marking the hidden objects **free with
1533    /// generation 65535**, an update section, and a cross-reference stream
1534    /// giving their real locations. Rewriting such a file means rebuilding
1535    /// that unit, which means knowing which side each object belongs on.
1536    ///
1537    /// §7.5.8.4's visibility rule answers a **different question** — what a
1538    /// producer is *permitted* to hide. This answers what this file *did*
1539    /// hide. A file may legally hide less than it could, and a rewrite that
1540    /// re-derived the maximum would move objects the operator never touched,
1541    /// which is exactly the "plausible, working, wrong file" `R33` guards
1542    /// against.
1543    ///
1544    /// Empty and readable for every non-hybrid file. See
1545    /// [`crate::xref::HybridPartition::is_reproducible`] for the case that
1546    /// still refuses: a file that says it hides objects and whose stream
1547    /// pdfcer could not parse.
1548    #[must_use]
1549    pub const fn hybrid_partition(&self) -> &crate::xref::HybridPartition {
1550        &self.hybrid
1551    }
1552
1553    /// The cross-reference **recovery** record, or `None` for a cleanly
1554    /// loaded file (decision 013).
1555    ///
1556    /// `Some` means the stored cross-reference table could not be parsed
1557    /// and pdfcer rebuilt it by scanning the file for `N G obj` headers
1558    /// (rebuild-by-scan). The returned [`RecoveryReport`] carries the
1559    /// counted disclosure (why the strict path failed, how many objects
1560    /// came from the file-level scan vs. object streams, collisions,
1561    /// trailer source, offset-start). This is a **reviewable fact**
1562    /// (fuzzy-never-sneaky, R20): the CLI prints it and forces a distinct
1563    /// exit status, and the GUI shows a banner. A recovered document also
1564    /// cannot be saved incrementally — see
1565    /// [`Document::save_incremental`]'s refusal.
1566    #[must_use]
1567    pub const fn recovery(&self) -> Option<&RecoveryReport> {
1568        self.recovery.as_ref()
1569    }
1570
1571    /// Whether this document was loaded via cross-reference recovery
1572    /// (decision 013) — the shorthand the writer's incremental-save refusal
1573    /// and the front ends' disclosure branch on.
1574    #[must_use]
1575    pub const fn loaded_via_recovery(&self) -> bool {
1576        self.recovery.is_some()
1577    }
1578
1579    /// Annex F linearization ("Fast Web View") state, detected at load.
1580    ///
1581    /// Reported so a save can warn before spending the property
1582    /// (F.1: an incremental update *"shall"* de-linearize). pdfcer never
1583    /// repairs it and never strips a stale `/Linearized` dictionary —
1584    /// see [`crate::linearization`].
1585    #[must_use]
1586    pub const fn linearization(&self) -> Linearization {
1587        self.linearization
1588    }
1589
1590    /// Save an incremental update (§7.5.6) to `path`.
1591    ///
1592    /// This is pdfcer's **default** save mode (`ARCHITECTURE.md` §5):
1593    /// the existing bytes are copied untouched and a new revision is
1594    /// appended, which is what keeps any pre-existing digital
1595    /// signature's `/ByteRange` digest valid (§12.8.1 NOTE 1).
1596    ///
1597    /// `dirty` is the **save-time diff against the base revision**, and
1598    /// the only thing that should compute one is
1599    /// `pdfcer_core::edit::EditSession::dirty_set` — see
1600    /// `ARCHITECTURE.md` §11.1 for the "union of every command ever run"
1601    /// bug that a hand-built dirty set reintroduces. An empty one gives
1602    /// byte-identical output.
1603    ///
1604    /// ⚠️ **Incremental save structurally preserves superseded
1605    /// content.** The old bytes of every replaced object remain in the
1606    /// file by construction. Any operation whose contract is *removal*
1607    /// — redaction above all — must therefore use
1608    /// [`Document::save_full`] and must refuse this mode (R35).
1609    ///
1610    /// # Errors
1611    ///
1612    /// [`crate::writer::WriteError`] — I/O, a broken provenance span,
1613    /// or a cross-reference form that cannot express an entry.
1614    pub fn save_incremental(
1615        &self,
1616        path: &Path,
1617        dirty: &crate::writer::DirtySet,
1618        options: &crate::writer::SaveOptions,
1619    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
1620        let (bytes, report) = crate::writer::save_incremental(self, dirty, options)?;
1621        std::fs::write(path, &bytes)?;
1622        Ok(report)
1623    }
1624
1625    /// Rewrite the whole document to `path` as a single revision.
1626    ///
1627    /// Every `File`-provenance object is re-emitted from its retained
1628    /// source bytes verbatim; only the header prefix, object offsets,
1629    /// the cross-reference section and the trailer are regenerated. So
1630    /// byte identity holds **per object definition**, never for the
1631    /// file as a whole (R32) — offsets legitimately move.
1632    ///
1633    /// ⚠️ **A full rewrite invalidates every existing digital
1634    /// signature**, because a signature covers a byte range that this
1635    /// mode necessarily disturbs (§12.8.1). That collides with R35's
1636    /// requirement that redaction use this mode; "redact a signed
1637    /// document" is a genuine either/or for the operator to resolve,
1638    /// never something pdfcer decides silently (R36, decision 007 W7).
1639    ///
1640    /// # Errors
1641    ///
1642    /// [`crate::writer::WriteError`], notably
1643    /// [`WriteError::HybridFullRewrite`](crate::writer::WriteError::HybridFullRewrite)
1644    /// for a §7.5.8.4 hybrid-reference input.
1645    pub fn save_full(
1646        &self,
1647        path: &Path,
1648        dirty: &crate::writer::DirtySet,
1649        options: &crate::writer::SaveOptions,
1650    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
1651        let (bytes, report) = crate::writer::save_full(self, dirty, options)?;
1652        std::fs::write(path, &bytes)?;
1653        Ok(report)
1654    }
1655
1656    /// The lowest object number this document does **not** already
1657    /// account for — where a newly created object goes.
1658    ///
1659    /// Four sources are consulted, and taking the maximum of all four
1660    /// is the point:
1661    ///
1662    /// 1. **the highest number the cross-reference chain mentions before
1663    ///    the `/Size` filter runs.** The unfiltered number, deliberately:
1664    ///    `/Size` is a hard reader-side filter, so a file that
1665    ///    under-reports it loads with real entries invisible, and
1666    ///    allocating from the *filtered* view picks a number the file
1667    ///    already defines. That produces an update section whose entry
1668    ///    collides with a live object — a file that looks fine and
1669    ///    resolves to the wrong bytes. Found by the `writer_roundtrip`
1670    ///    fuzz target, on a corpus file carrying `/Size 3` over six
1671    ///    entries.
1672    ///
1673    ///    Free entries count too. A free number is *reusable* in
1674    ///    principle (§7.5.4's free list exists to be consumed), but
1675    ///    reusing one correctly means honouring the generation rules —
1676    ///    a resurrected object takes the free entry's generation — and
1677    ///    pdfcer has no deletion path to have created those entries in
1678    ///    the first place. Allocating past them is always safe;
1679    ///    consuming them is Pass 3.2 work.
1680    /// 2. every parsed object, in case the two disagree;
1681    /// 3. the trailer's `/Size`, so a *stale, oversized* `/Size` cannot
1682    ///    hand out a number that a `/Prev` revision defines and this
1683    ///    merged view dropped.
1684    /// 4. **the newest cross-reference STREAM's own object number**, when
1685    ///    the file has one ([`Document::section_shape`]).
1686    ///
1687    /// ## Why source 4 exists, and the bug it closes
1688    ///
1689    /// A cross-reference stream is an indirect object, and the writer
1690    /// **reuses its number** for the update section it emits (`R33`: match
1691    /// the base's section shape). But it is *the section*, not a body
1692    /// object — the parser never files it in `objects`, and there is no
1693    /// requirement anywhere that it appear in its own `/Index` or be
1694    /// covered by its own `/Size`.
1695    ///
1696    /// So a file can carry `75 0 obj << /Type /XRef /Size 75 /Index [9 1 29
1697    /// 45] >>`: object 75 exists, and every one of sources 1–3 answers 74.
1698    /// This function then handed out **75**, the session wrote its new
1699    /// object there, and the writer wrote *its own cross-reference stream*
1700    /// over the top of it — same object number, later in the file, so the
1701    /// session's object simply vanished and the reader resolved the
1702    /// reference to the xref stream.
1703    ///
1704    /// The failure is silent in the worst way: the file parses, opens, and
1705    /// renders. Only the one thing the edit added is missing. Found by
1706    /// `tools/embed-sweep` over the pdfium corpus
1707    /// (`testing/resources/annotation_stamp_with_ap.pdf`), where an embedded
1708    /// font program came back as a 44-byte cross-reference stream and the
1709    /// text it should have drawn was silently skipped.
1710    ///
1711    /// **This was never specific to font embedding.** Any command that
1712    /// creates an object — adding text, an image, an annotation, a form
1713    /// field — hits it on any file shaped this way. It survived because a
1714    /// collision needs a file whose xref stream is outside its own `/Size`,
1715    /// which no producer pdfcer's fixtures came from emits.
1716    ///
1717    /// Returns `None` only if the document already reaches
1718    /// [`u32::MAX`], which Annex C's implementation limits put far out
1719    /// of reach for any real file — reported rather than wrapped,
1720    /// because silently allocating object 0 would corrupt the free list.
1721    ///
1722    /// ⚠️ A caller must **also** check
1723    /// [`Document::suppressed_object_count`] before creating an object:
1724    /// a valid number is not by itself a licence to write one.
1725    #[must_use]
1726    pub fn next_object_number(&self) -> Option<u32> {
1727        let from_objects = self.objects.keys().map(|id| id.num).max().unwrap_or(0);
1728        let from_size = self
1729            .trailer
1730            .get(b"Size")
1731            .and_then(Object::as_int)
1732            .and_then(|s| u32::try_from(s.saturating_sub(1)).ok())
1733            .unwrap_or(0);
1734        // Source 4 — see this function's docs. The writer reuses this number
1735        // for the section it emits, so handing it out would guarantee a
1736        // collision rather than merely risk one.
1737        let from_section = match self.section_shape {
1738            SectionShape::Stream { id, .. } => id.num,
1739            // A classic table is not an object and spends no number. The
1740            // `_` arm is deliberate: `SectionShape` is `#[non_exhaustive]`,
1741            // and a shape this build does not know must not silently be
1742            // treated as spending a number it might.
1743            _ => 0,
1744        };
1745        self.highest_object_number
1746            .max(from_objects)
1747            .max(from_size)
1748            .max(from_section)
1749            .checked_add(1)
1750            .filter(|n| *n != 0)
1751    }
1752
1753    /// How many cross-reference entries this file's `/Size` is hiding.
1754    ///
1755    /// ## Why anyone cares (and why it blocks object creation)
1756    ///
1757    /// Table 15 / §7.5.5 make `/Size` a hard filter: an object numbered
1758    /// at or above it *"shall be ignored and defined to be missing"*. A
1759    /// file whose `/Size` under-reports is therefore **relying on the
1760    /// filter** — the entries above it are invisible, and the document
1761    /// may only be loadable at all because they are (they can point at
1762    /// bytes that do not parse).
1763    ///
1764    /// Creating an object raises `/Size`. That does not merely add the
1765    /// new object: it **exposes every suppressed entry below the new
1766    /// number**, resurrecting objects the operator never touched. Two
1767    /// separate rules say no — §5's minimal-diff invariant (an edit must
1768    /// not change objects it did not name) and R27's fail-clean posture
1769    /// (name the refusal rather than produce a plausible wrong file).
1770    ///
1771    /// So a non-zero count means *"an edit may modify existing objects
1772    /// in this file, but must not create one"*. The eventual fix is to
1773    /// emit explicit free entries (§7.5.4, generation 65535 — the very
1774    /// mechanism §7.5.8.4 uses to hide an object) for the exposed range,
1775    /// which needs free-list writing that Pass 3.2 brings.
1776    ///
1777    /// Zero for essentially every well-formed file, which is why this is
1778    /// a refusal rather than a feature gap worth blocking on.
1779    #[must_use]
1780    pub const fn suppressed_object_count(&self) -> usize {
1781        self.suppressed_by_size
1782    }
1783}
1784
1785/// Parse the indirect object at `offset`, resolving indirect `/Length`
1786/// values through the xref table (the §7.3.10 EXAMPLE 3 pattern: the
1787/// length object is itself fetched and parsed on demand — it is always
1788/// a plain integer object, so this nested parse cannot recurse).
1789///
1790/// `pub(crate)` so the cross-reference recovery path (`crate::recover`) can
1791/// reuse the exact same object-parse + indirect-`/Length` resolution the
1792/// normal loader uses (rule 13: no new tokenizer) when confirming scanned
1793/// `N G obj` candidates.
1794///
1795/// `policy` selects the `/Length`-vs-`endstream` strictness
1796/// ([`StreamLengthPolicy`]). It is [`StreamLengthPolicy::Strict`] on every
1797/// clean-load call site and [`StreamLengthPolicy::RecoverFromEndstream`]
1798/// only under rebuild-by-scan recovery. Returns the parsed object together
1799/// with the number of stream extents that had to be re-derived (always `0`
1800/// under `Strict`), so the caller can fold it into the counted disclosure.
1801///
1802/// Note the nested `resolve_length` parse stays **strict** regardless: a
1803/// `/Length` object is a plain integer (§7.3.10 EXAMPLE 3), never a stream,
1804/// so the policy has nothing to act on there and holding it strict keeps
1805/// the nested parse from recursing into extent recovery.
1806pub(crate) fn parse_object_at(
1807    buf: &[u8],
1808    table: &XrefTable,
1809    offset: u64,
1810    policy: StreamLengthPolicy,
1811    terminator: TerminatorPolicy,
1812    duplicates: crate::parser::DuplicateKeyPolicy,
1813) -> Result<(IndirectObject, ParseRepairs), ParseError> {
1814    let offset = usize::try_from(offset).unwrap_or(usize::MAX);
1815    let mut resolve_length = |id: ObjId| -> Option<i64> {
1816        let XrefEntry::InUse {
1817            offset: len_offset,
1818            generation,
1819        } = table.get(id.num)?
1820        else {
1821            return None;
1822        };
1823        if generation != id.generation {
1824            return None;
1825        }
1826        let len_offset = usize::try_from(len_offset).ok()?;
1827        let io = Parser::at(buf, len_offset)
1828            .parse_indirect_object(&mut |_| None)
1829            .ok()?;
1830        (io.id == id).then_some(())?;
1831        io.value.as_int()
1832    };
1833    let mut parser = Parser::at(buf, offset)
1834        .with_stream_length_policy(policy)
1835        .with_terminator_policy(terminator)
1836        .with_duplicate_key_policy(duplicates);
1837    let io = parser.parse_indirect_object(&mut resolve_length)?;
1838    Ok((
1839        io,
1840        ParseRepairs {
1841            duplicate_keys: parser.duplicate_keys().to_vec(),
1842            stream_lengths: parser.stream_lengths_recovered(),
1843            missing_endobj: parser.missing_endobj_recovered(),
1844        },
1845    ))
1846}
1847
1848/// How to load a document that contradicts itself (`Pass 283.0`).
1849///
1850/// # Why this type exists rather than a global setting
1851///
1852/// The operator's ruling has two halves that pull in opposite directions:
1853/// a file with errors must open **without intervention**, and intervening must
1854/// **always be possible**. A default plus this struct is how both hold at once
1855/// — [`Default`] is what every existing caller already gets, and a shell that
1856/// wants to offer the operator a choice re-loads the same bytes with a
1857/// different policy and shows the difference.
1858///
1859/// Re-loading rather than patching in place is deliberate: a decision made
1860/// during parsing is not a value that can be edited afterwards, because the
1861/// discarded one was never built into the document. Carrying both would make
1862/// every dictionary lookup ambiguous for the life of the session to serve a
1863/// case that is one keystroke away from being re-read.
1864#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1865#[non_exhaustive]
1866pub struct LoadOptions {
1867    /// Which value wins when one dictionary names a key twice (§7.3.7).
1868    ///
1869    /// Defaults to [`crate::parser::DuplicateKeyPolicy::KeepLast`] — see that
1870    /// type for why last, and [`Document::load_anomalies`] for how a caller
1871    /// learns a choice was made at all.
1872    pub duplicate_keys: crate::parser::DuplicateKeyPolicy,
1873    /// What to do when a stream's `/Length` cannot be used (§7.3.8.2).
1874    ///
1875    /// Defaults to [`StreamLengthPolicy::RecoverFromEndstream`], which only
1876    /// acts when the stored value is unusable. Set
1877    /// [`StreamLengthPolicy::Strict`] to refuse such a file instead.
1878    pub stream_lengths: StreamLengthPolicy,
1879    /// What to do when an indirect object's `endobj` is missing (§7.3.10).
1880    ///
1881    /// Defaults to [`TerminatorPolicy::RecoverAtNextHeader`].
1882    pub terminators: TerminatorPolicy,
1883    /// What to do when one object cannot be loaded at all.
1884    ///
1885    /// Defaults to [`UnreadableObjectPolicy::TreatAsUndefined`] — §7.3.10's
1886    /// own answer for an object that is not there.
1887    pub unreadable_objects: UnreadableObjectPolicy,
1888}
1889
1890/// What to do when one indirect object cannot be loaded (`Pass 283.0`).
1891#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1892#[non_exhaustive]
1893pub enum UnreadableObjectPolicy {
1894    /// Load the document without it, and record a
1895    /// [`LoadAnomaly::ObjectUnreadable`].
1896    ///
1897    /// §7.3.10: an indirect reference to an undefined object *"shall not be
1898    /// considered an error by a conforming reader; it shall be treated as a
1899    /// reference to the null object."* An object whose bytes will not parse is
1900    /// undefined as far as every consumer is concerned, so this is the
1901    /// standard's own answer applied to the state the file is in — not a
1902    /// repair, and nothing invented.
1903    #[default]
1904    TreatAsUndefined,
1905    /// Refuse the document, as pdfcer did before `Pass 283.0`.
1906    Refuse,
1907}
1908
1909impl Default for LoadOptions {
1910    /// NOT the derived default. `DuplicateKeyPolicy`'s own `Default` is
1911    /// `Refuse`, which is right for a parser and wrong for a loader: deriving
1912    /// here would make `LoadOptions::default()` refuse the very files this
1913    /// Pass exists to open, and the two types would silently disagree about
1914    /// what "default" means.
1915    fn default() -> Self {
1916        Self::new()
1917    }
1918}
1919
1920impl LoadOptions {
1921    /// The defaults: open the file, decide the contradictions, report them.
1922    #[must_use]
1923    pub fn new() -> Self {
1924        Self {
1925            duplicate_keys: crate::parser::DuplicateKeyPolicy::KeepLast,
1926            stream_lengths: StreamLengthPolicy::RecoverFromEndstream,
1927            terminators: TerminatorPolicy::RecoverAtNextHeader,
1928            unreadable_objects: UnreadableObjectPolicy::TreatAsUndefined,
1929        }
1930    }
1931
1932    /// Refuse every malformation instead of deciding it — the pre-`Pass 283.0`
1933    /// behaviour, kept reachable.
1934    ///
1935    /// For a caller whose job is to say whether a file is well-formed rather
1936    /// than to open it: a conformance checker, a fuzz harness, a gate.
1937    #[must_use]
1938    pub const fn strict() -> Self {
1939        Self {
1940            duplicate_keys: crate::parser::DuplicateKeyPolicy::Refuse,
1941            stream_lengths: StreamLengthPolicy::Strict,
1942            terminators: TerminatorPolicy::Strict,
1943            unreadable_objects: UnreadableObjectPolicy::Refuse,
1944        }
1945    }
1946
1947    /// Take the OTHER value for every duplicated key — the operator's
1948    /// intervention, applied by re-loading the same bytes.
1949    #[must_use]
1950    pub const fn with_duplicate_keys(mut self, policy: crate::parser::DuplicateKeyPolicy) -> Self {
1951        self.duplicate_keys = policy;
1952        self
1953    }
1954}
1955
1956/// One thing the file said that contradicted itself, and what pdfcer decided
1957/// about it (`Pass 283.0`).
1958///
1959/// # The operator ruling this exists to satisfy
1960///
1961/// > *"We should be making pdfcer so that it opens pdfs that have errors, and
1962/// > have a way that it manages those errors such that they aren't fatal, and
1963/// > if the user can intervene in a decision that should always be an option
1964/// > along with them not having to intervene."*
1965///
1966/// Three obligations in one sentence, and this type carries all three:
1967///
1968/// 1. **Not fatal** — the document loads.
1969/// 2. **Intervention is possible** — the record names the object, the key, the
1970///    value kept and the value discarded, which is everything a shell needs to
1971///    offer the operator the other choice and re-load with it
1972///    ([`crate::parser::DuplicateKeyPolicy`]).
1973/// 3. **Intervention is not required** — pdfcer already picked, the default is
1974///    documented, and a caller that never reads this list gets a working
1975///    document.
1976///
1977/// It is a *disclosure*, not a prompt: project rule 4 as narrowed by decision
1978/// 059 — the inferred value is live document state, and what pdfcer guessed is
1979/// reported off to the side rather than gating the open.
1980#[derive(Debug, Clone, PartialEq)]
1981#[non_exhaustive]
1982pub enum LoadAnomaly {
1983    /// One dictionary named the same key twice (§7.3.7) and pdfcer kept one of
1984    /// the values.
1985    ///
1986    /// Both values are carried, not just the winner. A count would say *that*
1987    /// pdfcer chose; a shell offering the operator the choice needs to show
1988    /// **what it chose between**, and a report that cannot answer "what was the
1989    /// other one?" makes the intervention theoretical.
1990    DuplicateDictKey {
1991        /// The object whose dictionary contradicted itself. `None` when the
1992        /// dictionary is the trailer, which is not an indirect object.
1993        object: Option<ObjId>,
1994        /// The repeated key, e.g. `PageMode`.
1995        key: Vec<u8>,
1996        /// The value pdfcer KEPT — the last occurrence under the default
1997        /// policy.
1998        kept: Object,
1999        /// The value pdfcer DISCARDED. A caller offering the choice presents
2000        /// this as the alternative; a caller re-loading under
2001        /// [`crate::parser::DuplicateKeyPolicy::KeepFirst`] gets it instead.
2002        discarded: Object,
2003    },
2004    /// A stream's `/Length` was absent, non-integer, unresolvable or simply
2005    /// wrong, and pdfcer re-derived the data extent by scanning to
2006    /// `endstream` (§7.3.8.1).
2007    ///
2008    /// `/Length` is REQUIRED by §7.3.8.2 Table 5, so this is a `shall`
2009    /// violation — and one every reader recovers from, because the keyword
2010    /// that ends the data is right there in the file. Refusing costs the whole
2011    /// document to preserve a number the file itself contradicts.
2012    ///
2013    /// There is no operator choice to offer here, and that is not an
2014    /// oversight: the alternative to the scanned extent is **no object at
2015    /// all**. The record exists so the operator learns the file is damaged,
2016    /// not so a decision can be re-taken.
2017    StreamLengthRecovered {
2018        /// The object whose stream extent was re-derived.
2019        object: ObjId,
2020    },
2021    /// An indirect object's `endobj` keyword was missing and pdfcer accepted
2022    /// the definition anyway, ending it at the next object header (§7.3.10).
2023    ///
2024    /// Same shape as [`Self::StreamLengthRecovered`]: a required keyword the
2025    /// file omits, an unambiguous end, and no second reading to choose
2026    /// between.
2027    MissingEndobjRecovered {
2028        /// The object accepted without its terminator.
2029        object: ObjId,
2030    },
2031    /// One object could not be loaded at all, and the document was loaded
2032    /// **without it**.
2033    ///
2034    /// # Why this is continuing rather than guessing
2035    ///
2036    /// §7.3.10 already defines what a reference to an object that is not
2037    /// there means: *"An indirect reference to an undefined object shall not
2038    /// be considered an error by a conforming reader; it shall be treated as
2039    /// a reference to the null object."* An object whose bytes will not parse
2040    /// **is** an undefined object as far as every consumer is concerned — so
2041    /// omitting it is not a liberty pdfcer takes, it is the behaviour the
2042    /// standard prescribes for the state the file is in.
2043    ///
2044    /// That is the whole difference between this and a repair: nothing is
2045    /// invented, and the resulting document is one the standard describes.
2046    ///
2047    /// # What it replaces
2048    ///
2049    /// `DocError::BadObject`, `ObjectIdMismatch`, `ObjectStreamMissing`,
2050    /// `ObjectStream` and `ObjectStreamIdMismatch` — five ways one bad object
2051    /// used to cost the whole document. They survive as errors under
2052    /// [`LoadOptions::strict`].
2053    ///
2054    /// There is no alternative to offer here either. The choice is between
2055    /// this object and no document, and `reason` is carried so the operator
2056    /// can see WHICH object and WHY rather than being told a count.
2057    ObjectUnreadable {
2058        /// The object that could not be loaded.
2059        object: ObjId,
2060        /// Why, in the loader's own words — the error that would have been
2061        /// returned.
2062        reason: String,
2063    },
2064}
2065
2066impl LoadAnomaly {
2067    /// The object this anomaly is about, when it has one.
2068    #[must_use]
2069    pub const fn object(&self) -> Option<ObjId> {
2070        match self {
2071            Self::DuplicateDictKey { object, .. } => *object,
2072            Self::StreamLengthRecovered { object }
2073            | Self::MissingEndobjRecovered { object }
2074            | Self::ObjectUnreadable { object, .. } => Some(*object),
2075        }
2076    }
2077
2078    /// A short stable token for machine-readable output.
2079    #[must_use]
2080    pub const fn kind(&self) -> &'static str {
2081        match self {
2082            Self::DuplicateDictKey { .. } => "duplicate_dict_key",
2083            Self::StreamLengthRecovered { .. } => "stream_length_recovered",
2084            Self::MissingEndobjRecovered { .. } => "missing_endobj_recovered",
2085            Self::ObjectUnreadable { .. } => "object_unreadable",
2086        }
2087    }
2088}
2089
2090/// How much repair a single object's parse needed.
2091///
2092/// Every field counts a place where the file contradicted itself or
2093/// omitted something §7.3.10 requires, and pdfcer chose to continue rather
2094/// than refuse. **All of them are zero under the strict policies**, so a
2095/// non-zero total is proof the file was damaged — which is why these are
2096/// carried out to the recovery report and disclosed (R20,
2097/// fuzzy-never-sneaky) instead of being absorbed silently.
2098#[derive(Debug, Clone, Default, PartialEq)]
2099pub(crate) struct ParseRepairs {
2100    /// Dictionary keys that appeared twice and were resolved to the LAST
2101    /// value rather than refusing the object
2102    /// ([`crate::parser::DuplicateKeyPolicy::KeepLast`], `Pass 283.0`).
2103    ///
2104    /// Unlike its two siblings this one is **non-zero on the clean path**,
2105    /// because the clean loader opts into the tolerant policy — the whole
2106    /// point of the Pass was that a file every other reader opens must not
2107    /// cost pdfcer the whole document. It is still a repair and still
2108    /// disclosed.
2109    pub duplicate_keys: Vec<crate::parser::DuplicateKeyRecord>,
2110    /// Stream extents re-derived from `endstream` because `/Length` was
2111    /// unusable ([`StreamLengthPolicy::RecoverFromEndstream`]).
2112    pub stream_lengths: usize,
2113    /// Definitions accepted with no `endobj` keyword
2114    /// ([`TerminatorPolicy::RecoverAtNextHeader`]).
2115    pub missing_endobj: usize,
2116}
2117
2118/// Parse a catalog `/Version` name (`1.7`, `2.0`) into a version pair.
2119fn parse_version_name(name: &[u8]) -> Option<PdfVersion> {
2120    let text = std::str::from_utf8(name).ok()?;
2121    let (major, minor) = text.split_once('.')?;
2122    Some(PdfVersion {
2123        major: major.parse().ok()?,
2124        minor: minor.parse().ok()?,
2125    })
2126}
2127
2128#[cfg(test)]
2129#[allow(
2130    clippy::unwrap_used,
2131    clippy::expect_used,
2132    clippy::panic,
2133    clippy::indexing_slicing
2134)]
2135mod tests {
2136    use super::*;
2137
2138    /// Build a small, offset-consistent classic PDF from parts: each
2139    /// entry in `objects` is (object number, body text); generation 0.
2140    /// Returns the complete file bytes.
2141    fn build_pdf(objects: &[(u32, &str)], trailer_extra: &str) -> Vec<u8> {
2142        let mut buf = b"%PDF-1.4\n".to_vec();
2143        let mut offsets: Vec<(u32, usize)> = Vec::new();
2144        for (num, body) in objects {
2145            offsets.push((*num, buf.len()));
2146            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
2147        }
2148        let xref_at = buf.len();
2149        let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
2150        buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
2151        buf.extend_from_slice(b"0000000000 65535 f\r\n");
2152        for num in 1..=max_num {
2153            match offsets.iter().find(|(n, _)| *n == num) {
2154                Some((_, off)) => {
2155                    buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
2156                }
2157                None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
2158            }
2159        }
2160        buf.extend_from_slice(
2161            format!(
2162                "trailer\n<< /Size {} /Root 1 0 R {trailer_extra}>>\nstartxref\n{xref_at}\n%%EOF\n",
2163                max_num + 1
2164            )
2165            .as_bytes(),
2166        );
2167        buf
2168    }
2169
2170    fn minimal_doc() -> Vec<u8> {
2171        build_pdf(
2172            &[
2173                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2174                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2175            ],
2176            "",
2177        )
2178    }
2179
2180    #[test]
2181    fn loads_minimal_document() {
2182        let doc = Document::from_bytes(minimal_doc()).unwrap();
2183        assert_eq!(doc.object_count(), 2);
2184        assert_eq!(doc.version().to_string(), "1.4");
2185        let cat = doc.catalog().unwrap();
2186        assert_eq!(
2187            cat.get(b"Type").unwrap().as_name().unwrap().as_bytes(),
2188            b"Catalog"
2189        );
2190    }
2191
2192    #[test]
2193    fn resolve_follows_references_and_nulls_dangling() {
2194        let doc = Document::from_bytes(minimal_doc()).unwrap();
2195        let cat = doc.catalog().unwrap();
2196        // /Pages resolves through the reference to the Pages dict.
2197        let pages = doc.resolve(cat.get(b"Pages").unwrap());
2198        assert_eq!(
2199            pages.as_dict().unwrap().get(b"Count").unwrap().as_int(),
2200            Some(0)
2201        );
2202        // §7.3.10: dangling → null, not an error.
2203        let dangling = Object::Reference(ObjId::new(17, 0));
2204        assert_eq!(*doc.resolve(&dangling), Object::Null);
2205        // Stale generation → null too.
2206        let stale = Object::Reference(ObjId::new(2, 9));
2207        assert_eq!(*doc.resolve(&stale), Object::Null);
2208    }
2209
2210    #[test]
2211    fn reference_cycle_resolves_to_null() {
2212        // `3 0 obj 3 0 R endobj` — legal syntax, must not loop.
2213        let doc = Document::from_bytes(build_pdf(
2214            &[
2215                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2216                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2217                (3, "3 0 R"),
2218            ],
2219            "",
2220        ))
2221        .unwrap();
2222        let cyc = Object::Reference(ObjId::new(3, 0));
2223        assert_eq!(*doc.resolve(&cyc), Object::Null);
2224    }
2225
2226    #[test]
2227    fn provenance_spans_recover_source_bytes() {
2228        // The whole point of the retained buffer: every object's span
2229        // slices back to its exact definition bytes.
2230        let doc = Document::from_bytes(minimal_doc()).unwrap();
2231        let io = doc.get(ObjId::new(1, 0)).unwrap();
2232        let raw = io.file_span().unwrap().slice(doc.bytes()).unwrap();
2233        assert!(raw.starts_with(b"1 0 obj"));
2234        assert!(raw.ends_with(b"endobj"));
2235    }
2236
2237    #[test]
2238    fn catalog_version_upgrades_header() {
2239        // §7.5.5: effective version = max(header, catalog /Version).
2240        let doc = Document::from_bytes(build_pdf(
2241            &[
2242                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.7 >>"),
2243                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2244            ],
2245            "",
2246        ))
2247        .unwrap();
2248        assert_eq!(doc.version().to_string(), "1.7");
2249    }
2250
2251    #[test]
2252    fn catalog_version_cannot_downgrade_header() {
2253        let mut bytes = build_pdf(
2254            &[
2255                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.2 >>"),
2256                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2257            ],
2258            "",
2259        );
2260        // Bump the header to 1.6; catalog says 1.2; max wins.
2261        let pos = bytes.windows(3).position(|w| w == b"1.4").unwrap();
2262        bytes[pos..pos + 3].copy_from_slice(b"1.6");
2263        let doc = Document::from_bytes(bytes).unwrap();
2264        assert_eq!(doc.version().to_string(), "1.6");
2265    }
2266
2267    /// AMENDED BY `Pass 283.0`, and the old assertion is kept as the second
2268    /// half rather than deleted.
2269    ///
2270    /// This test was right for its time: it asserted that a cross-reference
2271    /// entry pointing at the wrong object refuses the whole document, *"rather
2272    /// than guessing which is right"*. pdfcer still does not guess — what
2273    /// changed is that not-guessing no longer means not-opening. The object
2274    /// the table promised is treated as **undefined** (§7.3.10), which is the
2275    /// standard's own answer for an object that is not there, and the operator
2276    /// is told which one was lost.
2277    ///
2278    /// The strict refusal survives by name under [`LoadOptions::strict`], and
2279    /// the second half of this test is the old one unchanged.
2280    #[test]
2281    fn an_object_id_mismatch_is_recorded_by_default_and_refused_under_strict() {
2282        // Corrupt the xref so object 2's entry points at object 1's offset.
2283        let bytes = minimal_doc();
2284        let text = String::from_utf8(bytes.clone()).unwrap();
2285        let obj1_off = text.find("1 0 obj").unwrap();
2286        let obj2_off = text.find("2 0 obj").unwrap();
2287        let entry = format!("{obj2_off:010} 00000 n");
2288        let entry_pos = text.find(&entry).unwrap();
2289        let mut corrupted = bytes;
2290        corrupted[entry_pos..entry_pos + 10].copy_from_slice(format!("{obj1_off:010}").as_bytes());
2291
2292        // Default: the document opens, object 2 is absent, and the loss is
2293        // named.
2294        let doc = Document::from_bytes(corrupted.clone())
2295            .expect("a table/body disagreement about ONE object is not an unreadable file");
2296        assert!(doc.get(ObjId::new(2, 0)).is_none());
2297        assert!(
2298            doc.load_anomalies().iter().any(|a| matches!(
2299                a,
2300                LoadAnomaly::ObjectUnreadable { object, .. } if *object == ObjId::new(2, 0)
2301            )),
2302            "{:?}",
2303            doc.load_anomalies()
2304        );
2305
2306        // Strict: the original assertion, unchanged.
2307        let err =
2308            Document::from_bytes_with_options(corrupted, None, LoadOptions::strict()).unwrap_err();
2309        assert!(matches!(err, DocError::ObjectIdMismatch { .. }));
2310    }
2311
2312    #[test]
2313    fn missing_root_is_no_catalog() {
2314        let mut buf = b"%PDF-1.4\n".to_vec();
2315        let xref_at = buf.len();
2316        buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
2317        buf.extend_from_slice(
2318            format!("trailer\n<< /Size 1 >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
2319        );
2320        let doc = Document::from_bytes(buf).unwrap();
2321        assert!(matches!(doc.catalog(), Err(DocError::NoCatalog)));
2322    }
2323
2324    #[test]
2325    fn stream_with_indirect_length_loads_end_to_end() {
2326        // §7.3.10 EXAMPLE 3 through the full Document path.
2327        let doc = Document::from_bytes(build_pdf(
2328            &[
2329                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
2330                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
2331                (3, "<< /Length 4 0 R >>\nstream\nhello wo\nendstream"),
2332                (4, "8"),
2333            ],
2334            "",
2335        ))
2336        .unwrap();
2337        let io = doc.get(ObjId::new(3, 0)).unwrap();
2338        let Object::Stream(s) = &io.value else {
2339            panic!("not a stream");
2340        };
2341        assert_eq!(s.data_span.slice(doc.bytes()).unwrap(), b"hello wo");
2342    }
2343}