Skip to content

fix(pathutil): save an encrypted input with its own encryption so RC4 edits land - #6

Open
weitheng wants to merge 1 commit into
AryanBV:mainfrom
weitheng:fix/rc4-reencrypt-upstream
Open

weitheng wants to merge 1 commit into
AryanBV:mainfrom
weitheng:fix/rc4-reencrypt-upstream

Conversation

@weitheng

@weitheng weitheng commented Nov 1, 2026

Copy link
Copy Markdown

What breaks

Every edit of an RC4-encrypted PDF (revision 2 or 3, for example an owner
password with an empty user password) fails instead of landing:

ValueError: Cannot encrypt metadata when R < 4

Why

_pathutil._save_pdf, the save helper every edit verb uses (A2.3, INV-W-5),
re-encrypts an encrypted input with
pikepdf.Encryption(owner=pw, user=pw, R=info.R, allow=pdf.allow).
pikepdf.Encryption defaults to aes=True and metadata=True, and pikepdf
refuses both below R 4. The encryption_dropped fallback catches only
pikepdf.PdfError, so the ValueError escapes and the edit fails. Seen on
pikepdf 10.5.1 and 10.17.0.

Rebuilding the encryption from the caller's password has quieter problems too:
an R 4 input using RC4 or /EncryptMetadata false comes back as AES with
metadata encrypted, owner and user collapse to the one password the edit used,
and pikepdf writes an R 2-4 str password as PDFDocEncoding but opens with its
UTF-8 bytes, so a non-ASCII password can lock the caller out of the output
while the edit reports success=True.

Fix

_save_pdf saves an encrypted input with encryption=True, so qpdf copies the
input's own encryption (R, V, key length, /O, /U, /P,
/EncryptMetadata, the first /ID and the file key). The output opens with
exactly the passwords that opened the input, each with its own owner or user
rights. The one scheme change is qpdf's: a V 4 file whose crypt filters use RC4
is written with AESV2 under the same key. The now unused reencrypt_password
parameter is removed; the verbs still take password to open the input. The
fallback is unchanged: only a pikepdf.PdfError from the injected encrypted
save retries unencrypted and records encryption_dropped. CHANGELOG,
LIMITATIONS and docs/decisions.md are updated.

Testing

tests/invariants/test_w_5_encryption_round_trip.py now checks, for each
candidate password, whether it opens the output and with which rights, against
the input: RC4 R 2 and R 3 with owner-only and owner+user passwords,
owner-password edits (R 2, 3, 4, 6), UTF-8- and PDFDoc-keyed non-ASCII
passwords as str and bytes, 40/64-bit R 3 keys, R 4 RC4,
/EncryptMetadata false, ValueError propagation, the fallback, and that
encrypt_pdf never saves a plaintext copy when its own encrypted save fails.
36 of its 48 tests fail on main and all 48 pass with the fix.

  • ruff check src/ tests/: all checks passed.
  • python -m pytest on macOS: 871 passed, 357 skipped, 27 failed. The same 27
    fail on main (831 passed there): 24 TTLibFileIsCollectionError from macOS
    .ttc system fonts, two from the tests/corpus/cidfont_synthetic.pdf
    fixture missing in a fresh checkout, and
    TestCIDFontReplace::test_winAnsi_regression_guard. None of them touch
    encryption.
  • python -m mypy: 21 unused "type: ignore" errors with pikepdf 10.17.0,
    the same 21 as on main, none in _pathutil.py.

Reproduction

python -c "import pikepdf; from pdf_edit_engine._pathutil import _save_pdf; p = pikepdf.new(); p.add_blank_page(); p.save('r3.pdf', encryption=pikepdf.Encryption(owner='owner', user='', R=3, aes=False, metadata=False)); _save_pdf(pikepdf.open('r3.pdf'), 'out.pdf')"

On main this raises ValueError: Cannot encrypt metadata when R < 4; with the
fix out.pdf is R 3 RC4 under the input's key.

… edits land

_save_pdf re-encrypted an encrypted input with
pikepdf.Encryption(owner=pw, user=pw, R=info.R, allow=pdf.allow).
Encryption defaults to aes=True and metadata=True, and pikepdf refuses
both below R 4, so every edit of an RC4 revision 2 or 3 input (an owner
password with an empty user password is the common case) failed with
ValueError: Cannot encrypt metadata when R < 4. The encryption_dropped
fallback catches only pikepdf.PdfError, so the edit did not land at all.
An R 4 input using RC4 or /EncryptMetadata false was re-encrypted as AES
with metadata encrypted. Rebuilding the key from the caller's password
also collapsed owner and user to that one password, and pikepdf writes an
R 2-4 str password as PDFDocEncoding but opens with its UTF-8 bytes, so a
UTF-8-keyed non-ASCII password could lock the caller out of the output
with success=True.

- _save_pdf saves an encrypted input with encryption=True, so qpdf copies
  R, V, key length, /O, /U, /P, /EncryptMetadata, the first /ID and the
  file key. The output opens with exactly the passwords that opened the
  input, each with its own rights. The one scheme change is qpdf's: a V 4
  file whose crypt filters use RC4 is written with AESV2 under the same
  key. The now unused reencrypt_password parameter is removed.
- The fallback stays a PdfError from the injected encrypted save only,
  logged with exc_info. A ValueError (overwriting the input,
  normalize_content) propagates, and a caller-pinned encryption never
  arms the fallback.
- CHANGELOG, LIMITATIONS and a decisions row describe the result,
  including that reorder_pages, split_pdf and merge_pdfs with an
  unencrypted first file write an unencrypted new document.

INV-W-5 now checks, for each candidate password, whether it opens the
output and with which rights, against the input: RC4 R 2 and R 3 inputs
with owner-only and owner+user passwords, owner-password edits (R2, R3,
R4, R6), UTF-8- and PDFDoc-keyed non-ASCII R 2-4 passwords as str and
bytes, hand-built 40/64-bit R 3 and R 2 /P -3904 RC4 inputs, R 4 RC4
written as AES under the same key, /EncryptMetadata false, ValueError
propagation, the fallback's traceback, and an import of the package
without pikepdf.models.EncryptionMethod (pikepdf 10.0-10.8).
@coderabbitai

coderabbitai Bot commented Nov 1, 2026

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff1e7225-3369-4ca0-a198-f7a0d5536a38
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@weitheng

weitheng commented Nov 1, 2026

Copy link
Copy Markdown
Author

When CI runs here, the Typecheck step will fail, and that failure is not from this change: main has failed Typecheck on every job since 22 Jul (21 Unused "type: ignore" comment errors once pikepdf 10.6+ typed Object), and with that fixed the Linux jobs also fail two Arabic corpus builder tests on DejaVu Sans. #7 fixes both; after it is merged, re-running CI here picks it up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants