Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading