xiangfu0 commented on code in PR #20427:
URL: https://github.com/apache/pinot/pull/20427#discussion_r4806917717


##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentUploadSourcePolicy.java:
##########
@@ -0,0 +1,291 @@
+/**
+ * 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 sameAuthority = Objects.equals(source.getRawAuthority(), 
_dataDir.getRawAuthority());
+    // Preserve metadata staging's namespace restrictions for providers that 
do not select a bucket from the URI.
+    Preconditions.checkArgument((tableDir != null && 
isRemoteStagingSource(source, tableDir, true, bucketFileSystem))
+        || ((!metadata || sameAuthority || bucketFileSystem) && 
_allowedSources.stream()
+            .anyMatch(prefix -> isRemoteStagingSource(source, prefix, false, 
bucketFileSystem))), 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" -> 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, 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) {
+    Path sourcePath = Path.of(source);
+    Path rootPath = Path.of(root);
+    if (!isNormalizedStoragePath(source, sourcePath) || 
!isNormalizedStoragePath(root, rootPath)) {
+      return false;
+    }
+    if (collapseSeparators) {
+      // S3 and GCS collapse consecutive separators when looking up object 
keys.
+      return directChild ? rootPath.equals(sourcePath.getParent())
+          : !rootPath.equals(sourcePath) && sourcePath.startsWith(rootPath);
+    }
+    String prefix = root.endsWith("/") ? root : root + "/";

Review Comment:
   Fixed in `d0d5b36fb1`. For the registered Hadoop provider, staging 
comparisons now use the same separator normalization as Hadoop. The regression 
test covers reingestion with and without a trailing slash on the configured 
data directory.
   



##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/upload/SegmentUploadSourcePolicy.java:
##########
@@ -0,0 +1,291 @@
+/**
+ * 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 sameAuthority = Objects.equals(source.getRawAuthority(), 
_dataDir.getRawAuthority());
+    // Preserve metadata staging's namespace restrictions for providers that 
do not select a bucket from the URI.
+    Preconditions.checkArgument((tableDir != null && 
isRemoteStagingSource(source, tableDir, true, bucketFileSystem))
+        || ((!metadata || sameAuthority || bucketFileSystem) && 
_allowedSources.stream()

Review Comment:
   Fixed in `d0d5b36fb1`. A no-copy METADATA upload can now use an explicitly 
configured HDFS prefix when the controller deep store uses another filesystem. 
Copies still use the deep-store filesystem, and prefixes for fixed-namespace 
providers keep their existing rules.
   



-- 
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