pdfcer_model/writer/encoder.rs
1//! # The object-encoder seam (ISO 32000-1 §7.6, decision 007 R37)
2//!
3//! A one-trait indirection between "the serializer has produced the
4//! bytes of a string or a stream" and "those bytes go into the file".
5//! In Pass 3.0 the only implementation is [`IdentityEncoder`], which
6//! returns its input untouched. **This module exists entirely so that
7//! Pass 5 (encryption) is a plug-in rather than a rewrite.**
8//!
9//! ## Why a seam now, when nothing uses it
10//!
11//! Decision 007 W8, verbatim: *"The crypt stage touches EVERY string
12//! and EVERY stream, and incremental save of an encrypted document must
13//! encrypt newly-appended objects with the existing key. Bolting that
14//! onto a completed serializer is a cross-cutting rewrite."* The two
15//! call sites that would have to be found and changed later are
16//! [`crate::writer::serialize`]'s string arm and its stream arm. Naming
17//! them now, as a trait boundary, costs one indirection and removes an
18//! entire class of Pass-5 archaeology.
19//!
20//! ## What the seam deliberately does NOT abstract
21//!
22//! Three categories of bytes are **never** routed through an encoder,
23//! and the type system should not make it look as though they could be:
24//!
25//! 1. **Verbatim re-emission of a `Provenance::File` object.** Those
26//! bytes are copied from the retained source buffer without ever
27//! being decomposed into strings and streams — in an encrypted
28//! document they are *already* ciphertext, and re-encrypting them
29//! would be catastrophic. The writer's verbatim path does not call
30//! into this module at all, which is the correct structural answer.
31//! 2. **Cross-reference streams.** §7.5.8.2: *"The cross-reference
32//! stream shall not be encrypted and strings appearing in the
33//! cross-reference stream dictionary shall not be encrypted. It
34//! shall not have a `Filter` entry that specifies a `Crypt`
35//! filter."* [`crate::writer::xref_out`] therefore serializes with
36//! [`IdentityEncoder`] unconditionally, in every Pass, forever.
37//! 3. **The two `/ID` strings when `/Encrypt` is present.** Table 15:
38//! both *"shall be direct and unencrypted"* — they are an input to
39//! key derivation, so encrypting them is circular.
40//!
41//! Each of those is a `shall`/`shall not` that Pass 5 will otherwise
42//! have to rediscover; they are recorded here because here is where a
43//! Pass-5 engineer will look.
44
45use std::borrow::Cow;
46
47use crate::object::ObjId;
48
49/// Transforms a serialized string or stream payload on its way into the
50/// file — the §7.6 encryption hook, in identity form for Pass 3.0.
51///
52/// Implementations receive the **containing indirect object's**
53/// identifier because §7.6.2's key derivation is per-object: the
54/// encryption key for object `N G` mixes the document key with `N` and
55/// `G`. A serializer that did not thread the id through would be
56/// unable to host a conforming standard security handler at all, which
57/// is the whole reason this parameter exists in Pass 3.0 where it is
58/// unused.
59///
60/// # Examples
61///
62/// ```
63/// use pdfcer_model::object::ObjId;
64/// use pdfcer_model::writer::{IdentityEncoder, ObjectEncoder};
65///
66/// let enc = IdentityEncoder;
67/// let id = ObjId::new(4, 0);
68/// assert_eq!(&*enc.encode_string(id, b"hello"), b"hello");
69/// assert_eq!(&*enc.encode_stream(id, b"data"), b"data");
70/// ```
71pub trait ObjectEncoder {
72 /// Transform the **decoded** bytes of a string object (§7.3.4)
73 /// belonging to indirect object `owner`.
74 ///
75 /// Called with the string's value, before any literal/hex escaping:
76 /// §7.6.2 encrypts the string's *value*, and the escaping is
77 /// syntax applied to the result.
78 fn encode_string<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]>;
79
80 /// Transform the **already-filter-encoded** bytes of a stream
81 /// (§7.3.8) belonging to indirect object `owner`.
82 ///
83 /// Called with the bytes that would otherwise be written between
84 /// `stream` and `endstream`. §7.6.2's ordering is load-bearing:
85 /// encryption is applied *after* the `/Filter` chain on write (and
86 /// therefore *before* it on read), so `/Length` must be computed
87 /// from this function's **output**, never its input.
88 fn encode_stream<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]>;
89}
90
91/// The Pass 3.0 encoder: returns every payload unchanged.
92///
93/// This is not a placeholder to be deleted — it stays as the encoder
94/// for unencrypted documents (the overwhelming majority) and as the
95/// mandatory encoder for cross-reference streams even in encrypted ones
96/// (module docs, item 2).
97///
98/// Deliberately **not** `#[non_exhaustive]`: a unit struct marked so
99/// cannot be constructed outside its defining crate at all, and this one
100/// exists precisely to be constructed by `pdfcer`, `pdfcer-render`
101/// and the round-trip harness.
102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
103pub struct IdentityEncoder;
104
105impl ObjectEncoder for IdentityEncoder {
106 /// Borrows through: no allocation, no copy.
107 fn encode_string<'a>(&self, _owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
108 Cow::Borrowed(data)
109 }
110
111 /// Borrows through: no allocation, no copy.
112 fn encode_stream<'a>(&self, _owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
113 Cow::Borrowed(data)
114 }
115}
116
117/// The AES-256 `/R` 6 encrypting encoder (`Pass 5.4`) — the seam's first
118/// non-identity implementation, and the reason it exists (decision 007 W8).
119///
120/// Encrypts every string and stream through **Algorithm 1.A** (§7.6.3.3): a
121/// fresh random 16-byte IV prefixed to AES-256-CBC ciphertext, PKCS#7 always
122/// padded. At `/V` 5 the object key IS the file key (T24), so no per-object
123/// derivation happens here.
124///
125/// # What it does NOT encrypt, and why the writer decides by OWNER id
126///
127/// The `ObjectEncoder` trait hands this only the bytes and the containing
128/// object's id — not the dictionary — so the exemptions that depend on an
129/// object's ROLE (the `/Encrypt` dict itself, cross-reference streams,
130/// `/Metadata` when `/EncryptMetadata` is false, external streams, an
131/// `/Identity` crypt filter) are resolved by the caller into two id sets and
132/// consulted here. A signed document is refused UPSTREAM (`EditError`), so the
133/// per-string `/Contents` exemption (N13) never has to be expressed at this
134/// granularity in this cut.
135#[derive(Debug, Clone)]
136pub struct EncryptingEncoder {
137 key: [u8; 32],
138 /// The `/Encrypt` dictionary's own object number — none of its strings or
139 /// streams are ever encrypted (§7.6: it is what you need to START
140 /// decrypting).
141 encrypt_dict: u32,
142 /// Stream objects whose DATA must be left in clear (xref streams,
143 /// clear `/Metadata`, external `/F` streams, `/Identity`-filtered streams).
144 /// Their non-`/Contents` strings, if any, are still encrypted.
145 clear_streams: std::collections::HashSet<u32>,
146}
147
148impl EncryptingEncoder {
149 /// Build the encoder from the file key and the two exemption sets.
150 #[must_use]
151 pub fn new(
152 key: [u8; 32],
153 encrypt_dict: ObjId,
154 clear_streams: std::collections::HashSet<u32>,
155 ) -> Self {
156 Self {
157 key,
158 encrypt_dict: encrypt_dict.num,
159 clear_streams,
160 }
161 }
162}
163
164impl ObjectEncoder for EncryptingEncoder {
165 fn encode_string<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
166 if owner.num == self.encrypt_dict {
167 return Cow::Borrowed(data);
168 }
169 // A fresh IV per string; on the (desktop-only) chance the CSPRNG is
170 // unreachable the string is left in clear rather than written with a
171 // zero IV — the save's own preflight has already proven entropy works,
172 // so this branch is defence, not a real path.
173 match crate::crypto::rng::array::<16>() {
174 Ok(iv) => Cow::Owned(crate::crypto::aes::encrypt_cbc_256(&self.key, &iv, data)),
175 Err(_) => Cow::Borrowed(data),
176 }
177 }
178
179 fn encode_stream<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
180 if owner.num == self.encrypt_dict || self.clear_streams.contains(&owner.num) {
181 return Cow::Borrowed(data);
182 }
183 match crate::crypto::rng::array::<16>() {
184 Ok(iv) => Cow::Owned(crate::crypto::aes::encrypt_cbc_256(&self.key, &iv, data)),
185 Err(_) => Cow::Borrowed(data),
186 }
187 }
188}
189
190/// Encrypts appended objects under a document's **existing** handler and file
191/// key — the encoder an incremental save of an encrypted document uses.
192///
193/// Every cipher the read side decrypts is written back the same way
194/// (Algorithm 1 per-object keys below `/V` 5, a fresh IV per AES payload).
195/// Objects in `clear` — those [`crate::crypto::apply::skip_value`] exempts —
196/// are written in clear, strings and stream alike, mirroring the read side.
197pub(crate) struct KeyEncoder<'k> {
198 key: &'k crate::crypto::FileKey,
199 clear: std::collections::HashSet<u32>,
200}
201
202impl<'k> KeyEncoder<'k> {
203 /// Encrypt under `key`, leaving the object numbers in `clear` unencrypted.
204 pub(crate) fn new(
205 key: &'k crate::crypto::FileKey,
206 clear: std::collections::HashSet<u32>,
207 ) -> Self {
208 Self { key, clear }
209 }
210
211 fn iv() -> [u8; 16] {
212 // The save preflights the CSPRNG before writing anything, so this
213 // fallback is unreachable; an all-zero IV still decrypts correctly.
214 crate::crypto::rng::array::<16>().unwrap_or([0; 16])
215 }
216}
217
218impl ObjectEncoder for KeyEncoder<'_> {
219 fn encode_string<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
220 if self.clear.contains(&owner.num) || !self.key.strings_encrypted() {
221 return Cow::Borrowed(data);
222 }
223 Cow::Owned(self.key.encrypt_string(owner, data, &Self::iv()))
224 }
225
226 fn encode_stream<'a>(&self, owner: ObjId, data: &'a [u8]) -> Cow<'a, [u8]> {
227 if self.clear.contains(&owner.num) || !self.key.streams_encrypted() {
228 return Cow::Borrowed(data);
229 }
230 Cow::Owned(self.key.encrypt_stream(owner, data, &Self::iv()))
231 }
232}
233
234#[cfg(test)]
235#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn identity_encoder_borrows_rather_than_copies() {
241 // The zero-cost property is part of the contract: an identity
242 // save of a 200 MB document must not clone every stream.
243 let enc = IdentityEncoder;
244 let data = b"payload".to_vec();
245 let out = enc.encode_stream(ObjId::new(1, 0), &data);
246 assert!(matches!(out, Cow::Borrowed(_)));
247 assert_eq!(&*out, b"payload");
248 }
249
250 #[test]
251 fn encoder_is_object_safe_and_usable_behind_a_reference() {
252 // Pass 5 will hand the writer a `&dyn ObjectEncoder` chosen at
253 // runtime from the document's /Encrypt dictionary; pin that
254 // this compiles now rather than discovering it later.
255 let boxed: &dyn ObjectEncoder = &IdentityEncoder;
256 assert_eq!(&*boxed.encode_string(ObjId::new(9, 1), b"x"), b"x");
257 }
258}