Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(mongodb): connect the legacy driver to old TLS servers

Loc Nguyen827d551c4623
diff --git a/agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java b/agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java
index 500bc4a7ee..fa4247e496 100644
--- a/agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java
+++ b/agents/drivers/mongodb/src/main/java/com/dbx/agent/mongodb/MongoAgent.java
@@ -60,8 +60,10 @@ import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
+import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -74,7 +76,9 @@ import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
@@ -88,6 +92,7 @@ import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
import org.bson.Document;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
@@ -115,6 +120,23 @@ public final class MongoAgent {
private static final int MAX_SESSIONS = 256;
/** MongoDB error code 13 (Unauthorized), returned when the account may not run listDatabases. */
private static final int LIST_DATABASES_UNAUTHORIZED_CODE = 13;
+ private static final int MAX_SERVER_SELECTION_TIMEOUT_SECS = 20;
+ private static final String TLS_DISABLED_ALGORITHMS_KEY = "jdk.tls.disabledAlgorithms";
+ private static final String TLS_LEGACY_ALGORITHMS_KEY = "jdk.tls.legacyAlgorithms";
+ // MongoDB 3.x servers built against older OpenSSL only offer static RSA key exchange
+ // (and the oldest only TLS 1.0), which current JREs disable by default.
+ private static final Set<String> LEGACY_TLS_ALGORITHMS_TO_ALLOW = Set.of(
+ "TLSV1",
+ "TLSV1.1",
+ "TLS_RSA_*",
+ "RSA_PKCS1_SHA1 USAGE HANDSHAKESIGNATURE");
+ // The static-RSA entries are demoted into jdk.tls.legacyAlgorithms instead of silently
+ // vanishing. JSSE consults that property only when it picks cipher suites as a TLS
+ // server (sun.security.ssl.ServerHello), never on the client side and never for
+ // protocol versions, so TLSv1/TLSv1.1 can only leave the disabled list outright.
+ private static final Set<String> LEGACY_TLS_ALGORITHMS_TO_DEMOTE = Set.of(
+ "TLS_RSA_*",
+ "RSA_PKCS1_SHA1 USAGE HANDSHAKESIGNATURE");
private static final ThreadLocal<MongoClient> CURRENT_CLIENT = new ThreadLocal<>();
private static final ThreadLocal<Set<String>> CURRENT_FIND_CURSOR_OWNER = new ThreadLocal<>();
private static final ConcurrentHashMap<String, MongoCursor<Document>> FIND_CURSORS = new ConcurrentHashMap<>();
@@ -152,9 +174,24 @@ public final class MongoAgent {
throw new IllegalArgumentException("Client certificate and key must be provided together");
}
+ Map<String, String> params = new LinkedHashMap<>();
+ if (connectionString != null && !connectionString.isBlank()) {
+ params.putAll(parseQueryParams(connectionString));
+ }
+ String urlParams = stringOrNull(connObj, "url_params");
+ if (urlParams != null && !urlParams.isBlank()) {
+ params.putAll(parseQueryParams(urlParams));
+ }
+
+ boolean allowInvalidCertificates = hasAllowInvalidCertificates(params);
+ // Per the connection-string spec only tlsInsecure relaxes both checks;
+ // tlsAllowInvalidCertificates on its own must keep hostname verification.
+ boolean allowInvalidHostnames = isTruthy(params.get("tlsinsecure")) || hasAllowInvalidHostnames(params);
+
MongoClientSettings.Builder builder = MongoClientSettings.builder();
+ ConnectionString cs = null;
if (connectionString != null && !connectionString.isBlank()) {
- ConnectionString cs = new ConnectionString(connectionString);
+ cs = new ConnectionString(connectionString);
builder.applyConnectionString(cs);
// Driver 3.12 predates the directConnection URI option (introduced in driver 4.x)
// and silently ignores it. When directConnection=true is present in the query of a
@@ -173,8 +210,39 @@ public final class MongoAgent {
}
}
- if (ssl) {
- applyTlsSettings(builder, caCertPath, clientCertPath, clientKeyPath);
+ // Driver 3.12 has no tlsAllowInvalidCertificates option and form mode never parsed the URL
+ // params, so the "skip certificate verification" setting has to be applied here.
+ boolean enableTls = ssl
+ || (cs != null && Boolean.TRUE.equals(cs.getSslEnabled()))
+ || isTruthy(params.get("ssl"))
+ || isTruthy(params.get("tls"));
+ if (enableTls) {
+ // Old MongoDB TLS servers need policy entries that current JREs disable. The
+ // relaxation cannot be scoped per connection (JSSE caches the policy once
+ // initialized), so modern peers keep modern TLS unless this connection
+ // explicitly opts in with tlsAllowLegacyProtocols=true.
+ if (hasAllowLegacyProtocols(params)) {
+ relaxLegacyTlsPolicy();
+ }
+ applyTlsSettings(builder, caCertPath, clientCertPath, clientKeyPath,
+ allowInvalidCertificates, allowInvalidHostnames);
+ }
+
+ // The driver's default 30s server selection matches the agent's connect RPC timeout, which
+ // replaced the real failure (e.g. a TLS handshake error) with "Agent RPC call timed out".
+ int connectTimeoutSecs = connObj.has("connect_timeout_secs") && !connObj.get("connect_timeout_secs").isJsonNull()
+ ? connObj.get("connect_timeout_secs").getAsInt()
+ : 0;
+ if (connectTimeoutSecs > 0) {
+ if (cs == null || cs.getServerSelectionTimeout() == null) {
+ long serverSelectionMs = Math.min(connectTimeoutSecs, MAX_SERVER_SELECTION_TIMEOUT_SECS) * 1000L;
+ builder.applyToClusterSettings(
+ s -> s.serverSelectionTimeout(serverSelectionMs, TimeUnit.MILLISECONDS));
+ }
+ if (cs == null || cs.getConnectTimeout() == null) {
+ int connectTimeoutMs = (int) Math.min(connectTimeoutSecs * 1000L, Integer.MAX_VALUE);
+ builder.applyToSocketSettings(s -> s.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS));
+ }
}
return builder;
@@ -220,6 +288,74 @@ public final class MongoAgent {
}
}
+ static Map<String, String> parseQueryParams(String query) {
+ Map<String, String> result = new LinkedHashMap<>();
+ if (query == null || query.isBlank()) {
+ return result;
+ }
+ int queryStart = query.indexOf('?');
+ int hashStart = query.indexOf('#');
+ int start = queryStart >= 0 ? queryStart + 1 : 0;
+ int end = hashStart >= 0 && hashStart >= start ? hashStart : query.length();
+ String cleanQuery = query.substring(start, end);
+ if (cleanQuery.isEmpty()) {
+ return result;
+ }
+ for (String param : cleanQuery.split("[&;]")) {
+ if (param.isEmpty()) {
+ continue;
+ }
+ int eq = param.indexOf('=');
+ String key = eq >= 0 ? param.substring(0, eq) : param;
+ String val = eq >= 0 ? param.substring(eq + 1) : "";
+ result.put(decodeUriComponent(key).trim().toLowerCase(Locale.ROOT), decodeUriComponent(val));
+ }
+ return result;
+ }
+
+ static boolean isTruthy(String value) {
+ if (value == null) {
+ return false;
+ }
+ String trimmed = value.trim();
+ return "true".equalsIgnoreCase(trimmed) || "1".equals(trimmed) || "yes".equalsIgnoreCase(trimmed);
+ }
+
+ static boolean hasAllowInvalidCertificates(Map<String, String> params) {
+ return isTruthy(params.get("tlsallowinvalidcertificates"))
+ || isTruthy(params.get("sslallowinvalidcertificates"))
+ || isTruthy(params.get("tlsinsecure"));
+ }
+
+ static boolean hasAllowInvalidHostnames(Map<String, String> params) {
+ return isTruthy(params.get("tlsallowinvalidhostnames"))
+ || isTruthy(params.get("sslallowinvalidhostnames"));
+ }
+
+ static boolean hasAllowLegacyProtocols(Map<String, String> params) {
+ return isTruthy(params.get("tlsallowlegacyprotocols"))
+ || isTruthy(params.get("sslallowlegacyprotocols"));
+ }
+
+ static TrustManager[] createTrustAllTrustManagers() {
+ return new TrustManager[] {
+ new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) {
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) {
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ }
+ };
+ }
+
private static MongoClient openClient(JsonObject params) {
JsonObject connObj = params.has("connection") && params.get("connection").isJsonObject()
? params.getAsJsonObject("connection")
@@ -245,13 +381,19 @@ public final class MongoAgent {
}
private static void applyTlsSettings(MongoClientSettings.Builder builder,
- String caCertPath, String clientCertPath, String clientKeyPath) {
+ String caCertPath, String clientCertPath, String clientKeyPath,
+ boolean allowInvalidCertificates, boolean allowInvalidHostnames) {
builder.applyToSslSettings(sslBuilder -> {
sslBuilder.enabled(true);
- if (caCertPath != null && !caCertPath.isBlank()
- || clientCertPath != null && !clientCertPath.isBlank()) {
+ if (allowInvalidHostnames) {
+ sslBuilder.invalidHostNameAllowed(true);
+ }
+ if (allowInvalidCertificates
+ || (caCertPath != null && !caCertPath.isBlank())
+ || (clientCertPath != null && !clientCertPath.isBlank())) {
try {
- sslBuilder.context(createTlsSslContext(caCertPath, clientCertPath, clientKeyPath));
+ sslBuilder.context(createTlsSslContext(
+ caCertPath, clientCertPath, clientKeyPath, allowInvalidCertificates));
} catch (Exception e) {
throw new RuntimeException("Failed to configure TLS: " + e.getMessage(), e);
}
@@ -261,9 +403,18 @@ public final class MongoAgent {
static SSLContext createTlsSslContext(String caCertPath, String clientCertPath, String clientKeyPath)
throws Exception {
- TrustManager[] trustManagers = null;
- if (caCertPath != null && !caCertPath.isBlank()) {
+ return createTlsSslContext(caCertPath, clientCertPath, clientKeyPath, false);
+ }
+
+ static SSLContext createTlsSslContext(String caCertPath, String clientCertPath, String clientKeyPath,
+ boolean allowInvalidCertificates) throws Exception {
+ TrustManager[] trustManagers;
+ if (allowInvalidCertificates) {
+ trustManagers = createTrustAllTrustManagers();
+ } else if (caCertPath != null && !caCertPath.isBlank()) {
trustManagers = loadTrustManagersFromPem(caCertPath);
+ } else {
+ trustManagers = null;
}
KeyManager[] keyManagers = null;
@@ -2526,6 +2677,81 @@ public final class MongoAgent {
}
}
+ static String relaxedDisabledAlgorithms(String current) {
+ if (current == null || current.isBlank()) {
+ return "";
+ }
+ List<String> kept = new ArrayList<>();
+ for (String rawPart : current.split(",")) {
+ String part = rawPart.trim();
+ if (!part.isEmpty() && !LEGACY_TLS_ALGORITHMS_TO_ALLOW.contains(part.toUpperCase(Locale.ROOT))) {
+ kept.add(part);
+ }
+ }
+ return String.join(", ", kept);
+ }
+
+ /** The disabled-list entries demoted into jdk.tls.legacyAlgorithms, in original casing. */
+ static List<String> demotedLegacyAlgorithms(String current) {
+ List<String> demoted = new ArrayList<>();
+ if (current == null) {
+ return demoted;
+ }
+ for (String rawPart : current.split(",")) {
+ String part = rawPart.trim();
+ if (!part.isEmpty() && LEGACY_TLS_ALGORITHMS_TO_DEMOTE.contains(part.toUpperCase(Locale.ROOT))) {
+ demoted.add(part);
+ }
+ }
+ return demoted;
+ }
+
+ // Mirrors DBeaver's launcher merge: jdk.tls.legacyAlgorithms keeps its existing
+ // entries and only gains the demoted ones, so they remain documented as fallbacks.
+ static String mergedLegacyAlgorithms(String current, List<String> additions) {
+ List<String> merged = new ArrayList<>();
+ if (current != null && !current.isBlank()) {
+ for (String rawPart : current.split(",")) {
+ String part = rawPart.trim();
+ if (!part.isEmpty()) {
+ merged.add(part);
+ }
+ }
+ }
+ for (String addition : additions) {
+ boolean present = false;
+ for (String existing : merged) {
+ if (existing.equalsIgnoreCase(addition)) {
+ present = true;
+ break;
+ }
+ }
+ if (!present) {
+ merged.add(addition);
+ }
+ }
+ return String.join(", ", merged);
+ }
+
+ // Must run before JSSE first reads the policy, i.e. before the first TLS connection
+ // of this process. JSSE caches jdk.tls.disabledAlgorithms when the sun.security.ssl
+ // classes initialize, so the relaxation is process-wide once applied; it therefore
+ // runs lazily and only for connections that explicitly request legacy TLS.
+ static synchronized void relaxLegacyTlsPolicy() {
+ String disabled = Security.getProperty(TLS_DISABLED_ALGORITHMS_KEY);
+ String legacy = Security.getProperty(TLS_LEGACY_ALGORITHMS_KEY);
+ String relaxed = relaxedDisabledAlgorithms(disabled);
+ String merged = mergedLegacyAlgorithms(legacy, demotedLegacyAlgorithms(disabled));
+ if (Objects.equals(disabled, relaxed) && Objects.equals(legacy, merged)) {
+ return;
+ }
+ Security.setProperty(TLS_DISABLED_ALGORITHMS_KEY, relaxed);
+ Security.setProperty(TLS_LEGACY_ALGORITHMS_KEY, merged);
+ System.err.println("INFO: relaxed jdk.tls.disabledAlgorithms (TLSv1, TLSv1.1, TLS_RSA_*, "
+ + "rsa_pkcs1_sha1) on request (tlsAllowLegacyProtocols); the legacy TLS policy "
+ + "is process-wide for this agent");
+ }
+
public static void main(String[] args) throws Exception {
System.out.println("{\"ready\":true}");
System.out.flush();
diff --git a/agents/drivers/mongodb/src/test/java/com/dbx/agent/mongodb/MongoAgentTest.java b/agents/drivers/mongodb/src/test/java/com/dbx/agent/mongodb/MongoAgentTest.java
index 0097092f30..d916791bce 100644
--- a/agents/drivers/mongodb/src/test/java/com/dbx/agent/mongodb/MongoAgentTest.java
+++ b/agents/drivers/mongodb/src/test/java/com/dbx/agent/mongodb/MongoAgentTest.java
@@ -1,9 +1,12 @@
package com.dbx.agent.mongodb;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -43,18 +46,32 @@ import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel;
import com.mongodb.client.result.UpdateResult;
import java.io.FileInputStream;
+import java.io.InputStream;
import java.lang.reflect.Proxy;
+import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
+import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
import org.bson.BsonDocument;
import org.bson.BsonRegularExpression;
import org.bson.Document;
@@ -1739,6 +1756,377 @@ class MongoAgentTest {
assertNotNull(ctx);
}
+ // ─── TLS: URL params and timeouts (issue #10657) ───
+
+ @Test
+ void formModeWithTlsAllowInvalidCertificatesEnablesSslAndTrustsSelfSignedCert() throws Exception {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+ connection.addProperty("url_params", "tlsAllowInvalidCertificates=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ // Only tlsInsecure skips hostname verification; cert-only skips just the chain check.
+ assertFalse(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNotNull(settings.getSslSettings().getContext());
+
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate selfSignedCert;
+ try (InputStream is = new FileInputStream(caPemPath.toFile())) {
+ selfSignedCert = (X509Certificate) cf.generateCertificate(is);
+ }
+ TrustManager[] trustManagers = MongoAgent.createTrustAllTrustManagers();
+ assertNotNull(trustManagers);
+ assertTrue(trustManagers.length > 0);
+ assertInstanceOf(X509TrustManager.class, trustManagers[0]);
+ X509TrustManager tm = (X509TrustManager) trustManagers[0];
+ assertDoesNotThrow(() -> tm.checkServerTrusted(new X509Certificate[] {selfSignedCert}, "RSA"));
+ assertDoesNotThrow(() -> tm.checkClientTrusted(new X509Certificate[] {selfSignedCert}, "RSA"));
+ assertEquals(0, tm.getAcceptedIssuers().length);
+ }
+
+ @Test
+ void formModeWithoutInvalidCertParamKeepsDefaultVerification() {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ assertFalse(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNull(settings.getSslSettings().getContext());
+ }
+
+ @Test
+ void formModeWithTruthyUrlParamVariants() {
+ for (String param : List.of(
+ "tlsAllowInvalidCertificates=1",
+ "sslAllowInvalidCertificates=yes",
+ "TLSALLOWINVALIDCERTIFICATES=TRUE")) {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+ connection.addProperty("url_params", "retryWrites=false&" + param);
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+ assertTrue(settings.getSslSettings().isEnabled(), "Failed for " + param);
+ assertFalse(settings.getSslSettings().isInvalidHostNameAllowed(), "Failed for " + param);
+ assertNotNull(settings.getSslSettings().getContext(), "Failed for " + param);
+ }
+ }
+
+ @Test
+ void formModeWithTlsInsecureSkipsCertificateAndHostnameChecks() {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+ connection.addProperty("url_params", "tlsInsecure=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ assertTrue(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNotNull(settings.getSslSettings().getContext());
+ }
+
+ @Test
+ void formModeWithInvalidHostnamesOnlyDoesNotTrustInvalidCertificates() {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+ connection.addProperty("url_params", "tlsAllowInvalidHostnames=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ assertTrue(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNull(settings.getSslSettings().getContext());
+ }
+
+ @Test
+ void uriModeHonoursTlsAllowInvalidCertificatesInConnectionString() {
+ JsonObject connection = new JsonObject();
+ connection.addProperty(
+ "connection_string",
+ "mongodb://127.0.0.1:27017/?ssl=true&tlsAllowInvalidCertificates=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ assertFalse(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNotNull(settings.getSslSettings().getContext());
+ }
+
+ @Test
+ void uriModeWithTlsInsecureSkipsCertificateAndHostnameChecks() {
+ JsonObject connection = new JsonObject();
+ connection.addProperty(
+ "connection_string",
+ "mongodb://127.0.0.1:27017/?ssl=true&tlsInsecure=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertTrue(settings.getSslSettings().isEnabled());
+ assertTrue(settings.getSslSettings().isInvalidHostNameAllowed());
+ assertNotNull(settings.getSslSettings().getContext());
+ }
+
+ @Test
+ void connectTimeoutSecsAppliedToServerSelectionTimeoutAndCapped() {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("connect_timeout_secs", 10);
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertEquals(10_000L, settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS));
+ assertEquals(10_000, settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS));
+
+ JsonObject longTimeoutConn = minimalConnection();
+ longTimeoutConn.addProperty("connect_timeout_secs", 30);
+ MongoClientSettings cappedSettings = MongoAgent.configureBuilder(longTimeoutConn).build();
+
+ assertEquals(20_000L, cappedSettings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS));
+ assertEquals(30_000, cappedSettings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS));
+ }
+
+ @Test
+ void explicitServerSelectionTimeoutMsInUriWinsOverConnectTimeoutSecs() {
+ JsonObject connection = new JsonObject();
+ connection.addProperty(
+ "connection_string",
+ "mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=5000");
+ connection.addProperty("connect_timeout_secs", 10);
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertEquals(5_000L, settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS));
+ assertEquals(10_000, settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS));
+ }
+
+ @Test
+ void formModeWithoutSslIgnoresInvalidCertificateParam() {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("url_params", "tlsAllowInvalidCertificates=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+
+ assertFalse(settings.getSslSettings().isEnabled());
+ }
+
+ @Test
+ void relaxedDisabledAlgorithmsAllowsLegacyMongoTlsOnly() {
+ String current = "SSLv3, TLSv1, TLSv1.1, RC4, DES, 3DES_EDE_CBC, anon, NULL, TLS_RSA_*, "
+ + "rsa_pkcs1_sha1 usage HandshakeSignature, ecdsa_sha1 usage HandshakeSignature";
+
+ assertEquals(
+ "SSLv3, RC4, DES, 3DES_EDE_CBC, anon, NULL, ecdsa_sha1 usage HandshakeSignature",
+ MongoAgent.relaxedDisabledAlgorithms(current));
+ assertEquals("", MongoAgent.relaxedDisabledAlgorithms(null));
+ }
+
+ @Test
+ void demotedLegacyAlgorithmsKeepOriginalCasing() {
+ String current = "SSLv3, TLSv1, TLS_RSA_*, rsa_pkcs1_sha1 usage HandshakeSignature, RC4";
+
+ assertEquals(
+ List.of("TLS_RSA_*", "rsa_pkcs1_sha1 usage HandshakeSignature"),
+ MongoAgent.demotedLegacyAlgorithms(current));
+ assertTrue(MongoAgent.demotedLegacyAlgorithms(null).isEmpty());
+ }
+
+ @Test
+ void mergedLegacyAlgorithmsMergeWithoutDuplicates() {
+ assertEquals(
+ "NULL, anon, RC4, DES, 3DES_EDE_CBC, TLS_RSA_*, rsa_pkcs1_sha1 usage HandshakeSignature",
+ MongoAgent.mergedLegacyAlgorithms(
+ "NULL, anon, RC4, DES, 3DES_EDE_CBC",
+ List.of("TLS_RSA_*", "rsa_pkcs1_sha1 usage HandshakeSignature")));
+ // Already-present entries (any casing) are not duplicated.
+ assertEquals(
+ "NULL, TLS_RSA_*",
+ MongoAgent.mergedLegacyAlgorithms("NULL, TLS_RSA_*", List.of("tls_rsa_*")));
+ assertEquals("TLS_RSA_*", MongoAgent.mergedLegacyAlgorithms(null, List.of("TLS_RSA_*")));
+ }
+
+ @Test
+ void relaxLegacyTlsPolicyUpdatesLiveSecurityProperties() {
+ String originalDisabled = Security.getProperty("jdk.tls.disabledAlgorithms");
+ String originalLegacy = Security.getProperty("jdk.tls.legacyAlgorithms");
+ assertNotNull(originalDisabled, "jdk.tls.disabledAlgorithms must be defined by the JRE");
+ Set<String> disabledBefore = upperCasedEntries(originalDisabled);
+ List<String> legacyEntries = List.of("TLSV1", "TLSV1.1", "TLS_RSA_*",
+ "RSA_PKCS1_SHA1 USAGE HANDSHAKESIGNATURE");
+ try {
+ MongoAgent.relaxLegacyTlsPolicy();
+ // A second run must not change anything (idempotent).
+ MongoAgent.relaxLegacyTlsPolicy();
+
+ Set<String> disabledAfter = upperCasedEntries(Security.getProperty("jdk.tls.disabledAlgorithms"));
+ for (String removed : legacyEntries) {
+ assertFalse(disabledAfter.contains(removed), removed + " must leave the disabled list");
+ }
+ // Unrelated JRE defaults must stay disabled; JDK 21 also disables these.
+ for (String kept : List.of("SSLV3", "DTLSV1.0", "ECDH")) {
+ assertTrue(disabledAfter.contains(kept), kept + " must stay disabled");
+ }
+ // Every other entry of the real starting value (RC4, DES, 3DES_EDE_CBC, anon, NULL,
+ // ecdsa_sha1/dsa_sha1 usage HandshakeSignature, ...) survives untouched.
+ for (String entry : disabledBefore) {
+ if (!legacyEntries.contains(entry)) {
+ assertTrue(disabledAfter.contains(entry), entry + " must stay disabled");
+ }
+ }
+
+ Set<String> legacyAfter = upperCasedEntries(Security.getProperty("jdk.tls.legacyAlgorithms"));
+ for (String entry : upperCasedEntries(originalLegacy)) {
+ assertTrue(legacyAfter.contains(entry), entry + " must stay legacy");
+ }
+ // The static-RSA entries move over when the running JRE disables them (Temurin 21
+ // does; older 21 updates do not list them, and then there is nothing to demote).
+ for (String demoted : List.of("TLS_RSA_*", "RSA_PKCS1_SHA1 USAGE HANDSHAKESIGNATURE")) {
+ if (disabledBefore.contains(demoted)) {
+ assertTrue(legacyAfter.contains(demoted), demoted + " must become legacy");
+ } else {
+ assertFalse(legacyAfter.contains(demoted));
+ }
+ }
+ } finally {
+ Security.setProperty("jdk.tls.disabledAlgorithms", originalDisabled);
+ Security.setProperty("jdk.tls.legacyAlgorithms",
+ originalLegacy == null ? "" : originalLegacy);
+ }
+ }
+
+ @Test
+ void legacyTlsPolicyRelaxationRequiresExplicitOptIn() {
+ String originalDisabled = Security.getProperty("jdk.tls.disabledAlgorithms");
+ String originalLegacy = Security.getProperty("jdk.tls.legacyAlgorithms");
+ boolean rsaDemotable = upperCasedEntries(originalDisabled).contains("TLS_RSA_*");
+ try {
+ // Without the option the policy must stay at the JRE defaults.
+ JsonObject plain = minimalConnection();
+ plain.addProperty("ssl", true);
+ MongoAgent.configureBuilder(plain).build();
+ assertEquals(originalDisabled, Security.getProperty("jdk.tls.disabledAlgorithms"));
+ assertEquals(originalLegacy, Security.getProperty("jdk.tls.legacyAlgorithms"));
+
+ // The option without TLS must not relax anything either.
+ JsonObject noTls = minimalConnection();
+ noTls.addProperty("url_params", "tlsAllowLegacyProtocols=true");
+ MongoAgent.configureBuilder(noTls).build();
+ assertEquals(originalDisabled, Security.getProperty("jdk.tls.disabledAlgorithms"));
+ assertEquals(originalLegacy, Security.getProperty("jdk.tls.legacyAlgorithms"));
+
+ // With TLS and the option the policy is relaxed process-wide.
+ JsonObject legacy = minimalConnection();
+ legacy.addProperty("ssl", true);
+ legacy.addProperty("url_params", "tlsAllowLegacyProtocols=true");
+ MongoAgent.configureBuilder(legacy).build();
+ assertFalse(upperCasedEntries(Security.getProperty("jdk.tls.disabledAlgorithms")).contains("TLSV1"));
+ assertEquals(rsaDemotable,
+ upperCasedEntries(Security.getProperty("jdk.tls.legacyAlgorithms")).contains("TLS_RSA_*"));
+
+ // The same option works inside a connection string.
+ Security.setProperty("jdk.tls.disabledAlgorithms", originalDisabled);
+ Security.setProperty("jdk.tls.legacyAlgorithms", originalLegacy);
+ JsonObject legacyUri = new JsonObject();
+ legacyUri.addProperty("connection_string",
+ "mongodb://127.0.0.1:27017/?ssl=true&tlsAllowLegacyProtocols=true");
+ MongoAgent.configureBuilder(legacyUri).build();
+ assertFalse(upperCasedEntries(Security.getProperty("jdk.tls.disabledAlgorithms")).contains("TLSV1.1"));
+ assertEquals(rsaDemotable,
+ upperCasedEntries(Security.getProperty("jdk.tls.legacyAlgorithms")).contains("TLS_RSA_*"));
+ } finally {
+ Security.setProperty("jdk.tls.disabledAlgorithms", originalDisabled);
+ Security.setProperty("jdk.tls.legacyAlgorithms",
+ originalLegacy == null ? "" : originalLegacy);
+ }
+ }
+
+ @Test
+ void relaxLegacyTlsPolicyDemotesRsaEntriesOnTemurinShapedPolicy() {
+ // Temurin 21 disables more entries than older 21 updates; seed that exact shape so
+ // the demotion path runs against live properties even on a JRE without the entries.
+ String temurinDisabled = "SSLv3, TLSv1, TLSv1.1, DTLSv1.0, RC4, DES, MD5withRSA, "
+ + "DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, ECDH, "
+ + "TLS_RSA_*, rsa_pkcs1_sha1 usage HandshakeSignature, "
+ + "ecdsa_sha1 usage HandshakeSignature, dsa_sha1 usage HandshakeSignature";
+ String originalDisabled = Security.getProperty("jdk.tls.disabledAlgorithms");
+ String originalLegacy = Security.getProperty("jdk.tls.legacyAlgorithms");
+ try {
+ Security.setProperty("jdk.tls.disabledAlgorithms", temurinDisabled);
+ Security.setProperty("jdk.tls.legacyAlgorithms", "NULL, anon, RC4, DES, 3DES_EDE_CBC");
+
+ MongoAgent.relaxLegacyTlsPolicy();
+
+ assertEquals(
+ "SSLv3, DTLSv1.0, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, "
+ + "3DES_EDE_CBC, anon, NULL, ECDH, "
+ + "ecdsa_sha1 usage HandshakeSignature, dsa_sha1 usage HandshakeSignature",
+ Security.getProperty("jdk.tls.disabledAlgorithms"));
+ assertEquals(
+ "NULL, anon, RC4, DES, 3DES_EDE_CBC, TLS_RSA_*, rsa_pkcs1_sha1 usage HandshakeSignature",
+ Security.getProperty("jdk.tls.legacyAlgorithms"));
+ } finally {
+ Security.setProperty("jdk.tls.disabledAlgorithms", originalDisabled);
+ Security.setProperty("jdk.tls.legacyAlgorithms",
+ originalLegacy == null ? "" : originalLegacy);
+ }
+ }
+
+ private static Set<String> upperCasedEntries(String property) {
+ if (property == null || property.isBlank()) {
+ return Set.of();
+ }
+ Set<String> entries = new HashSet<>();
+ for (String part : property.split(",")) {
+ if (!part.isBlank()) {
+ entries.add(part.trim().toUpperCase(Locale.ROOT));
+ }
+ }
+ return entries;
+ }
+
+ @Test
+ void sslContextInstalledInSettingsTrustsSelfSignedServer() throws Exception {
+ JsonObject connection = minimalConnection();
+ connection.addProperty("ssl", true);
+ connection.addProperty("url_params", "tlsAllowInvalidCertificates=true");
+
+ MongoClientSettings settings = MongoAgent.configureBuilder(connection).build();
+ SSLContext clientContext = settings.getSslSettings().getContext();
+ assertNotNull(clientContext);
+
+ SSLContext serverContext = SSLContext.getInstance("TLS");
+ serverContext.init(
+ MongoAgent.loadKeyManagersFromPem(clientPemPath.toString(), clientKeyPath.toString()),
+ null, null);
+ AtomicReference<Exception> serverError = new AtomicReference<>();
+ try (SSLServerSocket server = (SSLServerSocket) serverContext
+ .getServerSocketFactory()
+ .createServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ Thread serverThread = new Thread(() -> {
+ try (SSLSocket socket = (SSLSocket) server.accept()) {
+ socket.getOutputStream().write(42);
+ socket.getOutputStream().flush();
+ } catch (Exception e) {
+ serverError.set(e);
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ // The default JRE trust store would reject this self-signed certificate; the
+ // context installed into SslSettings must carry the trust-all manager.
+ try (SSLSocket client = (SSLSocket) clientContext
+ .getSocketFactory()
+ .createSocket("127.0.0.1", server.getLocalPort())) {
+ client.setSoTimeout(10_000);
+ assertEquals(42, client.getInputStream().read());
+ }
+ serverThread.join(10_000);
+ }
+ assertNull(serverError.get());
+ }
+
// ─── TLS: trust manager loading ───
@Test