oxidize-pdf 3.0.5

Pure Rust PDF library for AI/RAG: structure-aware chunking with bounding boxes, heading context, and token estimates. No Python, no ML, no C bindings.
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
use oxidize_pdf::document::{DocumentEncryption, EncryptionStrength};
use oxidize_pdf::encryption::Permissions;
use oxidize_pdf::parser::PdfReader;
use oxidize_pdf::text::ExtractionOptions;
use oxidize_pdf::writer::PdfWriter;
use oxidize_pdf::{Document, Font, Page};
use std::io::Cursor;

// ── Fase 2: Writer must emit /Encrypt and /ID in trailer ────────────────

#[test]
fn test_encrypted_document_has_encrypt_in_trailer() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("user", "owner");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    assert!(
        content.contains("/Encrypt"),
        "trailer must reference /Encrypt"
    );
    assert!(content.contains("/ID"), "trailer must contain /ID array");
    assert!(
        content.contains("/Filter /Standard"),
        "Encrypt dict must have /Filter /Standard"
    );
}

#[test]
fn test_unencrypted_document_has_no_encrypt() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    assert!(
        !content.contains("/Encrypt"),
        "unencrypted doc must not have /Encrypt"
    );
}

// ── Fase 1: EncryptionStrength AES variants ─────────────────────────────

#[test]
fn test_encryption_strength_aes128_creates_valid_dict() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes128,
    );
    let dict = enc
        .create_encryption_dict(Some(b"test_file_id_123"))
        .unwrap();
    // AES-128 requires V=4, R=4 per ISO 32000-1 §7.6.1 Table 20
    assert_eq!(dict.v, 4);
    assert_eq!(dict.r, 4);
    assert_eq!(dict.length, Some(16));
    // V=4 requires crypt filters
    assert!(dict.cf.is_some());
    assert!(dict.stm_f.is_some());
    assert!(dict.str_f.is_some());
}

#[test]
fn test_encryption_strength_aes256_creates_valid_dict() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes256,
    );
    let dict = enc
        .create_encryption_dict(Some(b"test_file_id_123"))
        .unwrap();
    // AES-256 requires V=5, R=5 per ISO 32000-2
    assert_eq!(dict.v, 5);
    assert_eq!(dict.r, 5);
    assert_eq!(dict.length, Some(32));
    assert!(dict.cf.is_some());
    assert!(dict.stm_f.is_some());
    assert!(dict.str_f.is_some());
}

#[test]
fn test_aes128_dict_has_aesv2_crypt_filter() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes128,
    );
    let dict = enc
        .create_encryption_dict(Some(b"test_file_id_123"))
        .unwrap();
    let cf = dict.cf.as_ref().unwrap();
    assert_eq!(cf.len(), 1);
    assert_eq!(cf[0].name, "StdCF");
    assert_eq!(
        cf[0].method,
        oxidize_pdf::encryption::CryptFilterMethod::AESV2
    );
}

#[test]
fn test_aes256_dict_has_aesv3_crypt_filter() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes256,
    );
    let dict = enc
        .create_encryption_dict(Some(b"test_file_id_123"))
        .unwrap();
    let cf = dict.cf.as_ref().unwrap();
    assert_eq!(cf.len(), 1);
    assert_eq!(cf[0].name, "StdCF");
    assert_eq!(
        cf[0].method,
        oxidize_pdf::encryption::CryptFilterMethod::AESV3
    );
}

#[test]
fn test_aes128_handler_uses_r4() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes128,
    );
    let handler = enc.handler();
    assert_eq!(
        handler.revision,
        oxidize_pdf::encryption::SecurityHandlerRevision::R4
    );
}

#[test]
fn test_aes256_handler_uses_r5() {
    let enc = DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes256,
    );
    let handler = enc.handler();
    assert_eq!(
        handler.revision,
        oxidize_pdf::encryption::SecurityHandlerRevision::R5
    );
}

// ── Fase 3: Objects must be encrypted when writing ──────────────────────

#[test]
fn test_encrypted_document_content_is_not_plaintext() {
    let mut doc = Document::new();
    let mut page = Page::a4();
    // Use a unique marker string that we can search for in the raw bytes
    page.text()
        .at(100.0, 700.0)
        .write("SECRET_MARKER_XYZ_12345")
        .unwrap();
    doc.add_page(page);
    doc.encrypt_with_passwords("user", "owner");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    // The plaintext marker must NOT appear in the raw PDF bytes
    let content = String::from_utf8_lossy(&buf);
    assert!(
        !content.contains("SECRET_MARKER_XYZ_12345"),
        "encrypted PDF must not contain plaintext content — objects are not being encrypted"
    );
}

