World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15135] fix(maintenance): Use lexical-only orphan location validation (#15136)
MaSaidda06d59e033
diff --git a/design-docs/iceberg-remove-orphan-files-maintenance-job.md b/design-docs/iceberg-remove-orphan-files-maintenance-job.mdindex 74421e3bc6..e2f5986a38 100644--- a/design-docs/iceberg-remove-orphan-files-maintenance-job.md+++ b/design-docs/iceberg-remove-orphan-files-maintenance-job.md@@ -511,12 +511,13 @@ Validation rules:duplicate slashes, resolve `.` / `..` segments, and strip trailing slashes.3. Reject the request unless the normalized `location` is the table locationitself or a descendant of it.-4. Reject symlinks or paths that resolve outside the table location after- normalization.Normalization must happen before the prefix check; comparing raw stringswould let `s3://bucket/db/table/../other_table` pass a naive-`startsWith` test.+`startsWith` test. Iceberg does not treat POSIX symlinks as part of the+orphan-cleanup contract (HDFS symlink support is incomplete; object stores+have none), so the job relies on lexical containment rather than filesystem+symlink walking.Validation happens in the job adapter (before submission) and again in theSpark job (before building the procedure call), so an ad-hoc job submissiondiff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.javaindex 10f9251189..4c6d0cff1c 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java@@ -25,10 +25,6 @@ import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableList;import java.io.IOException;-import java.net.URI;-import java.nio.file.Files;-import java.nio.file.Path;-import java.nio.file.Paths;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -36,7 +32,6 @@ import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;-import java.util.stream.Stream;import javax.annotation.Nullable;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;@@ -196,7 +191,7 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenanthrows IOException {IcebergJobUtils.requireEscapedStringLiteralsDisabled(spark);Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);- String normalizedLocation = resolveAndValidateLocation(spark, table, location);+ String normalizedLocation = resolveAndValidateLocation(table, location);List<Row> listed =callRemoveOrphanFiles(spark, catalogName, tableIdentifier, olderThan, normalizedLocation, true);@@ -319,58 +314,21 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan}private static String resolveAndValidateLocation(- SparkSession spark, String catalogName, String tableIdentifier, @Nullable String location)- throws IOException {+ SparkSession spark, String catalogName, String tableIdentifier, @Nullable String location) {Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);- return resolveAndValidateLocation(spark, table, location);+ return resolveAndValidateLocation(table, location);}- private static String resolveAndValidateLocation(- SparkSession spark, Table table, @Nullable String location) throws IOException {+ private static String resolveAndValidateLocation(Table table, @Nullable String location) {// Direct callers may pass an empty template value without CLI argument parsing.if (location == null || location.codePoints().allMatch(Character::isWhitespace)) {location = table.location();}+ // Lexical containment only — aligned with Iceberg DeleteOrphanFiles (no symlink model).OrphanFileLocationUtils.validateLocation(table.location(), location);- validateLocalLocation(table.location(), location);- validateRemoteLocation(spark, table.location(), location);return normalizeLocation(location).toString();}- private static void validateLocalLocation(String tableLocation, String location)- throws IOException {- URI requested = normalizeLocation(location);- if (!"file".equals(requested.getScheme())) {- return;- }- Path lexicalRoot = Paths.get(normalizeLocation(tableLocation));- Path root = lexicalRoot.toRealPath();- Path scan = Paths.get(requested);- Preconditions.checkArgument(- scan.toRealPath().startsWith(root),- "Scan location resolves outside the table's storage location");- for (Path ancestor = scan;- ancestor != null && ancestor.startsWith(lexicalRoot);- ancestor = ancestor.getParent()) {- Preconditions.checkArgument(- !Files.isSymbolicLink(ancestor), "Symlinks are not allowed in the scan location");- }- // Do not follow symlinks during validation. Iceberg must never list another table through one.- try (Stream<Path> paths = Files.walk(scan)) {- Preconditions.checkArgument(- paths.noneMatch(Files::isSymbolicLink), "Symlinks are not allowed in the scan location");- }- }-- private static void validateRemoteLocation(- SparkSession spark, String tableLocation, String location) throws IOException {- if ("file".equals(normalizeLocation(location).getScheme())) {- return;- }- RemoteLocationValidator.validate(- spark.sparkContext().hadoopConfiguration(), tableLocation, location);- }-private static List<String> buildArguments() {return Arrays.asList("--catalog",diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.javadeleted file mode 100644index 12b84b5514..0000000000--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java+++ /dev/null@@ -1,83 +0,0 @@-/*- * 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.maintenance.jobs.iceberg;--import com.google.common.base.Preconditions;-import java.io.IOException;-import java.util.ArrayDeque;-import java.util.Deque;-import org.apache.gravitino.maintenance.optimizer.common.util.OrphanFileLocationUtils;-import org.apache.hadoop.conf.Configuration;-import org.apache.hadoop.fs.FileStatus;-import org.apache.hadoop.fs.FileSystem;-import org.apache.hadoop.fs.Path;-import org.apache.hadoop.fs.RemoteIterator;--/** Validates scan paths on Hadoop filesystems that can resolve symbolic links. */-final class RemoteLocationValidator {- private RemoteLocationValidator() {}-- static void validate(Configuration conf, String tableLocation, String location)- throws IOException {- Path scan = new Path(location);- FileSystem fs = scan.getFileSystem(conf);- validate(fs, new Path(tableLocation), scan);- }-- static void validate(FileSystem fs, Path tableLocation, Path scan) throws IOException {- // Object stores do not support symbolic links. The URI containment check is sufficient there.- if (!fs.supportsSymlinks()) {- return;- }- Path lexicalRoot = new Path(tableLocation.toUri().normalize());- scan = new Path(scan.toUri().normalize());- OrphanFileLocationUtils.validateLocation(lexicalRoot.toString(), scan.toString());- Path root = fs.resolvePath(lexicalRoot);- OrphanFileLocationUtils.validateLocation(root.toString(), fs.resolvePath(scan).toString());- // Inspect the table root itself, but not warehouse parents outside this table. Use the- // lexical boundary because a warehouse parent symlink can change the resolved root.- for (Path ancestor = scan; ancestor != null; ancestor = ancestor.getParent()) {- Preconditions.checkArgument(- !fs.getFileLinkStatus(ancestor).isSymlink(),- "Symlinks are not allowed in the scan location");- if (ancestor.equals(lexicalRoot)) {- break;- }- }- Deque<Path> pending = new ArrayDeque<>();- pending.add(scan);- while (!pending.isEmpty()) {- Path path = pending.removeFirst();- FileStatus status = fs.getFileLinkStatus(path);- Preconditions.checkArgument(- !status.isSymlink(), "Symlinks are not allowed in the scan location");- if (status.isDirectory()) {- RemoteIterator<FileStatus> children = fs.listStatusIterator(path);- while (children.hasNext()) {- FileStatus child = children.next();- Preconditions.checkArgument(- !child.isSymlink(), "Symlinks are not allowed in the scan location");- if (child.isDirectory()) {- pending.addLast(child.getPath());- }- }- }- }- }-}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.javaindex d7fe870129..7dc0f5e066 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.IOException;+import java.io.UncheckedIOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.attribute.FileTime;@@ -129,7 +130,7 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {assertFalse(Files.exists(old));}- /** Verifies custom location and outside rejection. */+ /** Verifies custom location and outside rejection via lexical containment. */@Testpublic void testCustomLocationAndOutsideRejection() throws Exception {spark.sql("CREATE TABLE test_catalog.db.scoped (id INT) USING iceberg");@@ -146,10 +147,6 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {assertThrows(IllegalArgumentException.class, () -> execute("scoped", null, tempDir.toString(), false));assertTrue(Files.exists(outside));- Path link = root.resolve("escape");- Files.createSymbolicLink(link, tempDir);- assertThrows(- IllegalArgumentException.class, () -> execute("scoped", null, link.toString(), false));}/** Verifies UTC cutoffs from the policy adapter retain their meaning in other session zones. */@@ -181,7 +178,7 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {assertThrows(IllegalArgumentException.class, () -> IcebergRemoveOrphanFilesJob.parseDryRun("yes"));assertThrows(- IOException.class,+ UncheckedIOException.class,() -> execute("invalid", null, tempDir.resolve("db/invalid/missing").toString(), false));assertThrows(IllegalArgumentException.class,diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestRemoteLocationValidator.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestRemoteLocationValidator.javadeleted file mode 100644index af342db6ab..0000000000--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestRemoteLocationValidator.java+++ /dev/null@@ -1,197 +0,0 @@-/*- * 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.maintenance.jobs.iceberg;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;--import java.io.IOException;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import org.apache.hadoop.fs.FileStatus;-import org.apache.hadoop.fs.FilterFileSystem;-import org.apache.hadoop.fs.Path;-import org.apache.hadoop.fs.RemoteIterator;-import org.junit.jupiter.api.Test;--/** Tests table-scoped validation on symlink-capable filesystems. */-public class TestRemoteLocationValidator {- private final StubFileSystem fs = new StubFileSystem();- private final Path root = new Path("hdfs://host/table");- private final Path scan = new Path(root, "data");-- /** Verifies object store does not require symlink inspection. */- @Test- public void testObjectStoreDoesNotRequireSymlinkInspection() throws Exception {- fs.symlinksSupported = false;- RemoteLocationValidator.validate(fs, root, scan);- assertEquals(0, fs.resolveCalls);- }-- /** Verifies resolved path outside table is rejected. */- @Test- public void testResolvedPathOutsideTableIsRejected() {- fs.resolvedPaths.put(scan, new Path("hdfs://host/other/data"));- assertThrows(- IllegalArgumentException.class, () -> RemoteLocationValidator.validate(fs, root, scan));- }-- /** Verifies inspection failure is not ignored. */- @Test- public void testInspectionFailureIsNotIgnored() {- fs.failResolution = true;- assertThrows(IOException.class, () -> RemoteLocationValidator.validate(fs, root, scan));- }-- /** Verifies symbolic link is rejected. */- @Test- public void testSymbolicLinkIsRejected() {- fs.statuses.put(scan, link(scan));- assertThrows(- IllegalArgumentException.class, () -> RemoteLocationValidator.validate(fs, root, scan));- }-- /** Verifies descendant symbolic link is rejected. */- @Test- public void testDescendantSymbolicLinkIsRejected() {- fs.listings.put(scan, new FileStatus[] {link(new Path(scan, "link"))});- assertThrows(- IllegalArgumentException.class, () -> RemoteLocationValidator.validate(fs, root, scan));- }-- /** Verifies directories are inspected recursively. */- @Test- public void testDirectoriesAreInspectedRecursively() throws Exception {- Path sub = new Path(scan, "sub");- fs.listings.put(scan, new FileStatus[] {directory(sub)});- RemoteLocationValidator.validate(fs, root, scan);- assertTrue(fs.listedPaths.contains(sub));- }-- /** Verifies warehouse parent symlink is outside validation scope. */- @Test- public void testWarehouseParentSymlinkIsOutsideValidationScope() throws Exception {- Path table = new Path("hdfs://host/warehouse/table");- Path data = new Path(table, "data");- fs.resolvedPaths.put(table, new Path("hdfs://host/storage/table"));- fs.resolvedPaths.put(data, new Path("hdfs://host/storage/table/data"));- fs.statuses.put(table.getParent(), link(table.getParent()));- RemoteLocationValidator.validate(fs, table, data);- assertTrue(fs.listedPaths.contains(data));- }-- /** Verifies unreadable parent is outside validation scope. */- @Test- public void testUnreadableParentIsOutsideValidationScope() throws Exception {- fs.unreadablePath = root.getParent();- RemoteLocationValidator.validate(fs, root, scan);- assertTrue(fs.listedPaths.contains(scan));- }-- /** Verifies table root and intermediate symlinks are rejected. */- @Test- public void testTableRootAndIntermediateSymlinksAreRejected() {- fs.statuses.put(root, link(root));- assertThrows(- IllegalArgumentException.class, () -> RemoteLocationValidator.validate(fs, root, scan));- fs.statuses.clear();- fs.statuses.put(scan, link(scan));- assertThrows(- IllegalArgumentException.class,- () -> RemoteLocationValidator.validate(fs, root, new Path(scan, "nested")));- }-- /** Verifies normalized paths stop at the table boundary, including a whole-table scan. */- @Test- public void testNormalizedPathsAndWholeTableScan() throws Exception {- fs.unreadablePath = root.getParent();- RemoteLocationValidator.validate(fs, new Path(root, "."), new Path(root, "staged/../data"));- assertTrue(fs.listedPaths.contains(scan));- RemoteLocationValidator.validate(fs, root, root);- assertTrue(fs.listedPaths.contains(root));- }-- private static FileStatus directory(Path path) {- return new FileStatus(0, true, 1, 0, 0, path);- }-- private static FileStatus link(Path path) {- FileStatus status = directory(path);- status.setSymlink(new Path("hdfs://host/other"));- return status;- }-- /**- * In-memory filesystem responses for deterministic validation tests without external services.- */- private static class StubFileSystem extends FilterFileSystem {- private final Map<Path, Path> resolvedPaths = new HashMap<>();- private final Map<Path, FileStatus> statuses = new HashMap<>();- private final Map<Path, FileStatus[]> listings = new HashMap<>();- private final List<Path> listedPaths = new ArrayList<>();- private boolean symlinksSupported = true;- private boolean failResolution;- private Path unreadablePath;- private int resolveCalls;-- @Override- public boolean supportsSymlinks() {- return symlinksSupported;- }-- @Override- public Path resolvePath(Path path) throws IOException {- resolveCalls++;- if (failResolution) {- throw new IOException("Permission denied");- }- return resolvedPaths.getOrDefault(path, path);- }-- @Override- public FileStatus getFileLinkStatus(Path path) throws IOException {- if (path.equals(unreadablePath)) {- throw new IOException("Permission denied: " + path);- }- return statuses.getOrDefault(path, directory(path));- }-- @Override- public RemoteIterator<FileStatus> listStatusIterator(Path path) {- listedPaths.add(path);- FileStatus[] children = listings.getOrDefault(path, new FileStatus[0]);- return new RemoteIterator<FileStatus>() {- private int index;-- @Override- public boolean hasNext() {- return index < children.length;- }-- @Override- public FileStatus next() {- return children[index++];- }- };- }- }-}diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/OrphanFileLocationUtils.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/OrphanFileLocationUtils.javaindex 5149325c97..ddba367604 100644--- a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/OrphanFileLocationUtils.java+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/OrphanFileLocationUtils.java@@ -29,8 +29,9 @@ public final class OrphanFileLocationUtils {private OrphanFileLocationUtils() {}/**- * Validates that a scan is within the table root. Filesystem symlink validation must also run in- * the job, using its storage credentials and filesystem view.+ * Validates that a scan is within the table root using lexical URI containment. Iceberg does not+ * model POSIX symlinks for orphan cleanup; callers should not require Hadoop FileSystem+ * acquisition for this check.** @param tableLocation table storage root* @param location requested scan location