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

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 84a30b9ccdd Limit archive path processing during segment upload 
(#20424)
84a30b9ccdd is described below

commit 84a30b9ccdd2df85ffbe21857b036e0dab118b73
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Dec 4 14:42:00 2026 -0800

    Limit archive path processing during segment upload (#20424)
    
    Apply configurable archive path limits to controller segment uploads. Use 
one budget per request and return HTTP 413 when an archive exceeds a limit.
    
    To verify, run TarCompressionUtilsTest and 
PinotSegmentUploadDownloadRestletResourceTest.
---
 .../pinot/common/utils/TarCompressionUtils.java    | 112 ++++++++++++++++++++-
 .../common/utils/TarCompressionUtilsTest.java      |  46 +++++++++
 .../pinot/controller/BaseControllerStarter.java    |   1 +
 .../apache/pinot/controller/ControllerConf.java    |  35 +++++++
 .../PinotSegmentUploadDownloadRestletResource.java |  44 +++++---
 ...otSegmentUploadDownloadRestletResourceTest.java |  41 +++++++-
 .../core/metadata/DefaultMetadataExtractor.java    |  13 ++-
 7 files changed, 273 insertions(+), 19 deletions(-)

diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
index a0d18e64185..a1fd4bf0571 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/TarCompressionUtils.java
@@ -33,12 +33,14 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.function.Predicate;
+import javax.annotation.Nullable;
 import org.apache.commons.compress.archivers.ArchiveEntry;
 import org.apache.commons.compress.archivers.ArchiveInputStream;
 import org.apache.commons.compress.archivers.ArchiveOutputStream;
 import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
 import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
+import org.apache.commons.compress.archivers.tar.TarConstants;
 import org.apache.commons.compress.compressors.CompressorException;
 import org.apache.commons.compress.compressors.CompressorStreamFactory;
 import org.apache.commons.io.IOUtils;
@@ -190,8 +192,14 @@ public class TarCompressionUtils {
   /// For security reason, the untarred files must reside in the output 
directory.
   public static List<File> untar(File inputFile, File outputDir)
       throws IOException {
+    return untar(inputFile, outputDir, null);
+  }
+
+  /// Un-tars a compressed tar file with an optional budget for entry paths.
+  public static List<File> untar(File inputFile, File outputDir, @Nullable 
ArchivePathBudget pathBudget)
+      throws IOException {
     try (InputStream fileIn = Files.newInputStream(inputFile.toPath())) {
-      return untar(fileIn, outputDir);
+      return untarWithRateLimiter(fileIn, outputDir, NO_DISK_WRITE_RATE_LIMIT, 
pathBudget);
     }
   }
 
@@ -209,6 +217,12 @@ public class TarCompressionUtils {
   /// For security reason, the untarred files must reside in the output 
directory.
   public static List<File> untarWithRateLimiter(InputStream inputStream, File 
outputDir, long maxStreamRateInByte)
       throws IOException {
+    return untarWithRateLimiter(inputStream, outputDir, maxStreamRateInByte, 
null);
+  }
+
+  private static List<File> untarWithRateLimiter(InputStream inputStream, File 
outputDir, long maxStreamRateInByte,
+      @Nullable ArchivePathBudget pathBudget)
+      throws IOException {
     String outputDirCanonicalPath = outputDir.getCanonicalPath();
     // Prevent partial path traversal
     if (!outputDirCanonicalPath.endsWith(File.separator)) {
@@ -217,10 +231,14 @@ public class TarCompressionUtils {
     List<File> untarredFiles = new ArrayList<>();
     try (InputStream bufferedIn = new BufferedInputStream(inputStream);
         InputStream compressorIn = 
COMPRESSOR_STREAM_FACTORY.createCompressorInputStream(bufferedIn);
-        ArchiveInputStream tarIn = new TarArchiveInputStream(compressorIn)) {
+        TarArchiveInputStream tarIn = pathBudget == null ? new 
TarArchiveInputStream(compressorIn)
+            : new PathBudgetTarInputStream(compressorIn, pathBudget)) {
       ArchiveEntry entry;
       while ((entry = tarIn.getNextEntry()) != null) {
         String entryName = entry.getName();
+        if (pathBudget != null) {
+          pathBudget.charge(entryName);
+        }
         String[] parts = StringUtils.split(entryName, ENTRY_NAME_SEPARATOR);
         File outputFile = outputDir;
         for (String part : parts) {
@@ -269,6 +287,96 @@ public class TarCompressionUtils {
     return untarredFiles;
   }
 
+  /// Enforces the path budget on extension headers that Commons Compress 
handles inside getNextEntry().
+  /// Like the underlying TAR reader, this stream is not thread-safe.
+  private static final class PathBudgetTarInputStream extends 
TarArchiveInputStream {
+    private final ArchivePathBudget _budget;
+    private TarArchiveEntry _checkedEntry;
+
+    private PathBudgetTarInputStream(InputStream inputStream, 
ArchivePathBudget budget) {
+      super(inputStream);
+      _budget = budget;
+    }
+
+    @Override
+    public int read(byte[] buffer, int offset, int length)
+        throws IOException {
+      TarArchiveEntry entry = getCurrentEntry();
+      if (entry != null && entry != _checkedEntry) {
+        _budget.chargeExtendedHeader(entry);
+        _checkedEntry = entry;
+      }
+      return super.read(buffer, offset, length);
+    }
+  }
+
+  /// A request-scoped path budget shared by sequential archive extractions 
within that request.
+  public static final class ArchivePathBudget {
+    private final int _maxDepth;
+    private final int _maxNameLength;
+    private long _remainingPathWork;
+
+    public ArchivePathBudget(int maxDepth, int maxNameLength, long 
maxPathWork) {
+      Preconditions.checkArgument(maxDepth > 0 && maxNameLength > 0 && 
maxPathWork > 0,
+          "Archive path limits must be positive");
+      _maxDepth = maxDepth;
+      _maxNameLength = maxNameLength;
+      _remainingPathWork = maxPathWork;
+    }
+
+    private void chargeExtendedHeader(TarArchiveEntry entry)
+        throws ArchivePathLimitException {
+      // Allow a multibyte name plus its terminator, and one TAR record of 
framing for PAX metadata.
+      long maxHeaderBytes = 4L * _maxNameLength + 1;
+      if (entry.isPaxHeader() || entry.isGlobalPaxHeader()) {
+        maxHeaderBytes += TarConstants.DEFAULT_RCDSIZE;
+      } else if (!entry.isGNULongNameEntry() && !entry.isGNULongLinkEntry()) {
+        return;
+      }
+      long size = entry.getSize();
+      if (size > maxHeaderBytes || size > _remainingPathWork) {
+        throw new ArchivePathLimitException("Archive extended header exceeds 
the path limit");
+      }
+      _remainingPathWork -= size;
+    }
+
+    private void charge(String entryName)
+        throws ArchivePathLimitException {
+      int nameLength = entryName.length();
+      if (nameLength > _maxNameLength) {
+        throw new ArchivePathLimitException("Archive entry name length exceeds 
the limit");
+      }
+      int depth = 0;
+      boolean atComponentStart = true;
+      for (int i = 0; i < nameLength; i++) {
+        char character = entryName.charAt(i);
+        if (character == ENTRY_NAME_SEPARATOR || character == 
File.separatorChar) {
+          atComponentStart = true;
+        } else if (atComponentStart) {
+          if (++depth > _maxDepth) {
+            throw new ArchivePathLimitException("Archive entry path depth 
exceeds the limit");
+          }
+          atComponentStart = false;
+        }
+      }
+      // Each component can require processing a path prefix as long as the 
whole name.
+      long pathWork = (long) Math.max(1, depth) * Math.max(1, nameLength);
+      if (pathWork > _remainingPathWork) {
+        throw new ArchivePathLimitException("Archive path processing exceeds 
the request limit");
+      }
+      _remainingPathWork -= pathWork;
+    }
+  }
+
+  /// Signals that an archive entry exceeded a path limit.
+  public static final class ArchivePathLimitException extends IOException {
+    private static final long serialVersionUID = 1L;
+
+    private ArchivePathLimitException(String message) {
+      super(message);
+    }
+  }
+
   /// Un-tars one single file with the given file name from a compressed tar 
file.
   public static void untarOneFile(File inputFile, String fileName, File 
outputFile)
       throws IOException {
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
index 39566340e4c..c8203689e49 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/TarCompressionUtilsTest.java
@@ -38,6 +38,8 @@ import 
org.apache.commons.compress.compressors.CompressorOutputStream;
 import org.apache.commons.compress.compressors.CompressorStreamFactory;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
+import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
+import 
org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathLimitException;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.DataProvider;
@@ -48,7 +50,9 @@ import static 
org.apache.pinot.common.compression.Lz4CompressorStreamProvider.LZ
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertThrows;
 import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
 import static org.testng.Assert.fail;
 
 
@@ -291,6 +295,48 @@ public class TarCompressionUtilsTest {
     assertTrue(new File(new File(untarredDir, "nested"), 
nestedFile.getName()).isFile());
   }
 
+  @Test
+  public void testArchivePathBudget()
+      throws IOException {
+    File sourceDir = new File(DATA_DIR, "dir");
+    FileUtils.write(new File(sourceDir, "data"), "content", 
StandardCharsets.UTF_8);
+    File archive = new File(TAR_DIR, "dir.tar.gz");
+    TarCompressionUtils.createCompressedTarFile(sourceDir, archive);
+
+    // The directory entry costs 4 units and the two-component file entry 
costs 16.
+    ArchivePathBudget budget = new ArchivePathBudget(2, 8, 20);
+    assertEquals(TarCompressionUtils.untar(archive, UNTAR_DIR, budget).size(), 
2);
+
+    File nextOutputDir = new File(TEMP_DIR, "next");
+    assertThrows(ArchivePathLimitException.class, () -> 
TarCompressionUtils.untar(archive, nextOutputDir, budget));
+    assertFalse(nextOutputDir.exists());
+
+    assertThrows(ArchivePathLimitException.class,
+        () -> TarCompressionUtils.untar(archive, nextOutputDir, new 
ArchivePathBudget(1, 8, 20)));
+    assertThrows(ArchivePathLimitException.class,
+        () -> TarCompressionUtils.untar(archive, nextOutputDir, new 
ArchivePathBudget(2, 7, 20)));
+    assertFalse(new File(nextOutputDir, "dir/data").exists());
+  }
+
+  @Test
+  public void testExtendedPathHeaderLimit()
+      throws IOException {
+    for (int format : List.of(TarArchiveOutputStream.LONGFILE_GNU, 
TarArchiveOutputStream.LONGFILE_POSIX)) {
+      File archive = new File(TAR_DIR, "extended.tar.gz");
+      try (OutputStream fileOut = Files.newOutputStream(archive.toPath());
+          OutputStream gzOut = 
COMPRESSOR_STREAM_FACTORY.createCompressorOutputStream(CompressorStreamFactory.GZIP,
+              fileOut);
+          TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzOut)) {
+        tarOut.setLongFileMode(format);
+        tarOut.putArchiveEntry(new TarArchiveEntry("dir/".repeat(175) + 
"data"));
+        tarOut.closeArchiveEntry();
+      }
+      ArchivePathLimitException failure = 
expectThrows(ArchivePathLimitException.class,
+          () -> TarCompressionUtils.untar(archive, UNTAR_DIR, new 
ArchivePathBudget(2, 16, 4096)));
+      assertEquals(failure.getMessage(), "Archive extended header exceeds the 
path limit");
+    }
+  }
+
   @Test
   public void testSubDirectories()
       throws IOException, CompressorException {
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
index e9805772ac4..defe7c7eefe 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/BaseControllerStarter.java
@@ -265,6 +265,7 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
         ControllerConf.DEFAULT_DISABLE_GROOVY);
     applyCustomConfigs(_config);
     _config.validateSegmentMetadataEntryLimits();
+    _config.validateSegmentUploadArchivePathLimits();
     _config.setClusterIngestionGroovyDisabled(ingestionGroovyDisabled);
 
     
PinotInsecureMode.setPinotInInsecureMode(_config.getProperty(CommonConstants.CONFIG_OF_PINOT_INSECURE_MODE,
 false));
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
index b2ca72d0b9b..c9a3b7335a2 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/ControllerConf.java
@@ -383,6 +383,15 @@ public class ControllerConf extends PinotConfiguration {
   /// Match the stored raw table name exactly, including case, even when table 
lookup is case-insensitive.
   /// Percent-encode commas in directory URI paths as %2C.
   public static final String SEGMENT_UPLOAD_ALLOWED_SOURCES = 
"controller.segment.upload.allowedSources";
+  /// Positive maximum number of path components in a segment upload archive 
entry.
+  public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH =
+      "controller.segment.upload.archive.max.path.depth";
+  /// Positive maximum number of characters in a segment upload archive entry 
name.
+  public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH =
+      "controller.segment.upload.archive.max.entry.name.length";
+  /// Positive path-work budget shared by all archive extractions in a single 
segment upload request.
+  public static final String SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK =
+      "controller.segment.upload.archive.max.path.work";
   /// If true, the controller may reject single-segment uploads with HTTP 403 
when segment data end is past the table
   /// data retention window (see {@link 
org.apache.pinot.controller.api.upload.SegmentValidationUtils}).
   ///
@@ -445,6 +454,9 @@ public class ControllerConf extends PinotConfiguration {
   public static final String DEFAULT_REBALANCE_PRE_CHECKER =
       
"org.apache.pinot.controller.helix.core.rebalance.DefaultRebalancePreChecker";
   public static final long DEFAULT_SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS = 
600_000L; // 10 minutes
+  public static final int DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH = 32;
+  public static final int DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH 
= 4_096;
+  public static final long DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK = 64L 
* 1024 * 1024;
   /// Default for {@link #SEGMENT_UPLOAD_REJECT_OUT_OF_RETENTION}: disabled 
until explicitly enabled.
   public static final boolean DEFAULT_SEGMENT_UPLOAD_REJECT_OUT_OF_RETENTION = 
false;
   public static final int DEFAULT_MIN_NUM_CHARS_IN_IS_TO_TURN_ON_COMPRESSION = 
-1;
@@ -1299,6 +1311,29 @@ public class ControllerConf extends PinotConfiguration {
     return getProperty(SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS, 
DEFAULT_SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS);
   }
 
+  public int getSegmentUploadArchiveMaxPathDepth() {
+    return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH);
+  }
+
+  public int getSegmentUploadArchiveMaxEntryNameLength() {
+    return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH,
+        DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH);
+  }
+
+  public long getSegmentUploadArchiveMaxPathWork() {
+    return getProperty(SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK, 
DEFAULT_SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK);
+  }
+
+  /// Validates the archive path limits after applying controller 
configuration overrides.
+  public void validateSegmentUploadArchivePathLimits() {
+    Preconditions.checkState(getSegmentUploadArchiveMaxPathDepth() > 0, "%s 
must be positive",
+        SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH);
+    Preconditions.checkState(getSegmentUploadArchiveMaxEntryNameLength() > 0, 
"%s must be positive",
+        SEGMENT_UPLOAD_ARCHIVE_MAX_ENTRY_NAME_LENGTH);
+    Preconditions.checkState(getSegmentUploadArchiveMaxPathWork() > 0, "%s 
must be positive",
+        SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_WORK);
+  }
+
   public int getMinNumCharsInISToTurnOnCompression() {
     return getProperty(MIN_NUM_CHARS_IN_IS_TO_TURN_ON_COMPRESSION, 
DEFAULT_MIN_NUM_CHARS_IN_IS_TO_TURN_ON_COMPRESSION);
   }
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
index 17ead65442d..78f705a8ad8 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResource.java
@@ -81,6 +81,8 @@ import org.apache.pinot.common.utils.DatabaseUtils;
 import org.apache.pinot.common.utils.FileUploadDownloadClient;
 import org.apache.pinot.common.utils.FileUploadDownloadClient.FileUploadType;
 import org.apache.pinot.common.utils.TarCompressionUtils;
+import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
+import 
org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathLimitException;
 import org.apache.pinot.common.utils.URIUtils;
 import org.apache.pinot.common.utils.UploadedRealtimeSegmentName;
 import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
@@ -103,7 +105,6 @@ import org.apache.pinot.core.auth.Actions;
 import org.apache.pinot.core.auth.Authorize;
 import org.apache.pinot.core.auth.TargetType;
 import org.apache.pinot.core.metadata.DefaultMetadataExtractor;
-import org.apache.pinot.core.metadata.MetadataExtractorFactory;
 import org.apache.pinot.segment.local.constants.SegmentUploadConstants;
 import org.apache.pinot.segment.spi.SegmentMetadata;
 import org.apache.pinot.segment.spi.V1Constants;
@@ -340,8 +341,7 @@ public class PinotSegmentUploadDownloadRestletResource {
         decryptFile(crypterClassNameInHeader, tempEncryptedFile, 
tempDecryptedFile);
       }
 
-      String metadataProviderClass = DefaultMetadataExtractor.class.getName();
-      SegmentMetadata segmentMetadata = getSegmentMetadata(tempDecryptedFile, 
tempSegmentDir, metadataProviderClass);
+      SegmentMetadata segmentMetadata = getSegmentMetadata(tempDecryptedFile, 
tempSegmentDir);
 
       // Fetch segment name
       String segmentName = segmentMetadata.getName();
@@ -497,8 +497,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       tempSegmentDir = new File(provider.getUntarredFileTempDir(), 
tempFileName);
 
       createSegmentFileFromMultipart(multiPart, tempTarFile);
-      String metadataProviderClass = DefaultMetadataExtractor.class.getName();
-      SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir, metadataProviderClass);
+      SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir);
       String segmentName = segmentMetadata.getName();
       sourceDownloadURIStr = validateMetadataCopySource(sourceDownloadURIStr, 
rawTableName);
       long segmentSizeInBytes = getSegmentSizeFromFile(sourceDownloadURIStr);
@@ -590,7 +589,9 @@ public class PinotSegmentUploadDownloadRestletResource {
     List<String> segmentNames = new ArrayList<>();
 
     try {
-      Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap = 
createSegmentsMetadataInfoMap(multiPart, tempFiles);
+      ArchivePathBudget pathBudget = newArchivePathBudget();
+      Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
+          createSegmentsMetadataInfoMap(multiPart, tempFiles, pathBudget);
       LOGGER.info("Uploading segments in batch mode of size: {}", 
segmentsMetadataInfoMap.size());
       int entryCount = 0;
       for (Map.Entry<String, SegmentMetadataInfo> entry : 
segmentsMetadataInfoMap.entrySet()) {
@@ -629,8 +630,7 @@ public class PinotSegmentUploadDownloadRestletResource {
           decryptFile(crypterClassNameInHeader, tempEncryptedFile, 
tempDecryptedFile);
         }
 
-        String metadataProviderClass = 
DefaultMetadataExtractor.class.getName();
-        SegmentMetadata segmentMetadata = 
getSegmentMetadata(tempDecryptedFile, tempSegmentDir, metadataProviderClass);
+        SegmentMetadata segmentMetadata = 
getSegmentMetadata(tempDecryptedFile, tempSegmentDir, pathBudget);
         String segmentMetadataTableName =
             normalizeTableName(segmentMetadata.getTableName(), tableType, 
headers, "segment metadata table name");
         validateMatchingTableName(rawTableName, segmentMetadataTableName, 
"segment metadata table name");
@@ -877,10 +877,25 @@ public class PinotSegmentUploadDownloadRestletResource {
     SegmentFetcherFactory.fetchSegmentToLocal(currentSegmentLocationURI, 
destFile);
   }
 
-  private SegmentMetadata getSegmentMetadata(File tempDecryptedFile, File 
tempSegmentDir, String metadataProviderClass)
+  private ArchivePathBudget newArchivePathBudget() {
+    return new 
ArchivePathBudget(_controllerConf.getSegmentUploadArchiveMaxPathDepth(),
+        _controllerConf.getSegmentUploadArchiveMaxEntryNameLength(),
+        _controllerConf.getSegmentUploadArchiveMaxPathWork());
+  }
+
+  @VisibleForTesting
+  SegmentMetadata getSegmentMetadata(File archive, File tempSegmentDir)
+      throws Exception {
+    return getSegmentMetadata(archive, tempSegmentDir, newArchivePathBudget());
+  }
+
+  private static SegmentMetadata getSegmentMetadata(File archive, File 
tempSegmentDir, ArchivePathBudget pathBudget)
       throws Exception {
-    // Call metadata provider to extract metadata with file object uri
-    return 
MetadataExtractorFactory.create(metadataProviderClass).extractMetadata(tempDecryptedFile,
 tempSegmentDir);
+    try {
+      return new DefaultMetadataExtractor().extractMetadata(archive, 
tempSegmentDir, pathBudget);
+    } catch (ArchivePathLimitException e) {
+      throw new ControllerApplicationException(LOGGER, e.getMessage(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE);
+    }
   }
 
   private void decryptFile(String crypterClassName, File tempEncryptedFile, 
File tempDecryptedFile) {
@@ -1320,7 +1335,7 @@ public class PinotSegmentUploadDownloadRestletResource {
 // would contain the mappings from segment names to segment download URI's.
   @VisibleForTesting
   static Map<String, SegmentMetadataInfo> 
createSegmentsMetadataInfoMap(FormDataMultiPart multiPart,
-      List<File> tempFiles) {
+      List<File> tempFiles, ArchivePathBudget pathBudget) {
     List<BodyPart> bodyParts = multiPart.getBodyParts();
     validateMultiPartForBatchSegmentUpload(bodyParts);
     FormDataBodyPart bodyPartFromReq = (FormDataBodyPart) bodyParts.get(0);
@@ -1345,10 +1360,13 @@ public class PinotSegmentUploadDownloadRestletResource {
     tempFiles.add(allSegmentsMetadataDir);
     try {
       FileUtils.forceMkdir(allSegmentsMetadataDir);
-      List<File> metadataFiles = 
TarCompressionUtils.untar(allSegmentsMetadataTarFile, allSegmentsMetadataDir);
+      List<File> metadataFiles =
+          TarCompressionUtils.untar(allSegmentsMetadataTarFile, 
allSegmentsMetadataDir, pathBudget);
       if (!metadataFiles.isEmpty()) {
         segmentsMetadataFiles.addAll(metadataFiles);
       }
+    } catch (ArchivePathLimitException e) {
+      throw new ControllerApplicationException(LOGGER, e.getMessage(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE);
     } catch (IOException e) {
       throw new ControllerApplicationException(LOGGER, "Failed to unzip the 
segment metadata files. ",
           Response.Status.INTERNAL_SERVER_ERROR, e);
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
index ef90451103c..18eb567f60d 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/resources/PinotSegmentUploadDownloadRestletResourceTest.java
@@ -38,6 +38,7 @@ import javax.ws.rs.core.Response;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pinot.common.utils.TarCompressionUtils;
+import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
 import org.apache.pinot.controller.ControllerConf;
 import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
 import org.apache.pinot.controller.api.upload.SegmentMetadataInfo;
@@ -65,6 +66,7 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNull;
+import static org.testng.Assert.expectThrows;
 
 
 public class PinotSegmentUploadDownloadRestletResourceTest {
@@ -240,6 +242,30 @@ public class PinotSegmentUploadDownloadRestletResourceTest 
{
         SegmentUploadConstants.SEGMENT_METADATA_TAR_FILE_PREFIX), 
tempEntriesBefore);
   }
 
+  @Test
+  public void testGetSegmentMetadataRejectsArchiveAboveConfiguredPathDepth()
+      throws IOException {
+    File segmentDir = new File(_tempDir, "segment");
+    File columnDir = new File(segmentDir, "index/column");
+    FileUtils.forceMkdir(columnDir);
+    FileUtils.touch(new File(columnDir, "data"));
+    File archive = new File(_tempDir, "segment.tar.gz");
+    TarCompressionUtils.createCompressedTarFile(segmentDir, archive);
+    File outputDir = new File(_tempDir, "extracted");
+    FileUtils.forceMkdir(outputDir);
+
+    PinotSegmentUploadDownloadRestletResource resource = new 
PinotSegmentUploadDownloadRestletResource();
+    resource._controllerConf =
+        new 
ControllerConf(Map.of(ControllerConf.SEGMENT_UPLOAD_ARCHIVE_MAX_PATH_DEPTH, 
"2"));
+
+    ControllerApplicationException failure = 
expectThrows(ControllerApplicationException.class,
+        () -> resource.getSegmentMetadata(archive, outputDir));
+    assertEquals(failure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+    File allowedDir = new File(outputDir, "segment/index");
+    Assert.assertTrue(allowedDir.isDirectory());
+    Assert.assertFalse(new File(allowedDir, "column").exists());
+  }
+
   @Test
   public void testCreateSegmentsMetadataInfoMapRegistersTempFilesForCleanup()
       throws IOException {
@@ -266,7 +292,8 @@ public class PinotSegmentUploadDownloadRestletResourceTest {
 
     // test
     Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
-        
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles);
+        
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
+            new ArchivePathBudget(2, 256, 1024));
 
     // verify the map is built and its file handles are still readable, i.e. 
cleanup was deferred to the caller
     assertEquals(segmentsMetadataInfoMap.size(), 1);
@@ -280,6 +307,18 @@ public class PinotSegmentUploadDownloadRestletResourceTest 
{
     tempFiles.forEach(FileUtils::deleteQuietly);
     
assertEquals(listTempEntries(SegmentUploadConstants.ALL_SEGMENTS_METADATA_TAR_FILE_PREFIX,
         SegmentUploadConstants.ALL_SEGMENTS_METADATA_DIR_PREFIX), 
tempEntriesBefore);
+
+    // A rejected archive uses the same cleanup path and reports a 
request-size error.
+    tempFiles.clear();
+    try (InputStream retryInput = FileUtils.openInputStream(uberTarFile)) {
+      when(mockBodyPart.getValueAs(InputStream.class)).thenReturn(retryInput);
+      ControllerApplicationException failure = 
expectThrows(ControllerApplicationException.class,
+          () -> 
PinotSegmentUploadDownloadRestletResource.createSegmentsMetadataInfoMap(mockMultiPart,
 tempFiles,
+              new ArchivePathBudget(1, 256, 1024)));
+      assertEquals(failure.getResponse().getStatus(), 
Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
+    } finally {
+      tempFiles.forEach(FileUtils::deleteQuietly);
+    }
   }
 
   /// Names of the entries directly under the JVM temp directory that start 
with any of the given prefixes. Used to
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
index a68436f9a94..69addf19e99 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/metadata/DefaultMetadataExtractor.java
@@ -21,8 +21,10 @@ package org.apache.pinot.core.metadata;
 import java.io.File;
 import java.io.IOException;
 import java.util.List;
+import javax.annotation.Nullable;
 import org.apache.commons.io.FileUtils;
 import org.apache.pinot.common.utils.TarCompressionUtils;
+import org.apache.pinot.common.utils.TarCompressionUtils.ArchivePathBudget;
 import org.apache.pinot.segment.spi.SegmentMetadata;
 import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
 
@@ -36,9 +38,14 @@ public class DefaultMetadataExtractor implements 
MetadataExtractor {
   @Override
   public SegmentMetadata extractMetadata(File tarredSegmentFile, File 
unzippedSegmentDir)
       throws Exception {
-    // NOTE: While there is TarGzCompressionUtils.untarOneFile(), we use 
untar() here to unpack all files in the segment
-    //       in order to ensure the segment is not corrupted.
-    List<File> untarredFiles = TarCompressionUtils.untar(tarredSegmentFile, 
unzippedSegmentDir);
+    return extractMetadata(tarredSegmentFile, unzippedSegmentDir, null);
+  }
+
+  public SegmentMetadata extractMetadata(File tarredSegmentFile, File 
unzippedSegmentDir,
+      @Nullable ArchivePathBudget pathBudget)
+      throws Exception {
+    // Unpack all files so extraction fails if the archive is corrupt.
+    List<File> untarredFiles = TarCompressionUtils.untar(tarredSegmentFile, 
unzippedSegmentDir, pathBudget);
     File indexDir = untarredFiles.get(0);
     if (indexDir.isDirectory()) {
       return new SegmentMetadataImpl(indexDir);


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to