#[test]
fn test_encrypt_dict_object_is_not_encrypted() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("user", "owner");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    // The /Encrypt dictionary itself must remain readable (not encrypted)
    // per ISO 32000-1 §7.6.1
    assert!(
        content.contains("/Filter /Standard"),
        "/Encrypt dict must remain unencrypted per ISO 32000-1 §7.6.1"
    );
}

// ── Fase 4: Round-trip (write encrypted → read with password) ───────────

#[test]
fn test_round_trip_encrypted_pdf_is_parseable() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("testpass", "ownerpass");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    // The encrypted PDF must be parseable by our reader
    let mut reader = PdfReader::new(Cursor::new(buf)).expect("encrypted PDF must be parseable");
    assert!(reader.is_encrypted(), "reader must detect encryption");

    // Must be able to unlock with the user password
    reader
        .unlock("testpass")
        .expect("must unlock with correct user password");
}

#[test]
fn test_round_trip_wrong_password_fails() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("correct", "owner");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let mut reader = PdfReader::new(Cursor::new(buf)).expect("must parse");
    assert!(reader.is_encrypted());

    let result = reader.unlock("wrong_password");
    assert!(
        result.is_err(),
        "wrong password must fail to unlock encrypted PDF"
    );
}

// ── Fase 5: Edge cases and security tests ───────────────────────────────

#[test]
fn test_empty_password_encryption() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("", "");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let mut reader = PdfReader::new(Cursor::new(buf)).expect("must parse");
    assert!(reader.is_encrypted());
    reader.unlock("").expect("empty password must unlock");
}

#[test]
fn test_owner_password_also_unlocks() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("user_pass", "owner_pass");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let mut reader = PdfReader::new(Cursor::new(buf)).expect("must parse");
    assert!(reader.is_encrypted());
    reader
        .unlock("owner_pass")
        .expect("owner password must also unlock the PDF");
}

#[test]
fn test_encrypted_pdf_preserves_structure() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.encrypt_with_passwords("test", "test");

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    // Basic PDF structure must be present
    assert!(content.starts_with("%PDF-"));
    assert!(content.contains("%%EOF"));
    assert!(content.contains("/Type /Catalog"));
    assert!(content.contains("/Type /Pages"));
}

#[test]
fn test_encryption_with_different_permissions() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());

    let mut perms = Permissions::new();
    perms.set_print(true);
    perms.set_copy(false);

    doc.set_encryption(DocumentEncryption::new(
        "user",
        "owner",
        perms,
        EncryptionStrength::Rc4_128bit,
    ));

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    assert!(content.contains("/Encrypt"), "must have /Encrypt");
    assert!(content.contains("/P "), "must have /P permission entry");
}

// ── Fase 6: AES-128 (R4) round-trip — currently broken ──────────────────

#[test]
fn test_aes128_round_trip_write_read() {
    let mut doc = Document::new();
    doc.add_page(Page::a4());
    doc.set_encryption(DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes128,
    ));

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let mut reader =
        PdfReader::new(Cursor::new(buf)).expect("AES-128 encrypted PDF must be parseable");
    assert!(
        reader.is_encrypted(),
        "reader must detect AES-128 encryption"
    );
    reader
        .unlock("user")
        .expect("must unlock AES-128 encrypted PDF with correct user password");
}

#[test]
fn test_aes128_content_is_encrypted() {
    let mut doc = Document::new();
    let mut page = Page::a4();
    page.text()
        .at(100.0, 700.0)
        .write("SECRET_AES128_MARKER")
        .unwrap();
    doc.add_page(page);
    doc.set_encryption(DocumentEncryption::new(
        "user",
        "owner",
        Permissions::all(),
        EncryptionStrength::Aes128,
    ));

    let mut buf = Vec::new();
    PdfWriter::new_with_writer(&mut buf)
        .write_document(&mut doc)
        .unwrap();

    let content = String::from_utf8_lossy(&buf);
    assert!(
        !content.contains("SECRET_AES128_MARKER"),
        "AES-128 encrypted PDF must not contain plaintext content — objects are not being encrypted"
    );
}

// ── Issue #364: full round-trip — content must be recoverable after unlock ──
// The Fase 6 tests above stop at unlock() and never extract content, so the
// broken decryption path was untested. These assert the marker survives a
// write → read → unlock → extract round-trip for every cipher.

const ROUNDTRIP_MARKER: &str = "ROUNDTRIP_MARKER_42";

