Jackie-Jiang commented on code in PR #20428:
URL: https://github.com/apache/pinot/pull/20428#discussion_r4806960066


##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java:
##########
@@ -49,6 +65,154 @@ private 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);

Review Comment:
   [P2] Normalize the default table-directory join
   
   With `controller.data.dir=hdfs://nn/segments/`, this constructs 
`/segments//orders`. Built-in minion tasks stage files under 
`/segments/orders/` (`MinionTaskUtils.getOutputSegmentDirURI` and 
`BaseTaskExecutor.moveSegmentToOutputPinotFS`), but HDFS uses the 
literal-prefix validation branch, so valid metadata refresh/purge uploads now 
fail with HTTP 400. Normal config-file startup preserves the trailing slash; it 
does not call `ControllerConf.setDataDir`.
   
   Please join the directory and table with exactly one separator and add a 
regression case for a trailing slash in the HDFS data directory.



##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentValidationUtils.java:
##########
@@ -49,6 +65,154 @@ private SegmentValidationUtils() {
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(SegmentValidationUtils.class);
 
+  /// Validates a source before probing its size or copying it with the 
controller's storage credentials.
+  /// Built-in staging uses files directly in the destination table directory. 
Controller configuration can grant
+  /// access to separate staging directories for that table. Those directories 
must contain only trusted staging data.
+  public static String validateMetadataCopySource(String source, URI dataDir, 
String rawTableName,
+      List<String> stagingDirs) {
+    try {
+      URI sourceUri = new URI(source);
+      if (dataDir.getScheme().equals(sourceUri.getScheme()) && 
isAbsoluteStoragePath(sourceUri)
+          && !rawTableName.isEmpty() && !rawTableName.equals(".") && 
!rawTableName.equals("..")
+          && rawTableName.indexOf('/') < 0 && rawTableName.indexOf('\\') < 0 
&& rawTableName.indexOf('%') < 0
+          && rawTableName.indexOf('?') < 0 && rawTableName.indexOf('#') < 0) {
+        String scheme = sourceUri.getScheme();
+        boolean localFileSystem = 
PinotFSFactory.isSchemeRegisteredWith(scheme, LocalPinotFS.class);
+        if (CommonConstants.Segment.LOCAL_SEGMENT_SCHEME.equals(scheme)) {
+          if (localFileSystem && sourceUri.getRawAuthority() == null) {
+            Path sourcePath = resolveLocalStoragePath(sourceUri);
+            Path tableDir = 
localStoragePath(dataDir).toRealPath().resolve(URIUtils.decode(rawTableName));
+            if (Files.isRegularFile(sourcePath, LinkOption.NOFOLLOW_LINKS)
+                || Files.notExists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
+              if (tableDir.equals(sourcePath.getParent())) {
+                // Use the controller's spelling of the directory to preserve 
in-place pushes and sidecar checks.
+                String fileName = 
URIUtils.encode(sourcePath.getFileName().toString());
+                return URIUtils.getUri(dataDir.toString(), rawTableName, 
fileName).toString();
+              }
+              if (stagingDirs.stream().anyMatch(dir -> 
isLocalStagingSource(sourcePath, dir))) {
+                return sourcePath.toUri().toASCIIString().replace("+", "%2B");
+              }
+            }
+          }
+        } else if (!localFileSystem) {
+          URI tableDir = URIUtils.getUri(dataDir.toString(), rawTableName);
+          boolean bucketFileSystem = usesUriBucket(scheme);
+          boolean sameAuthority = Objects.equals(sourceUri.getRawAuthority(), 
dataDir.getRawAuthority());
+          if (isRemoteStagingSource(sourceUri, tableDir, true, 
bucketFileSystem)
+              || ((sameAuthority || bucketFileSystem)
+                  && stagingDirs.stream().anyMatch(dir -> 
isRemoteStagingSource(sourceUri, dir, bucketFileSystem)))) {
+            return source;
+          }
+        }
+      }
+    } catch (URISyntaxException | IOException | IllegalArgumentException e) {
+      LOGGER.debug("Could not validate the metadata upload source", e);
+    }
+    throw new ControllerApplicationException(LOGGER, "Metadata upload source 
must be in the table directory or in "
+        + "a staging directory configured by " + 
ControllerConf.SEGMENT_UPLOAD_ALLOWED_SOURCES,
+        Response.Status.BAD_REQUEST);
+  }
+
+  private static boolean isAbsoluteStoragePath(URI uri) {
+    return uri.getRawPath() != null && uri.getRawPath().startsWith("/")
+        && uri.getRawQuery() == null && uri.getRawFragment() == null;
+  }
+
+  private static Path localStoragePath(URI uri) {
+    // Match LocalPinotFS, which form-decodes the raw URI path.
+    return new File(URIUtils.decode(uri.getRawPath())).toPath();
+  }
+
+  private static Path resolveLocalStoragePath(URI uri)
+      throws IOException {
+    Path path = localStoragePath(uri);
+    if (!path.equals(path.normalize())) {
+      throw new IllegalArgumentException("Storage path must be normalized");
+    }
+    // An idempotent upload can arrive after staging cleanup. Resolve all 
existing ancestors, including symlinks,
+    // while allowing the missing portion to remain absent. A dangling symlink 
fails to resolve.
+    Path existing = path;
+    while (existing.getParent() != null && Files.notExists(existing, 
LinkOption.NOFOLLOW_LINKS)) {
+      existing = existing.getParent();
+    }
+    return existing.toRealPath().resolve(existing.relativize(path));
+  }
+
+  private static boolean isLocalStagingSource(Path source, String stagingDir) {
+    try {
+      URI uri = URIUtils.getUri(stagingDir);
+      if (CommonConstants.Segment.LOCAL_SEGMENT_SCHEME.equals(uri.getScheme()) 
&& uri.getRawAuthority() == null
+          && isAbsoluteStoragePath(uri)) {
+        Path root = resolveLocalStoragePath(uri);
+        return !source.equals(root) && source.startsWith(root);
+      }
+    } catch (IOException | IllegalArgumentException e) {
+      // An unavailable staging directory does not grant access.
+    }
+    return false;
+  }
+
+  private static boolean usesUriBucket(String scheme) {
+    // S3 and GCS select the bucket from the URI. Other plugins can use a 
single configured namespace regardless
+    // of the authority, so only accept alternate authorities when the 
corresponding plugin is registered.
+    return switch (scheme) {
+      case "s3", "s3a" -> isRegisteredBucketFileSystem(scheme, "pinot-s3", 
"S3PinotFS");
+      case "gs" -> isRegisteredBucketFileSystem(scheme, "pinot-gcs", 
"GcsPinotFS");
+      default -> false;
+    };
+  }
+
+  private static boolean isRegisteredBucketFileSystem(String scheme, String 
pluginName, String simpleClassName) {
+    String className = "org.apache.pinot.plugin.filesystem." + simpleClassName;
+    return isRegisteredFileSystem(scheme, className) || 
isRegisteredFileSystem(scheme, pluginName + ":" + className);
+  }
+
+  private static boolean isRegisteredFileSystem(String scheme, String 
className) {
+    try {
+      Class<? extends PinotFS> pluginClass = 
PluginManager.get().loadClass(className).asSubclass(PinotFS.class);
+      return PinotFSFactory.isSchemeRegisteredWith(scheme, pluginClass);
+    } catch (Exception | LinkageError e) {
+      // The optional plugin or plugin realm may be absent.
+      return false;
+    }
+  }
+
+  private static boolean isRemoteStagingSource(URI source, String stagingDir, 
boolean bucketFileSystem) {
+    try {
+      return isRemoteStagingSource(source, URIUtils.getUri(stagingDir), false, 
bucketFileSystem);
+    } catch (IllegalArgumentException e) {
+      return false;
+    }
+  }
+
+  private static boolean isRemoteStagingSource(URI source, URI root, boolean 
directChild, boolean collapseSeparators) {
+    // Some plugins form-decode the raw URI path. Require containment under 
both path interpretations.
+    return source.getScheme().equals(root.getScheme())
+        && Objects.equals(source.getRawAuthority(), root.getRawAuthority()) && 
isAbsoluteStoragePath(root)
+        && isStagingPath(source.getPath(), root.getPath(), directChild, 
collapseSeparators)
+        && isStagingPath(URIUtils.decode(source.getRawPath()), 
URIUtils.decode(root.getRawPath()), directChild,
+            collapseSeparators);
+  }
+
+  private static boolean isStagingPath(String source, String root, boolean 
directChild, boolean collapseSeparators) {
+    if (source.indexOf('%') >= 0 || source.indexOf('\\') >= 0) {
+      return false;

Review Comment:
   [P2] Preserve valid literal percent characters
   
   A source such as `s3://bucket/segments/orders/segment%25.tar.gz` decodes to 
the valid filename `segment%.tar.gz` and is rejected here, even inside the 
destination table directory or an explicitly allowed staging directory. 
`SegmentNameUtils` permits percent characters in segment names, and 
`S3PinotFS.copyFile` supports this once-decoded object key (`sanitizePath` only 
normalizes slashes). Adding an allowed staging prefix cannot restore this 
upload.
   
   Please validate containment using the filesystem's decoding semantics 
without blanket-rejecting literal percent characters, and add a `%25` 
regression case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to