Modern Apps git

← Modern-Apps.git

pdf: fix opening user-password PDFs and encrypted-string saving

Commit
10854ab7e61f26232a507767a1a642fcc92ecf09
Author
Vayun Mathur <[email protected]>
When
2026-11-07 19:03 UTC (28 days ago)
Parents
63c0038
Two defects in the Rust encryption path, found by CI (the three
encrypt save-roundtrip tests):

1. A saved encrypted PDF could not be read back. crypt_object wrote
   the encrypted string bytes as literal PDF strings; arbitrary binary
   (unbalanced parens/backslashes) corrupted the file so parsers lost
   every object except /Encrypt. Transformed strings are now re-tagged
   hexadecimal, which carries any bytes safely.

2. Opening a PDF whose USER password is non-empty returned a
   successful empty document. lopdf 0.45 load_mem authenticates with
   the empty load password and, on failure, loads no objects at all;
   decrypt_in_place then reported Ok after decrypting the husk. The
   production open path (new registry::open_decrypted, used by
   open_document_pw) now loads with the password via
   LoadOptions::with_password when lopdf can authenticate+decrypt
   during the parse, and only falls back to decrypt_in_place for
   passwords/variants lopdf cannot carry. The roundtrip tests go
   through that production path.

Verified: cargo +1.97.0 test --locked in pdf/src/main/rust —
571 passed, 0 failed (was 568 passed, 3 failed).

Diff

pdf/src/main/rust/src/decrypt.rs
diff --git a/pdf/src/main/rust/src/decrypt.rs b/pdf/src/main/rust/src/decrypt.rsindex ad3eefd582..269eac8fc1 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -57,9 +57,15 @@ fn crypt_object_split(     streams: Option<&dyn Fn(&[u8]) -> Vec<u8>>, ) {     match obj {-        Object::String(s, _) => {+        Object::String(s, fmt) => {             if let Some(apply) = strings {                 *s = apply(s);+                // Transformed (encrypted or decrypted) bytes are arbitrary+                // binary: as a literal string they can contain unbalanced+                // parens/backslashes that corrupt the file for every parser+                // (a saved-then-reloaded encrypted doc lost all objects but+                // the /Encrypt dict). Hex strings carry any bytes safely.+                *fmt = lopdf::StringFormat::Hexadecimal;             }         }         Object::Array(a) => {
pdf/src/main/rust/src/decrypt_part1.rs
diff --git a/pdf/src/main/rust/src/decrypt_part1.rs b/pdf/src/main/rust/src/decrypt_part1.rsindex 4ea07268d8..0b5ad27487 100644--- a/pdf/src/main/rust/src/decrypt_part1.rs+++ b/pdf/src/main/rust/src/decrypt_part1.rs@@ -310,7 +310,9 @@ mod tests {         ]);         crypt_object(&mut obj, &flip);         let Object::Array(a) = &obj else { panic!() };-        assert_eq!(a[0], Object::String(flip(b"s"), lopdf::StringFormat::Literal));+        // Transformed strings are re-tagged hexadecimal (binary-safe); the+        // payload is the flipped bytes either way.+        assert_eq!(a[0], Object::String(flip(b"s"), lopdf::StringFormat::Hexadecimal));         let Object::Stream(s) = &a[1] else { panic!() };         assert_eq!(s.content, flip(b"c"));     }
pdf/src/main/rust/src/fonts_part4.rs
diff --git a/pdf/src/main/rust/src/fonts_part4.rs b/pdf/src/main/rust/src/fonts_part4.rsindex ac1b24fe42..dc5fce87ad 100644--- a/pdf/src/main/rust/src/fonts_part4.rs+++ b/pdf/src/main/rust/src/fonts_part4.rs@@ -413,9 +413,11 @@ mod encrypt_tests {         let mut doc0 = Document::load_mem(&enc).unwrap();         assert!(doc0.trailer.get(b"Encrypt").is_ok(), "should be encrypted");         assert_ne!(crate::decrypt_in_place(&mut doc0, b""), crate::DecryptStatus::Ok);-        // Correct password decrypts and recovers the /Title string.-        let mut doc = Document::load_mem(&enc).unwrap();-        assert_eq!(crate::decrypt_in_place(&mut doc, pw), crate::DecryptStatus::Ok);+        // Correct password decrypts and recovers the /Title string. Goes+        // through the production open path: plain load_mem cannot carry a+        // user password (lopdf drops every object when its empty-password+        // authentication fails), so decrypt_in_place alone sees a husk.+        let doc = crate::registry::open_decrypted(&enc, pw).expect("open with correct password");         let info_ref = doc.trailer.get(b"Info").unwrap().as_reference().unwrap();         let info = doc.get_dictionary(info_ref).unwrap();         let got = info.get(b"Title").unwrap().as_str().unwrap();@@ -437,3 +439,5 @@ mod encrypt_tests {         roundtrip(crate::EncryptAlgo::Aes256);     } }++
pdf/src/main/rust/src/registry.rs
diff --git a/pdf/src/main/rust/src/registry.rs b/pdf/src/main/rust/src/registry.rsindex bea1c861e2..125aa65942 100644--- a/pdf/src/main/rust/src/registry.rs+++ b/pdf/src/main/rust/src/registry.rs@@ -47,20 +47,51 @@ pub(crate) fn next_handle() -> i64 { /// failure, wrong password, or unsupported encryption. /// /// Size guard: rejects inputs larger than 200 MB to prevent OOM DoS.+/// Load `bytes` and, if encrypted, decrypt with `password`; None on any+/// failure (bad password, unparseable, unsupported).+///+/// Why the password goes to the loader: lopdf 0.45's `load_mem` authenticates+/// with the (empty) load password and, when that fails, returns a document+/// whose objects were never loaded — only the /Encrypt dictionary survives.+/// `decrypt_in_place` on such a husk reports Ok after "decrypting" nothing,+/// so a user-password-protected PDF used to open as a successful empty+/// document. Loading with the password lets lopdf decrypt during the parse+/// (objects present, plaintext, /Encrypt cleared); the in-place path remains+/// as the fallback for passwords lopdf's &str API cannot carry and for+/// encryption variants its handler refuses.+pub(crate) fn open_decrypted(bytes: &[u8], password: &[u8]) -> Option<Document> {+    let mut doc = load_document_lenient(bytes)?;+    if doc.trailer.get(b"Encrypt").is_err() {+        return Some(doc);+    }+    if let Ok(pw) = std::str::from_utf8(password) {+        if let Ok(d2) = Document::load_mem_with_options(+            bytes,+            lopdf::LoadOptions::with_password(pw),+        ) {+            // was_encrypted + !is_encrypted means lopdf authenticated and+            // decrypted in-place; an auth failure comes back as a husk+            // (still "encrypted", no objects), which must not win.+            if d2.was_encrypted() && !d2.is_encrypted() && !d2.objects.is_empty() {+                return Some(d2);+            }+        }+    }+    if decrypt_in_place(&mut doc, password) != DecryptStatus::Ok {+        return None;+    }+    Some(doc)+}+ pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 {     // Zip-bomb / OOM guard: reject absurdly large PDF before parsing.     if bytes.len() > MAX_PDF_BYTES {         return 0;     }-    let mut doc = match load_document_lenient(bytes) {+    let doc = match open_decrypted(bytes, password) {         Some(d) => d,         None => return 0,     };-    if doc.trailer.get(b"Encrypt").is_ok()-        && decrypt_in_place(&mut doc, password) != DecryptStatus::Ok-    {-        return 0;-    }     let handle = next_handle();     // Lock ordering: registry first, then index_cache if eviction needed.     let mut map = registry()