flpdf 0.8.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Writer-side encryption and serialization of PDF strings.
//!
//! qpdf correspondence: QPDFWriter.cc:785-803 encryption-dictionary binary-key hex selection, QPDFWriter.cc:1567-1599 string-unparse, QPDFWriter.cc:1761-1796 object data-key lifecycle, and QPDFWriter.cc:2244-2256 encryption-dictionary emission responsibilities.
//!

use crate::encryption::standard::{encrypt_cipher_bytes, ObjectKeyAlg, StringEncryptCipher};
use crate::object_handle::ObjectHandle;
use crate::pdf_syntax::{write_hex_string, write_name_escaped, write_string_value};
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::writer::encryption_state::WriterEncryptionState;
use crate::writer::output::OutputSink;
use crate::writer::{
    EncryptionContext, ObjectWriterEmission, StreamDictionaryOptions, WriteCipher, WriterOptions,
};
use crate::ObjectRef;

type AesIvGenerator = dyn FnMut(&mut [u8; 16]) -> Result<(), getrandom::Error>;

#[derive(Clone, Copy)]
pub(crate) struct StreamDictOptions {
    qdf: bool,
    dictionary: StreamDictionaryOptions,
    encrypt_strings: bool,
}

impl StreamDictOptions {
    pub(crate) const fn new(
        qdf: bool,
        dictionary: StreamDictionaryOptions,
        encrypt_strings: bool,
    ) -> Self {
        Self {
            qdf,
            dictionary,
            encrypt_strings,
        }
    }
}

/// Writer-owned adapter that encrypts strings while an emitted object's data
/// key is active, without changing the source ObjectHandle graph.
pub(crate) struct EncryptedStringEmitter {
    state: WriterEncryptionState,
    cipher: WriteCipher,
    static_aes_iv: bool,
    aes_iv_generator: Box<AesIvGenerator>,
    encrypt_ref: ObjectRef,
}

impl EncryptedStringEmitter {
    pub(crate) fn from_context(ctx: &EncryptionContext) -> Self {
        Self::from_context_with_boxed_iv_generator(ctx, Box::new(|iv| getrandom::fill(iv)))
    }

    fn from_context_with_boxed_iv_generator(
        ctx: &EncryptionContext,
        aes_iv_generator: Box<AesIvGenerator>,
    ) -> Self {
        Self {
            state: WriterEncryptionState::new(
                true,
                ctx.file_key.clone(),
                crate::writer::cipher_needs_aes_iv(ctx.cipher),
                ctx.encryption_v,
                ctx.encryption_r,
            ),
            cipher: ctx.cipher,
            static_aes_iv: ctx.static_aes_iv,
            aes_iv_generator,
            encrypt_ref: ctx.encrypt_ref,
        }
    }

