This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git

commit a70af3a039d9a6ddac117751d7b144a66da9849b
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Dec 3 12:19:32 2026 -0500

    Add optional ZIP local header name validation (f010)
    
    Record raw filename differences between local headers and the central
    directory, with opt-in rejection through ZipFile.Builder.
    
    Preserve existing Unicode name and comment resolution by default.
    Document validation limits and add regression tests.
---
 src/changes/changes.xml                            |  1 +
 .../compress/archivers/zip/ZipArchiveEntry.java    | 26 ++++++
 .../commons/compress/archivers/zip/ZipFile.java    | 46 ++++++++++-
 .../compress/archivers/zip/ZipFileTest.java        | 94 ++++++++++++++++++++++
 4 files changed, 166 insertions(+), 1 deletion(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index ebb84ca2f..fcafaf32c 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -261,6 +261,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
Pack200CompressorInputStream.Builder.setMemoryLimitKiB(int) and apply the 
CompressorStreamFactory memory limit to the Pack200 JAR cache.</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
AbstractCompressorBuilder to share memory-limit configuration across the 
Pack200, XZ, and LZMA input stream builders.</action>
       <action type="add" dev="ggregory">Add AbstractCompressBuilder to share 
memory-limit configuration across archive and compressor builders.</action>
+      <action type="add" dev="ggregory">[Zip] Add optional rejection and 
detection of different raw local-header and central-directory file names while 
preserving default Unicode name and comment resolution.</action>
       <!-- UPDATE -->
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-parent from 85 to 107 #707, #752.</action>
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-lang3 from 3.18.0 to 3.22.0.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
index c1af2f578..8b55e14b5 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
@@ -307,6 +307,7 @@ private static String toEntryName(final Path inputPath, 
final String entryName,
     private long localHeaderOffset = OFFSET_UNKNOWN;
     private long dataOffset = OFFSET_UNKNOWN;
     private boolean isStreamContiguous;
+    private boolean localFileHeaderNameDivergent;
 
     private NameSource nameSource = NameSource.NAME;
 
@@ -1069,6 +1070,22 @@ public boolean isDirectory() {
         return isDirectoryEntryName(getName());
     }
 
+    /**
+     * Tests whether {@link ZipFile} observed different raw file name bytes in 
this entry's local file header and central directory.
+     *
+     * <p>
+     * This value is set when {@link ZipFile} reads local file header data. A 
value of {@code false} can also mean that the headers were not compared,
+     * for example when reading with {@link ZipArchiveInputStream} or ignoring 
local file headers. The comparison does not account for encoding flags
+     * or Unicode extra fields and does not establish whether different 
readers resolve the same name.
+     * </p>
+     *
+     * @return true if a raw file name mismatch was detected, false otherwise.
+     * @since 1.29.0
+     */
+    public boolean isLocalFileHeaderNameDivergent() {
+        return localFileHeaderNameDivergent;
+    }
+
     @Override
     public boolean isStreamContiguous() {
         return isStreamContiguous;
@@ -1384,6 +1401,15 @@ public ZipEntry setLastModifiedTime(final FileTime 
fileTime) {
         return this;
     }
 
+    /**
+     * Sets whether {@link ZipFile} observed different raw file name bytes in 
the local file header and central directory.
+     *
+     * @param localFileHeaderNameDivergent whether the raw file name bytes 
differed.
+     */
+    void setLocalFileHeaderNameDivergent(final boolean 
localFileHeaderNameDivergent) {
+        this.localFileHeaderNameDivergent = localFileHeaderNameDivergent;
+    }
+
     /**
      * Sets the local header offset.
      *
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
index 5b94db97a..bf197ae3f 100644
--- a/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
@@ -134,6 +134,7 @@ public static class Builder extends 
AbstractArchiveBuilder<ZipFile, Builder> {
         private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
         private boolean useUnicodeExtraFields = true;
         private boolean ignoreLocalFileHeader;
+        private boolean rejectLocalFileHeaderNameDivergence;
         private long maxNumberOfDisks = 1;
         private String name;
         private IOFunction<InputStream, InputStream> zstdInputStreamFactory;
@@ -190,6 +191,33 @@ Builder setName(final String name) {
             return this;
         }
 
+        /**
+         * Sets whether to reject entries whose local file header and central 
directory contain different raw file name bytes. Defaults to {@code false}.
+         *
+         * <p>
+         * When enabled, a mismatch causes {@link #get()} to throw an {@link 
ArchiveException} while reading the local file headers. When disabled,
+         * mismatches are recorded via {@link 
ZipArchiveEntry#isLocalFileHeaderNameDivergent()} without changing file name or 
comment resolution.
+         * InfoZIP Unicode extra fields continue to be handled according to 
{@link #setUseUnicodeExtraFields(boolean)}.
+         * </p>
+         *
+         * <p>
+         * Only raw file name bytes are compared, not encoding flags or 
Unicode extra fields. Matching bytes do not guarantee that different ZIP readers
+         * resolve the same name.
+         * </p>
+         *
+         * <p>
+         * Has no effect if {@link #setIgnoreLocalFileHeader(boolean) 
ignoreLocalFileHeader} is set, because local file names are not read then.
+         * </p>
+         *
+         * @param rejectLocalFileHeaderNameDivergence whether to reject 
entries with different raw file name bytes in the two headers.
+         * @return {@code this} instance.
+         * @since 1.29.0
+         */
+        public Builder setRejectLocalFileHeaderNameDivergence(final boolean 
rejectLocalFileHeaderNameDivergence) {
+            this.rejectLocalFileHeaderNameDivergence = 
rejectLocalFileHeaderNameDivergence;
+            return this;
+        }
+
         /**
          * The actual channel, overrides any other input aspects like a File, 
Path, and so on.
          *
@@ -695,6 +723,11 @@ private static boolean tryToLocateSignature(final 
SeekableByteChannel channel, f
      */
     private final boolean useUnicodeExtraFields;
 
+    /**
+     * Whether different raw file name bytes in an entry's local file header 
and central directory cause opening the archive to fail.
+     */
+    private final boolean rejectLocalFileHeaderNameDivergence;
+
     /**
      * Whether the file is closed.
      */
@@ -748,6 +781,7 @@ private ZipFile(final Builder builder) throws IOException {
             this.encoding = builder.getCharset();
             this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
             this.useUnicodeExtraFields = builder.useUnicodeExtraFields;
+            this.rejectLocalFileHeaderNameDivergence = 
builder.rejectLocalFileHeaderNameDivergence;
             this.zstdInputStreamFactory = builder.zstdInputStreamFactory;
             this.maxEntryNameLength = builder.getMaxEntryNameLength();
             final Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag 
= populateFromCentralDirectory();
@@ -1579,7 +1613,17 @@ private void resolveLocalFileHeaderData(final 
Map<ZipArchiveEntry, NameAndCommen
             final int[] lens = setDataOffset(ze);
             final int fileNameLen = lens[0];
             final int extraFieldLen = lens[1];
-            skipBytes(fileNameLen);
+            final byte[] localFileName = 
org.apache.commons.compress.utils.IOUtils.readRange(archive, fileNameLen);
+            if (localFileName.length < fileNameLen) {
+                throw new EOFException();
+            }
+            // Record or reject raw name differences independently of Unicode 
name and comment resolution.
+            if (!Arrays.equals(localFileName, ze.getRawName())) {
+                ze.setLocalFileHeaderNameDivergent(true);
+                if (rejectLocalFileHeaderNameDivergence) {
+                    throw new ArchiveException("Local file header name for 
'%s' differs from central directory name", ze.getName());
+                }
+            }
             final byte[] localExtraData = 
org.apache.commons.compress.utils.IOUtils.readRange(archive, extraFieldLen);
             if (localExtraData.length < extraFieldLen) {
                 throw new EOFException();
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java 
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
index 0ff9d3bd4..1caa621ea 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
@@ -73,6 +73,8 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Assumptions;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 import io.airlift.compress.zstd.ZstdInputStream;
 
@@ -123,6 +125,28 @@ private static byte[] createZip64Archive() throws 
IOException {
         return bos.toByteArray();
     }
 
+    private static byte[] createZipWithUnicodeExtraFields(final boolean 
divergentLocalFileHeaderName) throws IOException {
+        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(bos)) {
+            zos.setUseLanguageEncodingFlag(false);
+            final ZipArchiveEntry entry = new ZipArchiveEntry("other.txt");
+            entry.setComment("resume");
+            entry.addExtraField(new UnicodePathExtraField("local.txt", 
"other.txt".getBytes(UTF_8)));
+            entry.addExtraField(new 
UnicodeCommentExtraField("r\u00e9sum\u00e9", "resume".getBytes(UTF_8)));
+            zos.putArchiveEntry(entry);
+            zos.write("content".getBytes(UTF_8));
+            zos.closeArchiveEntry();
+        }
+        final byte[] data = bos.toByteArray();
+        if (divergentLocalFileHeaderName) {
+            // Replace only the local name with an equally long name, 
preserving all sizes and offsets.
+            final byte[] localName = "local.txt".getBytes(UTF_8);
+            assertEquals(localName.length, ZipShort.getValue(data, 26));
+            System.arraycopy(localName, 0, data, 30, localName.length);
+        }
+        return data;
+    }
+
     private static int indexOfSignature(final byte[] data, final byte[] 
signature) {
         for (int i = 0; i + signature.length <= data.length; i++) {
             int j = 0;
@@ -475,6 +499,50 @@ void testDelayedOffsetsAndSizes() throws Exception {
         }
     }
 
+    @Test
+    void testDivergentLocalFileHeaderNamePreservesUnicodeComment() throws 
IOException {
+        try (ZipFile zipFile = 
ZipFile.builder().setByteArray(createZipWithUnicodeExtraFields(true)).get()) {
+            final ZipArchiveEntry entry = zipFile.getEntries().nextElement();
+            assertTrue(entry.isLocalFileHeaderNameDivergent());
+            assertEquals("r\u00e9sum\u00e9", entry.getComment());
+            assertEquals(ZipArchiveEntry.CommentSource.UNICODE_EXTRA_FIELD, 
entry.getCommentSource());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { false, true })
+    void testDivergentLocalFileHeaderNamePreservesUnicodeName(final boolean 
explicitlyDisableRejection) throws IOException {
+        final byte[] data = createZipWithUnicodeExtraFields(true);
+        final ZipFile.Builder builder = ZipFile.builder().setByteArray(data);
+        if (explicitlyDisableRejection) {
+            builder.setRejectLocalFileHeaderNameDivergence(false);
+        }
+        try (ZipFile zipFile = builder.get(); ZipArchiveInputStream stream = 
ZipArchiveInputStream.builder().setByteArray(data).get()) {
+            final ZipArchiveEntry entry = zipFile.getEntries().nextElement();
+            assertTrue(entry.isLocalFileHeaderNameDivergent());
+            assertArrayEquals("other.txt".getBytes(UTF_8), entry.getRawName());
+            assertEquals("local.txt", entry.getName());
+            assertEquals(ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD, 
entry.getNameSource());
+            assertEquals(entry, zipFile.getEntry("local.txt"));
+            assertNull(zipFile.getEntry("other.txt"));
+            assertEquals(entry.getName(), stream.getNextEntry().getName());
+            try (InputStream input = zipFile.getInputStream(entry)) {
+                assertArrayEquals("content".getBytes(UTF_8), 
IOUtils.toByteArray(input));
+            }
+            assertArrayEquals("content".getBytes(UTF_8), 
IOUtils.toByteArray(stream));
+        }
+    }
+
+    @Test
+    void testDivergentLocalFileHeaderNameWithUnicodeExtraFieldsDisabled() 
throws IOException {
+        try (ZipFile zipFile = 
ZipFile.builder().setByteArray(createZipWithUnicodeExtraFields(true)).setUseUnicodeExtraFields(false).get())
 {
+            final ZipArchiveEntry entry = zipFile.getEntries().nextElement();
+            assertTrue(entry.isLocalFileHeaderNameDivergent());
+            assertEquals("other.txt", entry.getName());
+            assertEquals("resume", entry.getComment());
+        }
+    }
+
     @Test
     void testDoubleClose() throws Exception {
         readOrderTest();
@@ -724,6 +792,16 @@ void testGetEntriesInPhysicalOrder() throws Exception {
         }
     }
 
+    @Test
+    void testIgnoreLocalFileHeaderDisablesNameRejection() throws IOException {
+        try (ZipFile zipFile = 
ZipFile.builder().setByteArray(createZipWithUnicodeExtraFields(true)).setIgnoreLocalFileHeader(true)
+                .setRejectLocalFileHeaderNameDivergence(true).get()) {
+            final ZipArchiveEntry entry = zipFile.getEntries().nextElement();
+            assertFalse(entry.isLocalFileHeaderNameDivergent());
+            assertEquals("other.txt", entry.getName());
+        }
+    }
+
     /**
      * Test non power of 2 alignment.
      */
@@ -1042,6 +1120,22 @@ void testThrowsExceptionWhenWritingPreamble() throws 
IOException {
         }
     }
 
+    @Test
+    void testRejectDivergentLocalFileHeaderNameAcceptsMatchingNames() throws 
IOException {
+        try (ZipFile zipFile = 
ZipFile.builder().setByteArray(createZipWithUnicodeExtraFields(false)).setRejectLocalFileHeaderNameDivergence(true).get())
 {
+            final ZipArchiveEntry entry = zipFile.getEntries().nextElement();
+            assertFalse(entry.isLocalFileHeaderNameDivergent());
+            assertEquals("local.txt", entry.getName());
+            assertEquals("r\u00e9sum\u00e9", entry.getComment());
+        }
+    }
+
+    @Test
+    void testRejectDivergentLocalFileHeaderNameWithUnicodeExtraFields() throws 
IOException {
+        final byte[] data = createZipWithUnicodeExtraFields(true);
+        assertThrows(ArchiveException.class, () -> 
ZipFile.builder().setByteArray(data).setRejectLocalFileHeaderNameDivergence(true).get());
+    }
+
     @Test
     void testUnixSymlinkSampleFile() throws Exception {
         final String entryPrefix = "COMPRESS-214_unix_symlinks/";

Reply via email to