Skip to content

fix(write): restore post-CD positioning in ZipWriter::new_append - #1304

Closed
ByGh00st wants to merge 1 commit into
zip-rs:masterfrom
ByGh00st:fix/restore-new-append-eof
Closed

ByGh00st wants to merge 1 commit into
zip-rs:masterfrom
ByGh00st:fix/restore-new-append-eof

Conversation

@ByGh00st

@ByGh00st ByGh00st commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Restores the pre-#1302 stream position in ZipWriter::new_append_with_config while keeping the AddressHoleCursor test fix in tests/append_near_4gb.rs and adding streaming regression tests.

Unblocks v9.6.0 (#1297). Follow-up: reopen #1299 for a Truncate-based solution in v9.7+. /cc @Pr0methean @ychampion

Root Cause

ZipWriter<W> operates on generic W: Write + Seek, which cannot truncate the underlying stream when the rewritten central directory + EOCD is shorter than the existing archive tail (footer_end < stream_end).

  1. Before fix(write): seek to existing central directory start in ZipWriter::new_append #1302, ZipArchive::get_metadata left readwriter positioned at the end of the existing central directory (dir_start + dir_size), leaving the original PK\x01\x02 central directory header signature intact at dir_start immediately after the last local file entry.
  2. With fix(write): seek to existing central directory start in ZipWriter::new_append #1302 seeking back to metadata.shared.dir_start, if a subsequent operation produces a shorter tail (for example, shortening the archive comment or calling abort_file() after writing data past the new footer end), ZipWriter::finalize() (src/write.rs:1673-1706) enters the else if footer_end < stream_end branch:
    writer.seek(SeekFrom::Start(central_start))?;
    writer.write_all(&0_u32.to_le_bytes())?;
    It overwrites dir_start with 00 00 00 00 and relocates the central directory and EOCD to the end of the stream.
  3. Because dir_start (immediately following the last local file entry) now starts with 00 00 00 00 instead of PK\x01\x02, sequential streaming readers (read_zipfile_from_stream) fail after the last entry with Err(ZipError::InvalidArchive("Invalid local file header")) (caught by fuzz_write in CI run 43566959380).

Supporting in-place central directory overwriting when the archive shrinks will require a truncation mechanism.

Test Plan

  • Added new_append_shorter_comment_preserves_stream_readability and new_append_abort_file_preserves_stream_readability in tests/end_to_end.rs (both fail on 2b9a0e5 with InvalidArchive("Invalid local file header") and pass with this fix).
  • cargo fmt --check
  • cargo clippy --all-targets --all-features -- -D warnings
  • cargo test

@amazon-q-developer amazon-q-developer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

This PR correctly reverts the new_append_with_config seek-to-dir_start that was introduced in #1302. The fix is minimal and well-targeted: removing the three lines that caused ZipWriter to position readwriter at the beginning of the central directory, which then caused finalize() to overwrite the CD magic with 00 00 00 00 when the new footer was shorter than the old one, breaking sequential streaming readers.

Core change (src/write.rs)

The removal of the post-metadata seek restores the pre-#1302 invariant: after get_metadata returns, the reader is positioned at dir_start + dir_size (end of the central directory), which is exactly where new content should begin writing. This leaves the existing local file headers and data untouched.

Test coverage (tests/end_to_end.rs)

Both new regression tests are well-constructed and directly exercise the two failure modes described in the PR — shorter-comment append and abort-file-after-append — using read_zipfile_from_stream to validate sequential readability.

No blocking defects found. The fix is correct and the regression tests are appropriate.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

Seeking back to metadata.shared.dir_start in ZipWriter::new_append_with_config causes ZipWriter::finalize to overwrite dir_start with 0_u32 and relocate the central directory to stream_end whenever the rewritten footer is shorter than the existing archive tail (e.g. after shortening the archive comment or aborting a newly written entry), because generic W: Write + Seek cannot truncate the stream. This leaves 00 00 00 00 immediately after the last local file entry instead of a PK\x01\x02 central directory header, causing read_zipfile_from_stream to fail with InvalidArchive(Invalid local file header).

Restore the pre-zip-rs#1302 stream position in new_append_with_config while keeping the AddressHoleCursor fix in tests/append_near_4gb.rs and adding streaming regression tests.
@ByGh00st
ByGh00st force-pushed the fix/restore-new-append-eof branch from 8508d8c to ec90d2b Compare November 14, 2026 18:01

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please restore this test. We need it to ensure that #1299 remains fixed.

@Pr0methean

Pr0methean commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

@ByGh00st This (at least as you're describing it in the PR description) isn't actually a bug in write.rs, it's a bug in the fuzz_write test that it considers the archive streamable when this has happened, even though fuzz/write/src/main.rs lines 751-763 are supposed to detect that and clear the streamable flag. We don't reintroduce bugs in production code to work around bugs in test code.

@ByGh00st

Copy link
Copy Markdown
Contributor Author

@Pr0methean I downloaded and replayed the 3 crash inputs from run 43566959380 (fuzz_write_bad_inputs_no_features: id-000000, id-000001, id-000002) on 2b9a0e5. None of them call abort_file or SetArchiveComment, so fuzz/write/src/main.rs:751-763 isn't what missed them.

All 3 write a single entry with a central_only 0x5455 (ExtendedTimestamp) custom extra field ([47, 117, 255, 255] in id-000000/id-000001 and [43, 117] in id-000002, accepted by validate_extra_fields(true)), then reopen with ZipWriter::new_append and immediately call finish().

On the initial write, start_entry stores the field as ExtraField::Custom (8 bytes in the central directory for id-000000/01, 6 bytes for id-000002). When new_append reads the central directory back, ExtendedTimestamp::parse_central_header ignores the trailing bytes (bytes_to_read < 4 -> modified: None), so the second finish() serializes it as 5 bytes ([0x55, 0x54, 0x01, 0x00, 0x00]). Because the central directory shrinks by 1–3 bytes and self.comment.len() == 0, ZipWriter::finalize() takes the else if footer_end < stream_end branch, zeroes central_start, and moves the CD+EOCD to EOF - new_len — leaving [00, 00, 00, 50] at central_start and causing read_zipfile_from_stream to fail with InvalidArchive("Invalid local file header").

Minimal reproducer (passes on 2b9a0e5^, fails on 2b9a0e5):

#[test]
fn new_append_extended_timestamp_shrink_breaks_stream() {
    use std::io::{Cursor, Seek, SeekFrom, Write};
    use zip::read::read_zipfile_from_stream;
    use zip::write::FullFileOptions;
    use zip::{CompressionMethod, ZipArchive, ZipWriter};

    let mut opts = FullFileOptions::default()
        .compression_method(CompressionMethod::Stored)
        .validate_extra_fields(true);
    opts.add_extra_field(0x5455, [47u8, 117, 255, 255], true).unwrap();

    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
    writer.start_file("a.txt", opts).unwrap();
    writer.write_all(b"hello").unwrap();
    let initial = writer.finish().unwrap().into_inner(); // len = 121, dir_start = 40

    let writer = ZipWriter::new_append(Cursor::new(initial)).unwrap();
    let mut after = writer.finish().unwrap(); // after.get_ref()[40..44] == [00, 00, 00, 50]

    assert_eq!(ZipArchive::new(Cursor::new(after.get_ref())).unwrap().len(), 1);
    after.seek(SeekFrom::Start(0)).unwrap();
    while read_zipfile_from_stream(&mut after).unwrap().is_some() {}
}

Since #1299 (tests/append_overwrites_cd.rs) should stay fixed, how would you prefer to handle this for 9.6.0? We can either reject/preserve non-canonical extra fields so they don't shrink on new_append, or update fuzz_write to treat reopens that shrink central-directory extra fields as non-streamable.

@Pr0methean

Copy link
Copy Markdown
Member

@ByGh00st Treat them as non-streamable.

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