    /// QDF object emission variant keyed by qpdf's complete raw source
    /// identity. The ordinary `ObjectRef` sibling remains available for
    /// callers whose source graph is already inside the `N G R` projection;
    /// QDF live emission must use this route so out-of-range generations are
    /// still references rather than inlined values.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn write_handle_object_with_qpdf_obj_gen_map(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        object: &ObjectHandle,
        map: &dyn Fn(QpdfObjGen) -> crate::Result<ObjectRef>,
        removed_refs: &std::collections::BTreeSet<QpdfObjGen>,
    ) -> crate::Result<()> {
        self.write_handle_object_with_qpdf_obj_gen_map_and_mode(
            out,
            emitted_ref,
            object_stream_index,
            object,
            true,
            map,
            removed_refs,
        )
    }

    /// Raw-identity object emission for either compact or QDF output. The
    /// linearization writer uses this for ordinary non-QDF objects as well as
    /// QDF objects, so an out-of-range source generation is never narrowed to
    /// `ObjectRef` during serialization.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn write_handle_object_with_qpdf_obj_gen_map_and_mode(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        object: &ObjectHandle,
        qdf: bool,
        map: &dyn Fn(QpdfObjGen) -> crate::Result<ObjectRef>,
        removed_refs: &std::collections::BTreeSet<QpdfObjGen>,
    ) -> crate::Result<()> {
        if emitted_ref == self.encrypt_ref {
            return write_encryption_dictionary_handle(out, object); // cov:ignore: the canonical body emits /Encrypt through its dedicated unencrypted dictionary path
        }

        let cipher = self.cipher;
        let static_aes_iv = self.static_aes_iv;
        let aes_iv_generator = self.aes_iv_generator.as_mut();
        self.state
            .with_object_data_key(emitted_ref.number, object_stream_index, |state| {
                let mut write_string = |out: &mut OutputSink<'_>, plaintext: &[u8]| {
                    write_encrypted_or_plain_string(
                        state,
                        cipher,
                        static_aes_iv,
                        aes_iv_generator,
                        out,
                        plaintext,
                    )
                };
                if qdf {
                    object.unparse_object_qdf_with_qpdf_obj_gen_map_and_removed_with_string_writer(
                        out,
                        0,
                        map,
                        removed_refs,
                        &mut write_string,
                    )
                } else {
                    object.unparse_object_with_qpdf_obj_gen_map_and_removed_with_string_writer(
                        out,
                        map,
                        removed_refs,
                        &mut write_string,
                    )
                }
            })
    }

    /// Standard-writer dynamic object emission with the current object's
    /// encryption key and qpdf's direct-stream framing boundary.
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub(crate) fn write_handle_object_with_dynamic_ref_map_and_direct_stream_writer(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        object: &ObjectHandle,
        map: &mut crate::writer::object::DynamicObjectRefMap<'_>,
        removed_refs: &std::collections::BTreeSet<ObjectRef>,
        direct_stream_writer: &mut dyn crate::writer::object::DynamicDirectStreamWriter,
    ) -> crate::Result<()> {
        if emitted_ref == self.encrypt_ref {
            return write_encryption_dictionary_handle(out, object); // cov:ignore: the canonical body emits /Encrypt through its dedicated unencrypted dictionary path.
        }

        let cipher = self.cipher;
        let static_aes_iv = self.static_aes_iv;
        let aes_iv_generator = self.aes_iv_generator.as_mut();
        self.state
            .with_object_data_key(emitted_ref.number, object_stream_index, |state| {
                let mut write_string = |out: &mut OutputSink<'_>, plaintext: &[u8]| {
                    write_encrypted_or_plain_string(
                        state,
                        cipher,
                        static_aes_iv,
                        aes_iv_generator,
                        out,
                        plaintext,
                    )
                };
                crate::writer::object::unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
                    object,
                    out,
                    map,
                    removed_refs,
                    &mut write_string,
                    direct_stream_writer,
                )
            })
    }

    /// Emit a page or `/Contents` array holder that owns direct streams while
    /// keeping qpdf's per-object string data key active. The stream payload is
    /// deliberately handled by the content-container helper's raw-stream
    /// route; only dictionary strings use this callback, matching the legacy
    /// direct-stream writer's encryption boundary.
    #[allow(dead_code)] // legacy ObjectRef adapter remains covered by serializer tests
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn write_handle_content_container_with_ref_map(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        object: &ObjectHandle,
        options: &WriterOptions,
        map: &dyn Fn(ObjectRef) -> crate::Result<ObjectRef>,
        removed_refs: &std::collections::BTreeSet<ObjectRef>,
    ) -> crate::Result<()> {
        if emitted_ref == self.encrypt_ref {
            return write_encryption_dictionary_handle(out, object); // cov:ignore: the pre-scanned page-content container cannot be the /Encrypt object
        }

        let cipher = self.cipher;
        let static_aes_iv = self.static_aes_iv;
        let aes_iv_generator = self.aes_iv_generator.as_mut();
        self.state
            .with_object_data_key(emitted_ref.number, object_stream_index, |state| {
                let mut write_string = |out: &mut OutputSink<'_>, plaintext: &[u8]| {
                    write_encrypted_or_plain_string(
                        state,
                        cipher,
                        static_aes_iv,
                        aes_iv_generator,
                        out,
                        plaintext,
                    )
                };
                crate::writer::plain::body::emit_content_container_from_handle_with_ref_map_and_string_writer(
                    object,
                    options,
                    out,
                    map,
                    removed_refs,
                    &mut write_string,
                )
            })
    }

    /// Content-container emission keyed by qpdf's raw source identity. This
    /// is the live QDF/compact counterpart of the legacy `ObjectRef` wrapper;
    /// direct stream framing and string encryption remain at the same writer
    /// boundary.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn write_handle_content_container_with_qpdf_obj_gen_map(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        object: &ObjectHandle,
        options: &WriterOptions,
        map: &dyn Fn(QpdfObjGen) -> crate::Result<ObjectRef>,
        removed_refs: &std::collections::BTreeSet<QpdfObjGen>,
    ) -> crate::Result<()> {
        if emitted_ref == self.encrypt_ref {
            return write_encryption_dictionary_handle(out, object); // cov:ignore: the pre-scanned page-content container cannot be the /Encrypt object
        }

        let cipher = self.cipher;
        let static_aes_iv = self.static_aes_iv;
        let aes_iv_generator = self.aes_iv_generator.as_mut();
        self.state
            .with_object_data_key(emitted_ref.number, object_stream_index, |state| {
                let mut write_string = |out: &mut OutputSink<'_>, plaintext: &[u8]| {
                    write_encrypted_or_plain_string(
                        state,
                        cipher,
                        static_aes_iv,
                        aes_iv_generator,
                        out,
                        plaintext,
                    )
                };
                crate::writer::plain::body::emit_content_container_from_handle_with_qpdf_obj_gen_map_and_string_writer(
                    object,
                    options,
                    out,
                    map,
                    removed_refs,
                    &mut write_string,
                )
            })
    }

    /// QDF stream-dictionary emission keyed by qpdf's raw object identity.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn write_handle_stream_dict_with_qpdf_obj_gen_map(
        &mut self,
        out: &mut OutputSink<'_>,
        emitted_ref: ObjectRef,
        object_stream_index: Option<u32>,
        dict: &ObjectHandle,
        options: StreamDictOptions,
        map: &dyn Fn(QpdfObjGen) -> crate::Result<ObjectRef>,
        removed_refs: &std::collections::BTreeSet<QpdfObjGen>,
        length_ref: Option<ObjectRef>,
    ) -> crate::Result<()> {
        if options.qdf && !options.encrypt_strings {
            return dict
                .unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_options(
                    out,
                    0,
                    map,
                    removed_refs,
                    length_ref,
                    options.dictionary,
                );
        }

        if !options.qdf && !options.encrypt_strings {
            return dict.unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options(
                out,
                options.dictionary,
                map,
                removed_refs,
            );
        }

        let cipher = self.cipher;
        let static_aes_iv = self.static_aes_iv;
        let aes_iv_generator = self.aes_iv_generator.as_mut();
        self.state
            .with_object_data_key(emitted_ref.number, object_stream_index, |state| {
                let mut write_string = |out: &mut OutputSink<'_>, plaintext: &[u8]| {
                    write_encrypted_or_plain_string(
                        state,
                        cipher,
                        static_aes_iv,
                        aes_iv_generator,
                        out,
                        plaintext,
                    )
                };
                if options.qdf {
                    dict.unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_string_writer_with_options(
                        out,
                        0,
                        map,
                        removed_refs,
                        length_ref,
                        options.dictionary,
                        &mut write_string,
                    )
                } else {
                    dict.unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_string_writer(
                        out,
                        options.dictionary,
                        map,
                        removed_refs,
                        &mut write_string,
                    )
                }
            })
    }
}

