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 be0ed21cb4f Validate metadata upload staging sources (#20428)
be0ed21cb4f is described below

commit be0ed21cb4f4cbb9d3de109e7ec85639e78567e0
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Dec 4 12:08:19 2026 -0800

    Validate metadata upload staging sources (#20428)
    
    * Validate metadata upload staging sources
    
    Apply the same source checks to single, batch, and reingestion metadata 
uploads. Support trusted per-table staging directories.
    
    How to verify: Run SegmentValidationUtilsTest and the metadata upload 
integration tests.
    
    * Unify upload staging configuration and report invalid sources
    
    * Document segment upload staging configuration
    
    Clarify exact table name matching and percent-encoding for commas in 
staging URIs.
    
    Verify with SegmentValidationUtilsTest and 
PinotSegmentUploadAuthorizationTest.
---
 .../apache/pinot/controller/ControllerConf.java    |  20 +++
 .../PinotSegmentUploadDownloadRestletResource.java |  50 +++----
 .../api/upload/SegmentValidationUtils.java         | 164 +++++++++++++++++++++
 .../api/PinotSegmentUploadAuthorizationTest.java   |  10 ++
 .../api/upload/SegmentValidationUtilsTest.java     |  76 ++++++++++
 .../tests/SegmentUploadIntegrationTest.java        |  16 ++
 .../SparkSegmentMetadataPushIntegrationTest.java   |   2 +
 7 files changed, 307 insertions(+), 31 deletions(-)

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 6e6a16295a9..b2ca72d0b9b 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
@@ -378,6 +378,11 @@ public class ControllerConf extends PinotConfiguration {
   // Amount of the time the segment can take from the beginning of upload to 
the end of upload. Used when parallel push
   // protection is enabled. If the upload does not finish within the timeout, 
next upload can override the previous one.
   public static final String SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS = 
"controller.segment.upload.timeoutInMillis";
+  /// Comma-separated trusted source directories for segment uploads. Use 
rawTableName=directoryURI to scope a
+  /// directory to one table, or directoryURI for a staging area shared by all 
authorized uploaders.
+  /// 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";
   /// 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}).
   ///
@@ -1302,6 +1307,21 @@ public class ControllerConf extends PinotConfiguration {
     setProperty(SEGMENT_UPLOAD_TIMEOUT_IN_MILLIS, 
segmentUploadTimeoutInMillis);
   }
 
+  public List<String> getSegmentUploadAllowedSources(@Nullable String 
rawTableName) {
+    List<String> allowed = new ArrayList<>();
+    for (String entry : getCommaSeparatedList(SEGMENT_UPLOAD_ALLOWED_SOURCES, 
List.of())) {
+      // An equals sign after the URI scheme is part of the URI, not a table 
selector.
+      int selector = entry.indexOf('=');
+      int scheme = entry.indexOf(':');
+      if (selector < 0 || (scheme >= 0 && scheme < selector)) {
+        allowed.add(entry);
+      } else if (rawTableName != null && entry.substring(0, 
selector).equals(rawTableName)) {
+        allowed.add(entry.substring(selector + 1));
+      }
+    }
+    return allowed;
+  }
+
   /// @return whether out-of-retention single-segment upload rejection is 
enabled
   public boolean isSegmentUploadRejectOutOfRetention() {
     return getProperty(SEGMENT_UPLOAD_REJECT_OUT_OF_RETENTION, 
DEFAULT_SEGMENT_UPLOAD_REJECT_OUT_OF_RETENTION);
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 f269cc212cb..17ead65442d 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
@@ -287,7 +287,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       boolean uploadedSegmentIsEncrypted = 
StringUtils.isNotEmpty(crypterClassNameInHeader);
       FileUploadType uploadType = getUploadType(uploadTypeStr);
       File destFile = uploadedSegmentIsEncrypted ? tempEncryptedFile : 
tempDecryptedFile;
-      long segmentSizeInBytes;
+      long segmentSizeInBytes = -1;
       switch (uploadType) {
         case SEGMENT:
           if (multiPart == null) {
@@ -330,19 +330,6 @@ public class PinotSegmentUploadDownloadRestletResource {
               extractHttpHeader(headers, 
FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE);
           copySegmentToFinalLocation = 
Boolean.parseBoolean(copySegmentToDeepStore);
           createSegmentFileFromMultipart(multiPart, destFile);
-          PinotFS pinotFS = null;
-          try {
-            URI segmentURI = new URI(sourceDownloadURIStr);
-            pinotFS = PinotFSFactory.create(segmentURI.getScheme());
-            segmentSizeInBytes = pinotFS.length(segmentURI);
-          } catch (Exception e) {
-            segmentSizeInBytes = -1;
-            LOGGER.warn("Could not fetch segment size for metadata push", e);
-          } finally {
-            if (pinotFS != null) {
-              pinotFS.close();
-            }
-          }
           break;
         default:
           throw new ControllerApplicationException(LOGGER, "Unsupported upload 
type: " + uploadType,
@@ -391,6 +378,12 @@ public class PinotSegmentUploadDownloadRestletResource {
       
SegmentValidationUtils.validateUpsertSegmentPartitionMetadata(segmentMetadata, 
tableConfig);
       SegmentValidationUtils.rejectUploadIfOutOfRetention(segmentMetadata, 
tableConfig, System.currentTimeMillis(),
           _controllerConf.isSegmentUploadRejectOutOfRetention(), 
_controllerMetrics);
+      if (uploadType == FileUploadType.METADATA) {
+        if (copySegmentToFinalLocation) {
+          sourceDownloadURIStr = 
validateMetadataCopySource(sourceDownloadURIStr, rawTableName);
+        }
+        segmentSizeInBytes = getSegmentSizeFromFile(sourceDownloadURIStr);
+      }
       long untarredSegmentSizeInBytes;
       if (uploadType == FileUploadType.METADATA && segmentSizeInBytes > 0) {
         // TODO: Include the untarred segment size when using the METADATA 
push rest API. Currently we can only use the
@@ -503,25 +496,12 @@ public class PinotSegmentUploadDownloadRestletResource {
       tempTarFile = new File(provider.getFileUploadTempDir(), tempFileName);
       tempSegmentDir = new File(provider.getUntarredFileTempDir(), 
tempFileName);
 
-      long segmentSizeInBytes;
       createSegmentFileFromMultipart(multiPart, tempTarFile);
-      PinotFS pinotFS = null;
-      try {
-        URI segmentURI = new URI(sourceDownloadURIStr);
-        pinotFS = PinotFSFactory.create(segmentURI.getScheme());
-        segmentSizeInBytes = pinotFS.length(segmentURI);
-      } catch (Exception e) {
-        segmentSizeInBytes = -1;
-        LOGGER.warn("Could not fetch segment size for metadata push", e);
-      } finally {
-        if (pinotFS != null) {
-          pinotFS.close();
-        }
-      }
-
       String metadataProviderClass = DefaultMetadataExtractor.class.getName();
       SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir, metadataProviderClass);
       String segmentName = segmentMetadata.getName();
+      sourceDownloadURIStr = validateMetadataCopySource(sourceDownloadURIStr, 
rawTableName);
+      long segmentSizeInBytes = getSegmentSizeFromFile(sourceDownloadURIStr);
 
       String clientAddress = 
InetAddress.getByName(request.getRemoteAddr()).getHostName();
       LOGGER.info("Processing upload request for reingested segment: {} of 
table: {} from client: {}", segmentName,
@@ -663,6 +643,9 @@ public class PinotSegmentUploadDownloadRestletResource {
           SegmentValidationUtils.validateTimeInterval(segmentMetadata, 
tableConfig);
         }
         
SegmentValidationUtils.validateUpsertSegmentPartitionMetadata(segmentMetadata, 
tableConfig);
+        if (copySegmentToFinalLocation) {
+          sourceDownloadURIStr = 
validateMetadataCopySource(sourceDownloadURIStr, rawTableName);
+        }
         // TODO: Include the un-tarred segment size when using the METADATA 
push rest API. Currently we can only use the
         //  tarred segment size as an approximation.
         long segmentSizeInBytes = getSegmentSizeFromFile(sourceDownloadURIStr);
@@ -1427,6 +1410,12 @@ public class PinotSegmentUploadDownloadRestletResource {
     }
   }
 
+  private String validateMetadataCopySource(String source, String 
rawTableName) {
+    URI dataDir = ControllerFilePathProvider.getInstance().getDataDirURI();
+    return SegmentValidationUtils.validateMetadataCopySource(source, dataDir, 
rawTableName,
+        _controllerConf.getSegmentUploadAllowedSources(rawTableName));
+  }
+
   @VisibleForTesting
   static long getSegmentSizeFromFile(String sourceDownloadURIStr)
       throws IOException {
@@ -1437,8 +1426,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       pinotFS = PinotFSFactory.create(segmentURI.getScheme());
       segmentSizeInBytes = pinotFS.length(segmentURI);
     } catch (Exception e) {
-      LOGGER.warn(String.format("Exception while determining segment size for 
segment download uri: %s",
-          sourceDownloadURIStr), e);
+      LOGGER.warn("Could not fetch segment size for metadata push", e);
     } finally {
       if (pinotFS != null) {
         pinotFS.close();
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java
index f0a0c804975..3bc3a301aa6 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java
@@ -18,7 +18,16 @@
  */
 package org.apache.pinot.controller.api.upload;
 
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.OptionalLong;
 import java.util.Set;
 import javax.annotation.Nullable;
@@ -26,6 +35,8 @@ import javax.ws.rs.core.Response;
 import org.apache.pinot.common.metrics.ControllerMeter;
 import org.apache.pinot.common.metrics.ControllerMetrics;
 import org.apache.pinot.common.utils.RetentionUtils;
+import org.apache.pinot.common.utils.URIUtils;
+import org.apache.pinot.controller.ControllerConf;
 import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
 import org.apache.pinot.controller.validation.StorageQuotaChecker;
 import org.apache.pinot.segment.local.utils.TableConfigUtils;
@@ -36,6 +47,11 @@ import 
org.apache.pinot.spi.config.table.SegmentPartitionConfig;
 import org.apache.pinot.spi.config.table.SegmentsValidationAndRetentionConfig;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.filesystem.LocalPinotFS;
+import org.apache.pinot.spi.filesystem.PinotFS;
+import org.apache.pinot.spi.filesystem.PinotFSFactory;
+import org.apache.pinot.spi.plugin.PluginManager;
+import org.apache.pinot.spi.utils.CommonConstants;
 import org.apache.pinot.spi.utils.TimeUtils;
 import org.joda.time.Interval;
 import org.slf4j.Logger;
@@ -49,6 +65,154 @@ public class SegmentValidationUtils {
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(SegmentValidationUtils.class);
 
+  /// Validates a source before probing its size or copying it with the 
controller's storage credentials.
+  /// Built-in staging uses files directly in the destination table directory. 
Controller configuration can grant
+  /// access to separate staging directories for that table. Those directories 
must contain only trusted staging data.
+  public static String validateMetadataCopySource(String source, URI dataDir, 
String rawTableName,
+      List<String> stagingDirs) {
+    try {
+      URI sourceUri = new URI(source);
+      if (dataDir.getScheme().equals(sourceUri.getScheme()) && 
isAbsoluteStoragePath(sourceUri)
+          && !rawTableName.isEmpty() && !rawTableName.equals(".") && 
!rawTableName.equals("..")
+          && rawTableName.indexOf('/') < 0 && rawTableName.indexOf('\\') < 0 
&& rawTableName.indexOf('%') < 0
+          && rawTableName.indexOf('?') < 0 && rawTableName.indexOf('#') < 0) {
+        String scheme = sourceUri.getScheme();
+        boolean localFileSystem = 
PinotFSFactory.isSchemeRegisteredWith(scheme, LocalPinotFS.class);
+        if (CommonConstants.Segment.LOCAL_SEGMENT_SCHEME.equals(scheme)) {
+          if (localFileSystem && sourceUri.getRawAuthority() == null) {
+            Path sourcePath = resolveLocalStoragePath(sourceUri);
+            Path tableDir = 
localStoragePath(dataDir).toRealPath().resolve(URIUtils.decode(rawTableName));
+            if (Files.isRegularFile(sourcePath, LinkOption.NOFOLLOW_LINKS)
+                || Files.notExists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
+              if (tableDir.equals(sourcePath.getParent())) {
+                // Use the controller's spelling of the directory to preserve 
in-place pushes and sidecar checks.
+                String fileName = 
URIUtils.encode(sourcePath.getFileName().toString());
+                return URIUtils.getUri(dataDir.toString(), rawTableName, 
fileName).toString();
+              }
+              if (stagingDirs.stream().anyMatch(dir -> 
isLocalStagingSource(sourcePath, dir))) {
+                return sourcePath.toUri().toASCIIString().replace("+", "%2B");
+              }
+            }
+          }
+        } else if (!localFileSystem) {
+          URI tableDir = URIUtils.getUri(dataDir.toString(), rawTableName);
+          boolean bucketFileSystem = usesUriBucket(scheme);
+          boolean sameAuthority = Objects.equals(sourceUri.getRawAuthority(), 
dataDir.getRawAuthority());
+          if (isRemoteStagingSource(sourceUri, tableDir, true, 
bucketFileSystem)
+              || ((sameAuthority || bucketFileSystem)
+                  && stagingDirs.stream().anyMatch(dir -> 
isRemoteStagingSource(sourceUri, dir, bucketFileSystem)))) {
+            return source;
+          }
+        }
+      }
+    } catch (URISyntaxException | IOException | IllegalArgumentException e) {
+      LOGGER.debug("Could not validate the metadata upload source", e);
+    }
+    throw new ControllerApplicationException(LOGGER, "Metadata upload source 
must be in the table directory or in "
+        + "a staging directory configured by " + 
ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        Response.Status.BAD_REQUEST);
+  }
+
+  private static boolean isAbsoluteStoragePath(URI uri) {
+    return uri.getRawPath() != null && uri.getRawPath().startsWith("/")
+        && uri.getRawQuery() == null && uri.getRawFragment() == null;
+  }
+
+  private static Path localStoragePath(URI uri) {
+    // Match LocalPinotFS, which form-decodes the raw URI path.
+    return new File(URIUtils.decode(uri.getRawPath())).toPath();
+  }
+
+  private static Path resolveLocalStoragePath(URI uri)
+      throws IOException {
+    Path path = localStoragePath(uri);
+    if (!path.equals(path.normalize())) {
+      throw new IllegalArgumentException("Storage path must be normalized");
+    }
+    // An idempotent upload can arrive after staging cleanup. Resolve all 
existing ancestors, including symlinks,
+    // while allowing the missing portion to remain absent. A dangling symlink 
fails to resolve.
+    Path existing = path;
+    while (existing.getParent() != null && Files.notExists(existing, 
LinkOption.NOFOLLOW_LINKS)) {
+      existing = existing.getParent();
+    }
+    return existing.toRealPath().resolve(existing.relativize(path));
+  }
+
+  private static boolean isLocalStagingSource(Path source, String stagingDir) {
+    try {
+      URI uri = URIUtils.getUri(stagingDir);
+      if (CommonConstants.Segment.LOCAL_SEGMENT_SCHEME.equals(uri.getScheme()) 
&& uri.getRawAuthority() == null
+          && isAbsoluteStoragePath(uri)) {
+        Path root = resolveLocalStoragePath(uri);
+        return !source.equals(root) && source.startsWith(root);
+      }
+    } catch (IOException | IllegalArgumentException e) {
+      // An unavailable staging directory does not grant access.
+    }
+    return false;
+  }
+
+  private static boolean usesUriBucket(String scheme) {
+    // S3 and GCS select the bucket from the URI. Other plugins can use a 
single configured namespace regardless
+    // of the authority, so only accept alternate authorities when the 
corresponding plugin is registered.
+    return switch (scheme) {
+      case "s3", "s3a" -> isRegisteredBucketFileSystem(scheme, "pinot-s3", 
"S3PinotFS");
+      case "gs" -> isRegisteredBucketFileSystem(scheme, "pinot-gcs", 
"GcsPinotFS");
+      default -> false;
+    };
+  }
+
+  private static boolean isRegisteredBucketFileSystem(String scheme, String 
pluginName, String simpleClassName) {
+    String className = "org.apache.pinot.plugin.filesystem." + simpleClassName;
+    return isRegisteredFileSystem(scheme, className) || 
isRegisteredFileSystem(scheme, pluginName + ":" + className);
+  }
+
+  private static boolean isRegisteredFileSystem(String scheme, String 
className) {
+    try {
+      Class<? extends PinotFS> pluginClass = 
PluginManager.get().loadClass(className).asSubclass(PinotFS.class);
+      return PinotFSFactory.isSchemeRegisteredWith(scheme, pluginClass);
+    } catch (Exception | LinkageError e) {
+      // The optional plugin or plugin realm may be absent.
+      return false;
+    }
+  }
+
+  private static boolean isRemoteStagingSource(URI source, String stagingDir, 
boolean bucketFileSystem) {
+    try {
+      return isRemoteStagingSource(source, URIUtils.getUri(stagingDir), false, 
bucketFileSystem);
+    } catch (IllegalArgumentException e) {
+      return false;
+    }
+  }
+
+  private static boolean isRemoteStagingSource(URI source, URI root, boolean 
directChild, boolean collapseSeparators) {
+    // Some plugins form-decode the raw URI path. Require containment under 
both path interpretations.
+    return source.getScheme().equals(root.getScheme())
+        && Objects.equals(source.getRawAuthority(), root.getRawAuthority()) && 
isAbsoluteStoragePath(root)
+        && isStagingPath(source.getPath(), root.getPath(), directChild, 
collapseSeparators)
+        && isStagingPath(URIUtils.decode(source.getRawPath()), 
URIUtils.decode(root.getRawPath()), directChild,
+            collapseSeparators);
+  }
+
+  private static boolean isStagingPath(String source, String root, boolean 
directChild, boolean collapseSeparators) {
+    if (source.indexOf('%') >= 0 || source.indexOf('\\') >= 0) {
+      return false;
+    }
+    Path sourcePath = Path.of(source);
+    Path rootPath = Path.of(root);
+    if (!sourcePath.equals(sourcePath.normalize()) || 
!rootPath.equals(rootPath.normalize())) {
+      return false;
+    }
+    if (collapseSeparators) {
+      // S3 and GCS collapse consecutive separators when looking up object 
keys.
+      return directChild ? rootPath.equals(sourcePath.getParent())
+          : !rootPath.equals(sourcePath) && sourcePath.startsWith(rootPath);
+    }
+    String prefix = root.endsWith("/") ? root : root + "/";
+    return source.startsWith(prefix) && source.length() > prefix.length() && 
!source.endsWith("/")
+        && (!directChild || source.indexOf('/', prefix.length()) < 0);
+  }
+
   public static void validateTimeInterval(SegmentMetadata segmentMetadata, 
TableConfig tableConfig) {
     Interval timeInterval = segmentMetadata.getTimeInterval();
     if (timeInterval != null) {
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
index fa688c95468..8fa344fb398 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/PinotSegmentUploadAuthorizationTest.java
@@ -133,6 +133,16 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
       batchMetadataTar = createBatchMetadataTar(_segmentDatabase, 
SEGMENT_DATABASE,
           segmentUrl(segmentServer, SEGMENT_DATABASE));
       File batchMetadataTarForRequest = batchMetadataTar;
+      List<Header> copyHeaders = List.of(
+          new BasicHeader(FileUploadDownloadClient.CustomHeaders.UPLOAD_TYPE, 
"METADATA"),
+          new 
BasicHeader(FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE, 
"true"),
+          new BasicHeader(FileUploadDownloadClient.CustomHeaders.DOWNLOAD_URI, 
_segmentA.toURI().toString()));
+      HttpErrorStatusException stagingError = 
assertHttpStatus(Response.Status.BAD_REQUEST,
+          () -> client.uploadSegmentMetadata(uploadUri, _segmentA.getName(), 
_segmentA, copyHeaders,
+              uploadParameters(TABLE_A), 
HttpClient.DEFAULT_SOCKET_TIMEOUT_MS));
+      
Assert.assertTrue(stagingError.getMessage().contains(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES));
+      assertNoSegmentState(TABLE_A, TABLE_A_WITH_TYPE, SEGMENT_A);
+
       SimpleHttpResponse uploadResponse = uploadMultipart(client, uploadUri, 
_segmentA, TABLE_A, List.of());
       Assert.assertEquals(uploadResponse.getStatusCode(), 
Response.Status.OK.getStatusCode());
 
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/upload/SegmentValidationUtilsTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/upload/SegmentValidationUtilsTest.java
index 93cc38158de..4d784dd51ce 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/api/upload/SegmentValidationUtilsTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/api/upload/SegmentValidationUtilsTest.java
@@ -18,12 +18,21 @@
  */
 package org.apache.pinot.controller.api.upload;
 
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import javax.ws.rs.core.Response;
+import org.apache.commons.io.FileUtils;
 import org.apache.pinot.common.metrics.ControllerMeter;
 import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.common.utils.URIUtils;
+import org.apache.pinot.controller.ControllerConf;
 import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
 import org.apache.pinot.controller.validation.StorageQuotaChecker;
 import org.apache.pinot.segment.spi.ColumnMetadata;
@@ -56,6 +65,73 @@ public class SegmentValidationUtilsTest {
   private static final String PARTITION_COLUMN = "pk";
   private static final int NUM_PARTITIONS = 4;
 
+  @Test
+  public void testLocalMetadataCopySource()
+      throws IOException {
+    Path tempDir = Files.createTempDirectory("metadata-copy-source");
+    try {
+      Path dataDir = Files.createDirectory(tempDir.resolve("deep-store"));
+      Path tableDir = Files.createDirectory(dataDir.resolve(RAW_TABLE_NAME));
+      Path localStage = Files.createFile(tableDir.resolve(SEGMENT_NAME + 
".tmp"));
+      Path extraDir = Files.createDirectory(tempDir.resolve("staging,daily"));
+      Path externalStage = 
Files.createFile(extraDir.resolve("segment+part.tar.gz"));
+      Path otherDir = 
Files.createDirectory(tempDir.resolve("staging,daily-other"));
+      Path otherStage = Files.createFile(otherDir.resolve("segment.tar.gz"));
+      Path link = Files.createSymbolicLink(tableDir.resolve("link.tar.gz"), 
otherStage);
+
+      ControllerConf conf = new ControllerConf();
+      String stagingUri = extraDir.toUri().toString().replace(",", "%2C");
+      String tableStagingEntry = RAW_TABLE_NAME + "=" + stagingUri;
+      conf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
tableStagingEntry);
+      List<String> stagingDirs = 
conf.getSegmentUploadAllowedSources(RAW_TABLE_NAME);
+      
assertEquals(conf.getSegmentUploadAllowedSources(RAW_TABLE_NAME.toLowerCase(Locale.ROOT)),
 List.of());
+
+      String shared = "s3://shared/staging=approved/";
+      conf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, shared + 
"," + tableStagingEntry);
+      assertEquals(conf.getSegmentUploadAllowedSources(null), List.of(shared));
+      assertEquals(conf.getSegmentUploadAllowedSources(RAW_TABLE_NAME), 
List.of(shared, stagingUri));
+
+      URI dataUri = URI.create(dataDir.toUri().toString().replaceFirst("/$", 
""));
+      
assertEquals(SegmentValidationUtils.validateMetadataCopySource(localStage.toUri().toString(),
 dataUri,
+          RAW_TABLE_NAME, List.of()), URIUtils.getPath(dataUri.toString(), 
RAW_TABLE_NAME, SEGMENT_NAME + ".tmp"));
+      String externalUri = externalStage.toUri().toString().replace("+", 
"%2B");
+      
assertEquals(SegmentValidationUtils.validateMetadataCopySource(externalUri, 
dataDir.toUri(),
+          RAW_TABLE_NAME, stagingDirs),
+          externalStage.toRealPath().toUri().toString().replace("+", "%2B"));
+      Files.delete(localStage);
+      
assertEquals(SegmentValidationUtils.validateMetadataCopySource(localStage.toUri().toString(),
 dataUri,
+          RAW_TABLE_NAME, List.of()), URIUtils.getPath(dataUri.toString(), 
RAW_TABLE_NAME, SEGMENT_NAME + ".tmp"));
+      for (Path rejected : List.of(otherStage, link, tableDir)) {
+        ControllerApplicationException exception = 
expectThrows(ControllerApplicationException.class,
+            () -> 
SegmentValidationUtils.validateMetadataCopySource(rejected.toUri().toString(), 
dataDir.toUri(),
+                RAW_TABLE_NAME, stagingDirs));
+        assertEquals(exception.getResponse().getStatus(), 
Response.Status.BAD_REQUEST.getStatusCode());
+      }
+    } finally {
+      FileUtils.deleteDirectory(tempDir.toFile());
+    }
+  }
+
+  @Test
+  public void testRemoteMetadataCopySource() {
+    URI dataDir = URI.create("gs://deep-store/segments");
+    List<String> stagingDirs = List.of("gs://deep-store/jobs");
+    String source = "gs://deep-store/jobs/run/part.tar.gz";
+    assertEquals(SegmentValidationUtils.validateMetadataCopySource(source, 
dataDir, RAW_TABLE_NAME,
+        stagingDirs), source);
+    for (String rejected : List.of("gs://other-bucket/jobs/run/part.tar.gz",
+        "gs://deep-store/jobs-other/run/part.tar.gz", 
"gs://deep-store/jobs/%2e%2e/part.tar.gz")) {
+      assertThrows(ControllerApplicationException.class,
+          () -> SegmentValidationUtils.validateMetadataCopySource(rejected, 
dataDir, RAW_TABLE_NAME,
+              stagingDirs));
+    }
+    URI azureData = URI.create("abfss://[email protected]/segments");
+    String azureStage = "abfss://[email protected]/jobs";
+    assertThrows(ControllerApplicationException.class,
+        () -> SegmentValidationUtils.validateMetadataCopySource(azureStage + 
"/part.tar.gz", azureData,
+            RAW_TABLE_NAME, List.of(azureStage)));
+  }
+
   @Test
   public void 
testValidateUpsertSegmentPartitionMetadataAcceptsSinglePartitionId() {
     
SegmentValidationUtils.validateUpsertSegmentPartitionMetadata(mockSegmentMetadata(Set.of(2)),
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SegmentUploadIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SegmentUploadIntegrationTest.java
index e5fc4174069..55657c49e69 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SegmentUploadIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SegmentUploadIntegrationTest.java
@@ -23,6 +23,7 @@ import com.google.common.collect.Lists;
 import java.io.File;
 import java.io.IOException;
 import java.net.URI;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import org.apache.commons.io.FileUtils;
@@ -50,6 +51,7 @@ import org.apache.pinot.spi.utils.JsonUtils;
 import org.apache.pinot.util.TestUtils;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
@@ -68,6 +70,7 @@ import static org.testng.Assert.expectThrows;
 public class SegmentUploadIntegrationTest extends 
SharedOfflineUploadIntegrationTestSuite {
   private static String _tableNameSuffix;
   private Boolean _originalRejectOutOfRetention;
+  private List<String> _originalAllowedSources;
 
   @Override
   @BeforeClass
@@ -121,6 +124,19 @@ public class SegmentUploadIntegrationTest extends 
SharedOfflineUploadIntegration
       throws IOException {
     _tableNameSuffix = RandomStringUtils.secure().nextAlphabetic(12);
     TestUtils.ensureDirectoriesExistAndEmpty(_tempDir, _segmentDir, _tarDir);
+    ControllerConf controllerConf = getSharedControllerStarter().getConfig();
+    _originalAllowedSources = 
controllerConf.getProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
List.of());
+    List<String> sourceDirs = new ArrayList<>(_originalAllowedSources);
+    sourceDirs.add(getTableName() + "=" + _tarDir.toURI());
+    controllerConf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
sourceDirs);
+  }
+
+  @AfterMethod(alwaysRun = true)
+  public void restoreAllowedSources() {
+    if (_originalAllowedSources != null) {
+      getSharedControllerStarter().getConfig()
+          .setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_originalAllowedSources);
+    }
   }
 
   @Test
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SparkSegmentMetadataPushIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SparkSegmentMetadataPushIntegrationTest.java
index e933af5d812..f517e1c0fee 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SparkSegmentMetadataPushIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/SparkSegmentMetadataPushIntegrationTest.java
@@ -24,6 +24,7 @@ import java.io.IOException;
 import java.util.List;
 import java.util.Map;
 import org.apache.commons.io.FileUtils;
+import org.apache.pinot.controller.ControllerConf;
 import 
org.apache.pinot.plugin.ingestion.batch.spark3.SparkSegmentMetadataPushJobRunner;
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.config.table.TableType;
@@ -96,6 +97,7 @@ public class SparkSegmentMetadataPushIntegrationTest extends 
BaseClusterIntegrat
 
     // Start the Pinot cluster
     startController();
+    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_testTable + "=" + _tarDir.toURI());
     startBroker();
     startServer();
 


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

Reply via email to