Skip to content

Commit ecffce6

Browse files
mtlcl410claude
andauthored
fix(engine): Save writes a repaired file in full even without edits (#1937) (#2029)
* fix(engine): Save writes a repaired file in full even without edits (#1937) A damaged file is repaired on open (its cross-reference index rebuilt from object headers, as Document Properties reports), but Save wrote it back as it was: `Session::save_bytes` returned the bytes as opened whenever nothing was edited, and a repair is not an edit. The "repaired" file on disk was still the damaged one. `save_bytes` now writes a reconstructed document in full even with no edits. `Document::reconstructed()` in cos names the condition (no revision chain: rebuilt, or built from scratch), and `write_incremental` uses it too, so the writer and the engine share one definition. Tests: `engine::tests::a_repaired_file_is_rewritten_by_save_even_without_edits` (table offsets shifted; no table at all) and `automation::saving_a_repaired_file_puts_the_repair_on_disk` (doc_open, doc_info, doc_save over the same path, reopen). Both fail with the condition removed: the saved bytes equal the damaged file. parity: core.repair-broken-files cites them and notes that a repair still does not count as an unsaved change. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RUNQSPVXx3dDBabRZHAnjz * fix(engine): a signed repaired file keeps its bytes on Save without edits (#1937) Review follow-up: writing a reconstructed file in full on Save puts the repair on disk, but for a signed file it would also invalidate its signatures without warning. Save now skips the early return only when the document is reconstructed and not signed. A regression test signs a document, appends a `startxref` that points nowhere (the signed bytes stay intact, the cross-reference data must be rebuilt) and checks that Save without edits returns those bytes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RUNQSPVXx3dDBabRZHAnjz --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 1952a88 commit ecffce6

6 files changed

Lines changed: 98 additions & 4 deletions

File tree

‎crates/automation/tests/automation.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,30 @@ fn page_transitions_are_set_and_removed_through_the_tools() {
214214
);
215215
}
216216

217+
/// #1937 through the tools: a damaged file is repaired on open (`doc_info` lists the repair) and
218+
/// `doc_save` over it writes the rebuilt file, so opening it again needs no repair.
219+
#[test]
220+
fn saving_a_repaired_file_puts_the_repair_on_disk() {
221+
let dir = workdir("repaired-save");
222+
let good = fixture(2);
223+
let mut broken = b"%PDF-1.7\n%shifted\n".to_vec();
224+
broken.extend_from_slice(&good[b"%PDF-1.7\n".len()..]);
225+
std::fs::write(dir.join("broken.pdf"), &broken).unwrap();
226+
let mut a = auto(&dir);
227+
let doc = ok(&mut a, "doc_open", json!({ "path": "broken.pdf" }))["doc"].as_u64().unwrap();
228+
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
229+
assert!(info["repairs"].as_array().unwrap().iter().any(|r| r.as_str().unwrap_or("").contains("rebuilt")), "{}", info["repairs"]);
230+
let saved = ok(&mut a, "doc_save", json!({ "doc": doc }));
231+
assert_eq!(saved["incremental"], false, "{saved}");
232+
let bytes = std::fs::read(dir.join("broken.pdf")).unwrap();
233+
assert_ne!(bytes, broken, "the damaged bytes were written back");
234+
let reopened = pdfcraft_cos::Document::open(std::sync::Arc::new(bytes)).unwrap();
235+
assert!(reopened.repair_log().is_empty(), "{:?}", reopened.repair_log());
236+
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
237+
assert_eq!(info["repairs"].as_array().unwrap().len(), 0, "{}", info["repairs"]);
238+
assert_eq!(info["pages"].as_array().unwrap().len(), 2);
239+
}
240+
217241
#[test]
218242
fn autotag_preview_proposes_text_without_changing_the_pdf() {
219243
let dir = workdir("autotag-preview");

‎crates/cos/src/document.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -857,6 +857,14 @@ impl Document {
857857
&self.revisions
858858
}
859859

860+
/// There is no cross-reference chain to append to: the index was rebuilt from object
861+
/// headers because the file's own was unusable (see [`Self::repair_log`]), or the document
862+
/// was built from scratch ([`Self::new_empty`]). A save writes such a document in full, even
863+
/// when nothing was edited: for a repaired file that is what puts the repair on disk.
864+
pub fn reconstructed(&self) -> bool {
865+
self.revisions.is_empty()
866+
}
867+
860868
/// Where each revision of the file ends (oldest first): the byte after the `%%EOF` (and its
861869
/// end-of-line) that closes its cross-reference section. `data[..end]` is that revision as it
862870
/// was saved. A linearized file's first-page section belongs to the revision it precedes, so

‎crates/cos/src/writer.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>,
183183
}
184184
// Reconstructed files have no chain to append to; added or removed encryption must
185185
// rewrite every object; redaction must not leave the old revision behind. All need a full save.
186-
if doc.revisions().is_empty() || doc.encryption_changed() || doc.full_save_required() {
186+
if doc.reconstructed() || doc.encryption_changed() || doc.full_save_required() {
187187
return write_full(doc, opts);
188188
}
189189
let mut doc = doc.clone();

‎crates/engine/src/lib.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4078,11 +4078,16 @@ impl Session {
40784078

40794079
/// The bytes to write for Save: an incremental update of the file as opened/last saved,
40804080
/// with `/ModDate` stamped. Call `mark_saved` after writing them successfully.
4081+
///
4082+
/// A file whose cross-reference data had to be rebuilt is written in full even when nothing
4083+
/// was edited: its bytes as opened are the damaged file, and this save is how the repair the
4084+
/// user was told about reaches the disk (#1937). Not a signed one: a full rewrite would
4085+
/// break its signatures, so with no edits it keeps its bytes, damage and all.
40814086
pub fn save_bytes(&self, id: DocId) -> Result<Arc<Vec<u8>>, EditError> {
40824087
let doc = self.get(id).ok_or(EditError::NoDocument)?;
40834088
let Some(editor) = doc.editor.as_ref() else { return Ok(doc.bytes.clone()) };
40844089
let on_saved = Arc::ptr_eq(editor.cos.bytes(), &editor.saved);
4085-
if !editor.cos.is_modified() && on_saved {
4090+
if !editor.cos.is_modified() && on_saved && (!editor.cos.reconstructed() || doc.is_signed()) {
40864091
return Ok(editor.saved.clone());
40874092
}
40884093
let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };

‎crates/engine/src/tests.rs‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,63 @@ fn save_is_incremental_stamps_mod_date_and_rebases() {
519519
assert_eq!(reopened.revisions().len(), 3);
520520
}
521521

522+
/// #1937: a file whose cross-reference data had to be rebuilt saved as its original bytes when
523+
/// nothing was edited, so the damage Document Properties reported as repaired was still in the
524+
/// file. Save writes the rebuilt file in full; reopened, it needs no repair.
525+
#[test]
526+
fn a_repaired_file_is_rewritten_by_save_even_without_edits() {
527+
let good = fixture(2);
528+
// Every offset in the table is off by the inserted line: the chain reads but leads nowhere.
529+
let mut shifted = b"%PDF-1.7\n%shifted\n".to_vec();
530+
shifted.extend_from_slice(&good[b"%PDF-1.7\n".len()..]);
531+
// No cross-reference table at all.
532+
let mut lost = good.clone();
533+
lost.truncate(good.windows(9).rposition(|w| w == b"startxref").unwrap());
534+
lost.extend_from_slice(b"startxref\n999999\n%%EOF\n");
535+
for (name, damaged) in [("shifted", shifted), ("lost", lost)] {
536+
let mut s = Session::new().with_clock(|| 1_700_000_000);
537+
let id = s.open("broken.pdf", Some("/tmp/broken.pdf".into()), Arc::new(damaged.clone()), None).unwrap();
538+
let doc = s.get(id).unwrap();
539+
assert!(doc.repair_log().iter().any(|l| l.contains("rebuilt cross-reference index")), "{name}: {:?}", doc.repair_log());
540+
assert_eq!(doc.info.pages.len(), 2, "{name}");
541+
assert!(!doc.dirty, "{name}: a repair is not an edit");
542+
let saved = s.save_bytes(id).unwrap();
543+
assert_ne!(&saved[..], &damaged[..], "{name}: the damaged bytes are not what Save writes");
544+
let reopened = pdfcraft_cos::Document::open(saved.clone()).unwrap();
545+
assert!(reopened.repair_log().is_empty(), "{name}: {:?}", reopened.repair_log());
546+
assert_eq!(reopened.revisions().len(), 1, "{name}");
547+
s.mark_saved(id, saved.clone(), None).unwrap();
548+
let doc = s.get(id).unwrap();
549+
assert!(doc.repair_log().is_empty(), "{name}: {:?}", doc.repair_log());
550+
assert_eq!(doc.info.pages.len(), 2, "{name}");
551+
// Sound now: saving again without edits writes the same bytes.
552+
assert_eq!(s.save_bytes(id).unwrap(), saved, "{name}");
553+
}
554+
}
555+
556+
/// A damaged file that is signed keeps its bytes on a Save without edits: rewriting it in full
557+
/// to put the repair on disk would invalidate its signatures without a word.
558+
#[test]
559+
fn a_signed_repaired_file_keeps_its_bytes_when_saved_without_edits() {
560+
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
561+
let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
562+
// After the test certificate's start date (2026-10-02).
563+
let mut s = Session::new().with_clock(|| 1_800_000_000);
564+
let id = s.open("fixture.pdf", None, Arc::new(fixture(1)), None).unwrap();
565+
let opts = SignOptions { page: 0, rect: Some([20.0, 20.0, 180.0, 60.0]), ..SignOptions::default() };
566+
let signed = s.sign(id, &digital_id, opts).unwrap();
567+
// A trailing `startxref` that points nowhere: the signed revision's bytes are untouched, but
568+
// the file's cross-reference data has to be rebuilt.
569+
let mut damaged = signed.to_vec();
570+
damaged.extend_from_slice(b"\nstartxref\n999999\n%%EOF\n");
571+
let mut t = Session::new().with_clock(|| 1_800_000_000);
572+
let tid = t.open("damaged.pdf", Some("/tmp/damaged.pdf".into()), Arc::new(damaged.clone()), None).unwrap();
573+
let doc = t.get(tid).unwrap();
574+
assert!(doc.repair_log().iter().any(|l| l.contains("rebuilt cross-reference index")), "{:?}", doc.repair_log());
575+
assert!(doc.is_signed());
576+
assert_eq!(&t.save_bytes(tid).unwrap()[..], &damaged[..], "a signed file is not rewritten without edits");
577+
}
578+
522579
#[test]
523580
fn undo_still_works_after_save() {
524581
let (mut s, id) = session_with(2);

‎parity/acrobat-features.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ milestone = "M1"
4646
status = "shipped"
4747
commands = ["file.open"]
4848
tools = ["doc_open"]
49-
evidence = ["crates/cos/src/document.rs::damaged_xref_is_reconstructed", "crates/cos/src/parser.rs::indirect_stream_with_wrong_length_recovers", "crates/cos/src/document.rs::self_referential_length_does_not_overflow"]
50-
notes = ""
49+
evidence = ["crates/cos/src/document.rs::damaged_xref_is_reconstructed", "crates/cos/src/parser.rs::indirect_stream_with_wrong_length_recovers", "crates/cos/src/document.rs::self_referential_length_does_not_overflow", "crates/engine/src/tests.rs::a_repaired_file_is_rewritten_by_save_even_without_edits", "crates/automation/tests/automation.rs::saving_a_repaired_file_puts_the_repair_on_disk", "crates/engine/src/tests.rs::a_signed_repaired_file_keeps_its_bytes_when_saved_without_edits"]
50+
notes = "Save and doc_save write a reconstructed file in full even when nothing was edited, so the repair reaches the disk and the saved file opens without one (#1937); a signed one keeps its bytes, so its signatures stay valid. A repair does not mark the document as having unsaved changes, so closing it does not offer to save the repaired file"
5151

5252
[[feature]]
5353
id = "core.malformed-input-safety"

0 commit comments

Comments
 (0)