diff --git a/CHANGELOG.md b/CHANGELOG.md index 1752e7d..1e8e4b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Fixed + +- **Edits of RC4-encrypted PDFs land, and an edited encrypted PDF opens + with the passwords that opened it.** Every edit of an RC4 revision 2 or 3 + input (for example an owner password with an empty user password) failed + with `ValueError: Cannot encrypt metadata when R < 4`, because the output + was re-encrypted with pikepdf's AES and encrypt-metadata defaults. The + output is now saved with the input's own encryption (pikepdf + `encryption=True`: the same key, `/O`, `/U`, `/P`, key length and + `/EncryptMetadata`). An owner password and a user password both keep + working, each with its own rights, whichever one the edit used, where + both used to collapse to the caller's password; an owner-only file still + opens with no password; and a non-ASCII password still opens the output. + The one scheme change is qpdf's: an R 4 file whose crypt filters use RC4 + is written with AES-128 under the same key. + ## [0.2.0] — 2026-06-02 Editing-depth release. v0.2.0 widens the set of PDFs the engine can edit diff --git a/LIMITATIONS.md b/LIMITATIONS.md index 21fcd3f..e8c231a 100644 --- a/LIMITATIONS.md +++ b/LIMITATIONS.md @@ -60,7 +60,7 @@ Identity-H CIDFont PDFs (Chrome, Google Docs, Word) may be slower due to CMap pa ## PDF compatibility -- Encrypted PDFs require the password to open, but once it is provided they are edited and re-saved with their encryption preserved as of v0.2.0 (A2.3 — re-encrypted with the same algorithm and permissions; a genuine re-encryption failure falls back to an unencrypted save and surfaces an `encryption_dropped` Degradation) +- Encrypted PDFs require the password to open, but once it is provided they are edited and re-saved with their encryption preserved as of v0.2.0 (A2.3 — saved with the input's own encryption, RC4 R 2 and 3 included: the same key, revision, key length, `/EncryptMetadata` and permissions, and the same owner and user passwords; the one exception is an R 4 file whose crypt filters use RC4, which qpdf writes with AES-128 under the same key; a genuine re-encryption failure falls back to an unencrypted save and surfaces an `encryption_dropped` Degradation). `reorder_pages`, `split_pdf`, and `merge_pdfs` when its first file is not encrypted write a new document, so their output is not encrypted - PDF/A compliance is not maintained after editing - Digital signatures are invalidated by any edit (inherent to how PDF signatures work) - Linearization (Fast Web View) is preserved on save as of v0.2.0 (A2.2 — a linearized input is re-linearized; on the rare case pikepdf cannot re-linearize, the edit still succeeds via a normal save and surfaces a `linearization_dropped` Degradation). A non-linearized input is unaffected diff --git a/docs/decisions.md b/docs/decisions.md index 5b4bd05..b1146ed 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -46,6 +46,7 @@ Architectural and technical decisions for pdf-edit-engine. | 2026-06-02 | A2.3 encryption round-trip preservation (INV-W-5, v0.2.0): the single canonical save helper `_pathutil._save_pdf` reads `pdf.is_encrypted` ONCE before serializing and, when True AND the caller has not pinned an explicit `encryption=` save-kwarg, re-encrypts the output with `pikepdf.Encryption(owner=pw, user=pw, R=info.R, allow=pdf.allow)` where `pw` is the caller-supplied `reencrypt_password` (threaded from the verb that opened the file — bytes decoded `latin-1` losslessly), so the encryption property round-trips. A NON-encrypted input never sets `encryption`, so its save is byte-identical to pre-A2.3 (zero blast radius). NEW defaulted out-param `encryption_log: list[str] \| None = None` (mirrors A2.2 `linearization_log` / `fonts.extend_subset` `substitution_log`); on a genuine `pikepdf.PdfError` from the encrypted save it retries ONCE WITHOUT encryption (the edit still lands) and appends `_ENCRYPTION_DROPPED_DETAIL`, while an `OSError` is NOT caught (falls to the outer translator — INV-L-1 / F-C-03 path-strip preserved). `injected_encryption` gates the fallback on `isinstance(save_kwargs.get("encryption"), pikepdf.Encryption)` so a caller-pinned `encryption=False`/`Encryption(...)` never arms it. A ~13-verb keyword-only `password: str \| bytes \| None = None` cascade reaches `open_pdf` on all read+edit verbs (locator find/get_text/get_fonts/get_text_layout/extract_bbox_text ×5 forward-only; surgeon replace/replace_all/batch_replace ×3 + structural shift_content_below/replace_block/batch_replace_block/delete_block/insert_text_block ×5 ALSO thread `reencrypt_password`+`encryption_log` and surface the NEW `encryption_dropped` kind via a module-private `_surface_encryption_dropped` duplicated in surgeon+structural, mirroring `_surface_linearization_dropped`); `replace_all`/`batch_replace` ALSO forward `password` into their internal `find(pdf_path, ...)` re-open (the non-obvious cascade hop). The three v0.1.x surgeon `is_encrypted` "Cannot edit encrypted PDF" blanket refusals are REMOVED — an encrypted PDF opened with the correct password is now editable. Exempt verbs: `encrypt_pdf` pins its own `encryption=` (wins the guard), `decrypt_pdf` pins explicit `encryption=False` to OPT OUT (regression root-fix — without it decrypt would silently re-encrypt with an empty password), `merge_pdfs`/`split_pdf` open without a password. NEW `encryption_dropped` DegradationKind (#29, severity `warning`, NOT in FONT_AFFECTING_KINDS — an encryption change does not alter glyph identity, so `font_preserved` stays True; INV-J-8 truth-table gains a row) fires ONLY on a genuine re-encryption `pikepdf.PdfError`. DOCUMENTED HONESTY BOUNDARIES (NOT per-edit degradations): the owner password is unrecoverable from an opened pikepdf doc so a distinct owner!=user pair collapses to the single caller password; `/P` permissions are mirrored STRUCTURALLY via `allow=` but advisory because pikepdf does not enforce them. INV-L-1 preserved (all encryption logic — the `pikepdf.Encryption` construction + `pdf.encryption`/`pdf.allow`/`is_encrypted` reads — lives ONLY in `_pathutil._save_pdf`; verbs only forward strings). dry_run parity holds (the `is_encrypted` read is on the real-save path only; dry_run skips `_save_pdf`). INV-W-5 pins encrypted round-trip + the `_save_pdf`-layer preservation + the honest `encryption_dropped` fallback + the non-encrypted byte-identical control + the `decrypt_pdf` no-regression lock; the obsolete `test_encrypted_pdf_raises` is recharacterized (`test_encrypted_pdf_without_password_raises`) to assert the no-password open still raises. | Pre-A2.3 every edit verb either refused encrypted input outright (surgeon's 3 guards) or — for structural — silently DECRYPTED it on save (`_save_pdf` called `pdf.save` with no `encryption=`, down-converting an encrypted input to PLAINTEXT with zero caller signal — a fidelity AND security loss). Detect-via-`is_encrypted` + preserve-via-`encryption=` in the one canonical save helper is the root fix (one site, every edit verb inherits it); the honest `encryption_dropped` fallback covers the case pikepdf cannot re-encrypt; the `decrypt_pdf` `encryption=False` opt-out prevents auto-preservation from regressing the explicit-decrypt verb. W is the robustness/save-path layer (W-1 width-cache, W-2 q/Q depth, W-3 linearization, W-4 stream-size bound), the correct home for a save-time file-fidelity/security guard. | | 2026-06-02 | Multi-match-same-operator honest-refusal (INV-B-12, v0.2.0): `surgeon.replace_all` / `surgeon.batch_replace` detect — BEFORE any mutation — when N>1 matches on a page splice into the SAME show-text operator (intersection of each match's per-character `operator_index` set via the pure `surgeon._splice_ops`, NOT `operator_refs`: only the operators the chars actually write into; matches a/b collide iff `_splice_ops(a) & _splice_ops(b)`, grouped by union-find in `surgeon._colliding_shifting_matches`) AND the replacement is BYTE-SHIFTING (length-changing OR ligature-forcing — `surgeon._is_shifting`, mirroring `_apply_single_replacement`'s `same_length = (not has_ligatures) and len(new)==len(matched)` determinant; the byte-stable same-length splice is NOT refused). Each colliding match's `byte_position` was recorded against the ORIGINAL operand, so after the first splice shifts the operand bytes, every later same-operator match reads the WRONG slice and silently corrupts the output (empirically: resume `replace_all("and","order",reflow=False)` reports 24/24 success but yields 23 "order" + 3 surviving "and" — operators 1825×2 and 2053×3 collide; the synthetic one-Tj-operator `"cat dog cat bird cat fish"` `replace_all("cat","X",reflow=False)` reports `[True,True,True]` yet renders only `"X dog cat bird cat fish"`). `replace_all` REFUSES exactly the colliding+shifting matches as a group (`EditResult.success=False`, `font_action="kept"`, NEW typed `multi_match_same_operator_unsupported` Degradation) BEFORE the per-page reflow/splice loop (the `if id(m) in refused_ids` check sits at the TOP of the loop, so a refused match is never the reflow target either), while matches in DIFFERENT operators AND same-length non-ligature edits (the resume "and"→"but" case, 24/24 correct) edit normally (partial-success preserved). `batch_replace` keeps its existing reactive `used_ops_by_page` "first edit wins, rest skipped" partial-success semantic for a CROSS-edit overlap (two DIFFERENT edits touching one operator, e.g. `"Test"→"X"` + `"Test Document"→"Y"`) but surfaces the typed kind instead of the generic "overlapping" warning when such a skip is itself a same-show-text-operator + byte-shifting collision (`spliced_ops_by_page` tracks the operators that actually wrote bytes); a SAME-edit multi-match-into-one-operator group (one `Edit` whose search matched N>1 times in one operand — the `replace_all` corruption surface reached via batch) is refused up front as a group via `surgeon._same_edit_colliding` (per-`edit_idx` collision grouping). OUTPUT-WRITE semantics inherit the existing `any_success` gate: all-refused → no `_save_pdf` (no output, mirrors all-fail handling); some-succeed → file saved with the successful edits, colliding ones reported `success=False`. The decision is a pure function of the matches + per-call/per-edit search/replacement lengths computed pre-mutation, so dry_run parity holds. NEW DegradationKind #30 `multi_match_same_operator_unsupported` (severity `warning`, NOT in FONT_AFFECTING_KINDS — no edit was applied to the refused matches, glyph identity untouched, `font_preserved` stays True; INV-J-8 truth-table gains a row; INV-J-9 satisfied via `font_action="kept"`). `delete_block` / `batch_replace_block` (structural, bbox/region-driven single-pass keep-slot emptying) do NOT route N stale-byte_position splices and are untouched. INV-B-12 pins the same-operator length-change refusal + the disjoint-operator over-fire control + the same-length-same-operator NOT-refused control + the mixed partial-success case + dry_run parity + the batch typed-kind surface. A full reverse-order offset-rederivation rewrite (re-deriving each match's offsets against the mutated operand) is the 0.3.0 stretch deferred by the B.11 residue-remediation row. | The B.11 work (commit 298d995) explicitly deferred this pre-existing, NON-deletion-specific corruption to its own unit, noting "the correct fix re-derives offsets per match against the mutated operand." Honest-refusal is the safe shippable deliverable: detecting the collision on the character-derived splice set (not `operator_refs`) and gating on the byte-shifting rebuild path is the minimal root-fix that turns a silent multi-match corruption into an honest typed refusal WITHOUT regressing the common byte-stable same-length case (which a broader `operator_refs`-only or length-agnostic refusal would falsely refuse — the resume "and"→"but" 5-collision case). The `_is_shifting` length-change refinement is mandatory: a same-length non-ligature replacement splices fixed-width bytes at each `byte_position` with zero byte shift, so sibling same-operator matches are byte-stable and edit correctly today. `batch_replace`'s split (cross-edit reactive backstop + same-edit up-front group) preserves the documented "first edit wins" overlap semantic (a real test depends on `"Test"→"X"` winning over `"Test Document"→"Y"`) while still refusing the genuine `replace_all`-style same-edit corruption. The reverse-order rewrite is non-trivial/risky (the B.11 deferral signals it) and belongs in 0.3.0 with its own RED proof. | | 2026-06-02 | MCP wrapper rewritten TypeScript → Python (FastMCP), runs in-process (supersedes the 2026-04-03 "TS MCP wrapper" row) | The MCP **Python** SDK (FastMCP) removes the need for a TypeScript server + JSON-RPC `bridge.py` subprocess. `pdf-edit-mcp` v0.2.0 imports the engine in-process and distributes on PyPI (`pip install pdf-edit-mcp`); the legacy npm package `@aryanbv/pdf-edit-mcp` is deprecated. One runtime, no Node.js. | +| 2026-11-01 | `_pathutil._save_pdf` keeps an encrypted input's own encryption (amends the 2026-06-02 A2.3 row, INV-W-5). When the input `is_encrypted` and the caller pinned no `encryption`, it saves with `encryption=True`, so qpdf copies the input's encryption parameters (`R`, `V`, key length, `/O`, `/U`, `/P`, `/EncryptMetadata`, the first `/ID`) and the file key instead of rebuilding a `pikepdf.Encryption` from the caller's password. The output opens with exactly the passwords that opened the input, each with its own owner or user rights, whichever one the edit used; an owner-only file still opens with no password. The one scheme change is qpdf's: a `V 4` file whose crypt filters use RC4 (alone or beside AES) is written with AESV2 under the same key. The `reencrypt_password` parameter is removed (the verbs still open with `password`), so the owner!=user collapse boundary of the A2.3 row no longer exists. The honest fallback is the A2.3 one: only a `pikepdf.PdfError` from the injected encrypted save retries unencrypted, logged with `exc_info`; a `ValueError` (overwriting the input, `normalize_content`) propagates, and so does any failure when the caller pinned `encryption`. `reorder_pages`, `split_pdf` and `merge_pdfs` with an unencrypted first file save a new `Pdf`, so their output stays unencrypted (LIMITATIONS). | `pikepdf.Encryption` defaults to `aes=True, metadata=True`, which pikepdf refuses below R 4 (`ValueError: Cannot encrypt metadata when R < 4`), so every edit of an RC4 R 2 or 3 input failed. Mirroring R, cipher and metadata into a new `pikepdf.Encryption` would still rebuild the key from the caller's password: pikepdf writes an R 2-4 `str` password as PDFDocEncoding but opens with its UTF-8 bytes, so a UTF-8-keyed input would lock the caller out of the output with `success=True`, a PDFDoc-keyed `bytes` password could not be written and would be saved as plaintext, an owner-password edit would drop the user password, a user-password edit would make that password the owner, and 40-bit R 3 keys and `/P` bits pikepdf cannot write would change. Copying the parameters keeps every one of those as it was and needs no password. | ## Decision Details diff --git a/src/pdf_edit_engine/_pathutil.py b/src/pdf_edit_engine/_pathutil.py index 57fcfc8..f29dfe2 100644 --- a/src/pdf_edit_engine/_pathutil.py +++ b/src/pdf_edit_engine/_pathutil.py @@ -18,7 +18,7 @@ import sys import zlib from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import TYPE_CHECKING, Any import pikepdf from pikepdf.models import PdfParsingError @@ -569,7 +569,6 @@ def _save_pdf( output_path: str | Path, *, linearization_log: list[str] | None = None, - reencrypt_password: str | bytes | None = None, encryption_log: list[str] | None = None, **save_kwargs: Any, ) -> None: @@ -609,22 +608,22 @@ def _save_pdf( caller did not already pin an explicit ``encryption`` in ``save_kwargs``, so ``wrapper.encrypt_pdf``'s explicit ``encryption=`` still wins and ``wrapper.decrypt_pdf``'s explicit ``encryption=False`` opt-out is - honoured), it re-encrypts the output with a ``pikepdf.Encryption`` built - from the input's ``R`` and ``allow`` (permission bitmask) and the - caller-supplied ``reencrypt_password`` for BOTH owner and user. A - NON-encrypted input never sets ``encryption``, so its save call is - byte-identical to the pre-A2.3 behaviour (zero blast radius). DOCUMENTED - BOUNDARIES (NOT per-edit degradations): the owner password is NOT - recoverable from an opened pikepdf document, so a distinct owner!=user pair - collapses to the single caller password; ``/P`` is preserved STRUCTURALLY - (mirrored via ``allow=``) but is advisory because pikepdf does not enforce - permissions. If pikepdf raises ``pikepdf.PdfError`` on the encrypted save, - the helper retries ONCE WITHOUT ``encryption`` (so the edit still lands) - and appends ``_ENCRYPTION_DROPPED_DETAIL`` to ``encryption_log`` when one - was supplied (so an edit verb can surface a typed ``encryption_dropped`` - Degradation), else logs the drop at INFO. An ``OSError`` from the encrypted - save is NOT caught here — it falls through to the outer translator - identically to W-3 (INV-L-1 / F-C-03: no raw OSError, no path leak). + honoured), it saves with ``encryption=True``: qpdf copies the input's + encryption parameters (``R``, ``V``, key length, ``/O``, ``/U``, ``/P``, + ``/EncryptMetadata``, the first ``/ID`` and the file key), so the output + opens with exactly the passwords that opened the input, owner and user + keep their roles, and no password is re-encoded. The one scheme change is + qpdf's: a ``V 4`` file whose crypt filters use RC4 is written with AESV2 + under the same key. A NON-encrypted input never sets ``encryption``, so + its save call is byte-identical to the pre-A2.3 behaviour (zero blast + radius). ``/P`` is advisory because pikepdf does not enforce permissions. + If pikepdf raises ``pikepdf.PdfError`` on the encrypted save, the helper + retries ONCE WITHOUT ``encryption`` (so the edit still lands) and appends + ``_ENCRYPTION_DROPPED_DETAIL`` to ``encryption_log`` when one was supplied + (so an edit verb can surface a typed ``encryption_dropped`` Degradation), + else logs the drop at INFO. An ``OSError`` from the encrypted save is NOT + caught here — it falls through to the outer translator identically to W-3 + (INV-L-1 / F-C-03: no raw OSError, no path leak). Args: pdf: An open ``pikepdf.Pdf`` to serialize. @@ -636,14 +635,6 @@ def _save_pdf( ``linearization_dropped`` Degradation. When ``None`` (the default — wrapper/annotation verbs that carry no ``FidelityReport``), the fallback is logged only. - reencrypt_password: The password the calling verb used to OPEN the - (possibly encrypted) input. This is how the re-encryption password - reaches the helper so ALL encryption logic stays inside - ``_pathutil`` (INV-L-1 spirit). Bytes are decoded ``latin-1`` - (lossless for any byte sequence). When ``None``/``""`` on an - encrypted input, ``pikepdf.Encryption(owner="", user="")`` is the - honest best-effort (still structurally encrypted). Ignored for a - non-encrypted input. encryption_log: Optional out-parameter mirroring ``linearization_log``. When provided and re-encryption fell back to an unencrypted save, ``_ENCRYPTION_DROPPED_DETAIL`` is appended @@ -663,54 +654,14 @@ def _save_pdf( # ``encryption`` explicitly — ``wrapper.encrypt_pdf`` pins its own # ``encryption=`` (which wins), and ``wrapper.decrypt_pdf`` pins # ``encryption=False`` to OPT OUT of this auto-preservation. - was_encrypted = bool(pdf.is_encrypted) - if was_encrypted and "encryption" not in save_kwargs: - # The owner password is NOT recoverable from an opened pikepdf - # document, and ``user_password`` is recoverable ONLY when the file was - # opened with the USER password (it is ``b''`` when opened with the - # owner password). The HONEST, deterministic choice is to re-encrypt - # with the password the CALLER supplied, for owner AND user. - # Consequence (documented boundary, NOT a per-edit degradation): a file - # with a distinct owner!=user pair collapses to a single caller - # password, and ``/P`` is preserved STRUCTURALLY (mirrored via - # ``allow=``) but is advisory only because pikepdf does not enforce - # permissions. - # Pass the caller's password through WITH ITS ORIGINAL TYPE (str or - # bytes). pikepdf.Encryption owner/user are typed ``str`` but accept - # ``bytes`` at runtime. We must NOT decode bytes->str: pikepdf's R=6 - # (AES-256) key derivation hashes a ``bytes`` password from its RAW - # bytes but a ``str`` password from its UTF-8 encoding, so decoding a - # non-ASCII bytes password to str (even losslessly via latin-1) would - # re-encrypt under a DIFFERENT key than the caller used to open the - # file — silently locking them out of their own output (success=True, - # no degradation). Passing the original type keeps open-time and - # re-encrypt-time hashing identical. - pw: str | bytes = reencrypt_password if reencrypt_password is not None else "" - info = pdf.encryption - # Mirror only ``R`` and ``allow``: ``bits``/``V`` are DERIVED from - # ``R`` (R=4 -> V=4/128-bit, R=6 -> V=5/256-bit) and have no public - # Encryption kwarg, so they round-trip from ``R`` alone. - # ``info.R`` is an ``int`` per pikepdf's stub, but ``Encryption(R=...)`` - # narrows to ``Literal[2,3,4,5,6]``. R read from a real encrypted file is - # always in that range, so the cast is honest (not a value override). - save_kwargs["encryption"] = pikepdf.Encryption( - owner=pw, # type: ignore[arg-type] # str|bytes ok at runtime; bytes must pass through (R=6) - user=pw, # type: ignore[arg-type] - R=cast("Literal[2, 3, 4, 5, 6]", info.R), - allow=pdf.allow, - ) + injected_encryption = bool(pdf.is_encrypted) and "encryption" not in save_kwargs + if injected_encryption: + save_kwargs["encryption"] = True # A2.2 / INV-W-3: detect the input's linearization once, before save, and # ask pikepdf to preserve it. Only when the caller has not already pinned # ``linearize`` explicitly (e.g. a deterministic corpus builder). was_linearized = bool(pdf.is_linearized) - # True iff WE injected the ``encryption`` kwarg above (so the genuine- - # encryption-failure fallback applies). A caller-pinned ``encryption`` (or - # the ``encryption=False`` decrypt opt-out) is NOT a ``pikepdf.Encryption`` - # we built, so it does NOT enable the fallback. - injected_encryption = was_encrypted and isinstance( - save_kwargs.get("encryption"), pikepdf.Encryption - ) try: if was_linearized and "linearize" not in save_kwargs: try: diff --git a/src/pdf_edit_engine/structural.py b/src/pdf_edit_engine/structural.py index 08f5c58..2dcceba 100644 --- a/src/pdf_edit_engine/structural.py +++ b/src/pdf_edit_engine/structural.py @@ -935,7 +935,6 @@ def shift_content_below( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _invalidate_locator_cache() @@ -1871,7 +1870,6 @@ def replace_block( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _surface_linearization_dropped(result, lin_log) @@ -2093,7 +2091,6 @@ def batch_replace_block( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _invalidate_locator_cache() @@ -2332,7 +2329,6 @@ def insert_text_block( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _invalidate_locator_cache() @@ -2408,7 +2404,6 @@ def delete_block( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) empty_result = EditResult( @@ -2520,7 +2515,6 @@ def delete_block( pdf, output_path, linearization_log=main_lin_log, - reencrypt_password=password, encryption_log=main_enc_log, ) _invalidate_locator_cache() diff --git a/src/pdf_edit_engine/surgeon.py b/src/pdf_edit_engine/surgeon.py index 8446ae6..3273108 100644 --- a/src/pdf_edit_engine/surgeon.py +++ b/src/pdf_edit_engine/surgeon.py @@ -2098,7 +2098,6 @@ def replace( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _surface_linearization_dropped(result, lin_log) @@ -2156,7 +2155,6 @@ def replace( pdf, output_path, linearization_log=simple_lin_log, - reencrypt_password=password, encryption_log=simple_enc_log, ) _surface_linearization_dropped(result, simple_lin_log) @@ -2368,7 +2366,6 @@ def replace_all( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) _surface_linearization_dropped(results, lin_log) @@ -2548,7 +2545,6 @@ def batch_replace( pdf, output_path, linearization_log=lin_log, - reencrypt_password=password, encryption_log=enc_log, ) diff --git a/tests/corpus_builders/encrypted.py b/tests/corpus_builders/encrypted.py index e85b0f9..a1adce6 100644 --- a/tests/corpus_builders/encrypted.py +++ b/tests/corpus_builders/encrypted.py @@ -29,11 +29,16 @@ * :func:`build_encrypted_pdf_distinct` — distinct owner!=user passwords, for the documented owner-collapse boundary probe. * :func:`build_unencrypted_pdf` — the unencrypted control. +* :func:`build_encrypted_pdf_with` — any scheme pikepdf can write. +* :func:`build_rc4_pdf_pikepdf_cannot_write` — RC4 R 2 / 3 key lengths and + ``/P`` values pikepdf's writer cannot produce. """ from __future__ import annotations +import hashlib import io +import struct from typing import TYPE_CHECKING import pikepdf @@ -173,3 +178,127 @@ def build_unencrypted_pdf(out_path: Path | None = None) -> bytes: buf = io.BytesIO() pdf.save(buf, static_id=True) return emit_or_write(buf.getvalue(), out_path) + + +def build_encrypted_pdf_with( + encryption: pikepdf.Encryption, *, linearize: bool = False, out_path: Path | None = None +) -> bytes: + """Build the fixture encrypted with exactly ``encryption``. + + Covers the schemes :func:`build_encrypted_pdf` does not (RC4 R 2 / 3 / 4, + AES-128 R 4, ``/EncryptMetadata false``, an empty user password beside an + owner password, restricted permissions) for the re-encryption mirror + probes. + + Args: + encryption: The encryption to save with. + linearize: Save linearized ("Fast Web View") as well. + out_path: Optional destination; when given the bytes are written + there before being returned. + + Returns: + The encrypted PDF bytes. Never ``None``. + """ + pdf = _build_base_pdf() + buf = io.BytesIO() + pdf.save(buf, static_id=True, encryption=encryption, linearize=linearize) + return emit_or_write(buf.getvalue(), out_path) + + +# ISO 32000-1 7.6.3.3 Algorithm 2 step (a) password padding string. +_RC4_PAD = bytes.fromhex("28BF4E5E4E758A4164004E56FFFA01082E2E00B6D0683E802F0CA9FE6453697A") + + +def _rc4(key: bytes, data: bytes) -> bytes: + state = list(range(256)) + j = 0 + for i in range(256): + j = (j + state[i] + key[i % len(key)]) & 0xFF + state[i], state[j] = state[j], state[i] + out = bytearray() + i = j = 0 + for byte in data: + i = (i + 1) & 0xFF + j = (j + state[i]) & 0xFF + state[i], state[j] = state[j], state[i] + out.append(byte ^ state[(state[i] + state[j]) & 0xFF]) + return bytes(out) + + +def _rc4_owner_and_user_entries( + owner: bytes, user: bytes, revision: int, key_bytes: int, permissions: int, id0: bytes +) -> tuple[bytes, bytes]: + padded_user = (user + _RC4_PAD)[:32] + digest = hashlib.md5((owner + _RC4_PAD)[:32]).digest() + if revision >= 3: + for _ in range(50): + digest = hashlib.md5(digest[:key_bytes]).digest() + o_entry = _rc4(digest[:key_bytes], padded_user) + if revision >= 3: + for i in range(1, 20): + o_entry = _rc4(bytes(b ^ i for b in digest[:key_bytes]), o_entry) + digest = hashlib.md5(padded_user + o_entry + struct.pack("= 3: + for _ in range(50): + digest = hashlib.md5(digest[:key_bytes]).digest() + file_key = digest[:key_bytes] + if revision == 2: + return o_entry, _rc4(file_key, _RC4_PAD) + u_entry = _rc4(file_key, hashlib.md5(_RC4_PAD + id0).digest()) + for i in range(1, 20): + u_entry = _rc4(bytes(b ^ i for b in file_key), u_entry) + return o_entry, u_entry + bytes(16) + + +def build_rc4_pdf_pikepdf_cannot_write( + *, revision: int, key_bits: int, permissions: int, owner: str, user: str +) -> bytes: + """Build the fixture under an RC4 R 2 / 3 scheme pikepdf's writer cannot produce. + + pikepdf writes R 3 only with a 128-bit key and sets the ``/P`` bits a + reader ignores at R 2, so a 40- or 64-bit R 3 key, or an R 2 ``/P`` with + bits 9-12 clear, needs the Standard security handler written by hand (ISO + 32000-1 7.6.3, Algorithms 2, 3, 4 and 5). Only an empty document is + written by hand; qpdf then encrypts the copied pages under that key with + ``encryption=True``. + + Args: + revision: 2 or 3. + key_bits: The key length in bits (40 for R 2). + permissions: The signed ``/P`` value. + owner: The owner password (ASCII). + user: The user password (ASCII). + + Returns: + The encrypted PDF bytes. Never ``None``. + """ + id0 = hashlib.md5(b"build_rc4_pdf_pikepdf_cannot_write").digest() + o_entry, u_entry = _rc4_owner_and_user_entries( + owner.encode("ascii"), user.encode("ascii"), revision, key_bits // 8, permissions, id0 + ) + version = 1 if revision == 2 else 2 + objects = [ + b"<>", + b"<>", + f"< /U <{u_entry.hex()}>>>".encode(), + ] + shell = io.BytesIO() + shell.write(b"%PDF-1.4\n") + offsets = [] + for number, body in enumerate(objects, start=1): + offsets.append(shell.tell()) + shell.write(f"{number} 0 obj\n".encode() + body + b"\nendobj\n") + xref_at = shell.tell() + shell.write(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()) + for offset in offsets: + shell.write(f"{offset:010d} 00000 n \n".encode()) + shell.write( + f"trailer\n< <{id0.hex()}>]>>\nstartxref\n{xref_at}\n%%EOF\n".encode() + ) + with pikepdf.open(io.BytesIO(shell.getvalue()), password=user) as pdf: + pdf.pages.extend(_build_base_pdf().pages) + buf = io.BytesIO() + pdf.save(buf, encryption=True) + return buf.getvalue() diff --git a/tests/invariants/test_w_5_encryption_round_trip.py b/tests/invariants/test_w_5_encryption_round_trip.py index eef2106..77d287d 100644 --- a/tests/invariants/test_w_5_encryption_round_trip.py +++ b/tests/invariants/test_w_5_encryption_round_trip.py @@ -16,9 +16,9 @@ Root fix (A2.3, NOT a patch): the 13 public verbs gain a keyword-only ``password`` that flows to ``open_pdf`` (decrypting the in-memory object); ``_save_pdf`` reads ``pdf.is_encrypted`` BEFORE serializing and, when True and -the caller has not pinned an explicit ``encryption``, re-encrypts with the -caller-supplied password (threaded as ``reencrypt_password``) for owner AND -user so the property round-trips. The three surgeon ``is_encrypted`` refusals +the caller has not pinned an explicit ``encryption``, saves with +``encryption=True`` so qpdf copies the input's own encryption (key, ``/O``, +``/U``, ``/P``) and the property round-trips. The three surgeon ``is_encrypted`` refusals are removed. If pikepdf cannot re-encrypt (raises ``pikepdf.PdfError`` on the ``encryption=`` save), the helper falls back to a normal save AND records the loss so the edit verb can surface a typed ``encryption_dropped`` Degradation @@ -55,9 +55,14 @@ from __future__ import annotations import io +import logging +import os +import subprocess +import sys from typing import TYPE_CHECKING import pikepdf +import pytest from pdf_edit_engine import find, replace from pdf_edit_engine._pathutil import _save_pdf, open_pdf @@ -67,14 +72,14 @@ PASSWORD, REPLACEMENT, build_encrypted_pdf, + build_encrypted_pdf_with, + build_rc4_pdf_pikepdf_cannot_write, build_unencrypted_pdf, ) if TYPE_CHECKING: from pathlib import Path - import pytest - from pdf_edit_engine.models import EditResult @@ -190,21 +195,20 @@ def test_inv_w_5_encrypted_input_stays_encrypted_after_edit(tmp_path: Path) -> N assert result.fidelity_report.font_preserved is True -def test_inv_w_5_save_pdf_preserves_encryption_with_password(tmp_path: Path) -> None: - """``_save_pdf`` re-encrypts an encrypted input when given the password. +def test_inv_w_5_save_pdf_preserves_encryption(tmp_path: Path) -> None: + """``_save_pdf`` re-encrypts an encrypted input. Pins INV-W-5 at the exact layer the root fix lives. ``_save_pdf`` is the single canonical save chokepoint every edit verb routes through. An encrypted document opened WITH its password (via ``open_pdf``, the single canonical open) is decrypted into the in-memory object but still reports ``is_encrypted is True``. ``_save_pdf`` must read that once and re-encrypt - with the threaded ``reencrypt_password`` so the output stays - password-protected — not silently down-converted to plaintext. + so the output stays password-protected — not silently down-converted to + plaintext. (Pre-A2.3 this saved a PLAINTEXT output — the silent-decrypt-on-save bug; the RED proof for that lived in the RED phase. This GREEN probe pins the - fixed behavior at the helper boundary, exercising the ``reencrypt_password`` - parameter directly so a regression that ignored it would be caught.) + fixed behavior at the helper boundary.) """ inp = tmp_path / "encrypted_in.pdf" out = tmp_path / "encrypted_out.pdf" @@ -213,15 +217,14 @@ def test_inv_w_5_save_pdf_preserves_encryption_with_password(tmp_path: Path) -> pdf = open_pdf(str(inp), password=PASSWORD) try: assert pdf.is_encrypted, "fixture regression: opened object is not encrypted" - _save_pdf(pdf, str(out), reencrypt_password=PASSWORD) + _save_pdf(pdf, str(out)) finally: pdf.close() # The output stays encrypted and opens with the caller password ... with pikepdf.open(str(out), password=PASSWORD) as saved: assert saved.is_encrypted, ( - "INV-W-5 violated: _save_pdf did not re-encrypt an encrypted input " - "even when handed the reencrypt_password" + "INV-W-5 violated: _save_pdf did not re-encrypt an encrypted input" ) # ... and an unencrypted reopen genuinely fails (proves it is truly @@ -273,7 +276,7 @@ def test_inv_w_5_unencrypted_control_unchanged(tmp_path: Path) -> None: def test_inv_w_5_reencrypt_failure_surfaces_encryption_dropped( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: """When re-encryption fails, the edit still succeeds + surfaces the loss. @@ -302,9 +305,14 @@ def failing_save(self: pikepdf.Pdf, *args: object, **kwargs: object) -> None: return original_save(self, *args, **kwargs) # type: ignore[arg-type] monkeypatch.setattr(pikepdf.Pdf, "save", failing_save) + caplog.set_level(logging.INFO, logger="pdf_edit_engine._pathutil") result = _edit_anchor(inp, out, password=PASSWORD) + fallback_logs = [r for r in caplog.records if "INV-W-5 fallback" in r.getMessage()] + assert [r.exc_info is not None for r in fallback_logs] == [True], ( + "the INV-W-5 fallback must log once, with the forensic traceback" + ) assert not isinstance(result, BaseException), ( "INV-W-5 violated: re-encryption failure must fall back to an " f"unencrypted save, not raise: {type(result).__name__}: {result}" @@ -359,11 +367,10 @@ def test_inv_w_5_non_ascii_bytes_password_round_trips(tmp_path: Path) -> None: """A non-ASCII BYTES password round-trips under R=6 (AES-256). pikepdf's R=6 key derivation hashes a ``bytes`` password from its RAW bytes - but a ``str`` password from its UTF-8 encoding. ``_save_pdf`` must pass the - caller's password through WITH ITS ORIGINAL TYPE — decoding bytes->str - (even losslessly via latin-1) re-encrypts under a DIFFERENT key and silently - locks the caller out of their own output (success=True, no degradation). - Regression guard for the adversarial-critic Finding 1. + but a ``str`` password from its UTF-8 encoding, so re-keying the output + from a decoded password would silently lock the caller out of their own + output (success=True, no degradation). Regression guard for the + adversarial-critic Finding 1. """ pw = b"secr\xe9t" # non-ASCII byte 0xE9: latin-1 'é'; UTF-8 encodes differently inp = tmp_path / "enc_bytes_in.pdf" @@ -399,12 +406,11 @@ def test_inv_w_5_delete_block_on_encrypted_preserves_encryption(tmp_path: Path) """``delete_block`` on an encrypted input preserves the CALLER's encryption. Regression guard for the structural cascade (adversarial-critic Point-3 - gap): ``delete_block``'s MAIN deletion path must thread - ``reencrypt_password`` + surface ``encryption_dropped`` — else the output is - silently re-encrypted with an EMPTY password (the caller's protection - discarded, success=True). The output must require the caller's password, not - open for anyone. Pins the structural path, which the surgeon-only probes - above do not exercise. + gap): ``delete_block``'s MAIN deletion path must save through + ``_save_pdf`` + surface ``encryption_dropped`` — else the output silently + loses the caller's protection (success=True). The output must require the + caller's password, not open for anyone. Pins the structural path, which the + surgeon-only probes above do not exercise. """ from pdf_edit_engine import delete_block @@ -434,3 +440,502 @@ def test_inv_w_5_delete_block_on_encrypted_preserves_encryption(tmp_path: Path) ) except pikepdf.PasswordError: pass + + +_OWNER = "owner-pw" +_USER = "user-pw" +_RESTRICTED = pikepdf.Permissions(extract=False, modify_other=False, print_highres=False) +_CAFE_PDFDOC = b"caf\xe9" +_CAFE_UTF8 = "café".encode() +_CJK_UTF8 = "密码".encode() +_CANDIDATE_PASSWORDS: tuple[str | bytes, ...] = ( + "", + _OWNER, + _USER, + PASSWORD, + "café", + _CAFE_PDFDOC, + _CAFE_UTF8, + "密码", +) + + +def _scheme(path: Path, password: str | bytes) -> tuple[object, ...]: + """The encryption facts a round trip must keep: R, V, key bits, ciphers, metadata, /P.""" + with pikepdf.open(str(path), password=password) as pdf: + info = pdf.encryption + encrypt_dict = pdf.trailer.Encrypt + return ( + info.R, + info.V, + info.bits, + info.stream_method.name, + info.string_method.name, + encrypt_dict.get("/EncryptMetadata", True), + int(encrypt_dict.P), + ) + + +def _access(path: Path) -> list[bool | None]: + """Per candidate password: ``None`` when it does not open ``path``, else whether it is owner.""" + access: list[bool | None] = [] + for candidate in _CANDIDATE_PASSWORDS: + try: + with pikepdf.open(str(path), password=candidate) as pdf: + access.append(pdf.owner_password_matched) + except pikepdf.PasswordError: + access.append(None) + return access + + +def _assert_round_tripped(inp: Path, out: Path, password: str | bytes) -> None: + assert _scheme(out, password) == _scheme(inp, password), ( + "INV-W-5 violated: the edit changed the encryption scheme (R, V, bits, cipher, " + "/EncryptMetadata or /P)" + ) + assert _access(out) == _access(inp), ( + "INV-W-5 violated: the passwords that open the output, or the owner/user role each " + f"opens it with, differ from the input's: {_CANDIDATE_PASSWORDS!r}" + ) + + +_RC4_CASES = [ + pytest.param(2, "", id="R2-owner-only"), + pytest.param(2, _USER, id="R2-user-pw"), + pytest.param(3, "", id="R3-owner-only"), + pytest.param(3, _USER, id="R3-user-pw"), +] + + +def _build_rc4(tmp_path: Path, revision: int, user: str) -> Path: + inp = tmp_path / f"rc4_r{revision}_in.pdf" + inp.write_bytes( + build_encrypted_pdf_with( + pikepdf.Encryption( + owner=_OWNER, + user=user, + R=revision, # type: ignore[arg-type] + allow=_RESTRICTED, + aes=False, + metadata=False, + ) + ) + ) + return inp + + +@pytest.mark.parametrize(("revision", "user"), _RC4_CASES) +def test_inv_w_5_rc4_input_round_trips_through_replace( + tmp_path: Path, revision: int, user: str +) -> None: + """An RC4 R 2 / 3 input edited with ``replace`` keeps its encryption (it raised ValueError).""" + inp = _build_rc4(tmp_path, revision, user) + out = tmp_path / "rc4_out.pdf" + + result = _edit_anchor(inp, out, password=user) + + assert not isinstance(result, BaseException), ( + f"replace failed on an RC4 R{revision} input: {type(result).__name__}: {result}" + ) + assert result.success + assert not _has_encryption_dropped(result) + assert find(str(out), REPLACEMENT, password=user), "the replacement did not land" + _assert_round_tripped(inp, out, user) + + +@pytest.mark.parametrize(("revision", "user"), _RC4_CASES) +def test_inv_w_5_rc4_input_round_trips_through_replace_block( + tmp_path: Path, revision: int, user: str +) -> None: + """An RC4 R 2 / 3 input edited with ``replace_block`` keeps its encryption.""" + from pdf_edit_engine import replace_block + + inp = _build_rc4(tmp_path, revision, user) + out = tmp_path / "rc4_block_out.pdf" + match = find(str(inp), FIND_ANCHOR, password=user)[0] + + result = replace_block( + str(inp), match.page_number, match.bounding_box, REPLACEMENT, str(out), password=user + ) + + assert result.success + assert not _has_encryption_dropped(result) + assert find(str(out), REPLACEMENT, password=user), "the replacement did not land" + _assert_round_tripped(inp, out, user) + + +@pytest.mark.parametrize("revision", [2, 3]) +def test_inv_w_5_rc4_owner_only_input_round_trips_through_add_watermark( + tmp_path: Path, revision: int +) -> None: + """``add_watermark`` (no password kwarg) keeps an owner-password-only RC4 input's encryption.""" + from pdf_edit_engine import add_watermark + + inp = _build_rc4(tmp_path, revision, "") + mark = tmp_path / "mark.pdf" + mark.write_bytes(build_unencrypted_pdf()) + out = tmp_path / "rc4_mark_out.pdf" + + add_watermark(str(inp), str(mark), str(out)) + + with pikepdf.open(str(out)) as pdf: + assert pdf.is_encrypted + assert len(pdf.pages[0].Resources.XObject) == 1, "the watermark did not land" + _assert_round_tripped(inp, out, "") + + +@pytest.mark.parametrize( + "encryption", + [ + pytest.param( + pikepdf.Encryption(owner=_OWNER, user="", R=2, aes=False, metadata=False), + id="R2-owner-only", + ), + pytest.param( + pikepdf.Encryption( + owner=_OWNER, user=_USER, R=3, allow=_RESTRICTED, aes=False, metadata=False + ), + id="R3-user-pw", + ), + pytest.param(pikepdf.Encryption(owner=_OWNER, user="", R=4), id="R4-owner-only"), + pytest.param(pikepdf.Encryption(owner=_OWNER, user=_USER, R=6), id="R6-user-pw"), + ], +) +def test_inv_w_5_input_edited_with_owner_password_keeps_user_access( + tmp_path: Path, encryption: pikepdf.Encryption +) -> None: + """An edit made with the owner password leaves the user password (or none) opening it.""" + inp = tmp_path / "enc_in.pdf" + out = tmp_path / "enc_out.pdf" + inp.write_bytes(build_encrypted_pdf_with(encryption)) + + result = _edit_anchor(inp, out, password=_OWNER) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result) + assert find(str(out), REPLACEMENT, password=_OWNER), "the replacement did not land" + _assert_round_tripped(inp, out, _OWNER) + + +@pytest.mark.parametrize( + ("revision", "key", "password"), + [ + pytest.param(2, _CAFE_UTF8, "café", id="R2-utf8-keyed-str"), + pytest.param(3, _CAFE_UTF8, "café", id="R3-utf8-keyed-str"), + pytest.param(3, _CAFE_UTF8, _CAFE_UTF8, id="R3-utf8-keyed-bytes"), + pytest.param(4, _CAFE_UTF8, "café", id="R4-utf8-keyed-str"), + pytest.param(2, _CAFE_PDFDOC, _CAFE_PDFDOC, id="R2-pdfdoc-keyed-bytes"), + pytest.param(3, _CAFE_PDFDOC, _CAFE_PDFDOC, id="R3-pdfdoc-keyed-bytes"), + pytest.param(4, _CAFE_PDFDOC, _CAFE_PDFDOC, id="R4-pdfdoc-keyed-bytes"), + pytest.param(3, _CJK_UTF8, "密码", id="R3-utf8-keyed-cjk"), + pytest.param(4, _CJK_UTF8, "密码", id="R4-utf8-keyed-cjk"), + ], +) +def test_inv_w_5_non_ascii_r2_to_r4_password_round_trips( + tmp_path: Path, revision: int, key: bytes, password: str | bytes +) -> None: + """An R 2-4 input keyed by non-ASCII bytes stays encrypted and reopens with that password. + + pikepdf opens with the UTF-8 bytes of a ``str`` but writes an R 2-4 ``str`` as + PDFDocEncoding, so the fixture passes ``key.decode("pdfdoc")`` to put exactly ``key`` + on disk, the way a UTF-8 writer (``key`` = UTF-8) or a spec writer (PDFDoc) stores it. + """ + inp = tmp_path / "enc_in.pdf" + out = tmp_path / "enc_out.pdf" + aes = revision == 4 + inp.write_bytes( + build_encrypted_pdf_with( + pikepdf.Encryption( + owner=key.decode("pdfdoc"), + user=key.decode("pdfdoc"), + R=revision, # type: ignore[arg-type] + aes=aes, + metadata=aes, + ) + ) + ) + + result = _edit_anchor(inp, out, password=password) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result), "the output was saved unencrypted" + assert find(str(out), REPLACEMENT, password=password), ( + "INV-W-5 violated: the caller's password no longer opens the output" + ) + _assert_round_tripped(inp, out, password) + + +@pytest.mark.parametrize( + ("revision", "key_bits"), + [ + pytest.param(2, 40, id="R2-p-bits-9-to-12-clear"), + pytest.param(3, 40, id="R3-40-bit"), + pytest.param(3, 64, id="R3-64-bit"), + ], +) +def test_inv_w_5_rc4_key_length_and_permission_bits_round_trip( + tmp_path: Path, revision: int, key_bits: int +) -> None: + """An R 3 key shorter than 128 bits and an R 2 ``/P`` pikepdf cannot write survive an edit.""" + inp = tmp_path / "rc4_in.pdf" + out = tmp_path / "rc4_out.pdf" + inp.write_bytes( + build_rc4_pdf_pikepdf_cannot_write( + revision=revision, key_bits=key_bits, permissions=-3904, owner=_OWNER, user=_USER + ) + ) + assert _scheme(inp, _USER)[::2] == (revision, key_bits, "none", -3904), "fixture regression" + + result = _edit_anchor(inp, out, password=_USER) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result) + assert find(str(out), REPLACEMENT, password=_USER), "the replacement did not land" + _assert_round_tripped(inp, out, _USER) + + +@pytest.mark.parametrize( + "encryption", + [ + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=4, allow=_RESTRICTED), + id="R4-aes", + ), + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=4, metadata=False), + id="R4-aes-cleartext-metadata", + ), + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=6, allow=_RESTRICTED), + id="R6", + ), + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=6, metadata=False), + id="R6-cleartext-metadata", + ), + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=5), + id="R5", + marks=pytest.mark.filterwarnings("ignore:Encryption R=5 is deprecated"), + ), + ], +) +def test_inv_w_5_aes_input_round_trips_unchanged( + tmp_path: Path, encryption: pikepdf.Encryption +) -> None: + """R 4, 5 and 6 AES inputs keep their scheme, ``/EncryptMetadata`` and passwords.""" + inp = tmp_path / "enc_in.pdf" + out = tmp_path / "enc_out.pdf" + inp.write_bytes(build_encrypted_pdf_with(encryption)) + + result = _edit_anchor(inp, out, password=PASSWORD) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result) + _assert_round_tripped(inp, out, PASSWORD) + + +def test_inv_w_5_r4_rc4_input_is_written_as_aes_under_the_same_key(tmp_path: Path) -> None: + """qpdf writes a ``V 4`` RC4 input with AESV2; everything else, passwords included, stays.""" + inp = tmp_path / "rc4_r4_in.pdf" + out = tmp_path / "rc4_r4_out.pdf" + inp.write_bytes( + build_encrypted_pdf_with( + pikepdf.Encryption( + owner=_OWNER, user=_USER, R=4, allow=_RESTRICTED, aes=False, metadata=False + ) + ) + ) + + result = _edit_anchor(inp, out, password=_USER) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result) + before = _scheme(inp, _USER) + after = _scheme(out, _USER) + assert before[3:5] == ("rc4", "rc4"), "fixture regression" + assert after[3:5] == ("aes", "aes") + assert after[:3] + after[5:] == before[:3] + before[5:] + assert _access(out) == _access(inp) + + +@pytest.mark.parametrize( + "encryption", + [ + pytest.param( + pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=4, metadata=False), id="R4-aes" + ), + pytest.param(pikepdf.Encryption(owner=_OWNER, user=PASSWORD, R=6, metadata=False), id="R6"), + ], +) +def test_inv_w_5_cleartext_metadata_survives_explicit_conversion_mode( + tmp_path: Path, encryption: pikepdf.Encryption +) -> None: + """``/EncryptMetadata false`` stays false when pikepdf returns ``pikepdf.Boolean`` objects.""" + inp = tmp_path / "enc_in.pdf" + out = tmp_path / "enc_out.pdf" + inp.write_bytes(build_encrypted_pdf_with(encryption)) + + mode = pikepdf.get_object_conversion_mode() + pikepdf.set_object_conversion_mode("explicit") + try: + result = _edit_anchor(inp, out, password=PASSWORD) + finally: + pikepdf.set_object_conversion_mode(mode) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + _assert_round_tripped(inp, out, PASSWORD) + + +def test_inv_w_5_linearized_rc4_input_stays_linearized_and_encrypted(tmp_path: Path) -> None: + """A linearized R 3 input keeps both its Fast Web View layout and its encryption.""" + inp = tmp_path / "lin_rc4_in.pdf" + out = tmp_path / "lin_rc4_out.pdf" + inp.write_bytes( + build_encrypted_pdf_with( + pikepdf.Encryption(owner=_OWNER, user="", R=3, aes=False, metadata=False), + linearize=True, + ) + ) + + result = _edit_anchor(inp, out, password=None) + + assert not isinstance(result, BaseException), f"{type(result).__name__}: {result}" + assert result.success + assert not _has_encryption_dropped(result) + with pikepdf.open(str(out)) as pdf: + assert pdf.is_linearized + _assert_round_tripped(inp, out, "") + + +def test_inv_w_5_value_error_on_encrypted_save_propagates_without_fallback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A ``ValueError`` from the encrypted save is not a re-encryption failure: nothing is saved.""" + inp = tmp_path / "encrypted_in.pdf" + out = tmp_path / "encrypted_out.pdf" + inp.write_bytes(build_encrypted_pdf(PASSWORD)) + original_save = pikepdf.Pdf.save + + def failing_save(self: pikepdf.Pdf, *args: object, **kwargs: object) -> None: + if kwargs.get("encryption"): + raise ValueError("forced encrypted-save failure (INV-W-5 probe)") + return original_save(self, *args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(pikepdf.Pdf, "save", failing_save) + encryption_log: list[str] = [] + pdf = open_pdf(str(inp), password=PASSWORD) + try: + with pytest.raises(ValueError, match="INV-W-5 probe"): + _save_pdf(pdf, str(out), encryption_log=encryption_log) + finally: + pdf.close() + + assert encryption_log == [] + assert not out.exists(), "an encrypted input was saved unencrypted after a ValueError" + + +def test_inv_w_5_save_over_the_encrypted_input_raises_without_fallback( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """pikepdf's refusal to overwrite the input is not logged or recorded as an encryption drop.""" + inp = tmp_path / "encrypted_in.pdf" + inp.write_bytes(build_encrypted_pdf(PASSWORD)) + caplog.set_level(logging.INFO, logger="pdf_edit_engine._pathutil") + encryption_log: list[str] = [] + pdf = open_pdf(str(inp), password=PASSWORD) + try: + with pytest.raises(ValueError): + _save_pdf(pdf, str(inp), encryption_log=encryption_log) + finally: + pdf.close() + + assert encryption_log == [] + assert "INV-W-5 fallback" not in caplog.text + with pikepdf.open(str(inp), password=PASSWORD) as pdf: + assert pdf.is_encrypted + + +def test_inv_w_5_normalize_content_on_encrypted_input_raises_instead_of_saving_plaintext( + tmp_path: Path, +) -> None: + """pikepdf refuses ``normalize_content`` with encryption; the save fails, no plaintext copy.""" + inp = tmp_path / "encrypted_in.pdf" + out = tmp_path / "encrypted_out.pdf" + inp.write_bytes(build_encrypted_pdf(PASSWORD)) + encryption_log: list[str] = [] + pdf = open_pdf(str(inp), password=PASSWORD) + try: + with pytest.raises(ValueError): + _save_pdf(pdf, str(out), encryption_log=encryption_log, normalize_content=True) + finally: + pdf.close() + + assert encryption_log == [] + assert not out.exists() + + +def test_inv_w_5_value_error_without_injected_encryption_propagates( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Control: a ``ValueError`` on an unencrypted input's save is not swallowed.""" + pdf = pikepdf.open(io.BytesIO(build_unencrypted_pdf())) + + def failing_save(self: pikepdf.Pdf, *args: object, **kwargs: object) -> None: + raise ValueError("forced save failure (INV-W-5 control)") + + monkeypatch.setattr(pikepdf.Pdf, "save", failing_save) + try: + with pytest.raises(ValueError, match="INV-W-5 control"): + _save_pdf(pdf, str(tmp_path / "out.pdf"), encryption_log=[]) + finally: + pdf.close() + + +def test_inv_w_5_encrypt_pdf_save_failure_raises_without_plaintext_fallback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """``encrypt_pdf``'s own encryption failing to save raises; no plaintext copy is written.""" + from pdf_edit_engine import encrypt_pdf + + inp = tmp_path / "plain_in.pdf" + out = tmp_path / "encrypted_out.pdf" + inp.write_bytes(build_unencrypted_pdf()) + original_save = pikepdf.Pdf.save + + def failing_save(self: pikepdf.Pdf, *args: object, **kwargs: object) -> None: + if kwargs.get("encryption"): + raise pikepdf.PdfError("forced encrypted-save failure (INV-W-5 probe)") + return original_save(self, *args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(pikepdf.Pdf, "save", failing_save) + with pytest.raises(PDFEditError): + encrypt_pdf(str(inp), _OWNER, _USER, str(out)) + + assert not out.exists(), "encrypt_pdf saved an unencrypted copy after its encrypted save failed" + + +def test_inv_w_5_package_imports_without_the_pikepdf_10_9_encryption_method_export() -> None: + """The package imports on pikepdf 10.0-10.8, before ``pikepdf.models`` exported it. + + ``pyproject.toml`` allows ``pikepdf>=10``; ``pikepdf.models.EncryptionMethod`` arrived in 10.9. + """ + code = ( + "import pikepdf.models\n" + "vars(pikepdf.models).pop('EncryptionMethod', None)\n" + "import pdf_edit_engine\n" + ) + completed = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + check=False, + env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}, + ) + assert completed.returncode == 0, completed.stderr