fix(mongodb): treat SRV URLs as seed lists

This commit is contained in:
t8y2 committed 2026-07-02 00:49:05 +08:00
1 parent 58e2d983c2
commit bd659c322c
2 files changed
+37

No files matched your search

+15
View File
@@ -73,6 +73,11 @@ fn normalize_mongo_uri_direct_connection(uri: &str) -> String {
}
fn is_multi_host_mongo_uri(url: &str) -> bool {
if url.get(..14).is_some_and(|scheme| scheme.eq_ignore_ascii_case("mongodb+srv://")) {
// SRV URLs expand to a DNS seed list during driver parsing, so forcing
// directConnection would be rejected even though the URI shows one host.
return true;
}
let rest = match url.strip_prefix("mongodb://").or_else(|| url.strip_prefix("mongodb+srv://")) {
Some(r) => r,
None => return false,
@@ -925,6 +930,16 @@ mod tests {
assert_eq!(normalized, "mongodb://host1:27017,host2:27017/admin?authSource=admin#read");
}
#[test]
fn srv_uri_removes_direct_connection_true_before_driver_parse() {
let uri = "mongodb+srv://read:pass@cluster.example.net/admin?tls=true&directConnection=true&replicaSet=rs0";
let normalized = normalize_mongo_uri_direct_connection(uri);
assert_eq!(normalized, "mongodb+srv://read:pass@cluster.example.net/admin?tls=true&replicaSet=rs0");
assert!(is_multi_host_mongo_uri(&normalized));
}
#[test]
fn single_seed_uri_keeps_direct_connection_true() {
let uri = "mongodb://host1:27017/admin?directConnection=true&authSource=admin";
+22
View File
@@ -1245,11 +1245,20 @@ fn normalize_mongo_uri_query_path(uri: &str) -> String {
}
fn mongo_uri_has_multiple_seeds(uri: &str) -> bool {
if mongo_uri_is_srv(uri) {
// The Rust MongoDB driver resolves SRV records into a seed list, so an
// SRV URL must not keep directConnection=true even with one hostname.
return true;
}
mongo_uri_host_section(uri)
.map(|hosts| hosts.split(',').filter(|host| !host.trim().is_empty()).count() > 1)
.unwrap_or(false)
}
fn mongo_uri_is_srv(uri: &str) -> bool {
uri.get(..14).is_some_and(|scheme| scheme.eq_ignore_ascii_case("mongodb+srv://"))
}
fn mongo_uri_host_section(uri: &str) -> Option<&str> {
let rest = uri.strip_prefix("mongodb://").or_else(|| uri.strip_prefix("mongodb+srv://"))?;
let authority = rest.split('/').next()?.split('?').next().unwrap_or(rest);
@@ -2409,6 +2418,19 @@ mod tests {
assert_eq!(url, "mongodb://read:pass@host1:27017,host2:27017/admin?replicaSet=rs0&authSource=admin");
}
#[test]
fn mongodb_srv_connection_string_removes_direct_connection_true() {
let mut config = mongodb_config("root", "secret", Some("admin"));
config.connection_string = Some(
"mongodb+srv://read:pass@cluster.example.net/admin?tls=true&authSource=admin&directConnection=true&replicaSet=rs0"
.to_string(),
);
let url = config.connection_url();
assert_eq!(url, "mongodb+srv://read:pass@cluster.example.net/admin?tls=true&authSource=admin&replicaSet=rs0");
}
#[test]
fn mongodb_single_seed_connection_string_keeps_direct_connection_true() {
let mut config = mongodb_config("root", "secret", Some("admin"));