Repository navigation
feat: Provide erase_file() - #1343
Pr0methean wants to merge 12 commits into
Conversation
|
Warning Amazon Q Developer for GitHub: end of support On January 30, 2027, AWS will discontinue support for the Amazon Q Developer for GitHub App. New app installations will no longer be available starting November 18, 2026. For capabilities similar to the Amazon Q Developer for GitHub App, explore Kiro and the Kiro GitHub App. For more information about the end of support, see Amazon Q Developer end-of-support announcement on the AWS DevOps Blog. |
There was a problem hiding this comment.
Review Summary
This PR adds erase_file() for secure deletion (overwrite with zeroes or random bytes) alongside hide_file() (directory-only removal), and eagerly pre-resolves data_start for all entries in new_append_with_config.
Critical Issues
-
Data descriptor off-by-one in
erase_file(src/write.rslines 1130–1133): When an entry uses a data descriptor (e.g. ZipCrypto entries or stream-written entries), the 12/24-byte descriptor immediately follows the compressed data on disk.erase_filecomputesdata_end = data_start + compressed_size, which does not include the descriptor. As a result, thedata_end == position_to_resume_writingguard never fires for descriptor entries,position_to_resume_writingis not reset toheader_start, and the next appended entry is written after the surviving descriptor bytes — corrupting the archive. The full on-disk size of the entry must include any trailing data descriptor. -
Performance regression in
new_append_with_config(src/write.rslines 414–416): The new loop resolvesdata_starteagerly for every file on open, performing one local-header seek per entry. This O(n) seek cost is paid even whenerase_fileis never called. Thedata_startresolution should be done lazily — only whenerase_fileactually needs it — to avoid degrading the common append path for large archives. -
Incomplete test coverage for randomize mode (
tests/hide_file.rslines 253–279): The randomize test only asserts that the payload region differs from the original. It does not check that the local header was also overwritten, and does not verify the archive remains parseable with the surviving entry intact. The zeroes test covers these cases; the randomize test should too.
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.
ByGh00st
left a comment
There was a problem hiding this comment.
Tested this locally against a few edge cases (shallow copies, data descriptors, error paths, and new_append + finish()) and hit a few bugs worth fixing before merge:
- Erasing an entry that has a
shallow_copy_filesibling (or any overlapping range) overwrites the shared header/payload and corrupts the surviving entry. - On validation error (
data_end > position_to_resume_writing, overflow, etc.), the entry has already been removed fromself.filesandwriteris left parked atheader_start + 30fromdata_start(writer), so a subsequentfinish()orDropoverwrites surviving entries. len_with_headerdoesn't includedata_descriptor_len(), leaving the 16/24-byte data descriptor (PK\x07\x08, CRC32, sizes) intact on disk.data_descriptor_len()assumes the optional 4-bytePK\x07\x08signature is always present, which rejects valid 12/20-byte signature-less descriptors (and risks overwriting the next entry's local header oncelen_with_headercoversdata_end).- On
new_append+erase_file+finish(), the old central directory entry (plaintext filename, file comment, metadata) can survive in the gap before the relocated footer.
Details inline below.
| let removed_file = self | ||
| .files | ||
| .shift_remove(name.as_bytes()) | ||
| .ok_or(ZipError::FileNotFound)?; | ||
| let data_start = removed_file.data_start(writer)?; | ||
| let len = removed_file.compressed_size; | ||
| let data_end = data_start | ||
| .checked_add(len) | ||
| .ok_or(invalid!("File {:?} data range overflows u64", name))? | ||
| .checked_add(removed_file.data_descriptor_len() as u64) | ||
| .ok_or(invalid!( | ||
| "File {:?} data range overflows u64 with data descriptor included", | ||
| name | ||
| ))?; | ||
| if data_end > position_to_resume_writing { | ||
| return Err(invalid!( | ||
| "File {:?} data range extends past the end of the archive", | ||
| name | ||
| )); | ||
| } |
There was a problem hiding this comment.
Two issues here:
-
Corrupted writer state on error:
shift_removeruns before validation, andremoved_file.data_start(writer)seekswritertoheader_start + 30without restoring the cursor. Ifdata_start,checked_add, ordata_end > position_to_resume_writingreturnsErr, the entry is already gone fromself.filesandwriteris still sitting in the middle of the archive. Callingfinish()(or just dropping theZipWriter) then writes the central directory right over surviving entries (reproduced locally:by_name("kept.txt")fails withInvalidArchive("Invalid local file header")).
Validate viaself.files.get(name.as_bytes())before removing, and restorewriter.seek(SeekFrom::Start(position_to_resume_writing))on any error afterdata_start(writer). -
Shallow copies / overlapping entries: Unlike
abort_file(), this doesn't check whether any remaining entry inself.filesshares or overlaps[removed_file.header_start .. data_end). Callingshallow_copy_file("a.txt", "b.txt")followed byerase_file("a.txt", false)zeroes outb.txt's local header and data, so readingb.txtafterwards fails withInvalidArchive("Invalid local file header"). Checking remaining entries for overlap and returning an error (or refusing to overwrite shared bytes) would prevent silent corruption.
There was a problem hiding this comment.
Checking for overlap will have to be optional, since it requires that data_start() be called on all files, not just the one being erased, which can take linear time if the field isn't already initialized.
There was a problem hiding this comment.
You don't need to call data_start() on every file:
- For
shallow_copy_fileand any entry starting inside[header_start .. data_end), checkingother.header_start >= header_start && other.header_start < data_endis purely in-memory with zero seeks (same scanabort_file()already does). - For entries before
header_start, a local header is bounded in[30 ..= 30 + 2 * u16::MAX](+ at most 24 bytes for a data descriptor), so you can skip anything whose max end is<= header_startand only calldata_start()on the few entries in that ~128 KiB window right beforeheader_start.
| let len_with_header = | ||
| len.saturating_add(data_start.saturating_sub(removed_file.header_start)); | ||
| writer.seek(SeekFrom::Start(removed_file.header_start))?; |
There was a problem hiding this comment.
data_end includes removed_file.data_descriptor_len(), but len_with_header still uses len (compressed_size), so the 16/24-byte data descriptor (PK\x07\x08, CRC32, compressed/uncompressed sizes) is never overwritten. Tested on a new_stream entry and all 16 descriptor bytes stayed intact after erase_file.
Also data_end.checked_sub(removed_file.header_start) is safer than saturating_sub, since data_start < header_start in a malformed archive shouldn't silently turn into 0.
| /// Removes an entry from the archive's directory and overwrites it (both contents and local | ||
| /// header) with zeroes or random bytes. If the entry removed this way is the last one in the | ||
| /// archive, it is still overwritten, but new entries will be able to overwrite it again. | ||
| /// | ||
| /// # Parameters | ||
| /// randomize - If true, the file's content is overwritten with random bytes. If false, it is | ||
| /// overwritten with zeroes. Random bytes are only recommended when writing to magnetic storage, | ||
| /// since data overwritten with zeroes there is sometimes recoverable. |
There was a problem hiding this comment.
Worth either wiping the stale central directory region on new_append + finish() or documenting this caveat: when an archive opened via new_append has a file erased and is finished with finish(), finalize() relocates the smaller new central directory/EOCD to the end of the stream without wiping the old central directory bytes in between.
In a quick local test (top_secret_password_list_2026.txt with a file comment, erased via new_append + erase_file + finish()), both the plaintext filename and the full file comment survived intact in the output buffer (and the file comment still survived even when another short entry remained in the archive).
There was a problem hiding this comment.
The problem with that is that we don't currently track whether there even is a stale central directory.
There was a problem hiding this comment.
You actually don't need to track whether an old central directory exists separately, because finalize() already detects the stale tail whenever footer_end < stream_end.
In the else if footer_end < stream_end branch of finalize(), everything in [last_file_end .. stream_end - central_and_footer_size) is dead space (old CD entries or erased/aborted tail bytes). So a single Option<bool> (or bool) field set when erase_file is called would let finalize() wipe that gap right before relocating the footer, with zero overhead when erase_file isn't used.
Or if you'd rather leave finalize() untouched for now, just noting in erase_file's doc comment that old central directory metadata can remain in the tail under new_append + finish() (unless truncated/rewritten) works too.
There was a problem hiding this comment.
Right, it isn't in either of the two new copies that finalize() writes. What survives is the original central directory that was already in the buffer before new_append, sitting in the untouched gap between copy #1 ([last_file_end .. footer_end)) and copy #2 ([stream_end - central_and_footer_size .. stream_end)).
For a 200-byte archive with one file:
[0..70): local header + payload (wiped byerase_file)[70..178): original CD entry from beforenew_append(contains the filename + file comment)[178..200): original EOCD
When finish() runs after erase_file, copy #1 of the new empty EOCD writes to [0..22) and copy #2 writes to [178..200), so [70..178) is never touched at all. Wiping [last_file_end .. stream_end - central_and_footer_size) in finalize() covers [70..178) automatically without having to track where the old CD lived.
Here's the minimal reproducer if you want to run it locally:
#[test]
fn erase_file_does_not_leak_old_central_directory() -> ZipResult<()> {
let opts = zip::write::FullFileOptions::default()
.compression_method(CompressionMethod::Stored)
.with_file_comment("TOP_SECRET_FILE_COMMENT");
let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("top_secret_password_list_2026.txt", opts)?;
zip.write_all(b"hunter2")?;
let baseline = zip.finish()?.into_inner();
let mut zip = ZipWriter::new_append(Cursor::new(baseline))?;
zip.erase_file("top_secret_password_list_2026.txt", false)?;
let erased = zip.finish()?.into_inner();
assert!(
!erased
.windows(b"top_secret_password_list_2026.txt".len())
.any(|w| w == b"top_secret_password_list_2026.txt"),
"erased filename still present in output"
);
assert!(
!erased
.windows(b"TOP_SECRET_FILE_COMMENT".len())
.any(|w| w == b"TOP_SECRET_FILE_COMMENT"),
"erased file comment still present in output"
);
Ok(())
}| pub(crate) fn data_descriptor_len(&self) -> usize { | ||
| if !self.is_using_data_descriptor() { | ||
| return 0; | ||
| } | ||
| if self.large_file { | ||
| return Zip64DataDescriptorBlock::SIZE; | ||
| } | ||
| if self.compressed_size >= ZIP64_BYTES_THR || self.uncompressed_size >= ZIP64_BYTES_THR { | ||
| return Zip64DataDescriptorBlock::SIZE; | ||
| } | ||
| ZipDataDescriptorBlock::SIZE | ||
| } |
There was a problem hiding this comment.
Per APPNOTE 4.3.9.3 the 4-byte 0x08074b50 signature on a data descriptor is optional, so real-world archives can have 12-byte (ZIP32) or 20-byte (ZIP64) signature-less descriptors (and some older archives set the DD flag on 0-byte directory entries with no descriptor at all, as in #971).
Hardcoding ZipDataDescriptorBlock::SIZE (16) / Zip64DataDescriptorBlock::SIZE (24) causes two problems:
- If the entry with a 12-byte signature-less descriptor is the last file,
data_endovershootsposition_to_resume_writingby 4 bytes anderase_filefails withdata range extends past the end of the archive. - Once
len_with_headeris updated to include the descriptor, erasing a middle entry with a 12-byte signature-less descriptor (or a 0-byte directory DD) will overwrite the first 4 bytes (PK\x03\x04) of the next entry's local header.
Since erase_file already requires A: Read + Write + Seek, you can peek 4 bytes at data_start + compressed_size: if it matches Magic::DATA_DESCRIPTOR_SIGNATURE (0x08074b50) use 16/24, if it matches crc32.to_le_bytes() use 12/20, otherwise 0 (and verify it doesn't cross into the next entry's header_start).
There was a problem hiding this comment.
What about when the first field of the data descriptor happens to equal 0x08074b50 as a regular number?
There was a problem hiding this comment.
Good point, a signature-less descriptor starts with crc32, which could itself be 0x08074b50.
Since ZipFileData already holds (crc32, compressed_size, uncompressed_size), you can match the full descriptor bytes instead of just the first 4 bytes (bounded by min(next_entry_header_start, position_to_resume_writing)):
- If at least 16 (or 24 for ZIP64) bytes fit and match
[0x08074b50, crc32, compressed_size, uncompressed_size], it's a signatured descriptor (16/24 bytes). - Otherwise if at least 12 (or 20 for ZIP64) bytes fit and match
[crc32, compressed_size, uncompressed_size], it's a signature-less descriptor (12/20 bytes). - Otherwise 0 bytes (e.g. a 0-byte directory entry with the DD flag set).
Even when crc32 == 0x08074b50, the signatured form has 0x08074b50 twice ([0..4] and [4..8]) followed by compressed_size, while the signature-less form has compressed_size at [4..8], so comparing the whole block disambiguates them reliably.
| assert_ne!( | ||
| &erased[data_start as usize..(data_start + compressed_size) as usize], | ||
| &payload[..] | ||
| ); | ||
| assert!( | ||
| erased[data_start as usize..(data_start + compressed_size) as usize] | ||
| .iter() | ||
| .copied() | ||
| .any(|byte| byte != 0) | ||
| ); |
There was a problem hiding this comment.
This only asserts on data_start..data_start + compressed_size, not the local header (header_start..data_start). Adding coverage for the local header here, plus tests for a shallow_copy_file survivor, a data-descriptor entry, and failed erase_file leaving survivors readable would lock down the fixes above.
|
/q Address the feedback from @ByGh00st |
|
Addressing all feedback from @ByGh00st. Here's what I'll implement: Changes to implement:
Suggestions not implemented:
|
|
Implemented the feedback from @ByGh00st. Here's a summary of what was changed:
|
- Validate entry existence before shift_remove in erase_file to prevent corrupted writer state on error (CWE-404) - Use checked_sub instead of saturating_sub for len_with_header to avoid silently returning 0 on a malformed archive - Fix len_with_header to cover the full on-disk extent (header + data + descriptor) using data_end - header_start - Perform shift_remove only after all validation passes - Replace static data_descriptor_len() with a runtime-peeking version that disambiguates signatured (16/24 bytes) vs. signature-less (12/20 bytes) vs. absent descriptors per APPNOTE 4.3.9.3 - Remove eager data_start resolution loop from new_append_with_config to fix O(n) seeks performance regression - Add doc caveat noting stale central directory bytes may remain after new_append + erase_file + finish() - Extend erase_file_can_randomize_payload test to check the full header+data region is overwritten
|
@Pr0methean Heads up on
Happy to clean this up and push the fixes + tests directly to |
Yes please. |
…ecovery, and stale CD wipe
|
@Pr0methean Pushed
|
|
This PR's diff size is quite large. Please consider splitting it into multiple PRs if possible. |
|
@Pr0methean Heads up: the |
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.