Copilot commented on code in PR #11354:
URL: https://github.com/apache/gravitino/pull/11354#discussion_r3380143232
##########
core/src/test/java/org/apache/gravitino/job/TestJobManager.java:
##########
@@ -914,6 +933,71 @@ public void
testFetchFileFromUriWithMissingLocalFileShouldFail() throws IOExcept
RuntimeException.class, () -> JobManager.fetchFileFromUri(uri,
stagingDir, 1000));
}
+ @Test
+ public void testFetchFileFromUriSsrfBlocked() {
+ File stagingDir = new File(testStagingDir);
+ Assertions.assertTrue(stagingDir.mkdirs() || stagingDir.exists());
+
+ // Loopback address
+ RuntimeException e1 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobManager.fetchFileFromUri("http://127.0.0.1:8090/configs",
stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e1);
+
+ // AWS / GCP / Azure cloud-metadata endpoint (link-local 169.254.x.x)
+ RuntimeException e2 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ JobManager.fetchFileFromUri(
+ "http://169.254.169.254/latest/meta-data/", stagingDir,
1000));
+ assertRemoteUriBlockedMessage(e2);
+
+ // RFC-1918 private range
+ RuntimeException e3 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobManager.fetchFileFromUri("http://192.168.1.1/",
stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e3);
+
+ // Alibaba Cloud / Oracle Cloud metadata endpoint
+ RuntimeException e4 =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> JobManager.fetchFileFromUri("http://100.100.100.200/",
stagingDir, 1000));
+ assertRemoteUriBlockedMessage(e4);
+ }
+
+ @Test
+ public void testFetchFileFromUriShouldAllowLocalhostWhenBlockingDisabled()
throws Exception {
+ File stagingDir = new File(testStagingDir);
+ Assertions.assertTrue(stagingDir.mkdirs() || stagingDir.exists());
+ HttpServer server = createLoopbackHttpServer("job artifact");
+
+ try {
+ server.start();
+ int port = server.getAddress().getPort();
+
+ String fetchedFile =
+ JobManager.fetchFileFromUri(
+ String.format("http://127.0.0.1:%d/artifact.jar", port),
stagingDir, 1000, false);
+
+ Assertions.assertEquals("job artifact",
Files.readString(Path.of(fetchedFile)));
+ } finally {
+ server.stop(0);
+ }
+ }
Review Comment:
PR description says `testValidateRemoteUri()` was added to `TestJobManager`,
but this file only adds `testFetchFileFromUriSsrfBlocked()` /
`testFetchFileFromUriShouldAllowLocalhostWhenBlockingDisabled()` (and URI
validation coverage appears to live in
`common/src/test/.../TestRemoteUriValidator`). Please update the PR description
or add the mentioned test to avoid confusion for reviewers and release notes.
##########
common/src/main/java/org/apache/gravitino/utils/FetchFileUtils.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.gravitino.utils;
+
+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.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.Nullable;
+import org.apache.commons.io.FileUtils;
+
+/**
+ * Fetches a file referenced by a URI to a local destination. Supports {@code
file}, {@code http},
+ * {@code https}, {@code ftp} and {@code hdfs} schemes. This is the single
shared implementation
+ * used by the job manager and the Kerberos clients of the Hive, Iceberg,
Hadoop and Paimon
+ * catalogs.
+ *
+ * <p>The {@code hdfs} scheme is resolved reflectively against {@code
+ * org.apache.hadoop.fs.FileSystem} so that this class can live in the {@code
common} module, which
+ * does not declare a compile-time dependency on Hadoop. Callers that never
use {@code hdfs} URIs
+ * (for example the job manager and the Paimon catalog) simply pass {@code
null} for the Hadoop
+ * configuration.
+ */
+public final class FetchFileUtils {
+
+ /**
+ * Per-destination lock map used to serialize concurrent symlink creation
for the same destination
+ * file. Keyed by the normalized absolute destination path string to avoid
races caused by
+ * different path spellings referring to the same file. Entries should be
removed via {@link
+ * #removeLock(File)} when the destination file is deleted, so the map size
stays bounded by the
+ * number of live consumers.
+ */
+ private static final ConcurrentHashMap<String, Object> SYMLINK_LOCKS = new
ConcurrentHashMap<>();
+
+ private FetchFileUtils() {}
+
+ /**
+ * Removes the per-destination lock entry for the given file. Should be
called when the
+ * destination file is deleted (for example on a Kerberos client {@code
close()}) to prevent
+ * unbounded map growth.
+ *
+ * @param destFile the destination file whose lock entry should be removed
+ */
+ public static void removeLock(File destFile) {
+
SYMLINK_LOCKS.remove(destFile.toPath().toAbsolutePath().normalize().toString());
+ }
+
+ /**
+ * Fetches the file referenced by {@code fileUri} into {@code destFile}.
+ *
+ * @param fileUri the source URI; a missing scheme is treated as {@code file}
+ * @param destFile the local destination file
+ * @param timeoutMs the connect/read timeout in milliseconds, applied to
remote (http/https/ftp)
+ * downloads
+ * @param hadoopConf an {@code org.apache.hadoop.conf.Configuration}
instance, required only for
+ * the {@code hdfs} scheme; may be {@code null} when no {@code hdfs} URI
is fetched
+ * @param blockUnsafeAddress whether to reject remote URIs that resolve to
unsafe addresses
+ * @param blockUnsafeAddressHint the configuration hint appended to the
validation error message
+ * to tell the caller how to disable unsafe-address blocking
+ * @return the absolute path of {@code destFile}
+ * @throws IOException if the file cannot be fetched
+ */
+ public static String fetchFileFromUri(
+ String fileUri,
+ File destFile,
+ int timeoutMs,
+ @Nullable Object hadoopConf,
+ boolean blockUnsafeAddress,
+ String blockUnsafeAddressHint)
+ throws IOException {
+ try {
+ URI uri = new URI(fileUri);
+ String scheme = Optional.ofNullable(uri.getScheme()).orElse("file");
+
+ switch (scheme) {
+ case "http":
+ case "https":
+ case "ftp":
+ RemoteUriValidator.validate(uri, blockUnsafeAddress,
blockUnsafeAddressHint);
+ FileUtils.copyURLToFile(uri.toURL(), destFile, timeoutMs, timeoutMs);
+ break;
Review Comment:
SSRF validation can be bypassed because `copyURLToFile()` may follow HTTP
redirects and will perform a fresh DNS resolution at connection time. Currently
the code validates only the originally-supplied URI, so a redirect (or DNS
rebinding between validation and connection) can still reach
blocked/private/metadata IPs.
To make the protection effective, consider implementing the remote download
with explicit redirect handling (disable automatic redirects, validate each
`Location` hop, and cap redirect count) and/or pin the connection to the
validated `InetAddress` instead of re-resolving the hostname during the fetch.
--
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]