impl EncryptionContext {
    /// Return the context's canonical `/Encrypt` dictionary handle.
    pub(crate) fn encrypt_dict_handle(&self) -> ObjectHandle {
        self.encrypt_dict.clone()
    }
}

fn write_encrypted_or_plain_string(
    state: &WriterEncryptionState,
    cipher: WriteCipher,
    static_aes_iv: bool,
    aes_iv_generator: &mut AesIvGenerator,
    out: &mut OutputSink<'_>,
    plaintext: &[u8],
) -> crate::Result<()> {
    let Some(data_key) = state.current_data_key() else {
        return write_string_value(out, plaintext);
    };
    let ciphertext = encrypt_string(cipher, static_aes_iv, aes_iv_generator, data_key, plaintext)?;
    serialize_encrypted_string(out, &ciphertext, crate::writer::cipher_needs_aes_iv(cipher))
}

fn encrypt_string(
    cipher: WriteCipher,
    static_aes_iv: bool,
    aes_iv_generator: &mut AesIvGenerator,
    data_key: &[u8],
    plaintext: &[u8],
) -> crate::Result<Vec<u8>> {
    let mut bytes = plaintext.to_vec();
    let mut iv = if static_aes_iv {
        crate::pipeline::aes::static_initialization_vector()
    } else {
        [0; 16]
    };
    if crate::writer::cipher_needs_aes_iv(cipher) && !static_aes_iv {
        fill_aes_iv(aes_iv_generator, &mut iv)?;
    }
    match cipher {
        WriteCipher::PerObject(ObjectKeyAlg::Rc4) => {
            encrypt_cipher_bytes(&mut bytes, StringEncryptCipher::Rc4 { key: data_key }, &iv)?;
        }
        WriteCipher::PerObject(ObjectKeyAlg::Aes) => {
            // qpdf-deviation: qpdf hands Pl_AES_PDF the raw per-object key and its providers then read 16 bytes from a shorter buffer (undefined contents); reject instead of fabricating them
            let key: &[u8; 16] = data_key.try_into().map_err(|_| {
                crate::Error::Unsupported("V=4 AES-128 data key is not 16 bytes".to_string())
            })?;
            encrypt_cipher_bytes(&mut bytes, StringEncryptCipher::Aes128 { key }, &iv)?;
        }
        WriteCipher::FileKeyAes256 => {
            let key: &[u8; 32] = data_key.try_into().map_err(|_| {
                crate::Error::Unsupported("V=5 AES-256 data key is not 32 bytes".to_string())
            })?;
            encrypt_cipher_bytes(&mut bytes, StringEncryptCipher::Aes256 { key }, &iv)?;
        }
    }
    Ok(bytes)
}