/// Write a single-page PDF containing the marker, optionally encrypted, then
/// read it back, unlock, and extract the text of page 0.
fn roundtrip_extract(strength: Option<EncryptionStrength>) -> String {
    let mut doc = Document::new();
    let mut page = Page::new(595.0, 842.0);
    page.text()
        .set_font(Font::Helvetica, 24.0)
        .at(72.0, 760.0)
        .write(ROUNDTRIP_MARKER)
        .unwrap();
    doc.add_page(page);
    if let Some(s) = strength {
        doc.set_encryption(DocumentEncryption::new("u", "o", Permissions::all(), s));
    }

    let bytes = doc.to_bytes().expect("write document");
    let mut reader = PdfReader::new(Cursor::new(bytes)).expect("parse written PDF");
    if reader.is_encrypted() {
        reader
            .unlock_with_password("u")
            .expect("unlock with correct user password");
    }
    let pdfdoc = reader.into_document();
    pdfdoc
        .extract_text_from_page_with_options(0, ExtractionOptions::default())
        .expect("extract text")
        .text
}

#[test]
fn test_roundtrip_plaintext_baseline() {
    let text = roundtrip_extract(None);
    assert!(
        text.contains(ROUNDTRIP_MARKER),
        "plaintext round-trip must recover the marker, got: {text:?}"
    );
}

#[test]
fn test_roundtrip_rc4_128_baseline() {
    let text = roundtrip_extract(Some(EncryptionStrength::Rc4_128bit));
    assert!(
        text.contains(ROUNDTRIP_MARKER),
        "RC4-128 round-trip must recover the marker, got: {text:?}"
    );
}

#[test]
fn test_roundtrip_aes128_recovers_content() {
    let text = roundtrip_extract(Some(EncryptionStrength::Aes128));
    assert!(
        text.contains(ROUNDTRIP_MARKER),
        "AES-128 round-trip must recover the marker after unlock, got: {text:?}"
    );
}

#[test]
fn test_roundtrip_aes256_recovers_content() {
    let text = roundtrip_extract(Some(EncryptionStrength::Aes256));
    assert!(
        text.contains(ROUNDTRIP_MARKER),
        "AES-256 round-trip must recover the marker after unlock, got: {text:?}"
    );
}

/// A wrong password must not unlock an AES-256 document (it must report failure,
/// not silently yield a usable-but-empty reader). Guards against the unlock path
/// masking a decryption-key mismatch.
#[test]
fn test_roundtrip_aes256_wrong_password_does_not_unlock() {
    let mut doc = Document::new();
    let mut page = Page::new(595.0, 842.0);
    page.text()
        .set_font(Font::Helvetica, 24.0)
        .at(72.0, 760.0)
        .write(ROUNDTRIP_MARKER)
        .unwrap();
    doc.add_page(page);
    doc.set_encryption(DocumentEncryption::new(
        "u",
        "o",
        Permissions::all(),
        EncryptionStrength::Aes256,
    ));

    let bytes = doc.to_bytes().expect("write document");
    let mut reader = PdfReader::new(Cursor::new(bytes)).expect("parse written PDF");
    assert!(reader.is_encrypted());

    let unlocked = reader
        .unlock_with_password("definitely-wrong")
        .expect("unlock attempt itself must not error");
    assert!(!unlocked, "a wrong password must not unlock the document");
}

/// The owner password must also unlock an AES-256 document and recover content
/// (exercises the R5 owner-password path: validate /O, recover key from /OE).
#[test]
fn test_roundtrip_aes256_owner_password_recovers_content() {
    let mut doc = Document::new();
    let mut page = Page::new(595.0, 842.0);
    page.text()
        .set_font(Font::Helvetica, 24.0)
        .at(72.0, 760.0)
        .write(ROUNDTRIP_MARKER)
        .unwrap();
    doc.add_page(page);
    doc.set_encryption(DocumentEncryption::new(
        "u",
        "owner-secret",
        Permissions::all(),
        EncryptionStrength::Aes256,
    ));

    let bytes = doc.to_bytes().expect("write document");
    let mut reader = PdfReader::new(Cursor::new(bytes)).expect("parse written PDF");
    let unlocked = reader
        .unlock_with_password("owner-secret")
        .expect("owner unlock must not error");
    assert!(unlocked, "owner password must unlock the document");

    let pdfdoc = reader.into_document();
    let text = pdfdoc
        .extract_text_from_page_with_options(0, ExtractionOptions::default())
        .expect("extract text")
        .text;
    assert!(
        text.contains(ROUNDTRIP_MARKER),
        "owner-unlocked AES-256 must recover the marker, got: {text:?}"
    );
}