[JAVA-4912] Driver does not prevent application startup for wrong credentials Created: 20/Mar/23  Updated: 27/Oct/23  Resolved: 28/Mar/23

Status: Closed
Project: Java Driver
Component/s: Authentication
Affects Version/s: None
Fix Version/s: None

Type: Question Priority: Major - P3
Reporter: Sanjay Kumar Assignee: Jeffrey Yemin
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Documentation Changes Summary:

1. What would you like to communicate to the user about this feature?
2. Would you like the user to see examples of the syntax and/or executable code and its output?
3. Which versions of the driver/connector does this apply to?


 Description   

Summary

Hi Team,

We are using spring boot version 2.7.1,  driver version 4.9 and java version 11 and MongoDB Atlas version 5 sharded cluster.

Now, normally when a spring/boot application starts up, it tries to connect to dependent resources. in our case MongoDB Atlas, and if
the credentials are wrong then the startup fails. This is expected behavior.

But in our case for the given spring boot version the startup does not fails if the creds are wrong. In logs (root level info mode) it shows successfully connected to given Mongodb Atlas server and even listed down the different host information in our sharded cluster.

But when you hit the health endpoint, it will show application status as down.

Note, we have defined a custom MongoClient as the the uri for Managed MongoDB (Atlas) start as mongodb+srv://

  @Bean
      public MongoClient mongoClient()

{           return MongoClients.create(mongoClientSettings());       }

      private MongoClientSettings mongoClientSettings()

{           return MongoClientSettings.builder()                   .applyConnectionString(new ConnectionString(generateConnectionURI()))                   .build();          }

    
     private String generateConnectionURI()

{         return "mongodb+srv://"                 + username                 + ":"                 + password                 + "@"                 + hostname                 + "/?retryWrites="                 + true                 + "&w="                 + majority;     }

How to Reproduce

Regarding sample code,
You can simple replicate this issue by creating a demo project from start.spring.io having dependency of mongo, rest, actuator and creating a custom MongoClient as shown above and provide a valid Mongo Atlas uri and wrong creds.
Same problem is there with other version of Spring boot. You can test it with 2.7.9 version of spring boot as well.

Additional Background

If I provide the wrong creds it fails silently and prints successfully connected message in the logs

 