fn fill_aes_iv(aes_iv_generator: &mut AesIvGenerator, iv: &mut [u8; 16]) -> crate::Result<()> {
    aes_iv_generator(iv).map_err(|error| {
        crate::Error::Unsupported(format!(
            "OS CSPRNG (getrandom) unavailable for AES IV generation: {error}"
        ))
    })
}

/// Serialize encrypted bytes using qpdf's cipher-specific representation:
/// AES ciphertext is always hexadecimal; RC4 retains normal string heuristics.
pub(crate) fn serialize_encrypted_string(
    out: &mut OutputSink<'_>,
    ciphertext: &[u8],
    use_aes: bool,
) -> crate::Result<()> {
    if use_aes {
        write_hex_string(out, ciphertext)?;
    } else {
        write_string_value(out, ciphertext)?;
    }
    Ok(())
}

/// Serialize an ObjectHandle-backed `/Encrypt` dictionary with the same
/// direct-entry hex policy as the canonical encryption writer. The handle
/// tree is kept as the source of truth; nested values and indirect references
/// use the canonical ObjectHandle writer rather than materializing `Object`.
pub(crate) fn write_encryption_dictionary_handle(
    out: &mut OutputSink<'_>,
    handle: &ObjectHandle,
) -> crate::Result<()> {
    const HEX_ENCRYPT_KEYS: [&[u8]; 5] = [b"/O", b"/U", b"/OE", b"/UE", b"/Perms"];

    let Some(entries) = handle.as_dictionary() else {
        return Err(crate::Error::System(
            "encryption handle does not contain a dictionary".to_string(),
        ));
    };

    out.write_bytes(b"<<")?;
    for (key, value) in entries {
        let key_without_slash = key.strip_prefix(b"/").unwrap_or(&key);
        out.write_bytes(b" /")?;
        write_name_escaped(out, key_without_slash)?;
        out.write_bytes(b" ")?;
        if HEX_ENCRYPT_KEYS.contains(&key.as_slice()) {
            if let Some(bytes) = value.as_string() {
                write_hex_string(out, &bytes)?;
                continue;
            } // cov:ignore: LLVM attributes the covered hex-key string branch to its continue terminator.
        } // cov:ignore: LLVM attributes the covered non-string encryption-key fallback to this closing branch.
        value.unparse_object(out)?;
    }
    out.write_bytes(b" >>")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encryption::standard::ObjectKeyAlg;
    use crate::writer::{StreamDictionaryOptions, WriteCipher};
    use std::collections::BTreeSet;
    use std::rc::Rc;

    #[test]
    fn unencrypted_qdf_stream_dict_uses_the_shared_dictionary_policy() {
        let context = EncryptionContext {
            encrypt_dict: ObjectHandle::dictionary(Vec::new()),
            file_key: vec![1; 5],
            cipher: WriteCipher::PerObject(ObjectKeyAlg::Rc4),
            encryption_v: 2,
            encryption_r: 3,
            encrypt_ref: ObjectRef::new(99, 0),
            id0: b"id".to_vec(),
            static_aes_iv: true,
            encrypt_metadata: true,
            metadata_ref: None,
        };
        let mut emitter = EncryptedStringEmitter::from_context(&context);
        let dict = ObjectHandle::stream(
            ObjectHandle::dictionary(vec![
                (
                    b"/Filter".to_vec(),
                    ObjectHandle::name(b"ASCIIHexDecode".to_vec()),
                ),
                (b"/Length".to_vec(), ObjectHandle::integer(3)),
            ]),
            Rc::new(b"abc".to_vec()),
        );
        let mut output = Vec::new();
        crate::writer::output::with_buffer_sink(&mut output, |out| {
            emitter.write_handle_stream_dict_with_qpdf_obj_gen_map(
                out,
                ObjectRef::new(3, 0),
                None,
                &dict,
                StreamDictOptions::new(true, StreamDictionaryOptions::new(true, true), false),
                // cov:ignore-start: the direct test stream dictionary has no indirect child, so this callback is not invoked.
                &|object_gen| {
                    Ok(object_gen
                        .to_object_ref()
                        .expect("direct test dictionary has no raw child"))
                },
                // cov:ignore-end
                &BTreeSet::new(),
                None,
            )
        })
        .unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("/Filter /FlateDecode"));
        assert!(!text.contains("ASCIIHexDecode"));
    }

    #[test]
    fn content_container_encrypts_dictionary_strings_but_keeps_direct_stream_data_raw() {
        let mut pdf = crate::Pdf::empty().expect("create content-container reference owner");
        let mapped = pdf
            .make_indirect_object_handle(ObjectHandle::integer(7))
            .expect("create mapped content-container child");
        let mapped_ref = mapped.object_ref().unwrap();
        let context = EncryptionContext {
            encrypt_dict: ObjectHandle::dictionary(Vec::new()),
            file_key: vec![1; 5],
            cipher: WriteCipher::PerObject(ObjectKeyAlg::Rc4),
            encryption_v: 2,
            encryption_r: 3,
            encrypt_ref: ObjectRef::new(99, 0),
            id0: b"id".to_vec(),
            static_aes_iv: true,
            encrypt_metadata: true,
            metadata_ref: None,
        };
        let direct_stream = ObjectHandle::stream(
            ObjectHandle::dictionary(vec![(b"/Length".to_vec(), ObjectHandle::integer(8))]),
            Rc::new(b"raw-data".to_vec()),
        );
        let container = ObjectHandle::dictionary(vec![
            (
                b"/Label".to_vec(),
                ObjectHandle::string(b"secret-label".to_vec()),
            ),
            (b"/Contents".to_vec(), direct_stream),
            (b"/Mapped".to_vec(), mapped),
        ]);
        let mut emitter = EncryptedStringEmitter::from_context(&context);
        let mut output = Vec::new();

        crate::writer::output::with_buffer_sink(&mut output, |out| {
            emitter.write_handle_content_container_with_ref_map(
                out,
                ObjectRef::new(3, 0),
                None,
                &container,
                &WriterOptions::default(),
                &|object_ref| {
                    assert_eq!(object_ref, mapped_ref);
                    Ok(ObjectRef::new(7, 0))
                },
                &BTreeSet::new(),
            )
        })
        .expect("encrypted content-container emission");

        assert!(output
            .windows(b"stream\nraw-data\nendstream".len())
            .any(|window| window == b"stream\nraw-data\nendstream"));
        assert!(!output
            .windows(b"secret-label".len())
            .any(|window| window == b"secret-label"));
        assert!(output
            .windows(b"7 0 R".len())
            .any(|window| window == b"7 0 R"));
    }

    #[test]
    fn string_writer_without_an_object_data_key_uses_plain_pdf_string_syntax() {
        let state = WriterEncryptionState::new(false, Vec::new(), false, 0, 0);
        let mut iv_generator = |_iv: &mut [u8; 16]| Ok(());
        let mut output = Vec::new();

        crate::writer::output::with_buffer_sink(&mut output, |out| {
            write_encrypted_or_plain_string(
                &state,
                WriteCipher::PerObject(ObjectKeyAlg::Rc4),
                true,
                &mut iv_generator,
                out,
                b"plain text",
            )
        })
        .expect("plain string emission without a current data key");

        assert_eq!(output, b"(plain text)");
    }

    #[test]
    fn aes_iv_generation_errors_cross_the_writer_error_boundary() {
        let mut generator = |_iv: &mut [u8; 16]| Err(getrandom::Error::UNEXPECTED);
        let mut iv = [0_u8; 16];
        let error = fill_aes_iv(&mut generator, &mut iv).expect_err("CSPRNG failure");
        assert!(error.to_string().contains("OS CSPRNG"));
    }

    #[test]
    fn encryption_dictionary_hex_keys_use_hex_string_syntax() -> crate::Result<()> {
        let dictionary = ObjectHandle::dictionary(vec![
            (b"/O".to_vec(), ObjectHandle::string(vec![0x01, 0xab])),
            (b"/V".to_vec(), ObjectHandle::integer(4)),
        ]);
        let mut output = Vec::new();
        crate::writer::output::with_buffer_sink(&mut output, |out| {
            write_encryption_dictionary_handle(out, &dictionary)
        })?;
        assert!(String::from_utf8_lossy(&output).contains("/O <01ab>"));
        Ok(())
    }
}