This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 21220d631e [#14415] fix(fileset): Create HDFS file systems for the 
request user (#14416)
21220d631e is described below

commit 21220d631e9e0e80b5dffca0897faa6b82bba6f0
Author: YangJie <[email protected]>
AuthorDate: Fri Nov 13 06:50:18 2026 -0500

    [#14415] fix(fileset): Create HDFS file systems for the request user 
(#14416)
    
    ### What changes were proposed in this pull request?
    
    `getFileSystem` and `probeLocation` read the current user on the request
    thread, and `getFileSystemWithCache` uses the user in its cache key.
    Each passes the user to `createFileSystem`, which gives
    `ImpersonationHDFSFileSystemProxy` that fixed user instead of
    `PrincipalUtils::getCurrentUserName`, which the proxy called on the pool
    thread when creating the file system.
    
    ### Why are the changes needed?
    
    A pool thread keeps the `Subject` of the request that started it, so
    with impersonation enabled an HDFS file system created there could act
    for an earlier user.
    
    Fix: #14415
    
    ### Does this PR introduce _any_ user-facing change?
    
    No.
    
    ### How was this patch tested?
    
    New `testGetFileSystemUsesRequestUserOnPoolThread` (with and without the
    file system cache) and `testTestConnectionUsesRequestUserOnPoolThread`:
    the pool threads are started under alice, then bob calls
    `getFileSystem`, `getFileSystemWithCache` or `testConnection`, and
    `createFileSystem` must receive bob while running on a thread that
    carries alice's `Subject`. New `testHdfsFileSystemProxyUsesGivenUser`:
    the user handler passed to `ImpersonationHDFSFileSystemProxy` returns
    bob even when called under alice's `Subject`.
---
 .../catalog/fileset/FilesetCatalogOperations.java  |  37 +++++--
 .../fileset/TestFilesetCatalogOperations.java      | 110 ++++++++++++++++++++-
 2 files changed, 134 insertions(+), 13 deletions(-)

diff --git 
a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
 
b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
index 7da3a90b99..1c7120f5ba 100644
--- 
a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
+++ 
b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java
@@ -180,7 +180,8 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
   // BaseGVFSOperations
   @VisibleForTesting Cache<FileSystemCacheKey, FileSystem> fileSystemCache;
 
-  private final ThreadPoolExecutor fileSystemExecutor =
+  @VisibleForTesting
+  final ThreadPoolExecutor fileSystemExecutor =
       new ThreadPoolExecutor(
           Math.max(2, Math.min(Runtime.getRuntime().availableProcessors() * 2, 
16)),
           Math.max(2, Math.min(Runtime.getRuntime().availableProcessors() * 2, 
32)),
@@ -1475,7 +1476,8 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
         new FileSystemCacheKey(scheme, authority),
         cacheKey -> {
           try {
-            return getFileSystem(path, conf);
+            // Create the file system for the user it is cached under.
+            return getFileSystem(path, conf, cacheKey.currentUser);
           } catch (IOException e) {
             throw new GravitinoRuntimeException(
                 e, "Failed to get FileSystem for fileset: path: %s", path);
@@ -1492,6 +1494,11 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
   }
 
   FileSystem getFileSystem(Path path, Map<String, String> config) throws 
IOException {
+    // Read the user here: a pool thread keeps the Subject of the request that 
started it.
+    return getFileSystem(path, config, PrincipalUtils.getCurrentUserName());
+  }
+
+  FileSystem getFileSystem(Path path, Map<String, String> config, String user) 
throws IOException {
     if (path == null) {
       throw new IllegalArgumentException("Path should not be null");
     }
@@ -1518,7 +1525,7 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
 
     try {
       return executeFileSystemTask(
-          () -> createFileSystem(path, config, scheme, provider), 
timeoutSeconds);
+          () -> createFileSystem(path, config, scheme, provider, user), 
timeoutSeconds);
     } catch (TimeoutException e) {
       LOG.warn(
           "Timeout when getting FileSystem for path: {}, scheme: {}, provider: 
{} within {} seconds",
@@ -1622,6 +1629,8 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
           String.format("Fileset connection testing does not support scheme 
%s", scheme));
     }
 
+    // Read the user here: a pool thread keeps the Subject of the request that 
started it.
+    String user = PrincipalUtils.getCurrentUserName();
     String credentialHandle = null;
     try {
       credentialHandle = addVendedCredential(path, scheme, fileSystemProvider, 
probeConf);
@@ -1635,7 +1644,7 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
       executeFileSystemTask(
           () -> {
             try (FileSystem fileSystem =
-                createProbeFileSystem(path, probeConf, scheme, 
fileSystemProvider)) {
+                createProbeFileSystem(path, probeConf, scheme, 
fileSystemProvider, user)) {
               Path qualifiedPath =
                   path.makeQualified(fileSystem.getUri(), 
fileSystem.getWorkingDirectory());
               try {
@@ -1738,21 +1747,29 @@ public class FilesetCatalogOperations extends 
ManagedSchemaOperations
         credentialManagerSupplier.get(), "Catalog credential manager must not 
be null");
   }
 
-  private FileSystem createFileSystem(
-      Path path, Map<String, String> config, String scheme, FileSystemProvider 
provider)
+  @VisibleForTesting
+  FileSystem createFileSystem(
+      Path path,
+      Map<String, String> config,
+      String scheme,
+      FileSystemProvider provider,
+      String user)
       throws IOException {
     if (scheme.equals(SCHEME_HDFS)) {
-      return new ImpersonationHDFSFileSystemProxy(path, config, 
PrincipalUtils::getCurrentUserName)
-          .getProxy();
+      return new ImpersonationHDFSFileSystemProxy(path, config, () -> 
user).getProxy();
     }
     return provider.getFileSystem(path, config);
   }
 
   private FileSystem createProbeFileSystem(
-      Path path, Map<String, String> config, String scheme, FileSystemProvider 
provider)
+      Path path,
+      Map<String, String> config,
+      String scheme,
+      FileSystemProvider provider,
+      String user)
       throws IOException {
     try {
-      return createFileSystem(path, config, scheme, provider);
+      return createFileSystem(path, config, scheme, provider, user);
     } catch (Exception e) {
       throw new ProbeInitializationException(e);
     }
diff --git 
a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
 
b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
index dca9a991f4..5a51246bde 100644
--- 
a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
+++ 
b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
@@ -79,6 +79,7 @@ import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -182,6 +183,7 @@ import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.EnumSource;
 import org.junit.jupiter.params.provider.MethodSource;
 import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedConstruction;
 import org.mockito.MockedStatic;
 import org.mockito.Mockito;
 
@@ -2616,7 +2618,9 @@ public class TestFilesetCatalogOperations {
 
     try (FilesetCatalogOperations ops =
         Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {
-      doReturn(fileSystem).when(ops).getFileSystem(Mockito.eq(path), 
Mockito.anyMap());
+      doReturn(fileSystem)
+          .when(ops)
+          .getFileSystem(Mockito.eq(path), Mockito.anyMap(), 
Mockito.anyString());
       ConnectionFailedException failure =
           Assertions.assertThrows(
               ConnectionFailedException.class,
@@ -2655,6 +2659,103 @@ public class TestFilesetCatalogOperations {
     }
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void testGetFileSystemUsesRequestUserOnPoolThread(boolean cached) 
throws Exception {
+    try (FilesetCatalogOperations ops =
+        Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {
+      ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"), 
FILESET_PROPERTIES_METADATA);
+      List<String> users = recordFileSystemUsers(ops);
+      startPoolThreadsAs(ops, "alice");
+
+      Path path = new Path(TEST_ROOT_PATH, "pool_thread_user");
+      PrincipalUtils.doAs(
+          new UserPrincipal("bob"),
+          () -> {
+            if (cached) {
+              // ops.close() closes the cached file system.
+              ops.getFileSystemWithCache(path, ImmutableMap.of());
+            } else {
+              ops.getFileSystem(path, ImmutableMap.of()).close();
+            }
+            return null;
+          });
+
+      Assertions.assertEquals(Collections.singletonList("bob on alice"), 
users);
+    }
+  }
+
+  @Test
+  public void testTestConnectionUsesRequestUserOnPoolThread() throws Exception 
{
+    File location = new File(UNFORMALIZED_TEST_ROOT_PATH, 
"connection/pool-thread-user");
+    FileUtils.forceMkdir(location);
+
+    try (FilesetCatalogOperations ops =
+        Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {
+      ops.initialize(
+          ImmutableMap.of(LOCATION, location.toURI().toString()),
+          randomCatalogInfo("metalake", "catalog"),
+          FILESET_PROPERTIES_METADATA);
+      List<String> users = recordFileSystemUsers(ops);
+      startPoolThreadsAs(ops, "alice");
+
+      PrincipalUtils.doAs(
+          new UserPrincipal("bob"),
+          () -> {
+            ops.testConnection(NameIdentifier.of("metalake", "catalog"));
+            return null;
+          });
+
+      Assertions.assertEquals(Collections.singletonList("bob on alice"), 
users);
+    }
+  }
+
+  @Test
+  public void testHdfsFileSystemProxyUsesGivenUser() throws Exception {
+    List<ImpersonationHDFSFileSystemProxy.ProxyUserHandler> handlers = new 
ArrayList<>();
+    try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, 
secretManager);
+        MockedConstruction<ImpersonationHDFSFileSystemProxy> ignored =
+            Mockito.mockConstruction(
+                ImpersonationHDFSFileSystemProxy.class,
+                (proxy, context) ->
+                    handlers.add(
+                        (ImpersonationHDFSFileSystemProxy.ProxyUserHandler)
+                            context.arguments().get(2)))) {
+      ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"), 
FILESET_PROPERTIES_METADATA);
+      // Called directly: construction mocks only intercept on the current 
thread.
+      ops.createFileSystem(
+          new Path("hdfs://localhost:8020/proxy_user"), ImmutableMap.of(), 
"hdfs", null, "bob");
+
+      Assertions.assertEquals(1, handlers.size());
+      Assertions.assertEquals(
+          "bob", PrincipalUtils.doAs(new UserPrincipal("alice"), 
handlers.get(0)::getProxyUser));
+    }
+  }
+
+  private static List<String> recordFileSystemUsers(FilesetCatalogOperations 
ops)
+      throws IOException {
+    List<String> users = new CopyOnWriteArrayList<>();
+    Mockito.doAnswer(
+            invocation -> {
+              // The requested user, and the user whose Subject the pool 
thread carries.
+              users.add(invocation.getArgument(4) + " on " + 
PrincipalUtils.getCurrentUserName());
+              return invocation.callRealMethod();
+            })
+        .when(ops)
+        .createFileSystem(any(), any(), any(), any(), any());
+    return users;
+  }
+
+  // The tests rely on a thread started inside Subject.doAs keeping that 
Subject, as it does up to
+  // JDK 22. Revisit them when PrincipalUtils moves off Subject.getSubject, 
which later JDKs no
+  // longer support. Keep the threads alive so that bob's request does not 
start new ones.
+  private static void startPoolThreadsAs(FilesetCatalogOperations ops, String 
user)
+      throws Exception {
+    ops.fileSystemExecutor.allowCoreThreadTimeOut(false);
+    PrincipalUtils.doAs(
+        new UserPrincipal(user), () -> 
ops.fileSystemExecutor.prestartAllCoreThreads());
+  }
+
   @Test
   public void testTestConnectionWithoutCatalogLocation() throws IOException {
     try (FilesetCatalogOperations catalogOperations =
@@ -3408,7 +3509,7 @@ public class TestFilesetCatalogOperations {
       String subPath = "/test/test.parquet";
       when(mockOps.getFileLocation(filesetIdent, 
subPath)).thenCallRealMethod();
       when(mockOps.getFileLocation(filesetIdent, subPath, 
null)).thenCallRealMethod();
-      when(mockOps.getFileSystem(any(), any()))
+      when(mockOps.getFileSystem(any(), any(), any()))
           .thenReturn(FileSystem.getLocal(new Configuration()));
       when(mockOps.getFileSystemWithCache(any(), any())).thenCallRealMethod();
       String fileLocation = mockOps.getFileLocation(filesetIdent, subPath);
@@ -3421,6 +3522,7 @@ public class TestFilesetCatalogOperations {
       FileSystem fs2 =
           mockOps.getFileSystemWithCache(new 
Path("file:///dir1/subdir/file2"), mockOps.getConf());
 
+      Assertions.assertNotNull(fs1);
       Assertions.assertSame(fs1, fs2);
     } catch (Exception e) {
       throw new RuntimeException(e);
@@ -3952,7 +4054,9 @@ public class TestFilesetCatalogOperations {
           randomCatalogInfo("m1", "c1"),
           FILESET_PROPERTIES_METADATA);
       ops.fileSystemCache.invalidateAll();
-      Mockito.doThrow(cause).when(ops).getFileSystem(Mockito.eq(path), 
Mockito.eq(conf));
+      Mockito.doThrow(cause)
+          .when(ops)
+          .getFileSystem(Mockito.eq(path), Mockito.eq(conf), 
Mockito.anyString());
 
       GravitinoRuntimeException e =
           Assertions.assertThrows(

Reply via email to