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 fbf1cf6eae7 Validate segment upload source URIs (#20427)
fbf1cf6eae7 is described below

commit fbf1cf6eae7bcc0987212a5823117ffa4f50e6d6
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Dec 4 16:25:15 2026 -0800

    Validate segment upload source URIs (#20427)
    
    * Validate segment upload source URIs
    
    Use one source policy for segment uploads, validate configured staging 
prefixes on startup, and exercise the supported upload modes with the focused 
authorization and ingestion suites.
    
    * Preserve HDFS staging support for metadata uploads
---
 .../common/utils/FileUploadDownloadClient.java     |   8 +
 .../common/utils/fetcher/HttpSegmentFetcher.java   |  61 ++++-
 .../utils/fetcher/SegmentFetcherFactory.java       |  21 ++
 .../apache/pinot/common/utils/http/HttpClient.java |  13 +-
 .../utils/fetcher/HttpSegmentFetcherTest.java      |  43 +++
 .../pinot/controller/BaseControllerStarter.java    |   2 +
 .../apache/pinot/controller/ControllerConf.java    |  13 +-
 .../PinotSegmentUploadDownloadRestletResource.java | 155 ++++++-----
 .../api/upload/SegmentUploadSourcePolicy.java      | 301 +++++++++++++++++++++
 .../api/upload/SegmentValidationUtils.java         | 168 +-----------
 .../pinot/controller/api/upload/ZKOperator.java    |   5 +-
 .../api/PinotSegmentUploadAuthorizationTest.java   |  30 +-
 ...otSegmentUploadDownloadRestletResourceTest.java |  17 +-
 .../api/upload/SegmentValidationUtilsTest.java     | 121 +++++++--
 .../tests/BaseClusterIntegrationTest.java          |   9 +
 .../tests/PurgeMinionClusterIntegrationTest.java   |   3 +
 .../tests/SegmentUploadIntegrationTest.java        |  15 +-
 .../SparkSegmentMetadataPushIntegrationTest.java   |   7 +-
 .../CustomDataQueryClusterIntegrationTest.java     |  24 ++
 .../tests/custom/RefreshSegmentMinionTest.java     |   3 +
 .../BaseLogicalTableIntegrationTest.java           |   3 +-
 21 files changed, 734 insertions(+), 288 deletions(-)

diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
index 7565384133b..f9f641c37a7 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/FileUploadDownloadClient.java
@@ -1039,6 +1039,14 @@ public class FileUploadDownloadClient implements 
AutoCloseable {
     return _httpClient.downloadFile(uri, connectionRequestTimeoutMs, 
socketTimeoutMs, dest, authProvider, httpHeaders);
   }
 
+  /// Download a file without following redirects, using the configured 
transport and authentication.
+  public int downloadFileWithoutRedirects(URI uri, File dest, AuthProvider 
authProvider, List<Header> httpHeaders,
+      int connectionRequestTimeoutMs, int socketTimeoutMs)
+      throws IOException, HttpErrorStatusException {
+    return _httpClient.downloadFile(uri, connectionRequestTimeoutMs, 
socketTimeoutMs, dest, authProvider, httpHeaders,
+        false);
+  }
+
   /// Download and untar a file in a streamed way with rate limit
   ///
   /// @param uri URI
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcher.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcher.java
index dbb37455bc7..6ff44f75a84 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcher.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcher.java
@@ -22,6 +22,8 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.net.InetAddresses;
 import java.io.File;
 import java.io.IOException;
+import java.net.Inet4Address;
+import java.net.InetAddress;
 import java.net.URI;
 import java.util.LinkedList;
 import java.util.List;
@@ -79,16 +81,31 @@ public class HttpSegmentFetcher extends BaseSegmentFetcher {
   @Override
   public void fetchSegmentToLocal(URI downloadURI, File dest)
       throws Exception {
+    fetchSegmentToLocal(downloadURI, dest, false);
+  }
+
+  void fetchSegmentToLocalForUpload(URI downloadURI, File dest)
+      throws Exception {
+    fetchSegmentToLocal(downloadURI, dest, true);
+  }
+
+  private void fetchSegmentToLocal(URI downloadURI, File dest, boolean 
forUpload)
+      throws Exception {
     // Create a RoundRobinURIProvider to round robin IP addresses when retry 
uploading. Otherwise may always try to
     // download from a same broken host as: 1) DNS may not RR the IP addresses 
2) OS cache the DNS resolution result.
     RoundRobinURIProvider uriProvider = new 
RoundRobinURIProvider(List.of(downloadURI), true);
+    if (forUpload) {
+      validateUploadAddresses(downloadURI.getHost(), uriProvider);
+    }
 
     int retryCount = getRetryCount(uriProvider);
 
     _logger.info("Retry downloading for {} times. retryCount from pinot server 
config: {}, number of IP addresses for "
-        + "download URI: {}", retryCount, _retryCount, 
uriProvider.numAddresses());
+        + "download source {}", retryCount, _retryCount, 
uriProvider.numAddresses(),
+        forUpload ? downloadURI.getHost() : downloadURI);
     RetryPolicies.exponentialBackoffRetryPolicy(retryCount, _retryWaitMs, 
_retryDelayScaleFactor).attempt(() -> {
       URI uri = uriProvider.next();
+      Object source = forUpload ? downloadURI.getHost() : uri;
       try {
         String hostName = downloadURI.getHost();
         int port = downloadURI.getPort();
@@ -99,9 +116,12 @@ public class HttpSegmentFetcher extends BaseSegmentFetcher {
         if (!InetAddresses.isInetAddress(hostName)) {
           httpHeaders.add(new BasicHeader(HttpHeaders.HOST, hostName + ":" + 
port));
         }
-        int statusCode = _httpClient.downloadFile(uri, dest, _authProvider, 
httpHeaders, _connectionRequestTimeoutMs,
-            _socketTimeoutMs);
-        _logger.info("Downloaded segment from: {} to: {} of size: {}; Response 
status code: {}", uri, dest,
+        int statusCode = forUpload
+            ? _httpClient.downloadFileWithoutRedirects(uri, dest, 
_authProvider, httpHeaders,
+                _connectionRequestTimeoutMs, _socketTimeoutMs)
+            : _httpClient.downloadFile(uri, dest, _authProvider, httpHeaders, 
_connectionRequestTimeoutMs,
+                _socketTimeoutMs);
+        _logger.info("Downloaded segment from: {} to: {} of size: {}; Response 
status code: {}", source, dest,
             dest.length(), statusCode);
         return true;
       } catch (HttpErrorStatusException e) {
@@ -110,22 +130,47 @@ public class HttpSegmentFetcher extends 
BaseSegmentFetcher {
           // Temporary exception
           // 404 is treated as a temporary exception, as the downloadURI may 
be backed by multiple hosts,
           // if singe host is down, can retry with another host.
-          _logger.warn("Got temporary error status code: {} while downloading 
segment from: {} to: {}", statusCode, uri,
-              dest, e);
+          _logger.warn("Got temporary error status code: {} while downloading 
segment from: {} to: {}", statusCode,
+              source, dest, e);
           return false;
         } else {
           // Permanent exception
           _logger.error("Got permanent error status code: {} while downloading 
segment from: {} to: {}, won't retry",
-              statusCode, uri, dest, e);
+              statusCode, source, dest, e);
           throw e;
         }
       } catch (Exception e) {
-        _logger.warn("Caught exception while downloading segment from: {} to: 
{}", uri, dest, e);
+        if (forUpload) {
+          _logger.warn("Could not download segment from {}: {}", source, 
e.getClass().getSimpleName());
+        } else {
+          _logger.warn("Caught exception while downloading segment from: {} 
to: {}", source, dest, e);
+        }
         return false;
       }
     });
   }
 
+  private static void validateUploadAddresses(String host, 
RoundRobinURIProvider uriProvider) {
+    // The caller approves the URI's origin. A loopback address is usable only 
as a literal in that origin.
+    boolean literalHost = InetAddresses.isUriInetAddress(host);
+    for (int i = 0; i < uriProvider.numAddresses(); i++) {
+      InetAddress address = 
InetAddresses.forUriString(uriProvider.next().getHost());
+      if (address.isAnyLocalAddress() || address.isLinkLocalAddress() || 
address.isMulticastAddress()
+          || (address.isLoopbackAddress() && !literalHost) || 
isReservedIPv4Address(address)) {
+        throw new IllegalArgumentException("HTTP upload source resolves to a 
restricted address");
+      }
+    }
+  }
+
+  private static boolean isReservedIPv4Address(InetAddress address) {
+    if (!(address instanceof Inet4Address)) {
+      return false;
+    }
+    byte[] bytes = address.getAddress();
+    int first = Byte.toUnsignedInt(bytes[0]);
+    return first == 0 || first >= 240;
+  }
+
   private int getRetryCount(RoundRobinURIProvider uriProvider) {
     // Use the minimal value of configured retry count and number of IP 
addresses.
     return Math.min(_retryCount, uriProvider.numAddresses());
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/SegmentFetcherFactory.java
 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/SegmentFetcherFactory.java
index f6e0eb74f10..056693c2623 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/SegmentFetcherFactory.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/fetcher/SegmentFetcherFactory.java
@@ -22,6 +22,7 @@ import java.io.File;
 import java.net.URI;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Supplier;
@@ -124,6 +125,26 @@ public class SegmentFetcherFactory {
     getSegmentFetcher(uri.getScheme()).fetchSegmentToLocal(uri, dest);
   }
 
+  /// Fetches a segment for an upload after the caller validates the source 
against its upload policy.
+  /// HTTP(S) uploads require a built-in fetcher so the transport can enforce 
destination checks and disable redirects.
+  public static void fetchSegmentToLocalForUpload(URI uri, File dest)
+      throws Exception {
+    String scheme = uri.getScheme();
+    if (CommonConstants.HTTP_PROTOCOL.equalsIgnoreCase(scheme)
+        || CommonConstants.HTTPS_PROTOCOL.equalsIgnoreCase(scheme)) {
+      if (uri.getHost() == null || uri.getRawUserInfo() != null) {
+        throw new IllegalArgumentException("Invalid HTTP upload source");
+      }
+      SegmentFetcher fetcher = 
getSegmentFetcher(scheme.toLowerCase(Locale.ROOT));
+      if (fetcher.getClass() != HttpSegmentFetcher.class && fetcher.getClass() 
!= HttpsSegmentFetcher.class) {
+        throw new IllegalArgumentException("HTTP uploads require a built-in 
segment fetcher");
+      }
+      ((HttpSegmentFetcher) fetcher).fetchSegmentToLocalForUpload(uri, dest);
+    } else {
+      fetchSegmentToLocal(uri, dest);
+    }
+  }
+
   /// Fetches a segment from URI location to local.
   public static void fetchSegmentToLocal(String uri, File dest)
       throws Exception {
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/http/HttpClient.java 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/http/HttpClient.java
index 5ed05f1d334..a0d0c5c92fd 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/utils/http/HttpClient.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/utils/http/HttpClient.java
@@ -394,18 +394,27 @@ public class HttpClient implements AutoCloseable {
   public int downloadFile(URI uri, int connectionRequestTimeoutMs, int 
socketTimeoutMs, File dest,
       AuthProvider authProvider, List<Header> httpHeaders)
       throws IOException, HttpErrorStatusException {
+    return downloadFile(uri, connectionRequestTimeoutMs, socketTimeoutMs, 
dest, authProvider, httpHeaders, true);
+  }
+
+  /// Download a file with an explicit redirect policy for this request.
+  public int downloadFile(URI uri, int connectionRequestTimeoutMs, int 
socketTimeoutMs, File dest,
+      AuthProvider authProvider, List<Header> httpHeaders, boolean 
followRedirects)
+      throws IOException, HttpErrorStatusException {
     ClassicHttpRequest request = getDownloadFileRequest(uri, authProvider, 
httpHeaders);
 
     RequestConfig requestConfig =
         
RequestConfig.custom().setConnectionRequestTimeout(Timeout.ofMilliseconds(connectionRequestTimeoutMs))
-            
.setResponseTimeout(Timeout.ofMilliseconds(socketTimeoutMs)).build();
+            
.setResponseTimeout(Timeout.ofMilliseconds(socketTimeoutMs)).setRedirectsEnabled(followRedirects).build();
     HttpClientContext clientContext = HttpClientContext.create();
     clientContext.setRequestConfig(requestConfig);
 
     try (CloseableHttpResponse response = _httpClient.execute(request, 
clientContext)) {
       int statusCode = response.getCode();
       if (statusCode >= 300) {
-        throw new HttpErrorStatusException(HttpClient.getErrorMessage(request, 
response), statusCode);
+        String message = followRedirects ? HttpClient.getErrorMessage(request, 
response)
+            : "Unexpected HTTP download status: " + statusCode;
+        throw new HttpErrorStatusException(message, statusCode);
       }
 
       HttpEntity entity = response.getEntity();
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcherTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcherTest.java
index 2819ad542e2..14f1de78458 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcherTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/utils/fetcher/HttpSegmentFetcherTest.java
@@ -18,16 +18,22 @@
  */
 package org.apache.pinot.common.utils.fetcher;
 
+import com.sun.net.httpserver.HttpServer;
 import java.io.File;
 import java.io.IOException;
+import java.net.InetSocketAddress;
 import java.net.URI;
+import java.nio.file.Files;
 import java.util.List;
 import java.util.concurrent.ThreadLocalRandom;
 import java.util.function.Supplier;
 import org.apache.commons.io.FileUtils;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.pinot.common.exception.HttpErrorStatusException;
 import org.apache.pinot.common.utils.FileUploadDownloadClient;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.retry.AttemptsExceededException;
+import org.apache.pinot.spi.utils.retry.RetriableOperationException;
 import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
@@ -130,6 +136,43 @@ public class HttpSegmentFetcherTest {
     segmentFetcher.fetchSegmentToLocal(SEGMENT_NAME, () -> uris, SEGMENT_FILE);
   }
 
+  @Test
+  public void testUploadFetchDoesNotFollowRedirects()
+      throws Exception {
+    HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 
0), 0);
+    File dest = Files.createTempFile("upload-segment", ".tar.gz").toFile();
+    try (FileUploadDownloadClient client = new FileUploadDownloadClient()) {
+      server.createContext("/redirect", exchange -> {
+        exchange.getResponseHeaders().set("Location", "/segment");
+        exchange.sendResponseHeaders(HttpStatus.SC_MOVED_TEMPORARILY, -1);
+        exchange.close();
+      });
+      server.createContext("/segment", exchange -> {
+        exchange.sendResponseHeaders(HttpStatus.SC_OK, 1);
+        exchange.getResponseBody().write(0);
+        exchange.close();
+      });
+      server.start();
+      HttpSegmentFetcher fetcher = new HttpSegmentFetcher();
+      fetcher.setHttpClient(client);
+      fetcher.init(_fetcherConfig);
+      URI redirect = URI.create("http://127.0.0.1:"; + 
server.getAddress().getPort() + "/redirect");
+
+      RetriableOperationException exception = 
Assert.expectThrows(RetriableOperationException.class,
+          () -> fetcher.fetchSegmentToLocalForUpload(redirect, dest));
+      Assert.assertTrue(exception.getCause() instanceof 
HttpErrorStatusException);
+      Assert.assertEquals(((HttpErrorStatusException) 
exception.getCause()).getStatusCode(),
+          HttpStatus.SC_MOVED_TEMPORARILY);
+      Assert.assertEquals(dest.length(), 0L);
+
+      fetcher.fetchSegmentToLocal(redirect, dest);
+      Assert.assertEquals(dest.length(), 1L);
+    } finally {
+      server.stop(0);
+      FileUtils.deleteQuietly(dest);
+    }
+  }
+
   @Test
   public void testFetchUntarSegmentToLocalStreamedSucceedAtFirstAttempt()
       throws Exception {
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 defe7c7eefe..89cca1828bd 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
@@ -101,6 +101,7 @@ import 
org.apache.pinot.controller.api.access.AccessControlFactory;
 import org.apache.pinot.controller.api.events.MetadataEventNotifierFactory;
 import org.apache.pinot.controller.api.resources.ControllerFilePathProvider;
 import 
org.apache.pinot.controller.api.resources.InvalidControllerConfigException;
+import org.apache.pinot.controller.api.upload.SegmentUploadSourcePolicy;
 import org.apache.pinot.controller.helix.RealtimeConsumerMonitor;
 import org.apache.pinot.controller.helix.SegmentStatusChecker;
 import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
@@ -266,6 +267,7 @@ public abstract class BaseControllerStarter implements 
ServiceStartable {
     applyCustomConfigs(_config);
     _config.validateSegmentMetadataEntryLimits();
     _config.validateSegmentUploadArchivePathLimits();
+    SegmentUploadSourcePolicy.validateConfiguredSources(_config);
     _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 c9a3b7335a2..48e8e8a25cf 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
@@ -1343,6 +1343,15 @@ public class ControllerConf extends PinotConfiguration {
   }
 
   public List<String> getSegmentUploadAllowedSources(@Nullable String 
rawTableName) {
+    return getSegmentUploadAllowedSources(rawTableName, false);
+  }
+
+  /// Returns every configured source prefix for startup validation, 
regardless of table scope.
+  public List<String> getAllSegmentUploadAllowedSources() {
+    return getSegmentUploadAllowedSources(null, true);
+  }
+
+  private List<String> getSegmentUploadAllowedSources(@Nullable String 
rawTableName, boolean includeAllTables) {
     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.
@@ -1350,7 +1359,9 @@ public class ControllerConf extends PinotConfiguration {
       int scheme = entry.indexOf(':');
       if (selector < 0 || (scheme >= 0 && scheme < selector)) {
         allowed.add(entry);
-      } else if (rawTableName != null && entry.substring(0, 
selector).equals(rawTableName)) {
+      } else if (selector == 0) {
+        throw new IllegalArgumentException("Empty table name in " + 
SEGMENT_UPLOAD_ALLOWED_SOURCES);
+      } else if (includeAllTables || entry.substring(0, 
selector).equals(rawTableName)) {
         allowed.add(entry.substring(selector + 1));
       }
     }
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 78f705a8ad8..4f83874bfd6 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
@@ -38,6 +38,7 @@ import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.net.InetAddress;
 import java.net.URI;
+import java.net.URISyntaxException;
 import java.net.UnknownHostException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
@@ -71,6 +72,7 @@ import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
 import org.apache.pinot.common.metrics.ControllerGauge;
 import org.apache.pinot.common.metrics.ControllerMeter;
 import org.apache.pinot.common.metrics.ControllerMetrics;
@@ -94,6 +96,8 @@ import org.apache.pinot.controller.api.access.Authenticate;
 import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
 import org.apache.pinot.controller.api.upload.SegmentMetadataInfo;
 import org.apache.pinot.controller.api.upload.SegmentUploadMetadata;
+import org.apache.pinot.controller.api.upload.SegmentUploadSourcePolicy;
+import org.apache.pinot.controller.api.upload.SegmentUploadSourcePolicy.Mode;
 import org.apache.pinot.controller.api.upload.SegmentValidationUtils;
 import org.apache.pinot.controller.api.upload.ZKOperator;
 import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
@@ -288,7 +292,7 @@ public class PinotSegmentUploadDownloadRestletResource {
       boolean uploadedSegmentIsEncrypted = 
StringUtils.isNotEmpty(crypterClassNameInHeader);
       FileUploadType uploadType = getUploadType(uploadTypeStr);
       File destFile = uploadedSegmentIsEncrypted ? tempEncryptedFile : 
tempDecryptedFile;
-      long segmentSizeInBytes = -1;
+      long segmentSizeInBytes;
       switch (uploadType) {
         case SEGMENT:
           if (multiPart == null) {
@@ -311,7 +315,15 @@ public class PinotSegmentUploadDownloadRestletResource {
                 "Source download URI is required in header field 
'DOWNLOAD_URI' for URI upload mode",
                 Response.Status.BAD_REQUEST);
           }
-          downloadSegmentFileFromURI(sourceDownloadURIStr, destFile, 
requestedTableName);
+          if (requestedTableName != null) {
+            ResourceUtils.checkPermissionAndAccess(requestedTableName, 
request, headers, AccessType.CREATE,
+                Actions.Table.UPLOAD_SEGMENT, _accessControlFactory, LOGGER);
+          }
+          URI source = validateSource(provider, sourceDownloadURIStr, 
requestedTableName,
+              copySegmentToFinalLocation ? Mode.URI_COPY : Mode.URI_REFERENCE);
+          sourceDownloadURIStr = source.toString();
+          segmentDownloadURIStr = sourceDownloadURIStr;
+          fetchUploadSource(source, destFile);
           segmentSizeInBytes = destFile.length();
           break;
         case METADATA:
@@ -331,6 +343,7 @@ public class PinotSegmentUploadDownloadRestletResource {
               extractHttpHeader(headers, 
FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE);
           copySegmentToFinalLocation = 
Boolean.parseBoolean(copySegmentToDeepStore);
           createSegmentFileFromMultipart(multiPart, destFile);
+          segmentSizeInBytes = -1;
           break;
         default:
           throw new ControllerApplicationException(LOGGER, "Unsupported upload 
type: " + uploadType,
@@ -356,6 +369,17 @@ public class PinotSegmentUploadDownloadRestletResource {
       ResourceUtils.checkPermissionAndAccess(rawTableName, request, headers, 
AccessType.CREATE,
           Actions.Table.UPLOAD_SEGMENT, _accessControlFactory, LOGGER);
 
+      if (uploadType == FileUploadType.METADATA) {
+        URI source = validateMetadataSource(provider, sourceDownloadURIStr, 
rawTableName,
+            tableNameWithType, segmentName, copySegmentToFinalLocation);
+        sourceDownloadURIStr = source.toString();
+        segmentDownloadURIStr = sourceDownloadURIStr;
+        segmentSizeInBytes = 
SegmentValidationUtils.getSegmentSizeFromFile(source);
+      } else if (uploadType == FileUploadType.SEGMENT && 
!copySegmentToFinalLocation) {
+        segmentDownloadURIStr =
+            validateSource(provider, sourceDownloadURIStr, rawTableName, 
Mode.SEGMENT_REFERENCE).toString();
+      }
+
       if 
(UploadedRealtimeSegmentName.isUploadedRealtimeSegmentName(segmentName) && 
tableType != TableType.REALTIME) {
         throw new ControllerApplicationException(LOGGER, "Cannot upload 
segment: " + segmentName
             + " to OFFLINE table as this format is reserved for uploaded 
real-time segment",
@@ -378,12 +402,6 @@ 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
@@ -439,8 +457,8 @@ public class PinotSegmentUploadDownloadRestletResource {
         }
         finalSegmentLocationURI = URIUtils.getUri(finalSegmentLocationPath);
       }
-      LOGGER.info("Using segment download URI: {} for segment: {} of table: {} 
(move segment: {})",
-          segmentDownloadURIStr, segmentFile, tableNameWithType, 
copySegmentToFinalLocation);
+      LOGGER.info("Registering segment: {} of table: {} (copy to deep store: 
{})",
+          segmentName, tableNameWithType, copySegmentToFinalLocation);
 
       ZKOperator zkOperator = new ZKOperator(_pinotHelixResourceManager, 
_controllerConf, _controllerMetrics);
       zkOperator.completeSegmentOperations(tableConfig, segmentMetadata, 
uploadType, finalSegmentLocationURI,
@@ -464,9 +482,8 @@ public class PinotSegmentUploadDownloadRestletResource {
 
   private SuccessResponse uploadReingestedSegment(String tableName, 
FormDataMultiPart multiPart, HttpHeaders headers,
       Request request) {
-    tableName = DatabaseUtils.translateTableName(tableName, headers);
-    String rawTableName = TableNameBuilder.extractRawTableName(tableName);
-    String realtimeTableName = 
TableNameBuilder.REALTIME.tableNameWithType(tableName);
+    String rawTableName = normalizeTableName(tableName, TableType.REALTIME, 
headers, "request tableName");
+    String realtimeTableName = 
TableNameBuilder.REALTIME.tableNameWithType(rawTableName);
 
     // TODO: Consider validating the segment name and table name from the 
header against the actual segment
     extractHttpHeader(headers, 
CommonConstants.Controller.SEGMENT_NAME_HTTP_HEADER);
@@ -499,10 +516,10 @@ public class PinotSegmentUploadDownloadRestletResource {
       createSegmentFileFromMultipart(multiPart, tempTarFile);
       SegmentMetadata segmentMetadata = getSegmentMetadata(tempTarFile, 
tempSegmentDir);
       String segmentName = segmentMetadata.getName();
-      sourceDownloadURIStr = validateMetadataCopySource(sourceDownloadURIStr, 
rawTableName);
-      long segmentSizeInBytes = getSegmentSizeFromFile(sourceDownloadURIStr);
 
       String clientAddress = 
InetAddress.getByName(request.getRemoteAddr()).getHostName();
+      // The authorization filter checks UPLOAD_SEGMENT against the request's 
tableName before dispatch.
+      URI source = validateSource(provider, sourceDownloadURIStr, 
rawTableName, Mode.METADATA_COPY);
       LOGGER.info("Processing upload request for reingested segment: {} of 
table: {} from client: {}", segmentName,
           realtimeTableName, clientAddress);
 
@@ -523,7 +540,7 @@ public class PinotSegmentUploadDownloadRestletResource {
 
       ZKOperator zkOperator = new ZKOperator(_pinotHelixResourceManager, 
_controllerConf, _controllerMetrics);
       zkOperator.completeReingestedSegmentOperations(realtimeTableName, 
segmentMetadata, finalSegmentLocationURI,
-          sourceDownloadURIStr, segmentDownloadURIStr, segmentSizeInBytes);
+          source, segmentDownloadURIStr);
 
       return new SuccessResponse(
           "Successfully uploaded reingested segment: " + segmentName + " of 
table: " + realtimeTableName);
@@ -593,6 +610,14 @@ public class PinotSegmentUploadDownloadRestletResource {
       Map<String, SegmentMetadataInfo> segmentsMetadataInfoMap =
           createSegmentsMetadataInfoMap(multiPart, tempFiles, pathBudget);
       LOGGER.info("Uploading segments in batch mode of size: {}", 
segmentsMetadataInfoMap.size());
+      boolean copySegmentToFinalLocation = Boolean.parseBoolean(
+          extractHttpHeader(headers, 
FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE));
+      Map<String, URI> validatedSources = new HashMap<>();
+      for (Map.Entry<String, SegmentMetadataInfo> entry : 
segmentsMetadataInfoMap.entrySet()) {
+        validatedSources.put(entry.getKey(),
+            validateMetadataSource(provider, 
entry.getValue().getSegmentDownloadURI(), rawTableName,
+                tableNameWithType, entry.getKey(), 
copySegmentToFinalLocation));
+      }
       int entryCount = 0;
       for (Map.Entry<String, SegmentMetadataInfo> entry : 
segmentsMetadataInfoMap.entrySet()) {
         String segmentName = entry.getKey();
@@ -601,12 +626,8 @@ public class PinotSegmentUploadDownloadRestletResource {
         File tempEncryptedFile;
         File tempDecryptedFile;
         File tempSegmentDir;
-        String sourceDownloadURIStr = 
segmentMetadataInfo.getSegmentDownloadURI();
-        if (StringUtils.isEmpty(sourceDownloadURIStr)) {
-          throw new ControllerApplicationException(LOGGER,
-              "'DOWNLOAD_URI' is required as a field within the multipart 
object for METADATA batch upload mode.",
-              Response.Status.BAD_REQUEST);
-        }
+        URI source = validatedSources.get(segmentName);
+        String sourceDownloadURIStr = source.toString();
         // The downloadUri for putting into segment zk metadata
         String segmentDownloadURIStr = sourceDownloadURIStr;
 
@@ -620,11 +641,6 @@ public class PinotSegmentUploadDownloadRestletResource {
 
         boolean encryptSegment = 
StringUtils.isNotEmpty(crypterClassNameInHeader);
         File destFile = encryptSegment ? tempEncryptedFile : tempDecryptedFile;
-        // override copySegmentToFinalLocation if override provided in 
headers:COPY_SEGMENT_TO_DEEP_STORE
-        // else set to false for backward compatibility
-        String copySegmentToDeepStore = extractHttpHeader(headers,
-            FileUploadDownloadClient.CustomHeaders.COPY_SEGMENT_TO_DEEP_STORE);
-        boolean copySegmentToFinalLocation = 
Boolean.parseBoolean(copySegmentToDeepStore);
         createSegmentFileFromSegmentMetadataInfo(segmentMetadataInfo, 
destFile);
         if (encryptSegment) {
           decryptFile(crypterClassNameInHeader, tempEncryptedFile, 
tempDecryptedFile);
@@ -643,12 +659,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);
+        long segmentSizeInBytes = 
SegmentValidationUtils.getSegmentSizeFromFile(source);
         if (segmentSizeInBytes > 0) {
           // Only check storage quota when segment size is available
           SegmentValidationUtils.checkStorageQuota(segmentName, 
segmentSizeInBytes, segmentSizeInBytes, tableConfig,
@@ -683,8 +696,8 @@ public class PinotSegmentUploadDownloadRestletResource {
             new SegmentUploadMetadata(segmentDownloadURIStr, 
sourceDownloadURIStr, finalSegmentLocationURI,
                 segmentSizeInBytes, segmentMetadata, encryptionInfo);
         segmentUploadMetadataList.add(segmentUploadMetadata);
-        LOGGER.info("Using segment download URI: {} for segment: {} of table: 
{} (move segment: {})",
-            segmentDownloadURIStr, segmentFile, tableNameWithType, 
copySegmentToFinalLocation);
+        LOGGER.info("Registering segment: {} of table: {} (copy to deep store: 
{})",
+            segmentName, tableNameWithType, copySegmentToFinalLocation);
         // complete segment operations for all the segments
         if (++entryCount == segmentsMetadataInfoMap.size()) {
           ZKOperator zkOperator = new ZKOperator(_pinotHelixResourceManager, 
_controllerConf, _controllerMetrics);
@@ -860,21 +873,48 @@ public class PinotSegmentUploadDownloadRestletResource {
     return out;
   }
 
-  private void downloadSegmentFileFromURI(String currentSegmentLocationURI, 
File destFile,
-      @Nullable String tableName)
-      throws Exception {
-    if (currentSegmentLocationURI == null || 
currentSegmentLocationURI.isEmpty()) {
-      throw new ControllerApplicationException(LOGGER, "Failed to get 
downloadURI, needed for URI upload",
-          Response.Status.BAD_REQUEST);
+  private URI validateSource(ControllerFilePathProvider provider, @Nullable 
String source,
+      @Nullable String rawTableName, Mode mode) {
+    if (StringUtils.isEmpty(source)) {
+      throw new ControllerApplicationException(LOGGER, "DOWNLOAD_URI is 
required", Response.Status.BAD_REQUEST);
     }
-    LOGGER.info("Downloading segment from {} to {} for table {}", 
currentSegmentLocationURI, destFile.getAbsolutePath(),
-        tableName);
-    URI uri = new URI(currentSegmentLocationURI);
-    if (uri.getScheme().equalsIgnoreCase("file")) {
-      throw new ControllerApplicationException(LOGGER, "Unsupported URI: " + 
currentSegmentLocationURI,
+    try {
+      SegmentUploadSourcePolicy policy = new 
SegmentUploadSourcePolicy(provider.getDataDirURI(),
+          _controllerConf.getSegmentUploadAllowedSources(rawTableName));
+      return policy.validate(new URI(source), rawTableName, mode);
+    } catch (IllegalArgumentException | URISyntaxException e) {
+      LOGGER.debug("Could not validate segment upload source: {}", 
e.getClass().getSimpleName());
+      throw new ControllerApplicationException(LOGGER, "Segment upload source 
URI is not allowed; check "
+          + ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
Response.Status.BAD_REQUEST);
+    }
+  }
+
+  private URI validateMetadataSource(ControllerFilePathProvider provider,
+      @Nullable String source, String rawTableName, String tableNameWithType, 
String segmentName, boolean copy) {
+    // A minion can refresh the metadata of a segment that already uses the 
controller's download URL.
+    if (!copy && 
provider.getDataDirURI().getScheme().equals(CommonConstants.Segment.LOCAL_SEGMENT_SCHEME))
 {
+      String controllerUrl =
+          URIUtils.getPath(provider.getVip(), "segments", rawTableName, 
URIUtils.encode(segmentName));
+      if (controllerUrl.equals(source)) {
+        SegmentZKMetadata existing = 
_pinotHelixResourceManager.getSegmentZKMetadata(tableNameWithType, segmentName);
+        if (existing != null && 
controllerUrl.equals(existing.getDownloadUrl())) {
+          return URI.create(controllerUrl);
+        }
+      }
+    }
+    return validateSource(provider, source, rawTableName, copy ? 
Mode.METADATA_COPY : Mode.METADATA_REFERENCE);
+  }
+
+  private static void fetchUploadSource(URI source, File destination) {
+    try {
+      SegmentFetcherFactory.fetchSegmentToLocalForUpload(source, destination);
+    } catch (IllegalArgumentException e) {
+      throw new ControllerApplicationException(LOGGER, "Segment upload source 
URI is not allowed",
           Response.Status.BAD_REQUEST);
+    } catch (Exception e) {
+      throw new ControllerApplicationException(LOGGER, "Could not download 
segment from source",
+          Response.Status.INTERNAL_SERVER_ERROR);
     }
-    SegmentFetcherFactory.fetchSegmentToLocal(currentSegmentLocationURI, 
destFile);
   }
 
   private ArchivePathBudget newArchivePathBudget() {
@@ -1428,31 +1468,6 @@ 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 {
-    long segmentSizeInBytes = -1;
-    PinotFS pinotFS = null;
-    try {
-      URI segmentURI = new URI(sourceDownloadURIStr);
-      pinotFS = PinotFSFactory.create(segmentURI.getScheme());
-      segmentSizeInBytes = pinotFS.length(segmentURI);
-    } catch (Exception e) {
-      LOGGER.warn("Could not fetch segment size for metadata push", e);
-    } finally {
-      if (pinotFS != null) {
-        pinotFS.close();
-      }
-    }
-    return segmentSizeInBytes;
-  }
-
   @VisibleForTesting
   static void validateMultiPartForBatchSegmentUpload(List<BodyPart> bodyParts) 
{
     if (bodyParts.isEmpty()) {
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentUploadSourcePolicy.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentUploadSourcePolicy.java
new file mode 100644
index 00000000000..d6b34a98aea
--- /dev/null
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentUploadSourcePolicy.java
@@ -0,0 +1,301 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.controller.api.upload;
+
+import com.google.common.base.Preconditions;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.regex.Pattern;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.URIUtils;
+import org.apache.pinot.controller.ControllerConf;
+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;
+
+
+/// Immutable policy for caller-supplied segment upload sources. The 
controller's table directory is trusted for
+/// native filesystem operations. Additional staging prefixes and HTTP 
destinations are configured by the operator.
+public final class SegmentUploadSourcePolicy {
+  private static final String NOT_ALLOWED = "Segment upload source URI is not 
allowed";
+  private static final Pattern DOT_SEGMENT = 
Pattern.compile("(?:^|/)\\.{1,2}(?:/|$)");
+
+  private final URI _dataDir;
+  private final List<URI> _allowedSources;
+
+  public SegmentUploadSourcePolicy(URI dataDir, List<String> allowedSources) {
+    _dataDir = dataDir;
+    _allowedSources = 
allowedSources.stream().map(SegmentUploadSourcePolicy::parseAllowedSource).toList();
+  }
+
+  public enum Mode {
+    URI_REFERENCE,
+    URI_COPY,
+    SEGMENT_REFERENCE,
+    METADATA_REFERENCE,
+    METADATA_COPY
+  }
+
+  /// Validates all configured prefixes, including table-specific ones, 
without accessing storage.
+  public static void validateConfiguredSources(ControllerConf config) {
+    
config.getAllSegmentUploadAllowedSources().forEach(SegmentUploadSourcePolicy::parseAllowedSource);
+  }
+
+  /// Returns the approved source for the operation. HTTP(S) callers must also 
enforce network destination policy
+  /// when they connect. The returned local URI uses the resolved path that 
passed validation.
+  public URI validate(URI source, @Nullable String rawTableName, Mode mode) {
+    validateShape(source);
+    if (isHttp(source)) {
+      Preconditions.checkArgument(mode == Mode.URI_COPY
+          && _allowedSources.stream().anyMatch(prefix -> matchesHttp(source, 
prefix)), NOT_ALLOWED);
+      return source;
+    }
+
+    String scheme = source.getScheme();
+    boolean sameScheme = scheme.equals(_dataDir.getScheme());
+    boolean metadata = mode == Mode.METADATA_COPY || mode == 
Mode.METADATA_REFERENCE;
+    Preconditions.checkArgument(isAbsoluteStoragePath(source) && (mode != 
Mode.METADATA_COPY || sameScheme)
+        && ((metadata && sameScheme) || 
PinotFSFactory.isSchemeSupported(scheme)), NOT_ALLOWED);
+    if (rawTableName != null) {
+      Preconditions.checkArgument(isValidTableName(rawTableName), NOT_ALLOWED);
+    }
+    String managedTable = sameScheme ? rawTableName : null;
+    boolean local = PinotFSFactory.isSchemeRegisteredWith(scheme, 
LocalPinotFS.class);
+    if (PinotFSFactory.LOCAL_PINOT_FS_SCHEME.equals(scheme)) {
+      Preconditions.checkArgument(local && mode != Mode.URI_COPY && mode != 
Mode.URI_REFERENCE
+          && source.getRawAuthority() == null, NOT_ALLOWED);
+      return validateLocal(source, managedTable, metadata);
+    }
+
+    Preconditions.checkArgument(!local, NOT_ALLOWED);
+    URI tableDir = managedTable != null ? 
URI.create(asDirectory(_dataDir.toString()) + managedTable) : null;
+    boolean bucketFileSystem = usesUriBucket(scheme);
+    boolean hadoopFileSystem = ("hdfs".equals(scheme) || 
"viewfs".equals(scheme))
+        && isRegisteredFileSystem(scheme, "pinot-hdfs", "HadoopPinotFS");
+    boolean sameAuthority = Objects.equals(source.getRawAuthority(), 
_dataDir.getRawAuthority());
+    // Copy operations use the deep-store namespace. Hadoop references on 
another scheme use their own filesystem.
+    boolean configuredNamespace = !metadata || sameAuthority || 
bucketFileSystem || (!sameScheme && hadoopFileSystem);
+    Preconditions.checkArgument((tableDir != null
+        && isRemoteStagingSource(source, tableDir, true, bucketFileSystem, 
hadoopFileSystem))
+        || (configuredNamespace && _allowedSources.stream()
+            .anyMatch(prefix -> isRemoteStagingSource(source, prefix, false, 
bucketFileSystem, hadoopFileSystem))),
+        NOT_ALLOWED);
+    return source;
+  }
+
+  private URI validateLocal(URI source, @Nullable String rawTableName, boolean 
allowMissing) {
+    try {
+      Path sourcePath = resolveLocalStoragePath(source);
+      Preconditions.checkArgument(Files.isRegularFile(sourcePath, 
LinkOption.NOFOLLOW_LINKS)
+          || (allowMissing && Files.notExists(sourcePath, 
LinkOption.NOFOLLOW_LINKS)), NOT_ALLOWED);
+      if (rawTableName != null) {
+        Path managedRoot = 
localStoragePath(_dataDir).toRealPath().resolve(URIUtils.decode(rawTableName));
+        if (managedRoot.equals(sourcePath.getParent())) {
+          // Preserve the controller's URI spelling for in-place pushes and 
their sidecar checks.
+          return URIUtils.getUri(_dataDir.toString(), rawTableName,
+              URIUtils.encode(sourcePath.getFileName().toString()));
+        }
+      }
+      if (_allowedSources.stream().anyMatch(prefix -> 
isLocalStagingSource(sourcePath, prefix))) {
+        return URI.create(sourcePath.toUri().toASCIIString().replace("+", 
"%2B"));
+      }
+    } catch (IOException e) {
+      throw new IllegalArgumentException(NOT_ALLOWED);
+    }
+    throw new IllegalArgumentException(NOT_ALLOWED);
+  }
+
+  private static boolean isValidTableName(String name) {
+    return !name.isEmpty() && !name.equals(".") && !name.equals("..")
+        && name.indexOf('/') < 0 && name.indexOf('\\') < 0 && 
name.indexOf('%') < 0 && name.indexOf('?') < 0
+        && name.indexOf('#') < 0;
+  }
+
+  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.isAbsolute() || !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, URI prefix) {
+    if (!PinotFSFactory.LOCAL_PINOT_FS_SCHEME.equals(prefix.getScheme())) {
+      return false;
+    }
+    try {
+      Path root = resolveLocalStoragePath(prefix);
+      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" -> isRegisteredFileSystem(scheme, "pinot-s3", 
"S3PinotFS");
+      case "gs" -> isRegisteredFileSystem(scheme, "pinot-gcs", "GcsPinotFS");
+      default -> false;
+    };
+  }
+
+  private static boolean isRegisteredFileSystem(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, URI root, boolean 
directChild, boolean collapseSeparators,
+      boolean hadoopFileSystem) {
+    if (hadoopFileSystem) {
+      // Hadoop's Path normalizes repeated separators before accessing the 
filesystem.
+      source = source.normalize();
+      root = root.normalize();
+    }
+    // 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) {
+    Path sourcePath = Path.of(source);
+    Path rootPath = Path.of(root);
+    if (!isNormalizedStoragePath(source, sourcePath) || 
!isNormalizedStoragePath(root, rootPath)) {
+      return false;
+    }
+    if (collapseSeparators) {
+      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);
+  }
+
+  private static boolean isNormalizedStoragePath(String path, Path 
storagePath) {
+    return path.indexOf('%') < 0 && path.indexOf('\\') < 0 && 
storagePath.equals(storagePath.normalize());
+  }
+
+  private static URI parseAllowedSource(String value) {
+    try {
+      URI uri = URIUtils.getUri(value);
+      validateShape(uri);
+      Preconditions.checkArgument(uri.getRawQuery() == null, NOT_ALLOWED);
+      if (!isHttp(uri)) {
+        if (uri.getRawAuthority() != null && uri.getRawPath().isEmpty()
+            && !PinotFSFactory.LOCAL_PINOT_FS_SCHEME.equals(uri.getScheme())) {
+          uri = URI.create(value + "/");
+        }
+        Preconditions.checkArgument(isAbsoluteStoragePath(uri), NOT_ALLOWED);
+        if (PinotFSFactory.LOCAL_PINOT_FS_SCHEME.equals(uri.getScheme())) {
+          Path path = localStoragePath(uri);
+          Preconditions.checkArgument(uri.getRawAuthority() == null && 
path.isAbsolute()
+              && path.equals(path.normalize()), NOT_ALLOWED);
+        } else {
+          String path = uri.getPath();
+          String decodedPath = URIUtils.decode(uri.getRawPath());
+          Preconditions.checkArgument(isNormalizedStoragePath(path, 
Path.of(path))
+              && isNormalizedStoragePath(decodedPath, Path.of(decodedPath)), 
NOT_ALLOWED);
+        }
+      }
+      return uri;
+    } catch (IllegalArgumentException e) {
+      throw new IllegalArgumentException("Invalid URI in " + 
ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
+    }
+  }
+
+  private static void validateShape(URI uri) {
+    String path = uri.getPath();
+    Preconditions.checkArgument(uri.isAbsolute() && !uri.isOpaque() && 
uri.getRawFragment() == null && path != null
+        && path.indexOf('\\') < 0 && !DOT_SEGMENT.matcher(path).find()
+        && path.chars().noneMatch(Character::isISOControl), NOT_ALLOWED);
+    if (isHttp(uri)) {
+      // Avoid interpreting an encoded separator or repeatedly decoded path 
differently at the destination.
+      int port = uri.getPort();
+      
Preconditions.checkArgument(uri.getScheme().equals(uri.getScheme().toLowerCase(Locale.ROOT))
+          && uri.getHost() != null && uri.getRawUserInfo() == null && port != 
0 && port <= 65535
+          && path.indexOf('%') < 0 && 
!uri.getRawPath().toLowerCase(Locale.ROOT).contains("%2f"), NOT_ALLOWED);
+    }
+  }
+
+  private static boolean isHttp(URI uri) {
+    return "http".equalsIgnoreCase(uri.getScheme()) || 
"https".equalsIgnoreCase(uri.getScheme());
+  }
+
+  private static boolean matchesHttp(URI source, URI prefix) {
+    String path = source.getPath().isEmpty() ? "/" : source.getPath();
+    return source.getScheme().equals(prefix.getScheme()) && 
source.getHost().equalsIgnoreCase(prefix.getHost())
+        && effectivePort(source) == effectivePort(prefix)
+        && (prefix.getPath().isEmpty() || path.equals(prefix.getPath()) || 
isWithin(path, prefix.getPath()));
+  }
+
+  private static int effectivePort(URI uri) {
+    int port = uri.getPort();
+    return port >= 0 ? port : "https".equals(uri.getScheme()) ? 443 : 80;
+  }
+
+  private static boolean isWithin(String path, String directory) {
+    String prefix = asDirectory(directory);
+    return path.length() > prefix.length() && path.startsWith(prefix);
+  }
+
+  private static String asDirectory(String path) {
+    return path.endsWith("/") ? path : path + "/";
+  }
+}
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 3bc3a301aa6..a982c6d895f 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,16 +18,8 @@
  */
 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;
@@ -35,8 +27,6 @@ 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;
@@ -47,11 +37,8 @@ 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;
@@ -65,152 +52,19 @@ 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;
+  /// Looks up an approved source's size, or returns -1 when no size is 
available.
+  public static long getSegmentSizeFromFile(URI source) {
+    String scheme = source.getScheme();
+    // An existing controller-managed HTTP URL can be retained on refresh 
without a source lookup.
+    if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
+      return -1;
     }
-  }
-
-  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);
+    try (PinotFS pinotFS = PinotFSFactory.create(scheme)) {
+      return pinotFS.length(source);
+    } catch (Exception e) {
+      LOGGER.warn("Could not determine segment source size ({}): {}", scheme, 
e.getClass().getSimpleName());
+      return -1;
     }
-    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) {
diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/ZKOperator.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/ZKOperator.java
index a57b1e12dbb..bb5f2402aac 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/ZKOperator.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/ZKOperator.java
@@ -183,7 +183,7 @@ public class ZKOperator {
   }
 
   public void completeReingestedSegmentOperations(String realtimeTableName, 
SegmentMetadata segmentMetadata,
-      URI finalSegmentLocationURI, String sourceDownloadURIStr, String 
segmentDownloadURIStr, long segmentSizeInBytes)
+      URI finalSegmentLocationURI, URI source, String segmentDownloadURIStr)
       throws Exception {
     String segmentName = segmentMetadata.getName();
     ZNRecord segmentMetadataZNRecord =
@@ -200,8 +200,9 @@ public class ZKOperator {
               + segmentZKMetadata.getStatus(), Response.Status.CONFLICT);
     }
 
+    long segmentSizeInBytes = 
SegmentValidationUtils.getSegmentSizeFromFile(source);
     // Copy the segment to the final location
-    copyFromSegmentURIToDeepStore(new URI(sourceDownloadURIStr), 
finalSegmentLocationURI);
+    copyFromSegmentURIToDeepStore(source, finalSegmentLocationURI);
     LOGGER.info("Copied reingested segment: {} of table: {} to final location: 
{}", segmentName, realtimeTableName,
         finalSegmentLocationURI);
 
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 8fa344fb398..1c5e0068d46 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
@@ -126,17 +126,28 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
     URI batchUploadUri = URI.create(getControllerBaseApiUrl() + 
"/segments/batchUpload");
     AtomicInteger segmentDownloadCount = new AtomicInteger();
     HttpServer segmentServer = startSegmentServer(
-        Map.of(SEGMENT_A, _segmentA, SEGMENT_B, _segmentB, SEGMENT_DATABASE, 
_segmentDatabase),
-        segmentDownloadCount);
+        Map.of(SEGMENT_A, _segmentA, SEGMENT_B, _segmentB), 
segmentDownloadCount);
+    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        segmentUrl(segmentServer, "") + "," + _testDir.toURI());
     File batchMetadataTar = null;
     try (FileUploadDownloadClient client = new FileUploadDownloadClient()) {
       batchMetadataTar = createBatchMetadataTar(_segmentDatabase, 
SEGMENT_DATABASE,
-          segmentUrl(segmentServer, SEGMENT_DATABASE));
+          _segmentDatabase.toURI().toString());
       File batchMetadataTarForRequest = batchMetadataTar;
+
+      int downloadsBeforeDeniedSource = segmentDownloadCount.get();
+      String unapprovedSource = "http://localhost:"; + 
segmentServer.getAddress().getPort() + "/" + SEGMENT_A;
+      assertHttpStatus(Response.Status.BAD_REQUEST,
+          () -> uploadJson(client, v2UploadUri, unapprovedSource, TABLE_A, 
List.of()));
+      Assert.assertEquals(segmentDownloadCount.get(), 
downloadsBeforeDeniedSource);
+      assertNoSegmentState(TABLE_A, TABLE_A_WITH_TYPE, SEGMENT_A);
+
+      String unconfiguredStagingFile = new 
File(_controllerConfig.getDataDir(), "separate-staging/part.tar.gz")
+          .toURI().toString();
       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()));
+          new BasicHeader(FileUploadDownloadClient.CustomHeaders.DOWNLOAD_URI, 
unconfiguredStagingFile));
       HttpErrorStatusException stagingError = 
assertHttpStatus(Response.Status.BAD_REQUEST,
           () -> client.uploadSegmentMetadata(uploadUri, _segmentA.getName(), 
_segmentA, copyHeaders,
               uploadParameters(TABLE_A), 
HttpClient.DEFAULT_SOCKET_TIMEOUT_MS));
@@ -161,7 +172,7 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
           earlyHeaderMismatch.getMessage());
       Assert.assertEquals(segmentDownloadCount.get(), 
downloadsBeforeInvalidRequest);
 
-      SimpleHttpResponse refreshResponse = uploadJson(client, uploadUri, 
segmentAUri, TABLE_A, List.of());
+      SimpleHttpResponse refreshResponse = uploadJson(client, v2UploadUri, 
segmentAUri, TABLE_A, List.of());
       Assert.assertEquals(refreshResponse.getStatusCode(), 
Response.Status.OK.getStatusCode());
       segmentAMetadata = 
_helixResourceManager.getSegmentZKMetadata(TABLE_A_WITH_TYPE, SEGMENT_A);
       Assert.assertTrue(segmentAMetadata.getRefreshTime() > 0);
@@ -227,8 +238,10 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
           client, uploadUri, _segmentB, null, List.of()));
       assertNoSegmentState(TABLE_B, TABLE_B_WITH_TYPE, SEGMENT_B);
 
+      int downloadsBeforeForbiddenRequest = segmentDownloadCount.get();
       assertHttpStatus(Response.Status.FORBIDDEN,
-          () -> uploadJson(client, uploadUri, segmentUrl(segmentServer, 
SEGMENT_B), null, List.of()));
+          () -> uploadJson(client, v2UploadUri, segmentUrl(segmentServer, 
SEGMENT_B), TABLE_B, List.of()));
+      Assert.assertEquals(segmentDownloadCount.get(), 
downloadsBeforeForbiddenRequest);
       assertNoSegmentState(TABLE_B, TABLE_B_WITH_TYPE, SEGMENT_B);
 
       HttpErrorStatusException mismatch = 
assertHttpStatus(Response.Status.BAD_REQUEST,
@@ -272,6 +285,7 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
     } finally {
       DestinationAccessControlFactory.setAllowedTables(Set.of(TABLE_A));
       FileUtils.deleteQuietly(batchMetadataTar);
+      
_controllerConfig.clearProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
       segmentServer.stop(0);
     }
   }
@@ -347,7 +361,7 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
 
   private static HttpServer startSegmentServer(Map<String, File> segments, 
AtomicInteger segmentDownloadCount)
       throws IOException {
-    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+    HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 
0), 0);
     for (Map.Entry<String, File> entry : segments.entrySet()) {
       server.createContext("/" + entry.getKey(), exchange -> {
         segmentDownloadCount.incrementAndGet();
@@ -363,7 +377,7 @@ public class PinotSegmentUploadAuthorizationTest extends 
ControllerTest {
   }
 
   private static String segmentUrl(HttpServer server, String segmentName) {
-    return "http://localhost:"; + server.getAddress().getPort() + "/" + 
segmentName;
+    return "http://127.0.0.1:"; + server.getAddress().getPort() + "/" + 
segmentName;
   }
 
   private void assertNoSegmentState(String rawTableName, String 
tableNameWithType, String segmentName) {
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 18eb567f60d..16fecffa901 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
@@ -25,6 +25,7 @@ import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.lang.reflect.Method;
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -42,6 +43,9 @@ 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;
+import org.apache.pinot.controller.api.upload.SegmentUploadSourcePolicy;
+import org.apache.pinot.controller.api.upload.SegmentUploadSourcePolicy.Mode;
+import org.apache.pinot.controller.api.upload.SegmentValidationUtils;
 import org.apache.pinot.segment.local.constants.SegmentUploadConstants;
 import org.apache.pinot.spi.config.table.TableType;
 import org.apache.pinot.spi.crypt.NoOpPinotCrypter;
@@ -387,12 +391,13 @@ public class 
PinotSegmentUploadDownloadRestletResourceTest {
     File allSegmentsMetadataTarFile = new File(segmentDir, 
"allSegments.tar.gz");
     TarCompressionUtils.createCompressedTarFile(segmentDir, 
allSegmentsMetadataTarFile);
 
-    // test
-    long segmentSizeInBytes =
-        
PinotSegmentUploadDownloadRestletResource.getSegmentSizeFromFile(allSegmentsMetadataTarFile.toURI().toString());
-
-    // verify
-    Assert.assertTrue(segmentSizeInBytes > 0);
+    SegmentUploadSourcePolicy policy = new 
SegmentUploadSourcePolicy(_tempDir.toURI(), List.of());
+    URI source = allSegmentsMetadataTarFile.toURI();
+    Assert.expectThrows(IllegalArgumentException.class,
+        () -> policy.validate(source, "otherTable", Mode.METADATA_REFERENCE));
+    URI approvedSource = policy.validate(source, segmentDir.getName(), 
Mode.METADATA_REFERENCE);
+    
Assert.assertEquals(SegmentValidationUtils.getSegmentSizeFromFile(approvedSource),
+        allSegmentsMetadataTarFile.length());
   }
 
   @Test
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 4d784dd51ce..5506dc98dc7 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
@@ -34,6 +34,7 @@ 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.api.upload.SegmentUploadSourcePolicy.Mode;
 import org.apache.pinot.controller.validation.StorageQuotaChecker;
 import org.apache.pinot.segment.spi.ColumnMetadata;
 import org.apache.pinot.segment.spi.SegmentMetadata;
@@ -48,10 +49,16 @@ import 
org.apache.pinot.spi.config.table.assignment.InstancePartitionsType;
 import 
org.apache.pinot.spi.config.table.assignment.InstanceReplicaGroupPartitionConfig;
 import org.apache.pinot.spi.config.table.assignment.InstanceTagPoolConfig;
 import org.apache.pinot.spi.config.table.assignment.SegmentAssignmentConfig;
+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.builder.TableConfigBuilder;
+import org.mockito.MockedStatic;
 import org.testng.annotations.Test;
 
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
@@ -92,21 +99,22 @@ public class SegmentValidationUtilsTest {
       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"));
+      SegmentUploadSourcePolicy managed = new 
SegmentUploadSourcePolicy(dataUri, List.of());
+      SegmentUploadSourcePolicy staging = new 
SegmentUploadSourcePolicy(dataDir.toUri(), stagingDirs);
+      String managedUri = URIUtils.getPath(dataUri.toString(), RAW_TABLE_NAME, 
SEGMENT_NAME + ".tmp");
+      assertEquals(managed.validate(localStage.toUri(), RAW_TABLE_NAME, 
Mode.METADATA_COPY).toString(), managedUri);
       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());
+      for (Mode mode : List.of(Mode.METADATA_COPY, Mode.METADATA_REFERENCE, 
Mode.SEGMENT_REFERENCE)) {
+        assertEquals(staging.validate(URI.create(externalUri), RAW_TABLE_NAME, 
mode).toString(),
+            externalStage.toRealPath().toUri().toString().replace("+", "%2B"));
+        for (Path rejected : List.of(otherStage, link, tableDir, extraDir)) {
+          assertThrows(IllegalArgumentException.class, () -> 
staging.validate(rejected.toUri(), RAW_TABLE_NAME, mode));
+        }
       }
+      Files.delete(localStage);
+      assertEquals(managed.validate(localStage.toUri(), RAW_TABLE_NAME, 
Mode.METADATA_COPY).toString(), managedUri);
+      assertThrows(IllegalArgumentException.class,
+          () -> managed.validate(localStage.toUri(), RAW_TABLE_NAME, 
Mode.SEGMENT_REFERENCE));
     } finally {
       FileUtils.deleteDirectory(tempDir.toFile());
     }
@@ -114,22 +122,83 @@ public class SegmentValidationUtilsTest {
 
   @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 dataDir = URI.create("gs://deep-store/segments/");
+    SegmentUploadSourcePolicy policy = new SegmentUploadSourcePolicy(dataDir, 
List.of("gs://deep-store/jobs/"));
+    URI source = URI.create("gs://deep-store/jobs/run/part.tar.gz");
+    URI managed = URI.create("gs://deep-store/segments/" + RAW_TABLE_NAME + 
"/part.tar.gz");
+    for (Mode mode : List.of(Mode.METADATA_COPY, Mode.METADATA_REFERENCE)) {
+      assertEquals(policy.validate(source, RAW_TABLE_NAME, mode), source);
+      assertEquals(policy.validate(managed, RAW_TABLE_NAME, mode), managed);
+      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",
+          "gs://deep-store/jobs", "gs://deep-store/segments/" + RAW_TABLE_NAME 
+ "/nested/part.tar.gz")) {
+        assertThrows(IllegalArgumentException.class, () -> 
policy.validate(URI.create(rejected), RAW_TABLE_NAME, mode));
+      }
     }
     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)));
+    SegmentUploadSourcePolicy azure = new SegmentUploadSourcePolicy(azureData, 
List.of(azureStage));
+    assertThrows(IllegalArgumentException.class,
+        () -> azure.validate(URI.create(azureStage + "/part.tar.gz"), 
RAW_TABLE_NAME, Mode.METADATA_COPY));
+  }
+
+  @Test
+  public void testHadoopMetadataSources()
+      throws ClassNotFoundException {
+    PluginManager pluginManager = mock(PluginManager.class);
+    
doReturn(PinotFS.class).when(pluginManager).loadClass("org.apache.pinot.plugin.filesystem.HadoopPinotFS");
+    try (MockedStatic<PluginManager> plugins = mockStatic(PluginManager.class);
+        MockedStatic<PinotFSFactory> fileSystems = 
mockStatic(PinotFSFactory.class)) {
+      plugins.when(PluginManager::get).thenReturn(pluginManager);
+      fileSystems.when(() -> 
PinotFSFactory.isSchemeSupported("hdfs")).thenReturn(true);
+      fileSystems.when(() -> PinotFSFactory.isSchemeRegisteredWith("hdfs", 
PinotFS.class)).thenReturn(true);
+
+      URI reingestionSource = URI.create("hdfs://nn:8020/segments//" + 
RAW_TABLE_NAME + "/part.tar.gz");
+      for (String dataDir : List.of("hdfs://nn:8020/segments", 
"hdfs://nn:8020/segments/")) {
+        SegmentUploadSourcePolicy policy = new 
SegmentUploadSourcePolicy(URI.create(dataDir), List.of());
+        assertEquals(policy.validate(reingestionSource, RAW_TABLE_NAME, 
Mode.METADATA_COPY), reingestionSource);
+      }
+
+      String staging = "hdfs://nn:8020/jobs/out";
+      SegmentUploadSourcePolicy policy =
+          new 
SegmentUploadSourcePolicy(URI.create("file:///var/pinot/segments"), 
List.of(staging));
+      URI source = URI.create(staging + "/part.tar.gz");
+      assertEquals(policy.validate(source, RAW_TABLE_NAME, 
Mode.METADATA_REFERENCE), source);
+      assertThrows(IllegalArgumentException.class, () -> 
policy.validate(source, RAW_TABLE_NAME, Mode.METADATA_COPY));
+
+      fileSystems.when(() -> PinotFSFactory.isSchemeRegisteredWith("hdfs", 
PinotFS.class)).thenReturn(false);
+      SegmentUploadSourcePolicy customProvider =
+          new SegmentUploadSourcePolicy(URI.create("hdfs://nn:8020/segments"), 
List.of());
+      assertThrows(IllegalArgumentException.class,
+          () -> customProvider.validate(reingestionSource, RAW_TABLE_NAME, 
Mode.METADATA_COPY));
+    }
+  }
+
+  @Test
+  public void testValidateConfiguredUploadSources() {
+    ControllerConf conf = new ControllerConf();
+    String shared = "/var/pinot/staging";
+    conf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        List.of(shared, RAW_TABLE_NAME + "=gs://deep-store"));
+    SegmentUploadSourcePolicy.validateConfiguredSources(conf);
+    conf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        List.of(shared, RAW_TABLE_NAME + "=https://staging.example/invalid 
prefix"));
+    IllegalArgumentException exception =
+        expectThrows(IllegalArgumentException.class, () -> 
SegmentUploadSourcePolicy.validateConfiguredSources(conf));
+    assertEquals(exception.getMessage(), "Invalid URI in " + 
ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
+  }
+
+  @Test
+  public void testHttpUploadRequiresCopyMode() {
+    String staging = "https://staging.example/orders/";;
+    URI source = URI.create(staging + "segment.tar.gz");
+    SegmentUploadSourcePolicy policy =
+        new 
SegmentUploadSourcePolicy(URI.create("file:///var/pinot/deep-store"), 
List.of(staging));
+    assertEquals(policy.validate(source, RAW_TABLE_NAME, Mode.URI_COPY), 
source);
+    for (Mode mode : List.of(Mode.URI_REFERENCE, Mode.SEGMENT_REFERENCE, 
Mode.METADATA_REFERENCE,
+        Mode.METADATA_COPY)) {
+      assertThrows(IllegalArgumentException.class, () -> 
policy.validate(source, RAW_TABLE_NAME, mode));
+    }
   }
 
   @Test
diff --git 
a/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/BaseClusterIntegrationTest.java
 
b/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/BaseClusterIntegrationTest.java
index c25f68f0ddf..b15944ff6e2 100644
--- 
a/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/BaseClusterIntegrationTest.java
+++ 
b/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/BaseClusterIntegrationTest.java
@@ -70,6 +70,7 @@ import 
org.apache.pinot.common.restlet.resources.ValidDocIdsType;
 import org.apache.pinot.common.utils.LLCSegmentName;
 import org.apache.pinot.common.utils.TarCompressionUtils;
 import org.apache.pinot.common.utils.config.TagNameUtils;
+import org.apache.pinot.controller.ControllerConf;
 import 
org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager;
 import 
org.apache.pinot.controller.util.ConsumingSegmentInfoReader.ConsumingSegmentInfo;
 import 
org.apache.pinot.controller.util.ConsumingSegmentInfoReader.ConsumingSegmentsInfoMap;
@@ -153,6 +154,14 @@ public abstract class BaseClusterIntegrationTest extends 
ClusterTest {
   protected Connection _h2Connection;
   protected QueryGenerator _queryGenerator;
 
+  @Override
+  public Map<String, Object> getDefaultControllerConfiguration() {
+    Map<String, Object> properties = super.getDefaultControllerConfiguration();
+    // Metadata-only uploads reference segment archives in this test's 
temporary directory.
+    properties.putIfAbsent(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_tempDir.toURI().toString());
+    return properties;
+  }
+
   /// The following getters can be overridden to change default settings.
 
   protected String getTableName() {
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/PurgeMinionClusterIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/PurgeMinionClusterIntegrationTest.java
index ae4ee1b30a9..d5275588474 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/PurgeMinionClusterIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/PurgeMinionClusterIntegrationTest.java
@@ -30,6 +30,7 @@ import org.apache.helix.task.TaskState;
 import org.apache.pinot.common.lineage.SegmentLineageAccessHelper;
 import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
 import org.apache.pinot.common.minion.MinionTaskMetadataUtils;
+import org.apache.pinot.common.utils.URIUtils;
 import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
 import 
org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager;
 import org.apache.pinot.controller.helix.core.minion.PinotTaskManager;
@@ -203,6 +204,8 @@ public class PurgeMinionClusterIntegrationTest extends 
BaseClusterIntegrationTes
     
tableTaskConfigs.put(MinionConstants.PurgeTask.LAST_PURGE_TIME_THREESOLD_PERIOD,
 "1d");
     tableTaskConfigs.put(BatchConfigProperties.PUSH_MODE, 
BatchConfigProperties.SegmentPushType.METADATA.name());
     tableTaskConfigs.put(MinionTaskUtils.ALLOW_METADATA_PUSH_WITH_LOCAL_FS, 
"true");
+    tableTaskConfigs.put(BatchConfigProperties.OUTPUT_SEGMENT_DIR_URI,
+        URIUtils.getUri(_controllerStarter.getConfig().getDataDir(), 
PURGE_METADATA_PUSH_FIRST_RUN_TABLE).toString());
     return new TableTaskConfig(Map.of(MinionConstants.PurgeTask.TASK_TYPE, 
tableTaskConfigs));
   }
 
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 55657c49e69..a121b5819fb 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
@@ -70,7 +70,7 @@ import static org.testng.Assert.expectThrows;
 public class SegmentUploadIntegrationTest extends 
SharedOfflineUploadIntegrationTestSuite {
   private static String _tableNameSuffix;
   private Boolean _originalRejectOutOfRetention;
-  private List<String> _originalAllowedSources;
+  private Object _originalAllowedSources;
 
   @Override
   @BeforeClass
@@ -125,17 +125,20 @@ public class SegmentUploadIntegrationTest extends 
SharedOfflineUploadIntegration
     _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);
+    _originalAllowedSources = 
controllerConf.getRawProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
+    List<String> sourceDirs = new 
ArrayList<>(controllerConf.getCommaSeparatedList(
+        ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, List.of()));
     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);
+    ControllerConf controllerConf = getSharedControllerStarter().getConfig();
+    if (_originalAllowedSources == null) {
+      
controllerConf.clearProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES);
+    } else {
+      
controllerConf.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_originalAllowedSources);
     }
   }
 
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 f517e1c0fee..bf864730f91 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
@@ -89,6 +89,12 @@ public class SparkSegmentMetadataPushIntegrationTest extends 
BaseClusterIntegrat
     TestUtils.ensureDirectoriesExistAndEmpty(_tempDir, _segmentDir, _tarDir);
   }
 
+  @Override
+  protected void overrideControllerConf(Map<String, Object> properties) {
+    super.overrideControllerConf(properties);
+    properties.put(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_tarDir.toURI().toString());
+  }
+
   @BeforeClass
   public void setUp()
       throws Exception {
@@ -97,7 +103,6 @@ public class SparkSegmentMetadataPushIntegrationTest extends 
BaseClusterIntegrat
 
     // Start the Pinot cluster
     startController();
-    
_controllerConfig.setProperty(ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES, 
_testTable + "=" + _tarDir.toURI());
     startBroker();
     startServer();
 
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
index a67349cafa0..da05664ae40 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
@@ -42,6 +42,7 @@ import org.apache.kafka.common.PartitionInfo;
 import org.apache.kafka.common.serialization.ByteArrayDeserializer;
 import org.apache.pinot.broker.broker.helix.BaseBrokerStarter;
 import org.apache.pinot.controller.BaseControllerStarter;
+import org.apache.pinot.controller.ControllerConf;
 import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
 import 
org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager;
 import org.apache.pinot.controller.helix.core.minion.PinotTaskManager;
@@ -324,6 +325,29 @@ public abstract class 
CustomDataQueryClusterIntegrationTest extends CustomSuiteH
     }
   }
 
+  @Override
+  protected void uploadSegments(String tableName, TableType tableType, 
List<File> tarDirs)
+      throws Exception {
+    // The shared controller only knows the suite owner's fixture directory at 
startup.
+    ControllerConf controllerConf = getSharedControllerStarter().getConfig();
+    String sourcesKey = ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES;
+    synchronized (controllerConf) {
+      Object originalSources = controllerConf.getRawProperty(sourcesKey);
+      List<String> stagingDirs = new 
ArrayList<>(controllerConf.getCommaSeparatedList(sourcesKey, List.of()));
+      tarDirs.forEach(dir -> stagingDirs.add(dir.toURI().toString()));
+      controllerConf.setProperty(sourcesKey, stagingDirs);
+      try {
+        super.uploadSegments(tableName, tableType, tarDirs);
+      } finally {
+        if (originalSources == null) {
+          controllerConf.clearProperty(sourcesKey);
+        } else {
+          controllerConf.setProperty(sourcesKey, originalSources);
+        }
+      }
+    }
+  }
+
   @AfterClass
   public void tearDown()
       throws IOException {
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/RefreshSegmentMinionTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/RefreshSegmentMinionTest.java
index 1bb7ece47d8..6fec89f54de 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/RefreshSegmentMinionTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/RefreshSegmentMinionTest.java
@@ -30,6 +30,7 @@ import org.apache.avro.file.DataFileWriter;
 import org.apache.avro.generic.GenericData;
 import org.apache.helix.task.TaskState;
 import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
+import org.apache.pinot.common.utils.URIUtils;
 import 
org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager;
 import org.apache.pinot.controller.helix.core.minion.TaskSchedulingContext;
 import org.apache.pinot.core.common.MinionConstants;
@@ -401,6 +402,8 @@ public class RefreshSegmentMinionTest extends 
CustomDataQueryClusterIntegrationT
     Map<String, String> tableTaskConfigs = new HashMap<>();
     tableTaskConfigs.put(BatchConfigProperties.PUSH_MODE, 
BatchConfigProperties.SegmentPushType.METADATA.name());
     tableTaskConfigs.put(MinionTaskUtils.ALLOW_METADATA_PUSH_WITH_LOCAL_FS, 
"true");
+    tableTaskConfigs.put(BatchConfigProperties.OUTPUT_SEGMENT_DIR_URI,
+        URIUtils.getUri(getSharedControllerStarter().getConfig().getDataDir(), 
TABLE_NAME).toString());
     return new TableTaskConfig(
         Map.of(MinionConstants.RefreshSegmentTask.TASK_TYPE, 
tableTaskConfigs));
   }
diff --git 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/logicaltable/BaseLogicalTableIntegrationTest.java
 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/logicaltable/BaseLogicalTableIntegrationTest.java
index 07c84d222cb..e1934270a9d 100644
--- 
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/logicaltable/BaseLogicalTableIntegrationTest.java
+++ 
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/logicaltable/BaseLogicalTableIntegrationTest.java
@@ -135,7 +135,8 @@ public abstract class BaseLogicalTableIntegrationTest 
extends BaseClusterIntegra
       String tableName = entry.getKey();
       List<File> avroFilesForTable = entry.getValue();
 
-      File tarDir = new File(_tarDir, tableName);
+      // Each member stages its tar files under the root configured for the 
shared controller.
+      File tarDir = new File(new File(_sharedClusterTestSuite._tarDir, 
getClass().getSimpleName()), tableName);
 
       TestUtils.ensureDirectoriesExistAndEmpty(tarDir);
 


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

Reply via email to