This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 916631b9a1a3 CAMEL-27346: camel-mongodb - SslAwareMongoClient has a 
readPreference property and percent-encodes the username and password (#30554)
916631b9a1a3 is described below

commit 916631b9a1a35e2469e1563800dcbdf0381342fe
Author: Claus Ibsen <[email protected]>
AuthorDate: Sat Nov 21 18:40:56 2026 +0100

    CAMEL-27346: camel-mongodb - SslAwareMongoClient has a readPreference 
property and percent-encodes the username and password (#30554)
    
    SslAwareMongoClient gets a readPreference property, and the username and 
password are percent-encoded in the connection string it builds, so credentials 
with reserved characters work.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../camel/catalog/docs/mongodb-component.adoc      |   5 +
 .../src/main/docs/mongodb-component.adoc           |   5 +
 .../camel/component/mongodb/MongoDbEndpoint.java   |  13 +-
 .../component/mongodb/SslAwareMongoClient.java     |  85 +++++++----
 .../component/mongodb/SslAwareMongoClientTest.java | 167 +++++++++++++++++++++
 .../mongodb/integration/SslAwareMongoClientIT.java |  95 ++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   8 +
 7 files changed, 349 insertions(+), 29 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
index 2c1b68aeaa93..724c83a6ae78 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
@@ -98,6 +98,11 @@ These options cannot change a `MongoClient` the endpoint did 
not create (set wit
 or from the registry). Configure such a client with its own 
`MongoClientSettings`. In that case the endpoint logs a WARN
 that lists the options it does not use.
 
+The `org.apache.camel.component.mongodb.SslAwareMongoClient` client, which the 
MongoDB Kamelets create as a bean, has
+the properties `hosts`, `username`, `password` (of a user defined in the 
`admin` database), `ssl`,
+`sslValidationEnabled` and `readPreference` (the same values as the endpoint 
option). The username and password are
+given as they are: the client percent-encodes them.
+
 // component options: START
 include::partial$component-configure-options.adoc[]
 include::partial$component-endpoint-options.adoc[]
diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc 
b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index 2c1b68aeaa93..724c83a6ae78 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -98,6 +98,11 @@ These options cannot change a `MongoClient` the endpoint did 
not create (set wit
 or from the registry). Configure such a client with its own 
`MongoClientSettings`. In that case the endpoint logs a WARN
 that lists the options it does not use.
 
+The `org.apache.camel.component.mongodb.SslAwareMongoClient` client, which the 
MongoDB Kamelets create as a bean, has
+the properties `hosts`, `username`, `password` (of a user defined in the 
`admin` database), `ssl`,
+`sslValidationEnabled` and `readPreference` (the same values as the endpoint 
option). The username and password are
+given as they are: the client percent-encodes them.
+
 // component options: START
 include::partial$component-configure-options.adoc[]
 include::partial$component-endpoint-options.adoc[]
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
index 2116b4eeac01..425dbcd870fb 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
@@ -1142,10 +1142,19 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
         if (readPreference == null) {
             return ReadPreference.primary();
         }
+        return toReadPreference(readPreference);
+    }
+
+    /**
+     * The read preference of a readPreference value: PRIMARY, 
PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED,
+     * NEAREST, or a driver name such as secondaryPreferred.
+     *
+     * @throws IllegalArgumentException if the value is unknown
+     */
+    static ReadPreference toReadPreference(String name) {
         // PRIMARY_PREFERRED and SECONDARY_PREFERRED are the documented 
values, the driver knows them without the
         // underscore (primaryPreferred, secondaryPreferred), case-insensitive
-        // will throw an IllegalArgumentException if the input is incorrect
-        return ReadPreference.valueOf(readPreference.replace("_", ""));
+        return ReadPreference.valueOf(name.replace("_", ""));
     }
 
     public String getUsername() {
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/SslAwareMongoClient.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/SslAwareMongoClient.java
index 14132b51b06c..5d14340aaa03 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/SslAwareMongoClient.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/SslAwareMongoClient.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.mongodb;
 
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
@@ -64,33 +66,7 @@ public class SslAwareMongoClient implements MongoClient {
     private final Supplier<MongoClient> wrappedMongoClient = 
Suppliers.memorize(new Supplier<MongoClient>() {
         @Override
         public MongoClient get() {
-            String credentials = username == null ? "" : username;
-
-            if (!credentials.isEmpty()) {
-                credentials += password == null ? "@" : ":" + password + "@";
-            }
-
-            MongoClientSettings settings = MongoClientSettings.builder()
-                    .applyToSslSettings(builder -> {
-                        builder.enabled(ssl);
-                        if (!sslValidationEnabled) {
-                            builder.invalidHostNameAllowed(true);
-                            SSLContext sc = null;
-                            try {
-                                sc = SSLContext.getInstance("TLS");
-                            } catch (NoSuchAlgorithmException e) {
-                                throw new RuntimeException("Error 
instantiating trust all SSL context.", e);
-                            }
-                            try {
-                                sc.init(null, trustAllCerts, new 
SecureRandom());
-                            } catch (KeyManagementException e) {
-                                throw new RuntimeException("Error 
instantiating trust all SSL context.", e);
-                            }
-                            builder.context(sc);
-                        }
-                    })
-                    .applyConnectionString(new 
ConnectionString(String.format("mongodb://%s%s", credentials, hosts)))
-                    .build();
+            MongoClientSettings settings = createSettings();
             LOG.info("Connection created using provided credentials");
             return MongoClients.create(settings);
         }
@@ -101,6 +77,51 @@ public class SslAwareMongoClient implements MongoClient {
     private boolean ssl = true;
 
     private boolean sslValidationEnabled = true;
+    private String readPreference;
+
+    /**
+     * The settings of the client: the hosts, the credentials (authenticated 
against the admin database), TLS and the
+     * read preference. Package-private so the unit tests can check the 
settings without creating a client.
+     */
+    MongoClientSettings createSettings() {
+        // the username and password are percent-encoded, so characters such 
as @ : / ? % reach the server as they are
+        String credentials = username == null ? "" : encode(username);
+
+        if (!credentials.isEmpty()) {
+            credentials += password == null ? "@" : ":" + encode(password) + 
"@";
+        }
+
+        MongoClientSettings.Builder builder = MongoClientSettings.builder()
+                .applyToSslSettings(sslSettings -> {
+                    sslSettings.enabled(ssl);
+                    if (!sslValidationEnabled) {
+                        sslSettings.invalidHostNameAllowed(true);
+                        SSLContext sc = null;
+                        try {
+                            sc = SSLContext.getInstance("TLS");
+                        } catch (NoSuchAlgorithmException e) {
+                            throw new RuntimeException("Error instantiating 
trust all SSL context.", e);
+                        }
+                        try {
+                            sc.init(null, trustAllCerts, new SecureRandom());
+                        } catch (KeyManagementException e) {
+                            throw new RuntimeException("Error instantiating 
trust all SSL context.", e);
+                        }
+                        sslSettings.context(sc);
+                    }
+                })
+                .applyConnectionString(new 
ConnectionString(String.format("mongodb://%s%s", credentials, hosts)));
+        if (readPreference != null && !readPreference.isBlank()) {
+            // will throw an IllegalArgumentException if the value is unknown
+            
builder.readPreference(MongoDbEndpoint.toReadPreference(readPreference.trim()));
+        }
+        return builder.build();
+    }
+
+    private static String encode(String value) {
+        // the driver decodes a + as a +, not as a space: a space must be %20 
(URLEncoder writes a + as %2B)
+        return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", 
"%20");
+    }
 
     public MongoClient getWrappedMongoClient() {
         return wrappedMongoClient.get();
@@ -319,6 +340,16 @@ public class SslAwareMongoClient implements MongoClient {
         this.sslValidationEnabled = sslValidationEnabled;
     }
 
+    /**
+     * How the client routes read operations to the members of a replica set: 
PRIMARY, PRIMARY_PREFERRED, SECONDARY,
+     * SECONDARY_PREFERRED or NEAREST (the driver names such as 
secondaryPreferred are accepted too). Not set: the
+     * driver default (primary). An unknown value fails when the client is 
created. There is no getter for the value:
+     * {@link #getReadPreference()} of {@link MongoClient} returns the read 
preference of the client.
+     */
+    public void setReadPreference(String readPreference) {
+        this.readPreference = readPreference;
+    }
+
     @Override
     public void appendMetadata(MongoDriverInformation mongoDriverInformation) {
 
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/SslAwareMongoClientTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/SslAwareMongoClientTest.java
new file mode 100644
index 000000000000..8df5021a8fce
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/SslAwareMongoClientTest.java
@@ -0,0 +1,167 @@
+/*
+ * 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.camel.component.mongodb;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.MongoCredential;
+import com.mongodb.ReadPreference;
+import com.mongodb.ServerAddress;
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.PropertyBindingSupport;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The settings of the client the MongoDB Kamelets create as a bean: the read 
preference, and the credentials with
+ * characters a connection string must percent-encode.
+ */
+class SslAwareMongoClientTest {
+
+    private static final List<ServerAddress> HOSTS
+            = List.of(new ServerAddress("host1", 27017), new 
ServerAddress("host2", 27017));
+
+    private static SslAwareMongoClient client(String username, String 
password) {
+        SslAwareMongoClient client = new SslAwareMongoClient();
+        client.setHosts("host1:27017,host2:27017");
+        client.setUsername(username);
+        client.setPassword(password);
+        client.setSsl(false);
+        return client;
+    }
+
+    @Test
+    void readPreferenceNotSetIsPrimary() {
+        MongoClientSettings settings = client(null, null).createSettings();
+
+        assertEquals(ReadPreference.primary(), settings.getReadPreference());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "", "  " })
+    void blankReadPreferenceIsPrimary(String value) {
+        SslAwareMongoClient client = client(null, null);
+        client.setReadPreference(value);
+
+        assertEquals(ReadPreference.primary(), 
client.createSettings().getReadPreference());
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+            "PRIMARY, primary",
+            "PRIMARY_PREFERRED, primaryPreferred",
+            "SECONDARY, secondary",
+            "SECONDARY_PREFERRED, secondaryPreferred",
+            "NEAREST, nearest",
+            "secondaryPreferred, secondaryPreferred",
+            "nearest, nearest" })
+    void readPreferenceIsApplied(String value, String driverName) {
+        SslAwareMongoClient client = client(null, null);
+        client.setReadPreference(value);
+
+        assertEquals(ReadPreference.valueOf(driverName), 
client.createSettings().getReadPreference());
+    }
+
+    @Test
+    void readPreferenceOfTheClient() {
+        SslAwareMongoClient client = client(null, null);
+        client.setReadPreference("SECONDARY_PREFERRED");
+        try {
+            // creating the client does not connect to the hosts
+            assertEquals(ReadPreference.secondaryPreferred(), 
client.getReadPreference());
+        } finally {
+            client.close();
+        }
+    }
+
+    @Test
+    void propertiesAreBoundAsInTheKamelets() throws Exception {
+        // the Kamelets configure the client as a bean with properties
+        SslAwareMongoClient client = new SslAwareMongoClient();
+        Map<String, Object> properties = new HashMap<>();
+        properties.put("hosts", "host1:27017");
+        properties.put("username", "scott");
+        properties.put("password", "t@ger:/?%");
+        properties.put("ssl", "false");
+        properties.put("readPreference", "SECONDARY_PREFERRED");
+        try (CamelContext context = new DefaultCamelContext()) {
+            
PropertyBindingSupport.build().withReflection(true).withMandatory(true).bind(context,
 client, properties);
+        }
+
+        MongoClientSettings settings = client.createSettings();
+        assertEquals(ReadPreference.secondaryPreferred(), 
settings.getReadPreference());
+        assertArrayEquals("t@ger:/?%".toCharArray(), 
settings.getCredential().getPassword());
+        assertFalse(settings.getSslSettings().isEnabled());
+    }
+
+    @Test
+    void unknownReadPreferenceFails() {
+        SslAwareMongoClient client = client(null, null);
+        client.setReadPreference("SOMEWHERE");
+
+        IllegalArgumentException e = 
assertThrows(IllegalArgumentException.class, client::createSettings);
+        assertTrue(e.getMessage().contains("SOMEWHERE"), e.getMessage());
+    }
+
+    @Test
+    void noUsernameHasNoCredential() {
+        MongoClientSettings settings = client(null, null).createSettings();
+
+        assertNull(settings.getCredential());
+        assertEquals(HOSTS, settings.getClusterSettings().getHosts());
+    }
+
+    @Test
+    void credentialIsAuthenticatedAgainstTheAdminDatabase() {
+        MongoCredential credential = client("scott", 
"tiger").createSettings().getCredential();
+
+        assertEquals("scott", credential.getUserName());
+        assertArrayEquals("tiger".toCharArray(), credential.getPassword());
+        assertEquals("admin", credential.getSource());
+        assertNull(credential.getAuthenticationMechanism());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "p@ss", "p:ss", "p/ss", "p?ss", "p%ss", "p%41ss", 
"p+s s#&=", "@:/?%", "pässwörd" })
+    void passwordIsGivenAsIs(String password) {
+        MongoClientSettings settings = client("scott", 
password).createSettings();
+
+        assertArrayEquals(password.toCharArray(), 
settings.getCredential().getPassword());
+        assertEquals(HOSTS, settings.getClusterSettings().getHosts());
+    }
+
+    @Test
+    void usernameIsGivenAsIs() {
+        MongoCredential credential = client("us@er:/?%41", 
"tiger").createSettings().getCredential();
+
+        assertEquals("us@er:/?%41", credential.getUserName());
+        assertArrayEquals("tiger".toCharArray(), credential.getPassword());
+    }
+}
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/SslAwareMongoClientIT.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/SslAwareMongoClientIT.java
new file mode 100644
index 000000000000..e8e4be685769
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/SslAwareMongoClientIT.java
@@ -0,0 +1,95 @@
+/*
+ * 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.camel.component.mongodb.integration;
+
+import com.mongodb.MongoSecurityException;
+import com.mongodb.ReadPreference;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.mongodb.MongoDbEndpoint;
+import org.apache.camel.component.mongodb.SslAwareMongoClient;
+import org.apache.camel.test.infra.core.annotations.ContextFixture;
+import org.bson.Document;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The client the MongoDB Kamelets create as a bean: it logs in with a 
password that has characters a connection string
+ * must percent-encode, and reads with its read preference.
+ */
+// public: the ContextFixture of the test-infra is called by reflection
+public class SslAwareMongoClientIT extends AbstractMongoDbITSupport {
+
+    private static final String KAMELET_USER = "kamelet-user";
+    private static final String KAMELET_PASSWORD = "p@ss:w/o?r%d %41";
+
+    private static SslAwareMongoClient kameletClient;
+
+    private static SslAwareMongoClient client(String password) {
+        SslAwareMongoClient client = new SslAwareMongoClient();
+        client.setHosts(service.getConnectionAddress());
+        client.setUsername(KAMELET_USER);
+        client.setPassword(password);
+        client.setSsl(false);
+        return client;
+    }
+
+    @ContextFixture
+    @Override
+    public void configureContext(CamelContext context) throws Exception {
+        super.configureContext(context);
+        // a user defined in the admin database, as the Kamelets document
+        createAuthorizationUser("admin", KAMELET_USER, KAMELET_PASSWORD);
+
+        kameletClient = client(KAMELET_PASSWORD);
+        kameletClient.setReadPreference("SECONDARY_PREFERRED");
+        context.getRegistry().bind("kameletClient", kameletClient);
+    }
+
+    @AfterAll
+    static void closeKameletClient() {
+        // the endpoint does not close a client it did not create
+        if (kameletClient != null) {
+            kameletClient.close();
+            kameletClient = null;
+        }
+    }
+
+    @Test
+    void readsWithTheReadPreferenceOfTheClient() {
+        testCollection.insertOne(new Document("a", 1));
+        MongoDbEndpoint endpoint = context.getEndpoint(
+                
"mongodb:kameletClient?database={{mongodb.testDb}}&collection={{mongodb.testCollection}}&operation=count",
+                MongoDbEndpoint.class);
+
+        Long count = template.requestBody(endpoint, "{}", Long.class);
+
+        assertEquals(1L, count);
+        assertEquals(ReadPreference.secondaryPreferred(), 
endpoint.getMongoCollection().getReadPreference());
+    }
+
+    @Test
+    void wrongPasswordFailsToLogIn() {
+        // the server checks the credentials, so the test above logged in with 
the password as it is
+        try (SslAwareMongoClient client = client("p@ss:w/o?r%d A")) {
+            assertThrows(MongoSecurityException.class,
+                    () -> 
client.getDatabase(dbName).getCollection(testCollectionName).countDocuments());
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index ef2b4e5fc4bf..e95fd3c6f009 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -7598,6 +7598,14 @@ The options cannot change a `MongoClient` the endpoint 
did not create (set with
 from the registry). Such an endpoint now logs a WARN that lists the options it 
does not use; configure them on the
 `MongoClient` instead.
 
+=== camel-mongodb - SslAwareMongoClient percent-encodes the username and 
password
+
+`org.apache.camel.component.mongodb.SslAwareMongoClient` (the client the 
MongoDB Kamelets create) put the username and
+password into its connection string without percent-encoding them. A password 
with `@`, `:`, `/`, `?` or `%` failed to
+connect, and an encoded sequence such as `%41` was decoded, so the client 
logged in with another password. The client
+now encodes both itself: give the username and password as they are. A 
password that was percent-encoded by hand to
+work around this (for example `p%40ss` for `p@ss`) must now be given unencoded.
+
 === camel-mongodb-gridfs - the consumer routes a file once, offers the file of 
a failed exchange again and sets CamelFileName, and an unknown operation fails
 
 With the `TimeStamp` (default) and `PersistentTimestamp` query strategies, the 
`mongodb-gridfs` consumer routed

Reply via email to