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


##########
bin/start_be.sh:
##########
@@ -596,6 +596,9 @@ add_java_opt_if_missing "-Djol.skipHotspotSAAttach=true"
 add_java_opt_if_missing "-Djavax.security.auth.useSubjectCredsOnly=false"
 add_java_opt_if_missing "-Dsun.security.krb5.debug=true"
 add_java_opt_if_missing "-Dfile.encoding=UTF-8"
+# UDF resource checks must not make JDK 17 replace common-pool workers with 
innocuous workers,
+# which cannot install the context classloaders that JNI scanner plugins 
require.
+add_java_opt_if_missing 
"-Djava.util.concurrent.ForkJoinPool.common.threadFactory=org.apache.doris.jni.bootstrap.DorisForkJoinWorkerThreadFactory"

Review Comment:
   [P2] Supply the required JVM options on the native launch path
   
   The native launcher supports starting without this script. It builds the 
fallback classpath in `scan_class_path()` and creates the JVM from 
`JvmLauncher::_build_options()`. When neither `JAVA_OPTS` nor `LIBHDFS_OPTS` 
supplies the required property, the first downloaded Java UDF fails the 
exact-factory check in `UdfSecurity.install()`, before its permission file is 
read. The native defaults also omit the module openings used by the factory and 
the policy. Put the required options in the shared JVM launcher and cover its 
fallback options in `JvmLauncherOptionsTest`.



