PKIX path building failed

Hi All,

I am trying to connect MongoDB , using simple Java code from windows 11 through Eclipse, and MongoDB is on a Linux machine.

But getting the PKIX path building failed error.

Added MongoDB root CA and server cert on truststore and keystore but still getting the same error.

Giving Java code and erorr details below, please do suggest how to fix issue.

Java code:

package MongoDBConnection_03262024.MongoDBConnection;

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.MongoDatabase;

public class AppTest
{

public static void main(String[] args) {
// Your MongoDB connection string obtained from Ops Manager
String connectionString = "mongodb://user_name:Password@server_name:port/?ssl=true";

// Create a connection string
ConnectionString connString = new ConnectionString(connectionString);

// Create a MongoDB client
try (MongoClient mongoClient = MongoClients.create(connString)) {
    // Get the list of database names
    MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();

    // Print each database name
    for (String dbName : databaseNames) {
        System.out.println("Database: " + dbName);
    }
} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
}

}
}

Error

12:11:38.819 [main] DEBUG org.mongodb.driver.cluster - Updating cluster description to {type=UNKNOWN, servers=[{address=SERVER_NAME:PORT, type=UNKNOWN, state=CONNECTING}]
12:11:38.841 [main] INFO org.mongodb.driver.client - MongoClient with metadata {“driver”: {“name”: “mongo-java-driver|sync”, “version”: “4.9.1”}, “os”: {“type”: “Windows”, “name”: “Windows 11”, “architecture”: “amd64”, “version”: “10.0”}, “platform”: “Java/Eclipse Adoptium/17.0.10+7”} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=MongoCredential{mechanism=null, userName=‘test’, source=‘admin’, password=, mechanismProperties=}, streamFactoryFactory=null, commandListeners=, codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, CollectionCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.client.model.mql.ExpressionCodecProvider@1757cd72, com.mongodb.Jep395RecordCodecProvider@445b295b]}, loggerSettings=LoggerSettings{maxDocumentLength=1000}, clusterSettings={hosts=[SERVER_NAME:PORT], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName=‘null’, serverSelector=‘null’, clusterListeners=‘’, serverSelectionTimeout=‘30000 ms’, localThreshold=‘30000 ms’}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, sendBufferSize=0}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, sendBufferSize=0}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=, maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners=‘’, serverMonitorListeners=‘’}, sslSettings=SslSettings{enabled=true, invalidHostNameAllowed=false, context=null}, applicationName=‘null’, compressorList=, uuidRepresentation=UNSPECIFIED, serverApi=null, autoEncryptionSettings=null, contextProvider=null}
12:11:38.855 [main] INFO org.mongodb.driver.cluster - Cluster description not yet available. Waiting for 30000 ms before timing out
12:11:39.105 [cluster-ClusterId{value=‘660f79fa2e7a0331dfea6fa3’, description=‘null’}-SERVER_NAME:PORT] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
12:11:39.105 [cluster-rtt-ClusterId{value=‘660f79fa2e7a0331dfea6fa3’, description=‘null’}-SERVER_NAME:PORT] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
12:11:39.109 [cluster-ClusterId{value=‘660f79fa2e7a0331dfea6fa3’, description=‘null’}-SERVER_NAME:PORT] INFO org.mongodb.driver.cluster - Exception in monitor thread while connecting to server iSERVER_NAME:PORTSERVER_NAME:PORT
com.mongodb.MongoSocketWriteException: Exception sending message
at com.mongodb.internal.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:706)
at com.mongodb.internal.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:580)
at com.mongodb.internal.connection.InternalStreamConnection.sendCommandMessage(InternalStreamConnection.java:411)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:357)
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:102)
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:49)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:129)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.startHandshake(InternalStreamConnectionInitializer.java:77)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:206)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:199)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:159)
at java.base/java.lang.Thread.run(Thread.java:840)
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:378)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:316)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:654)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369)
at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:396)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:480)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:458)
at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:201)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1510)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1425)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:455)
at java.base/sun.security.ssl.SSLSocketImpl.ensureNegotiated(SSLSocketImpl.java:925)
at java.base/sun.security.ssl.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:1295)
at com.mongodb.internal.connection.SocketStream.write(SocketStream.java:102)
at com.mongodb.internal.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:577)
… 10 common frames omitted

2 thoughts (maybe helpful, maybe not :man_shrugging:)

Natraj, how did you add these?
2.

"mongodb://user_name:Password@server_name:port/?ssl=true";

Try mongodb://user_name:Password@server_name:port?tls=true";

Hi @Jack_Woehr ,

Thanks for your reply.

  1. I added root and server cert using below command.

  2. Tried to connect with TLS below, but still getting same error.

“mongodb://user_name:Password@server_name:port/?tls=true”;

Am I missing anything ?

Looking at the stack trace, I’m not sure, but it looks like you’re simply not connecting to the server. Are you sure you can reach the server? Firewall, etc.?