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


##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UdfSecurity.java:
##########
@@ -0,0 +1,184 @@
+// 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.File;
+import java.io.FilePermission;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.security.AccessControlContext;
+import java.security.AllPermission;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.Policy;
+import java.security.ProtectionDomain;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.concurrent.ForkJoinPool;
+
+/**
+ * JDK 17 resource permissions for CREATE FUNCTION's Java code, not for the 
Doris executor itself.
+ *
+ * <p>The security manager is JVM-wide. Only domains tagged by 
UserFunctionClassLoader are restricted;
+ * the executor and scanner libraries retain their existing process 
privileges. Standard stack
+ * inspection also checks an inherited AccessControlContext when user code 
starts another thread.
+ * No thread-local flag or temporary installation is involved.
+ */
+@SuppressWarnings("removal")
+final class UdfSecurity {
+    private static final String COMMON_POOL_FACTORY =
+            
"org.apache.doris.common.classloader.DorisForkJoinWorkerThreadFactory";
+    private static final PermissionCollection TRUSTED_PERMISSIONS = 
trustedPermissions();
+    private static SecurityManager installedManager;
+    private static PermissionCollection configuredPermissions;
+
+    private UdfSecurity() {
+    }
+
+    static synchronized void install() {
+        SecurityManager current = System.getSecurityManager();
+        if (installedManager != null) {
+            if (current != installedManager) {
+                throw new IllegalStateException("The Java UDF security manager 
has been replaced");
+            }
+            return;
+        }
+        if (current != null) {
+            throw new IllegalStateException("Java UDF permissions cannot 
replace an existing SecurityManager");
+        }
+        // The factory must be the trusted implementation on the BE system 
classpath.
+        Class<?> factoryClass = 
ForkJoinPool.commonPool().getFactory().getClass();
+        if (!COMMON_POOL_FACTORY.equals(factoryClass.getName())
+                || factoryClass.getClassLoader() != 
ClassLoader.getSystemClassLoader()) {
+            throw new IllegalStateException("Java UDF resource restrictions 
require "
+                    + 
"-Djava.util.concurrent.ForkJoinPool.common.threadFactory="
+                    + COMMON_POOL_FACTORY + " at JVM startup; restart BE "
+                    + "with the updated start_be.sh to preserve JNI scanner 
permissions");
+        }
+        // Construct the marker before installing the policy, so its class 
cannot be loaded
+        // recursively from a permission check. All functions share this 
immutable BE configuration.
+        PermissionCollection loaded = new 
UserPermissions(UdfPermissionConfig.loadConfigured().permissions());
+        Policy previous = Policy.getPolicy();
+        Policy.setPolicy(new UdfPolicy());
+        try {
+            SecurityManager manager = new SecurityManager();
+            System.setSecurityManager(manager);
+            installedManager = manager;
+            configuredPermissions = loaded;
+        } catch (RuntimeException e) {
+            Policy.setPolicy(previous);
+            throw new IllegalStateException("Java UDF resource restrictions 
require a JVM that supports "
+                    + "SecurityManager installation (JDK 17)", e);
+        }
+    }
+
+    /**
+     * URLClassLoader captures its creator's context and later uses it in 
privileged lazy loads.
+     * Apply the user's configured permissions to lazy dependency resolution 
as well. The loader
+     * additionally needs permission to construct itself and read the supplied 
jars, even when the
+     * user configuration does not grant those operations to the function body.
+     */
+    static AccessControlContext loaderContext(URL[] jars, PermissionCollection 
userPermissions) {
+        Permissions permissions = new Permissions();
+        permissions.add(new RuntimePermission("createClassLoader"));
+        for (URL jar : jars) {
+            permissions.add(jarPermission(jar));
+        }
+        // The two-argument constructor makes a static domain: the trusted 
policy cannot enlarge it.
+        return new AccessControlContext(new ProtectionDomain[] {
+                new ProtectionDomain(null, new 
UserPermissions(userPermissions, permissions))});
+    }
+
+    static PermissionCollection userPermissions() {
+        return configuredPermissions;
+    }
+
+    static FilePermission jarPermission(URL jar) {
+        if (!"file".equals(jar.getProtocol())) {
+            throw new IllegalArgumentException("Java UDF dependencies must be 
local JARs: " + jar);
+        }
+        try {
+            File file = new File(jar.toURI());
+            if (!file.isFile()) {
+                throw new IllegalArgumentException("Java UDF dependency is not 
a JAR file: " + jar);
+            }
+            return new FilePermission(file.getPath(), "read");
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException("Invalid Java UDF JAR location: 
" + jar, e);
+        }
+    }
+
+    private static PermissionCollection trustedPermissions() {
+        Permissions permissions = new Permissions();
+        permissions.add(new AllPermission());
+        permissions.setReadOnly();
+        return permissions;
+    }
+
+    private static final class UdfPolicy extends Policy {
+        @Override
+        public PermissionCollection getPermissions(ProtectionDomain domain) {
+            PermissionCollection permissions = domain.getPermissions();
+            return permissions instanceof UserPermissions ? permissions : 
TRUSTED_PERMISSIONS;

Review Comment:
   [P1] Require positive trust before granting unrestricted permissions
   
   The fallback gives `AllPermission` to every unmarked dynamic domain. When an 
operator turns on `allow_classloader_creation` for a UDF library, secondary 
loaders may define code in unmarked domains and this policy assigns those 
domains full permissions. That is broader than the individual grant and leaves 
those domains outside the configured file, process and network limits. Restrict 
full permissions to positively identified framework and scanner domains, and 
keep dynamically loaded UDF code under the configured policy. [OpenJDK dynamic 
protection 
domains](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/security/SecureClassLoader.java#L198-L222)



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UserFunctionLoaders.java:
##########
@@ -0,0 +1,136 @@
+// 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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Builds the classloader a user function is loaded from. There are two kinds 
and they differ only
+ * in where the jar comes from; both hang off {@link UdfContractClassLoader}, 
which is what keeps a
+ * user function from reaching into Doris.
+ *
+ * <ul>
+ *   <li><b>Per function</b> - CREATE FUNCTION named a jar, BE downloaded it, 
and this function gets
+ *       a loader of its own over that one file. It is closed when the 
function is dropped.</li>
+ *   <li><b>Pre-installed</b> - CREATE FUNCTION named no jar, so the class is 
expected in
+ *       {@code plugins/java_extensions} or the deprecated {@code custom_lib}. 
Those directories are
+ *       read once, as they were when they were part of BE's start-up 
classpath: adding a jar to
+ *       them still requires restarting BE.</li>
+ * </ul>
+ */
+final class UserFunctionLoaders {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(UserFunctionLoaders.class);
+
+    /** Where a function with no jar of its own is looked for, in search 
order. */
+    private static final String[] PREINSTALLED_DIRS = 
{"plugins/java_extensions", "custom_lib"};

Review Comment:
   [P2] Preserve FE and BE precedence for preinstalled functions
   
   For fileless functions, the FE still searches `custom_lib` before 
`plugins/java_extensions`, as the BE did before this change. If an operator 
leaves the old JAR in place while installing its replacement in the plugin 
directory, the FE validates the old class and the BE now executes the 
replacement. A changed signature fails at query time, and a changed 
implementation can silently return different results. Keep the preinstalled 
directory order consistent with FE validation.



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UdfContractClassLoader.java:
##########
@@ -0,0 +1,103 @@
+// 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.util.Objects;
+
+/**
+ * Exposes the JDK and the shared Hive/Joda API types to user functions.
+ *
+ * <p>Each user jar must bundle its own third-party dependencies, such as 
Jackson, Gson and Hutool.
+ * They must not resolve against unrelated Doris plugin or system libraries.
+ *
+ * <p>Hive UDF base classes and Joda date types are shared because the 
framework and user code must
+ * agree on their class identity. In particular, the supported Joda 
parameter/return types are
+ * matched as Class objects, so a private copy would not match the framework's 
types.
+ */
+public final class UdfContractClassLoader extends ClassLoader {
+
+    /**
+     * The only names delegated into the framework. Prefixes rather than exact 
names because the Hive
+     * UDF base class drags a small closure with it and joda's date classes 
reference the rest of
+     * joda; listing the leaves would break on the first library upgrade.
+     */
+    private static final String[] CONTRACT_PREFIXES = {
+            "org.apache.hadoop.hive.ql.exec.",
+            "org.apache.hadoop.hive.ql.metadata.",
+            "org.joda.time.",
+    };
+
+    static {
+        registerAsParallelCapable();
+    }
+
+    private final ClassLoader frameworkClassLoader;
+
+    /**
+     * @param frameworkClassLoader the executor's loader, the only place 
contract classes come from
+     */
+    public UdfContractClassLoader(ClassLoader frameworkClassLoader) {
+        // In 4.2 the executor is loaded by the BE system loader, whose parent 
is the
+        // JDK platform loader. Do not expose the trusted system classpath to 
user jars.
+        // Taking the parent keeps this module compilable at Java 8.
+        super(parentOf(frameworkClassLoader));
+        this.frameworkClassLoader = frameworkClassLoader;
+    }
+
+    private static ClassLoader parentOf(ClassLoader frameworkClassLoader) {
+        Objects.requireNonNull(frameworkClassLoader, "frameworkClassLoader");
+        ClassLoader platform = frameworkClassLoader.getParent();
+        if (platform == null) {
+            // A null parent is the bootstrap loader, which would leave user 
functions unable to
+            // resolve java.sql and the rest of the platform modules. It can 
only happen if this
+            // executor was loaded by a loader without the expected JDK parent.
+            throw new IllegalStateException("The java-udf executor was loaded 
by a classloader with no"
+                    + " parent (" + frameworkClassLoader + "), so there is no 
platform classloader to put"
+                    + " behind user functions.");
+        }
+        return platform;
+    }
+
+    @Override
+    protected Class<?> loadClass(String name, boolean resolve) throws 
ClassNotFoundException {
+        synchronized (getClassLoadingLock(name)) {
+            if (isContractClass(name)) {
+                Class<?> contract = frameworkClassLoader.loadClass(name);
+                if (resolve) {
+                    resolveClass(contract);
+                }
+                return contract;
+            }
+            // Platform only: this loader owns no classes of its own, so 
anything that is not in
+            // the JDK and not in the user's jar ends here. The failure is 
left bare because the
+            // caller is always a user function's own loader, which discards 
whatever its parent
+            // threw and reports its own miss; the explanation lives there, in
+            // UserFunctionClassLoader.
+            return super.loadClass(name, resolve);

Review Comment:
   [P1] Preserve existing UDF dependencies on the default upgrade path
   
   This parent restriction also applies with the shipped 
`allow_all_permissions=true`. The existing `test_javaudf_string.groovy` loads 
`StringTest` from the regression JAR, whose Maven dependencies are all 
`provided`. Its `evaluate` method calls `StringUtils.repeat`. The 4.2 BE 
previously supplied Commons Lang through the executor’s classloader. The new 
loader cannot resolve it, so the existing SQL query fails with 
`NoClassDefFoundError`. Preserve the default upgrade behavior, or update the 
existing fixture and provide an explicit dependency migration for 4.2 
deployments before enabling the new loader by default.



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/BaseExecutor.java:
##########
@@ -112,19 +113,27 @@ protected void init(TJavaUdfExecutorCtorParams request, 
String jarPath,
             objCache = getClassCache(jarPath, request.getFn().getSignature(), 
request.getFn().getId(),
                     expirationTime, funcRetType, parameterTypes);
             Constructor<?> ctor = objCache.udfClass.getConstructor();
-            udf = ctor.newInstance();
+            try (ThreadClassLoaderContext ignored = new 
ThreadClassLoaderContext(udfClassLoader())) {

Review Comment:
   [P2] Close the per-executor JAR when initialization is rejected
   
   The new cleanup covers class loading and signature setup. A permission 
denial in the user constructor or `UdfExecutor.prepare` happens after that 
block, and JNI never obtains an executor it can close. With the default 
non-static load mode, each failed open leaves the downloaded JAR handle 
awaiting JVM collection. Close the executor-owned loader on either failure and 
preserve the ownership of cached and shared preinstalled loaders.



##########
bin/start_be.sh:
##########
@@ -262,20 +262,9 @@ if [[ -d "${DORIS_HOME}/lib/java_extensions/juicefs" ]]; 
then
     done
 fi
 
-# add custom_libs to CLASSPATH
-# ATTN, custom_libs is deprecated, use plugins/java_extensions
-if [[ -d "${DORIS_HOME}/custom_lib" ]]; then
-    for f in "${DORIS_HOME}/custom_lib"/*.jar; do
-        DORIS_CLASSPATH="${DORIS_CLASSPATH}:${f}"
-    done
-fi
-
-# add plugins/java_extensions to CLASSPATH
-if [[ -d "${DORIS_HOME}/plugins/java_extensions" ]]; then
-    for f in "${DORIS_HOME}/plugins/java_extensions"/*.jar; do
-        CLASSPATH="${CLASSPATH}:${f}"
-    done
-fi
+# Preinstalled UDF jars in plugins/java_extensions (or deprecated custom_lib)
+# are loaded by UserFunctionLoaders with the configured UDF permissions.
+# Keep them off the trusted system classpath.

Review Comment:
   [P2] Apply the classpath separation to the native JVM fallback
   
   The script removes preinstalled UDF JARs from the system classpath, but the 
self-managed JVM’s fallback in `be/src/util/jni-util.cpp` still adds 
`custom_lib` when launched without `DORIS_CLASSPATH`. That startup path can put 
user archives on the trusted classpath even with the required worker factory 
configured. Exclude preinstalled UDF directories from the native default as 
well.



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/BaseExecutor.java:
##########
@@ -150,21 +159,28 @@ public UdfClassCache getClassCache(String jarPath, String 
functionSignature, lon
         if (cache == null) {
             ClassLoader loader;
             if (Strings.isNullOrEmpty(jarPath)) {
-                // if jarPath is empty, which means the UDF jar is located in 
custom_lib
-                // and already be loaded when BE start.
-                // so here we use system class loader to load UDF class.
-                loader = ClassLoader.getSystemClassLoader();
+                // Preinstalled user jars share a restricted loader owned by 
the BE JVM.
+                loader = UserFunctionLoaders.preinstalled();
             } else {
-                ClassLoader parent = getClass().getClassLoader();
-                classLoader = UdfUtils.getClassLoader(jarPath, parent);
+                classLoader = UserFunctionLoaders.forJar(jarPath);
                 loader = classLoader;
             }
             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 (ThreadClassLoaderContext ignored = new 
ThreadClassLoaderContext(loader)) {
+                    cache.udfClass = Class.forName(className, true, loader);
+                }
+                cache.methodAccess = MethodAccess.get(cache.udfClass);

Review Comment:
   [P2] Keep generated accessors bound to the executor’s ReflectASM
   
   A self-contained UDF JAR that bundles ReflectASM can fail to initialize on a 
standard BE. With the `java.lang` opening in `start_be.sh`, ReflectASM 1.11.9 
can define the generated accessor in the UDF loader. That loader resolves its 
`MethodAccess` superclass to the bundled copy, so ReflectASM’s cast to the 
executor copy fails with `ClassCastException`. Bind the generated accessor to 
the executor’s ReflectASM and cover this with a bundled dependency under the 
production JVM options. [ReflectASM class 
definition](https://github.com/EsotericSoftware/reflectasm/blob/reflectasm-1.11.9/src/com/esotericsoftware/reflectasm/AccessClassLoader.java#L60-L79)
 [ReflectASM accessor 
construction](https://github.com/EsotericSoftware/reflectasm/blob/reflectasm-1.11.9/src/com/esotericsoftware/reflectasm/MethodAccess.java)



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UserFunctionLoaders.java:
##########
@@ -0,0 +1,136 @@
+// 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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Builds the classloader a user function is loaded from. There are two kinds 
and they differ only
+ * in where the jar comes from; both hang off {@link UdfContractClassLoader}, 
which is what keeps a
+ * user function from reaching into Doris.
+ *
+ * <ul>
+ *   <li><b>Per function</b> - CREATE FUNCTION named a jar, BE downloaded it, 
and this function gets
+ *       a loader of its own over that one file. It is closed when the 
function is dropped.</li>
+ *   <li><b>Pre-installed</b> - CREATE FUNCTION named no jar, so the class is 
expected in
+ *       {@code plugins/java_extensions} or the deprecated {@code custom_lib}. 
Those directories are
+ *       read once, as they were when they were part of BE's start-up 
classpath: adding a jar to
+ *       them still requires restarting BE.</li>
+ * </ul>
+ */
+final class UserFunctionLoaders {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(UserFunctionLoaders.class);
+
+    /** Where a function with no jar of its own is looked for, in search 
order. */
+    private static final String[] PREINSTALLED_DIRS = 
{"plugins/java_extensions", "custom_lib"};
+
+    private static volatile ClassLoader contract;
+    private static volatile ClassLoader preinstalled;
+
+    private UserFunctionLoaders() {
+    }
+
+    /**
+     * A loader over one self-contained user jar, including its third-party 
dependencies.
+     * Framework libraries are not added to its search path. The caller owns 
and closes the loader.
+     */
+    static URLClassLoader forJar(String jarPath) throws MalformedURLException, 
FileNotFoundException {
+        File file = new File(jarPath);
+        if (!file.exists()) {
+            throw new FileNotFoundException("Can not find local file: " + 
jarPath);
+        }
+        return UserFunctionClassLoader.create(new URL[] 
{file.toURI().toURL()}, contract());
+    }
+
+    /**
+     * The shared loader over the pre-installed directories. Never closed - 
several functions are
+     * loaded from it and there is no moment at which the last one is known to 
be gone.
+     */
+    static ClassLoader preinstalled() {
+        ClassLoader current = preinstalled;
+        if (current == null) {
+            synchronized (UserFunctionLoaders.class) {
+                if (preinstalled == null) {
+                    List<URL> jars = preinstalledJars();
+                    LOG.info("Java functions with no jar of their own are 
loaded from {} jar(s) in {}",
+                            jars.size(), Arrays.toString(PREINSTALLED_DIRS));
+                    preinstalled = 
UserFunctionClassLoader.create(jars.toArray(new URL[0]), contract());
+                }
+                current = preinstalled;
+            }
+        }
+        return current;
+    }
+
+    /** Where {@link #preinstalled} looks, in search order. */
+    static String[] preinstalledDirs() {
+        return PREINSTALLED_DIRS.clone();
+    }
+
+    private static ClassLoader contract() {
+        ClassLoader current = contract;
+        if (current == null) {
+            synchronized (UserFunctionLoaders.class) {
+                if (contract == null) {
+                    contract = new 
UdfContractClassLoader(UserFunctionLoaders.class.getClassLoader());
+                }
+                current = contract;
+            }
+        }
+        return current;
+    }
+
+    private static List<URL> preinstalledJars() {
+        List<URL> jars = new ArrayList<>();
+        String dorisHome = System.getenv("DORIS_HOME");
+        if (dorisHome == null || dorisHome.trim().isEmpty()) {
+            LOG.warn("DORIS_HOME is not set, so {} cannot be found; a Java 
function created without a"
+                    + " jar will not resolve", 
Arrays.toString(PREINSTALLED_DIRS));
+            return jars;
+        }
+        for (String dir : PREINSTALLED_DIRS) {
+            File[] files = new File(dorisHome.trim(), dir).listFiles(

Review Comment:
   [P2] Keep valid preinstalled JARs loadable when a directory contains a stale 
entry
   
   The suffix filter includes a dangling symlink or directory named `*.jar`. 
`jarPermission` then rejects that entry while constructing the shared loader, 
causing every preinstalled UDF to fail even if its own JAR is valid. Skip and 
log unusable entries while scanning the preinstalled directories. Keep strict 
validation for a JAR explicitly selected by a function.



##########
fe/be-java-extensions/java-common/src/main/java/org/apache/doris/common/classloader/DorisForkJoinWorkerThreadFactory.java:
##########
@@ -0,0 +1,46 @@
+// 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.common.classloader;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ForkJoinWorkerThread;
+
+/**
+ * Keeps the BE's common pool usable by trusted scanner plugins after Java UDF 
permissions are enabled.
+ * JDK 17's default factory switches to innocuous workers when a 
SecurityManager is installed: those
+ * workers cannot install a plugin context classloader and carry an empty 
inherited permission set.
+ * Set the common.threadFactory JVM property before the common pool is 
initialized.
+ */
+@SuppressWarnings("removal")
+public final class DorisForkJoinWorkerThreadFactory implements 
ForkJoinPool.ForkJoinWorkerThreadFactory {
+    @Override
+    public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
+        // Only worker construction is privileged. A task still executes with 
its own protection
+        // domain, so user UDF bytecode does not acquire the worker factory's 
privileges.
+        return 
AccessController.doPrivileged((PrivilegedAction<ForkJoinWorkerThread>) () -> 
new Worker(pool));
+    }
+
+    private static final class Worker extends ForkJoinWorkerThread {
+        private Worker(ForkJoinPool pool) {
+            super(pool);

Review Comment:
   [P2] Preserve common-pool cleanup of worker-local state
   
   The protected `ForkJoinWorkerThread` constructor disables the cleanup flag 
the stock JDK 17 common pool sets even without a security manager. Setting the 
context classloader at worker creation leaves other thread-local state intact 
across unrelated task batches. Workers can retain query objects and pin UDF 
classes after `DROP FUNCTION`. Preserve the stock cleanup or isolate scanner 
work that needs a mutable context classloader in a scanner-owned pool. [OpenJDK 
common-pool 
factory](https://github.com/openjdk/jdk17u/blob/jdk-17.0.2-ga/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java#L815-L833)
 [OpenJDK worker 
cleanup](https://github.com/openjdk/jdk17u/blob/jdk-17.0.2-ga/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java#L1145-L1157)



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UserFunctionClassLoader.java:
##########
@@ -0,0 +1,80 @@
+// 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.net.URL;
+import java.net.URLClassLoader;
+import java.security.AccessController;
+import java.security.CodeSource;
+import java.security.PermissionCollection;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+
+/**
+ * Loads self-contained user jars, with {@link UdfContractClassLoader} 
providing shared API types.
+ *
+ * <p>User permissions come from the BE's local configuration. Lazy dependency 
resolution uses
+ * those permissions plus the loader's own bootstrap permissions, rather than 
the executor's full
+ * privileges.
+ *
+ * <p>A class that could not be found anywhere is reported with what the 
search covered. This is the
+ * loader that has to say it -
+ * {@code ClassLoader.loadClass} discards whatever the parent threw and 
reports its own miss, so a
+ * message attached further up never reaches anyone.
+ */
+@SuppressWarnings("removal")
+final class UserFunctionClassLoader extends URLClassLoader {
+
+    static {
+        registerAsParallelCapable();
+    }
+
+    private final PermissionCollection userPermissions;
+
+    private UserFunctionClassLoader(URL[] urls, ClassLoader contract, 
PermissionCollection userPermissions) {
+        super(urls, contract);
+        this.userPermissions = userPermissions;
+    }
+
+    static UserFunctionClassLoader create(URL[] urls, ClassLoader contract) {
+        UdfSecurity.install();
+        PermissionCollection permissions = UdfSecurity.userPermissions();
+        return AccessController.doPrivileged(
+                (PrivilegedAction<UserFunctionClassLoader>) () ->
+                        new UserFunctionClassLoader(urls, contract, 
permissions),
+                UdfSecurity.loaderContext(urls, permissions));
+    }
+
+    @Override
+    protected PermissionCollection getPermissions(CodeSource source) {
+        // Do not inherit URLClassLoader's automatic file/socket grants or 
java.policy grants.
+        return userPermissions;

Review Comment:
   [P2] Support resources inside the approved UDF JAR
   
   The loader context can read the JAR to resolve classes, but JDK 17 checks 
the resource URL again under the caller’s permissions. A restricted function 
whose dependency uses `getResourceAsStream` for a bundled file can therefore 
get `null` even when its classes load. An explicit file grant would have to 
cover the BE’s generated cache path for downloaded JARs. Support access 
confined to the function’s approved archive, or document and test the 
additional grant for bundled resources. [OpenJDK resource 
lookup](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/net/URLClassLoader.java#L586-L645)
 [OpenJDK resource permission 
check](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java#L496-L544)



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