##########
fe/be-java-extensions/java-udf/src/test/java/org/apache/doris/udf/SecurityTestUdf.java:
##########
@@ -0,0 +1,322 @@
+// 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.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.Socket;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ForkJoinPool;
+
+/** Packaged into a separate user jar by UdfSecurityTest; no framework 
dependencies. */
+@SuppressWarnings("removal")
+public class SecurityTestUdf {
+    private static final ThreadLocal<String> QUERY = new ThreadLocal<>();
+    private static final InheritableThreadLocal<String> INHERITED = new 
InheritableThreadLocal<>();
+    public static volatile Thread worker;
+
+    static {
+        checkContext(SecurityTestUdf.class);
+    }
+
+    public SecurityTestUdf() {
+        checkContext(getClass());
+    }
+
+    public void prepare() {
+        checkContext(getClass());
+    }
+
+    public String evaluate(String operation) throws Exception {
+        checkContext(getClass());
+        if (operation.startsWith("read:")) {
+            return new 
String(Files.readAllBytes(Paths.get(operation.substring(5))), 
StandardCharsets.UTF_8);
+        }
+        if (operation.startsWith("write:")) {
+            Files.write(Paths.get(operation.substring(6)), new byte[] {1});
+            return "written";
+        }
+        if (operation.startsWith("connect:")) {
+            try (Socket socket = new Socket("127.0.0.1", 
Integer.parseInt(operation.substring(8)))) {
+                return "connected";
+            }
+        }
+        if (operation.startsWith("lyingChild:")) {
+            String[] parts = operation.substring(11).split(":", 2);
+            byte[] bytes = Base64.getDecoder().decode(parts[1]);
+            Class<?> child = new 
LyingLoader(Integer.parseInt(parts[0])).define(bytes);
+            return (String) child.getMethod("read").invoke(null);
+        }
+        if (operation.startsWith("child:")) {
+            byte[] bytes = Base64.getDecoder().decode(operation.substring(6));
+            Class<?> child = new ChildLoader().define(bytes);
+            return (String) child.getMethod("read").invoke(null);
+        }
+        if (operation.startsWith("urlChild:")) {
+            try (URLClassLoader child = URLClassLoader.newInstance(
+                    new URL[] {new 
java.io.File(operation.substring(9)).toURI().toURL()}, null)) {
+                return childEnvironment(child);
+            }
+        }
+        if (operation.startsWith("forgedPlugin:")) {
+            Class<?> pluginType = ClassLoader.getSystemClassLoader().loadClass(
+                    "org.apache.doris.jni.bootstrap.DorisPluginClassLoader");
+            URL url = new 
java.io.File(operation.substring(13)).toURI().toURL();
+            try (URLClassLoader child = (URLClassLoader) 
pluginType.getConstructor(
+                    String.class, List.class, ClassLoader.class).newInstance(
+                            "forged", Collections.singletonList(url), 
ClassLoader.getSystemClassLoader())) {
+                return childEnvironment(child);
+            }
+        }
+        switch (operation) {
+            case "resource":
+                try (InputStream in = 
getClass().getClassLoader().getResourceAsStream("udf-config.txt")) {
+                    return in == null ? "missing" : new String(readAll(in), 
StandardCharsets.UTF_8);
+                }
+            case "inheritedOnFirstTask": {
+                INHERITED.set("caller context");
+                CompletableFuture<String> result = new CompletableFuture<>();
+                ForkJoinPool.commonPool().execute(() -> 
result.complete(INHERITED.get()));
+                return result.get();
+            }
+            case "threadLocalSet": {
+                CompletableFuture<String> result = new CompletableFuture<>();
+                ForkJoinPool.commonPool().execute(() -> {
+                    worker = Thread.currentThread();
+                    QUERY.set("previous query");
+                    INHERITED.set("previous inherited query");
+                    result.complete("set");
+                });
+                return result.get();
+            }
+            case "threadLocalRead": {
+                CompletableFuture<String> result = new CompletableFuture<>();
+                ForkJoinPool.commonPool().execute(() -> result.complete(
+                        QUERY.get() == null ? INHERITED.get() : QUERY.get()));
+                return result.get();
+            }
+            case "environment":
+                return System.getenv("DORIS_HOME");
+            case "property":
+                return System.getProperty("java.version");
+            case "async":
+                return CompletableFuture.supplyAsync(() -> 
System.getenv("DORIS_HOME")).join();
+            case "thread": {
+                String[] result = new String[1];
+                Throwable[] failure = new Throwable[1];
+                Thread thread = new Thread(() -> {
+                    try {
+                        result[0] = System.getenv("DORIS_HOME");
+                    } catch (Throwable t) {
+                        failure[0] = t;
+                    }
+                });
+                thread.start();
+                thread.join();
+                if (failure[0] != null) {
+                    throw new RuntimeException(failure[0]);
+                }
+                return result[0];
+            }
+            case "exit":
+                System.getSecurityManager().checkExit(0);
+                return "allowed";
+            case "process":
+                return Integer.toString(new 
ProcessBuilder("/bin/true").start().waitFor());

Review Comment:
   [P3] Use a subprocess executable available on macOS
   
   The unrestricted and trusted-preinstalled probes expect this command to 
return zero. macOS installs `true` under `/usr/bin`, so the Java suite fails on 
Macs when `ProcessBuilder` tries to start `/bin/true`. Use a portable 
executable for the probe, such as `/bin/sh` with an immediate zero exit. [Apple 
shell command install 
settings](https://github.com/apple-oss-distributions/shell_cmds/blob/main/shell_cmds.xcodeproj/project.pbxproj#L7273-L7275)
 ยท [Apple true 
target](https://github.com/apple-oss-distributions/shell_cmds/blob/main/shell_cmds.xcodeproj/project.pbxproj#L7665-L7674)



##########
conf/java_udf_security.properties:
##########
@@ -0,0 +1,23 @@
+# 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.
+
+# Resource permissions apply to CREATE FUNCTION archives downloaded into the 
BE function cache.
+# Operator-preinstalled jars in custom_lib and plugins/java_extensions remain 
trusted.
+# Allow all permissions for downloaded Java UDFs by default.
+# Approved user archives remain readable for their bundled resources.
+# This does not grant reads of other files or the surrounding UDF cache 
directory.

Review Comment:
   [P3] Document how to activate and configure restricted mode
   
   The archive-only read comment sits beside `allow_all_permissions=true`, 
which permits reads throughout the filesystem. The shipped file gives operators 
no example of a restricted configuration or indication that the running BE 
keeps the permissions it loaded on first use. Qualify the read comment, show a 
minimal configuration with `allow_all_permissions=false` and an explicit grant, 
and document the BE restart requirement.



##########
fe/be-java-extensions/java-udf/src/main/java/org/apache/doris/udf/UserFunctionLoaders.java:
##########
@@ -25,44 +25,49 @@
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLClassLoader;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 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.
+ * Builds the classloader a function is loaded from. Both kinds use {@link 
UdfContractClassLoader}
+ * for shared APIs; only downloaded function archives use the configured UDF 
resource permissions.
  *
  * <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>
+ *       a restricted loader of its own over that 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>
+ *       operator-controlled and trusted, independently of the UDF permission 
configuration. They
+ *       are read once; adding a jar to them still requires restarting BE.</li>
  * </ul>
  */
+@SuppressWarnings("removal")
 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 final String[] PREINSTALLED_DIRS = {"custom_lib", 
"plugins/java_extensions"};

Review Comment:
   [P2] Preserve the preinstalled JAR selected by existing functions during 
upgrades
   
   An existing function registered without an archive can have a legacy copy in 
`custom_lib` and a newer copy in `plugins/java_extensions`. BEs before this 
patch load the latter first. This change makes upgraded BEs load the legacy 
copy, so different BEs can execute different implementations of the same 
function during a rolling upgrade. The FE's classpath order explains the 
proposed alignment, but existing definitions store the class name without a JAR 
path and cannot pin the implementation. Preserve BE's existing order for this 
change, or handle duplicates explicitly and document the required migration.



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