hello-stephen commented on code in PR #71291:
URL: https://github.com/apache/doris/pull/71291#discussion_r4796374928


##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/BaseExecutor.java:
##########
@@ -156,10 +185,19 @@ public UdfClassCache getClassCache(String jarPath, long 
functionId, String funct
             }
             cache = new UdfClassCache();
             cache.allMethods = new HashMap<>();
-            cache.udfClass = Class.forName(className, true, loader);
-            cache.methodAccess = MethodAccess.get(cache.udfClass);
             cache.classLoader = classLoader;
-            checkAndCacheUdfClass(cache, funcRetType, parameterTypes);
+            try {
+                try (ThreadContextClassLoader ignored = new 
ThreadContextClassLoader(loader)) {
+                    cache.udfClass = Class.forName(className, true, loader);
+                }
+                cache.methodAccess = MethodAccess.get(cache.udfClass);
+                checkAndCacheUdfClass(cache, funcRetType, parameterTypes);
+            } catch (Exception | LinkageError e) {

Review Comment:
   [P2] Close unpublished static UDF loaders after initializer errors
   
   When a function created with `static_load=true` throws an `AssertionError` 
during class initialization, `Class.forName` propagates the error directly. It 
skips this catch and the outer cleanup skips static loads. The cache has yet to 
be published, so neither JNI cleanup nor `DROP FUNCTION` can close the open 
JAR, and retries can retain descriptors until GC. Use a success-guarded 
`finally` for the unpublished cache and test this branch with static loading 
enabled. [Java SE 17 class 
initialization](https://docs.oracle.com/javase/specs/jls/se17/html/jls-12.html#jls-12.4.2)



##########
fe/be-java-extensions/jni-bootstrap/src/main/java/org/apache/doris/jni/bootstrap/TrustedClassLoaders.java:
##########
@@ -0,0 +1,113 @@
+// 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.doris.jni.bootstrap;
+
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Field;
+import java.net.URLClassLoader;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Predicate;
+
+/** Bootstrap-owned trust identities, independent of plugin-private copies of 
the UDF policy. */
+@SuppressWarnings("removal")
+public final class TrustedClassLoaders {
+    private static final RuntimePermission REGISTER = new 
RuntimePermission("doris.registerTrustedClassLoader");
+    private static final ClassLoader SYSTEM = 
ClassLoader.getSystemClassLoader();
+    private static final ClassLoader PLATFORM = SYSTEM.getParent();
+    private static final List<WeakReference<ClassLoader>> PLUGINS = new 
CopyOnWriteArrayList<>();
+
+    private TrustedClassLoaders() {
+    }
+
+    static void register(ClassLoader loader) {
+        // A UDF with createClassLoader/getClassLoader must not manufacture a 
trusted plugin loader.
+        SecurityManager manager = System.getSecurityManager();
+        if (manager != null) {
+            manager.checkPermission(REGISTER);
+        }
+        PLUGINS.removeIf(reference -> reference.get() == null);
+        PLUGINS.add(new WeakReference<>(loader));
+    }
+
+    /** Called before installing the policy; only a JDK interface crosses the 
plugin boundary. */
+    public static Predicate<ProtectionDomain> trustedDomains() {
+        // Resolve private JDK metadata now, never recursively from a 
permission check.
+        UrlLoaderContext.initialize();
+        return TrustedClassLoaders::isTrusted;
+    }
+
+    private static boolean registered(ClassLoader loader) {
+        // ClassLoader subclasses may override equals/hashCode. Trust is an 
object identity,
+        // not a user-overridable equality test, and weak references must not 
pin failed plugins.
+        for (WeakReference<ClassLoader> reference : PLUGINS) {
+            if (reference.get() == loader) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean isTrusted(ProtectionDomain domain) {
+        ClassLoader loader = domain.getClassLoader();
+        if (loader == null || loader == SYSTEM || loader == PLATFORM || 
registered(loader)) {
+            return true;
+        }
+        if (!(loader instanceof URLClassLoader)) {
+            // SDK-defined code generators belong to their genuine registered 
plugin. A class
+            // loader implementation defined by user bytecode has an 
unregistered defining loader.
+            ClassLoader implementation = AccessController.doPrivileged(
+                    (PrivilegedAction<ClassLoader>) () -> 
loader.getClass().getClassLoader());
+            return implementation == SYSTEM || registered(implementation);

Review Comment:
   [P3] Preserve driver permissions for generated classes
   
   `JdbcDriverUtils` creates a secondary URL loader for each driver JAR. Its 
creator context qualifies it as trusted, but the loader itself is absent from 
`PLUGINS`. If a trusted driver uses a non-URL loader implemented in its JAR to 
generate a callback class, this branch sees the driver's URL loader as 
`implementation` and gives the callback UDF permissions. Ordinary operations 
from that code can then start failing after a restricted UDF runs. Apply the 
verified trust check to the implementation's defining domain and cover a 
generated callback in the trusted-driver probe.



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UdfPermissionConfig.java:
##########
@@ -0,0 +1,309 @@
+// 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.doris.udf;
+
+import java.io.FilePermission;
+import java.io.IOException;
+import java.io.Reader;
+import java.net.NetPermission;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.AllPermission;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.PropertyPermission;
+import java.util.Set;
+
+/** Fixed operator allow settings, parsed once into a read-only permission 
collection. */
+final class UdfPermissionConfig {
+    private static final String FILE_NAME = "java_udf_security.properties";
+    private final PermissionCollection permissions;
+
+    private UdfPermissionConfig(PermissionCollection permissions) {
+        this.permissions = permissions;
+    }
+
+    static UdfPermissionConfig loadConfigured() {
+        String home = System.getenv("DORIS_HOME");
+        if (home == null || home.isEmpty()) {
+            throw new IllegalArgumentException("Set DORIS_HOME to locate the 
Java UDF permission file");
+        }
+        // start_be.sh sets DORIS_HOME to the deployed BE root, e.g. 
output/be, not output.
+        return load(Paths.get(home, "conf", FILE_NAME));
+    }
+
+    static UdfPermissionConfig load(Path path) {
+        Properties properties = new Properties();
+        try {
+            try (Reader reader = Files.newBufferedReader(path, 
StandardCharsets.UTF_8)) {
+                properties.load(reader);
+            } catch (NoSuchFileException e) {
+                // A configured symlink with a missing target is still an 
error.
+                if (Files.isSymbolicLink(path)) {
+                    throw e;
+                }
+                // Upgrades that retain conf/ have no permission file; keep 
the compatibility defaults.
+            }
+            boolean allowAll = booleanSetting(properties, 
"allow_all_permissions", true);
+            Permissions granted = new Permissions();
+            Set<String> allowedTypes = new HashSet<>();
+            parsePermissions(properties, granted, allowedTypes);
+            if (!properties.isEmpty()) {
+                throw new IllegalArgumentException("Unknown permission 
setting: "
+                        + properties.stringPropertyNames().iterator().next());
+            }
+            // Parse and validate every setting even when AllPermission 
overrides individual grants.
+            if (allowAll) {
+                granted.add(new AllPermission());
+            }
+            return new UdfPermissionConfig(new ConfiguredPermissions(granted, 
allowedTypes));
+        } catch (IOException | IllegalArgumentException e) {
+            throw new IllegalArgumentException("Cannot load Java UDF 
permissions from " + path + ": "
+                    + e.getMessage(), e);
+        }
+    }
+
+    PermissionCollection permissions() {
+        return permissions;
+    }
+
+    private static void parsePermissions(Properties properties, Permissions 
granted, Set<String> allowedTypes) {
+        if (booleanSetting(properties, "allow_process_execution", false)) {
+            granted.add(new FilePermission("<<ALL FILES>>", "execute"));
+        }
+        if (booleanSetting(properties, "allow_network_access", false)) {
+            allowedTypes.add("java.net.SocketPermission");
+            allowedTypes.add("java.net.URLPermission");
+            granted.add(new NetPermission("accessUnixDomainSocket"));
+        }
+        addPaths(properties, granted, "allow_file_read_paths", "read");
+        addPaths(properties, granted, "allow_file_write_paths", 
"write,delete");
+        addPaths(properties, granted, "allow_file_readlink_paths", "readlink");
+        for (String name : listSetting(properties, 
"allow_environment_variables")) {
+            if (!"*".equals(name) && name.contains("*")) {
+                throw new 
IllegalArgumentException("allow_environment_variables requires exact names or 
*");
+            }
+            granted.add(new RuntimePermission("getenv." + name));
+        }
+        addProperties(properties, granted, "allow_system_property_reads", 
"read");
+        addProperties(properties, granted, "allow_system_property_writes", 
"write");
+        if (booleanSetting(properties, "allow_privileged_reflection", false)) {
+            allowedTypes.add("java.lang.reflect.ReflectPermission");
+            granted.add(new RuntimePermission("accessDeclaredMembers"));
+        }
+        if (booleanSetting(properties, "allow_network_information", false)) {
+            granted.add(new NetPermission("getNetworkInformation"));
+        }
+        addRuntimeSwitch(properties, granted, "allow_process_management",
+                "manageProcess");
+        addRuntimeSwitch(properties, granted, "allow_file_system_attributes",
+                "getFileSystemAttributes");
+        addRuntimeSwitch(properties, granted, "allow_preferences_access",
+                "preferences");
+        addRuntimeSwitch(properties, granted, "allow_jvm_exit",
+                "exitVM.*");
+        addRuntimeSwitch(properties, granted, "allow_native_library_loading",
+                "loadLibrary.*");
+        addRuntimeSwitch(properties, granted, "allow_shutdown_hooks",
+                "shutdownHooks");
+        addRuntimeSwitch(properties, granted, "allow_standard_io_changes",
+                "setIO");
+        addRuntimeSwitch(properties, granted, "allow_file_descriptor_access",
+                "readFileDescriptor", "writeFileDescriptor");
+        addRuntimeSwitch(properties, granted, "allow_classloader_creation",

Review Comment:
   [P2] Make the scope of the custom class loader grant explicit
   
   `allow_classloader_creation=true` independently grants a JDK permission that 
permits assigning protection domains to loaded classes. Static domains are 
outside the policy check that enforces the other UDF settings. This makes the 
guarantee in `UdfSecurity` that secondary loaders remain restricted too broad, 
even with `allow_class_definition` disabled. Treat custom loader creation as a 
privileged grant in the shipped configuration and narrow the guarantee to the 
loader paths the policy can enforce. The current secondary-domain test 
exercises the default domain. [JDK 17 
RuntimePermission](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/RuntimePermission.html)



##########
be/src/util/jvm_launcher.cpp:
##########
@@ -67,18 +67,32 @@ std::string join_options(const std::vector<std::string>& 
options) {
     return joined;
 }
 
-// Every jar below `base_path`, in no particular order.
+// Trusted jars below `base_path`, excluding user caches, in no particular 
order.
 void collect_jars(const std::string& base_path, std::string* class_path) {
     std::error_code ec;
     if (!std::filesystem::exists(base_path, ec)) {
         return;
     }
-    for (const auto& entry : 
std::filesystem::recursive_directory_iterator(base_path, ec)) {
-        if (entry.path().extension() == ".jar") {
+    const auto user_cache = 
std::filesystem::absolute(config::user_function_dir).lexically_normal();

Review Comment:
   [P2] Exclude relocated UDF caches with a trailing slash
   
   A setting such as `user_function_dir=/opt/doris/be/lib/moved-udf-cache/` 
works for `UserFunctionCache`, but `lexically_normal()` preserves a trailing 
empty component. The recursive iterator yields the directory without that 
component, so the equality check misses the cache and puts its JARs on the 
fallback system classpath. `TrustedClassLoaders` treats that classpath as 
trusted. Compare directory identities and cover the trailing-slash spelling in 
`FallbackClassPathExcludesUserArchives`. [C++ path iteration and 
comparison](https://eel.is/c++draft/fs.path.itr)



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