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


##########
fe/be-java-extensions/jni-bootstrap/src/main/java/org/apache/doris/jni/bootstrap/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.jni.bootstrap;
+
+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 thread-local cleanup
   
   `super(pool)` takes the non-innocuous worker path. OpenJDK 17’s default 
common-pool workers clear their thread-local maps after a top-level batch even 
when the BE has no security manager. Because `start_be.sh` sets this factory 
globally, a Java UDF library that caches a scratch object from its JAR in a 
`ThreadLocal` during a `CompletableFuture` task can now keep that object and 
its loader alive beyond query completion and `DROP FUNCTION`. Preserve 
common-pool cleanup or scope the worker workaround to the scanner work that 
needs a mutable context classloader. [OpenJDK common-pool 
factory](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java#L809-L834),
 [worker 
cleanup](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java#L1145-L1156),
 [worker 
constructor](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/util/concurrent/ForkJoinWorke
 rThread.java#L66-L96)



##########
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 
Java plugin itself.
+ *
+ * <p>The security manager is JVM-wide. Only domains tagged by 
UserFunctionClassLoader are restricted;
+ * the executor, JNI SPI and scanner plugins 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.jni.bootstrap.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");
+        }
+        // Bootstrap implementation classes are deliberately invisible to 
plugin classloaders.
+        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()) {

Review Comment:
   [P2] Keep a stale JAR entry from disabling all preinstalled Java functions
   
   `preinstalledJars()` includes every entry ending in `.jar`. If `custom_lib` 
contains a dangling JAR symlink, this eager `isFile()` check throws while 
creating the shared loader, even when the requested function is in a healthy 
JAR in `plugins/java_extensions`. Previously the classpath was searched lazily 
and an unavailable entry could be skipped. Skip and log unusable entries when 
building the shared preinstalled classpath, and keep validation for 
individually requested JARs. [OpenJDK classpath 
lookup](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java#L399-L444)



##########
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 
Java plugin itself.
+ *
+ * <p>The security manager is JVM-wide. Only domains tagged by 
UserFunctionClassLoader are restricted;
+ * the executor, JNI SPI and scanner plugins 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.jni.bootstrap.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");
+        }
+        // Bootstrap implementation classes are deliberately invisible to 
plugin classloaders.
+        Class<?> factoryClass = 
ForkJoinPool.commonPool().getFactory().getClass();

Review Comment:
   [P2] Preserve unrestricted UDF execution with customized JDK 17 launch 
options
   
   The exact-factory check runs before the permission file is read, and the 
manager is installed even with the shipped `allow_all_permissions=true`. If an 
existing deployment configures its own common-pool factory in 
`JAVA_OPTS_FOR_JDK_17`, `start_be.sh` preserves the value and the first Java 
UDF now fails. A valid JDK 17 `java.security.manager=disallow` setting also 
makes the unrestricted path fail at installation. Read and validate the 
configuration first, then require the new factory and manager only when 
restrictions are enabled. [OpenJDK SecurityManager installation 
contract](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/lang/System.java#L331-L357)



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UserFunctionClassLoader.java:
##########
@@ -19,34 +19,62 @@
 
 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;
 
 /**
- * A user function's own jars, with {@link UdfContractClassLoader} behind them.
+ * Loads self-contained user jars, with {@link UdfContractClassLoader} 
providing shared API types.
  *
- * <p>Ordinary {@link URLClassLoader} behaviour plus one thing: the class that 
could not be found
- * anywhere is reported with what the search covered. This is the loader that 
has to say it -
+ * <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();
     }
 
-    UserFunctionClassLoader(URL[] urls, ClassLoader contract) {
+    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] Keep resources inside the UDF’s own JAR usable with restrictions enabled
   
   The bootstrap context can read the submitted JAR to load classes, but 
`URLClassLoader` checks resource URLs again against the caller’s permissions. 
With `allow_all_permissions=false` and file reads limited to the function’s 
input directory, a self-contained UDF can load while `getResourceAsStream()` 
returns `null` for its own bundled configuration or `ServiceLoader` misses a 
bundled provider. That now requires an additional read grant for the BE-local 
cached JAR. Preserve narrowly scoped access to bundled resources, or document 
the required grant and cover this case in a restricted executor test. [OpenJDK 
resource 
lookup](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/java/net/URLClassLoader.java#L593-L639),
 [resource permission 
check](https://github.com/openjdk/jdk17u/blob/master/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java#L497-L530)



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