This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new ce53f9f7d0 fix(bindings/java): validate JNI map strings, bound local
refs, sync enabledServices, and avoid OperatorOutputStream leak on OOM (#8948)
ce53f9f7d0 is described below
commit ce53f9f7d0b852bd33e2228d44fd5dba664fe49a
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 06:19:21 2026 +0800
fix(bindings/java): validate JNI map strings, bound local refs, sync
enabledServices, and avoid OperatorOutputStream leak on OOM (#8948)
* fix(bindings/java): validate JNI map strings, bound local refs, sync
enabledServices, and avoid OperatorOutputStream leak on OOM
* test(bindings/java): scope -Xcheck:jni assertion to loadEnabledServices
and remove redundant OOM test
---
bindings/java/src/convert.rs | 30 ++++++--
.../org/apache/opendal/OperatorOutputStream.java | 3 +-
.../apache/opendal/test/ExecutorShutdownTest.java | 7 +-
.../apache/opendal/test/JniMapValidationTest.java | 81 ++++++++++++++++++++++
.../java/org/apache/opendal/test/UtilityTest.java | 54 ++++++++++++++-
bindings/java/src/utility.rs | 67 +++---------------
6 files changed, 175 insertions(+), 67 deletions(-)
diff --git a/bindings/java/src/convert.rs b/bindings/java/src/convert.rs
index a0f04c990f..42d1f4ef04 100644
--- a/bindings/java/src/convert.rs
+++ b/bindings/java/src/convert.rs
@@ -49,9 +49,8 @@ pub(crate) fn jmap_to_hashmap(env: &mut Env, params:
&JObject) -> Result<HashMap
};
let k = entry.key(env)?;
let v = entry.value(env)?;
- // SAFETY: a `java.util.Map<String, String>` only yields String
keys and values.
- let k = unsafe { JString::from_raw(env, k.into_raw()) };
- let v = unsafe { JString::from_raw(env, v.into_raw()) };
+ let k = cast_map_string(env, k, "key")?;
+ let v = cast_map_string(env, v, "value")?;
result.insert(k.mutf8_chars(env)?.into(),
v.mutf8_chars(env)?.into());
Ok(true)
})?;
@@ -63,6 +62,28 @@ pub(crate) fn jmap_to_hashmap(env: &mut Env, params:
&JObject) -> Result<HashMap
Ok(result)
}
+fn cast_map_string<'local>(
+ env: &Env<'_>,
+ obj: JObject<'local>,
+ role: &str,
+) -> Result<JString<'local>> {
+ if obj.is_null() {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ format!("map {role} must not be null"),
+ )
+ .into());
+ }
+ env.cast_local::<JString>(obj).map_err(|err| match err {
+ jni::errors::Error::WrongObjectType => Error::new(
+ ErrorKind::ConfigInvalid,
+ format!("map {role} must be java.lang.String"),
+ )
+ .into(),
+ other => other.into(),
+ })
+}
+
pub(crate) fn hashmap_to_jmap<'a, K: AsRef<str>, V: AsRef<str>>(
env: &mut Env<'a>,
map: impl IntoIterator<Item = (K, V)>,
@@ -116,8 +137,7 @@ pub(crate) fn read_string_field(
if result.is_null() {
Ok(None)
} else {
- // SAFETY: the field is declared as `java.lang.String`.
- let result = unsafe { JString::from_raw(env, result.into_raw()) };
+ let result = env.cast_local::<JString>(result)?;
Ok(Some(jstring_to_string(env, &result)?))
}
}
diff --git
a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
index bb5eb31ff1..8c20c601c7 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
@@ -86,9 +86,10 @@ public class OperatorOutputStream extends OutputStream {
if (maxBytes <= 0) {
throw new IllegalArgumentException("maxBytes must be positive");
}
- this.writer = new Writer(operator.withHandle(handle ->
constructWriter(handle, path, options)));
+ Objects.requireNonNull(operator, "operator");
this.bytes = new byte[maxBytes];
this.maxBatchBytes = maxBatchBytes;
+ this.writer = new Writer(operator.withHandle(handle ->
constructWriter(handle, path, options)));
}
@Override
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/ExecutorShutdownTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/ExecutorShutdownTest.java
index d961e0f025..42ce2679a4 100644
---
a/bindings/java/src/test/java/org/apache/opendal/test/ExecutorShutdownTest.java
+++
b/bindings/java/src/test/java/org/apache/opendal/test/ExecutorShutdownTest.java
@@ -43,7 +43,7 @@ public class ExecutorShutdownTest {
Path tempDir;
@ParameterizedTest
- @ValueSource(strings = {"blocking", "async", "derived", "streams",
"callback", "recreate"})
+ @ValueSource(strings = {"blocking", "async", "derived", "streams",
"output_stream_oom", "callback", "recreate"})
void testJvmExitsAfterClosingOperator(String mode) throws Exception {
final String executable =
System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
final Path java = Paths.get(System.getProperty("java.home"), "bin",
executable);
@@ -125,6 +125,11 @@ public class ExecutorShutdownTest {
op.close();
writer.write(content);
}
+ } else if (args[0].equals("output_stream_oom")) {
+ try (final Operator op = Operator.of("memory",
Collections.emptyMap())) {
+ assertThatThrownBy(() ->
op.createOutputStream("example.txt", Integer.MAX_VALUE))
+ .isInstanceOf(OutOfMemoryError.class);
+ }
} else if (args[0].equals("callback")) {
try (final AsyncOperator op = AsyncOperator.of("memory",
Collections.emptyMap())) {
op.write("example.txt", content).join();
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/JniMapValidationTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/JniMapValidationTest.java
new file mode 100644
index 0000000000..b48db86e73
--- /dev/null
+++
b/bindings/java/src/test/java/org/apache/opendal/test/JniMapValidationTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.OpenDALException;
+import org.apache.opendal.Operator;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.WriteOptions;
+import org.apache.opendal.test.condition.OpenDALExceptionCondition;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class JniMapValidationTest {
+ private static Stream<Arguments> invalidMaps() {
+ return Stream.of(
+ Arguments.of("non-string value", "root", 12345),
+ Arguments.of("non-string key", 12345, "/"),
+ Arguments.of("null value", "root", null),
+ Arguments.of("null key", null, "/"));
+ }
+
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private static Map<String, String> rawMapWith(Object key, Object value) {
+ final Map map = new HashMap();
+ map.put(key, value);
+ return (Map<String, String>) map;
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("invalidMaps")
+ void testOperatorOfRejectsInvalidMapEntries(String label, Object key,
Object value) {
+ final Map<String, String> map = rawMapWith(key, value);
+ assertThatThrownBy(() -> Operator.of("memory", map))
+ .as(label)
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ assertThatThrownBy(() -> AsyncOperator.of("memory", map))
+ .as(label)
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("invalidMaps")
+ void testWriteOptionsUserMetadataRejectsInvalidMapEntries(String label,
Object key, Object value) {
+ final WriteOptions options =
+ WriteOptions.builder().userMetadata(rawMapWith(key,
value)).build();
+ try (final Operator op =
Operator.of(ServiceConfig.Memory.builder().build())) {
+ assertThatThrownBy(() -> op.write("test.txt", "hello", options))
+ .as(label)
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ }
+ try (final AsyncOperator op =
+ AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+ assertThatThrownBy(() -> op.write("test.txt", "hello", options))
+ .as(label)
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ }
+ }
+}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/UtilityTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/UtilityTest.java
index 4d1d1222aa..178c2d5d8d 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/UtilityTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/UtilityTest.java
@@ -20,14 +20,66 @@
package org.apache.opendal.test;
import static org.assertj.core.api.Assertions.assertThat;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.Collection;
+import java.util.concurrent.TimeUnit;
import org.apache.opendal.OpenDAL;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
public class UtilityTest {
+ @TempDir
+ Path tempDir;
+
@Test
public void testLoadEnabledServices() {
final Collection<String> enabledServices = OpenDAL.enabledServices();
- assertThat(enabledServices).isNotEmpty();
+ assertThat(enabledServices).contains("memory", "fs", "gcs-grpc",
"goosefs", "minio", "r2");
+ if (!System.getProperty("os.name").startsWith("Windows")) {
+ assertThat(enabledServices).contains("sftp");
+ }
+ }
+
+ @Test
+ public void testLoadEnabledServicesUnderCheckJni() throws Exception {
+ final String executable =
System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ final Path java = Paths.get(System.getProperty("java.home"), "bin",
executable);
+ final Path log = tempDir.resolve("enabled-services-check-jni.log");
+ final Process process = new ProcessBuilder(
+ java.toString(),
+ "-Xcheck:jni",
+ "-Djava.library.path=" +
System.getProperty("java.library.path"),
+ "-cp",
+ System.getProperty("surefire.test.class.path",
System.getProperty("java.class.path")),
+ EnabledServicesCheck.class.getName())
+ .redirectErrorStream(true)
+ .redirectOutput(log.toFile())
+ .start();
+ final boolean exited;
+ try {
+ exited = process.waitFor(15, TimeUnit.SECONDS);
+ } finally {
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ process.waitFor(5, TimeUnit.SECONDS);
+ }
+ }
+ final String output = new String(Files.readAllBytes(log),
StandardCharsets.UTF_8);
+ assertThat(exited).as("JVM must exit cleanly: %s", output).isTrue();
+ assertThat(process.exitValue()).as(output).isZero();
+ assertThat(output).contains("ENABLED_SERVICES_LOADED");
+ assertThat(output).doesNotContain("FATAL ERROR in native method");
+
assertThat(output).doesNotContain("org.apache.opendal.OpenDAL.loadEnabledServices");
+ }
+
+ public static class EnabledServicesCheck {
+ public static void main(String[] args) {
+ final Collection<String> enabledServices =
OpenDAL.enabledServices();
+ assertThat(enabledServices).contains("memory", "gcs-grpc",
"goosefs", "minio", "r2");
+ System.out.println("ENABLED_SERVICES_LOADED");
+ }
}
}
diff --git a/bindings/java/src/utility.rs b/bindings/java/src/utility.rs
index 3a8cbc764a..3fcfb32b69 100644
--- a/bindings/java/src/utility.rs
+++ b/bindings/java/src/utility.rs
@@ -15,18 +15,17 @@
// specific language governing permissions and limitations
// under the License.
-use std::collections::HashSet;
-
use jni::Env;
use jni::EnvUnowned;
use jni::jni_str;
+use jni::objects::IntoAuto;
use jni::objects::JClass;
use jni::objects::JObject;
use jni::objects::JObjectArray;
use jni::sys::jsize;
+use opendal::{Error, ErrorKind};
use crate::Result;
-use crate::convert::string_to_jstring;
use crate::error::ThrowException;
/// # Safety
@@ -42,65 +41,15 @@ pub unsafe extern "system" fn
Java_org_apache_opendal_OpenDAL_loadEnabledService
}
fn intern_load_enabled_services<'local>(env: &mut Env<'local>) ->
Result<JObjectArray<'local>> {
- let services = HashSet::from([
- opendal::services::ALIYUN_DRIVE_SCHEME,
- opendal::services::ALLUXIO_SCHEME,
- opendal::services::AZBLOB_SCHEME,
- opendal::services::AZDLS_SCHEME,
- opendal::services::AZFILE_SCHEME,
- opendal::services::B2_SCHEME,
- opendal::services::CACACHE_SCHEME,
- opendal::services::COS_SCHEME,
- opendal::services::DASHMAP_SCHEME,
- opendal::services::DROPBOX_SCHEME,
- opendal::services::ETCD_SCHEME,
- opendal::services::FS_SCHEME,
- opendal::services::GCS_SCHEME,
- opendal::services::GDRIVE_SCHEME,
- opendal::services::GHAC_SCHEME,
- opendal::services::GRIDFS_SCHEME,
- opendal::services::HTTP_SCHEME,
- opendal::services::HF_SCHEME,
- opendal::services::IPFS_SCHEME,
- opendal::services::IPMFS_SCHEME,
- opendal::services::KOOFR_SCHEME,
- opendal::services::MEMCACHED_SCHEME,
- opendal::services::MEMORY_SCHEME,
- opendal::services::MINI_MOKA_SCHEME,
- opendal::services::MOKA_SCHEME,
- opendal::services::MONGODB_SCHEME,
- opendal::services::MYSQL_SCHEME,
- opendal::services::OBS_SCHEME,
- opendal::services::ONEDRIVE_SCHEME,
- opendal::services::OSS_SCHEME,
- opendal::services::PERSY_SCHEME,
- opendal::services::POSTGRESQL_SCHEME,
- opendal::services::REDB_SCHEME,
- opendal::services::REDIS_SCHEME,
- opendal::services::S3_SCHEME,
- opendal::services::SEAFILE_SCHEME,
- #[cfg(unix)]
- opendal::services::SFTP_SCHEME,
- opendal::services::SLED_SCHEME,
- opendal::services::SQLITE_SCHEME,
- opendal::services::SWIFT_SCHEME,
- opendal::services::TIKV_SCHEME,
- opendal::services::TOS_SCHEME,
- opendal::services::UPYUN_SCHEME,
- opendal::services::VERCEL_ARTIFACTS_SCHEME,
- opendal::services::WEBDAV_SCHEME,
- opendal::services::WEBHDFS_SCHEME,
- opendal::services::YANDEX_DISK_SCHEME,
- ]);
+ opendal::init_default_registry();
+ let services = opendal::OperatorRegistry::get().schemes();
+ let len = jsize::try_from(services.len())
+ .map_err(|err| Error::new(ErrorKind::Unexpected, err.to_string()))?;
- let res = env.new_object_array(
- services.len() as jsize,
- jni_str!("java/lang/String"),
- JObject::null(),
- )?;
+ let res = env.new_object_array(len, jni_str!("java/lang/String"),
JObject::null())?;
for (idx, service) in services.into_iter().enumerate() {
- let srv = string_to_jstring(env, Some(service))?;
+ let srv = env.new_string(service)?.auto();
res.set_element(env, idx, &srv)?;
}