2023-03-20 18:03:41.033  INFO 61240 — [ngodb.net:27016] org.mongodb.driver.connection            : Opened connection [connectionId\{localValue:11, serverValue:201556}] to dev-shard-01-00.bgj1m.mongodb.net:27016
2023-03-20 18:03:41.033  INFO 61240 — [ngodb.net:27016] org.mongodb.driver.connection            : Opened connection [connectionId\{localValue:8, serverValue:193485}] to dev-shard-00-01.bgj1m.mongodb.net:27016
2023-03-20 18:03:41.038  INFO 61240 — [ngodb.net:27016] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=dev-shard-00-01.bgj1m.mongodb.net:27016, type=SHARD_ROUTER, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=402444800}
2023-03-20 18:03:41.038  INFO 61240 — [ngodb.net:27016] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=dev-shard-00-02.bgj1m.mongodb.net:27016, type=SHARD_ROUTER, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=407949900}
2023-03-20 18:03:41.045  INFO 61240 — [ngodb.net:27016] org.mongodb.driver.cluster               : Discovered cluster type of SHARDED
2023-03-20 18:03:41.724  INFO 61240 — [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2023-03-20 18:03:41.797  INFO 61240 — [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

 

 

But if I provide wrong host (MongoDB Atlas uri) it fails with unknown host, which implies that the mongo client did tried to reach out to the host.

 

023-03-20 18:07:30.906  INFO 84452 — [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2057 ms
2023-03-20 18:07:31.344  INFO 84452 — [j1m.mongodb.net] org.mongodb.driver.cluster               : Exception while resolving SRV records

com.mongodb.MongoConfigurationException: Failed looking up SRV record for '_mongodb._tcp.dev123-002.bgj1m.mongodb.net'.
    at com.mongodb.internal.dns.DefaultDnsResolver.resolveHostFromSrvRecords(DefaultDnsResolver.java:92) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.connection.DefaultDnsSrvRecordMonitor$DnsSrvRecordMonitorRunnable.run(DefaultDnsSrvRecordMonitor.java:80) ~[mongodb-driver-core-4.6.1.jar:na]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: com.mongodb.spi.dns.DnsWithResponseCodeException: DNS name not found [response code 3]
    at com.mongodb.internal.dns.JndiDnsClient.getResourceRecordData(JndiDnsClient.java:52) ~[mongodb-driver-core-4.6.1.jar:na]
    at com.mongodb.internal.dns.DefaultDnsResolver.resolveHostFromSrvRecords(DefaultDnsResolver.java:74) ~[mongodb-driver-core-4.6.1.jar:na]
    ... 2 common frames omitted
Caused by: javax.naming.NameNotFoundException: DNS name not found [response code 3]
    at jdk.naming.dns/com.sun.jndi.dns.DnsClient.checkResponseCode(DnsClient.java:661) ~[jdk.naming.dns:na]
    at jdk.naming.dns/com.sun.jndi.dns.DnsClient.isMatchResponse(DnsClient.java:579) ~[jdk.naming.dns:na]
    at jdk.naming.dns/com.sun.jndi.dns.DnsClient.doUdpQuery(DnsClient.java:427) ~[jdk.naming.dns:na]
    at jdk.naming.dns/com.sun.jndi.dns.DnsClient.query(DnsClient.java:212) ~[jdk.naming.dns:na]
    at jdk.naming.dns/com.sun.jndi.dns.Resolver.query(Resolver.java:81) ~[jdk.naming.dns:na]
    at jdk.naming.dns/com.sun.jndi.dns.DnsContext.c_getAttributes(DnsContext.java:434) ~[jdk.naming.dns:na]
    at java.naming/com.sun.jndi.toolkit.ctx.ComponentDirContext.p_getAttributes(ComponentDirContext.java:235) ~[na:na]
    at java.naming/com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.getAttributes(PartialCompositeDirContext.java:141) ~[na:na]
    at java.naming/com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.getAttributes(PartialCompositeDirContext.java:129) ~[na:na]
    at java.naming/javax.naming.directory.InitialDirContext.getAttributes(InitialDirContext.java:142) ~[na:na]
    at com.mongodb.internal.dns.JndiDnsClient.getResourceRecordData(JndiDnsClient.java:41) ~[mongodb-driver-core-4.6.1.jar:na]
Caused by: com.mongodb.spi.dns.DnsWithResponseCodeException: DNS name not found [response code 3]



 Comments   
Comment by Jeffrey Yemin [ 28/Mar/23 ]

Hi sanjaykmruk@gmail.com

When the application creates a MongoClient instance, the MongoClient constructor returns immediately, before doing any I/O. Rather, it starts some background threads that attempt to connect to all the servers in the host list, and also discover any servers (i.e. other replica set members) not mentioned in the host list. So those background thread do DNS lookup, and will log any DNS lookup failures as well as connectivity failures. That logging is what you're seeing. However, those threads don't actually authenticate the connections it makes for this discovery and monitoring. Rather, authentication is deferred until the application attempts to execute an operation, via a call to some method that requires sending a command to the server (e.g. a generic method like runCommand, a CRUD method like insertOne, or an admin method like listIndexes).

So if you want to ensure all mis-configuration is detected at startup, you should make sure that you execute some operation, e.g:

var client = MongoClients.create(...);
client.getDatabase("admin").runCommand(new Document("ping", 1));

and the call to runCommand will throw an exception for DNS lookup failure, connectivity issues, and authentication failure.

You can read some of the justification for this behavior here.

Generated at Thu Feb 08 09:03:16 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.