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。

feat(mongodb): offer srv url for atlas cluster hosts

Loc Nguyenc345d1694add
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 3a7713758a..1ad594c470 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -88,7 +88,7 @@ import { firstZooKeeperEndpoint, normalizeZooKeeperConnectString } from "@/lib/z
import { setZooKeeperAuthScheme, zooKeeperAuthScheme as resolveZooKeeperAuthScheme, type ZooKeeperAuthScheme } from "@/lib/zookeeper/zookeeperConnectionOptions";
import { isLocalFileTypeDb } from "@/lib/connection/connectionFile";
import { MQ_PINNED_VERSION_OPTIONS, pinnedVersionToSelection, selectionToPinnedVersion } from "@/lib/mq/mqPinnedVersionOptions";
-import { mongodbAuthFailureHint, mongoConnectionUsesOidc, mongoUrlParam, mongoUrlParamIsTrue, normalizeMongoTlsFormState, setMongoUrlParam, setMongoUrlParamBoolean } from "@/lib/mongo/mongoConnectionOptions";
+import { looksLikeMongoSrvHost, mongodbAuthFailureHint, mongoConnectionUsesOidc, mongoSrvConnectionString, mongoUrlParam, mongoUrlParamIsTrue, normalizeMongoTlsFormState, setMongoUrlParam, setMongoUrlParamBoolean } from "@/lib/mongo/mongoConnectionOptions";
import { isMongoLegacyDriverProfile } from "@/lib/mongo/mongoCapabilities";
import { mysqlCleartextPasswordAuthEnabled, setMysqlCleartextPasswordAuthEnabled } from "@/lib/database/mysqlConnectionOptions";
import { supportsOracleDatabaseLinks } from "@/lib/database/oracleDatabaseLinks";
@@ -4427,6 +4427,11 @@ const mongoTlsAllowInvalidCertificates = computed({
form.value.url_params = next;
},
});
+const mongoSrvHostSuggested = computed(() => form.value.db_type === "mongodb" && !mongoUseUrl.value && looksLikeMongoSrvHost(form.value.host));
+function switchMongoFormToSrvUrl() {
+ form.value.connection_string = mongoSrvConnectionString(form.value);
+ mongoUseUrl.value = true;
+}
const mongoRetryWrites = computed({
get: () => mongoUrlParamIsTrue(form.value.url_params, "retryWrites", true),
set: (value: boolean) => {
@@ -8401,6 +8406,12 @@ function openExternalUrl(url: string) {
<Input v-model="form.host" class="col-span-2" />
<Input v-model.number="form.port" type="number" class="col-span-1" />
</div>
+ <div v-if="mongoSrvHostSuggested" class="grid grid-cols-4 items-start gap-4">
+ <div class="col-start-2 col-span-3 flex flex-col items-start gap-2 text-xs leading-5 text-muted-foreground">
+ <span>{{ t("connection.mongoSrvHostHint") }}</span>
+ <Button size="sm" variant="outline" @click="switchMongoFormToSrvUrl">{{ t("connection.mongoUseSrvUrl") }}</Button>
+ </div>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 text-sm">
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 22e7da5f7e..29031c0188 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -1384,6 +1384,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "tlsAllowInvalidCertificates=true parametrinə uyğundur və yalnız host adı yoxlamalarını deyil, bütün sertifikat yoxlamalarını deaktiv edir. Bu, MITM riskini artırır. SSH tuneli üzərindən AWS DocumentDB üçün adətən tələb olunur.",
mongoRetryWrites: "Yazma əməliyyatlarına yenidən cəhd et",
mongoRetryWritesHint: "retryWrites parametrinə uyğundur. Təkrar yazma cəhdlərini dəstəkləməyən AWS DocumentDB üçün deaktiv edin.",
+ mongoSrvHostHint: "Bu, yalnız SRV DNS qeydləri olan və host:port kimi qoşulmaq mümkün olmayan MongoDB Atlas klaster adına bənzəyir.",
+ mongoUseSrvUrl: "mongodb+srv:// URL istifadə et",
color: "Rəng",
colorNone: "Rəngsiz",
colorGreen: "Yaşıl",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index d9ecc63719..93af7ffb5f 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -2024,6 +2024,8 @@ export default {
mongoTlsAllowInvalidCertificatesHint: "Maps to tlsAllowInvalidCertificates=true and disables all certificate validation, not just hostname checks. This increases MITM risk. Commonly required for AWS DocumentDB over an SSH tunnel.",
mongoRetryWrites: "Retry writes",
mongoRetryWritesHint: "Maps to retryWrites. Disable for AWS DocumentDB, which does not support retryable writes.",
+ mongoSrvHostHint: "This looks like a MongoDB Atlas cluster name, which only has SRV DNS records and cannot be reached as host:port.",
+ mongoUseSrvUrl: "Use mongodb+srv:// URL",
color: "Color",
colorNone: "No color",
colorGreen: "Green",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index b009c85a61..60876271ff 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1602,6 +1602,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "Se asigna a tlsAllowInvalidCertificates=true y desactiva toda la validación de certificados, no solo la del nombre de host. Aumenta el riesgo de MITM. Suele ser necesario para AWS DocumentDB a través de un túnel SSH.",
mongoRetryWrites: "Reintentar escrituras",
mongoRetryWritesHint: "Se asigna a retryWrites. Desactívalo para AWS DocumentDB, que no admite escrituras reintentables.",
+ mongoSrvHostHint: "Parece el nombre de un clúster de MongoDB Atlas, que solo tiene registros DNS SRV y no se puede alcanzar como host:port.",
+ mongoUseSrvUrl: "Usar URL mongodb+srv://",
color: "Color",
colorNone: "Sin color",
colorGreen: "Verde",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index b9d1129ead..05291fa481 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -1650,6 +1650,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "Memetakan ke tlsAllowInvalidCertificates=true dan menonaktifkan semua validasi sertifikat, bukan hanya pemeriksaan hostname. Ini meningkatkan risiko MITM. Umumnya diperlukan untuk AWS DocumentDB melalui tunnel SSH.",
mongoRetryWrites: "Coba ulang penulisan",
mongoRetryWritesHint: "Memetakan ke retryWrites. Nonaktifkan untuk AWS DocumentDB, yang tidak mendukung retryable writes.",
+ mongoSrvHostHint: "Ini tampaknya nama cluster MongoDB Atlas, yang hanya memiliki catatan DNS SRV dan tidak dapat dijangkau sebagai host:port.",
+ mongoUseSrvUrl: "Gunakan URL mongodb+srv://",
color: "Warna",
colorNone: "Tanpa warna",
colorGreen: "Hijau",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d9d68e713f..6052acd025 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1514,6 +1514,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "Corrisponde a tlsAllowInvalidCertificates=true e disabilita tutta la validazione del certificato, non solo il controllo dell'hostname. Aumenta il rischio MITM. Di solito è necessario per AWS DocumentDB tramite tunnel SSH.",
mongoRetryWrites: "Riprova scritture",
mongoRetryWritesHint: "Corrisponde a retryWrites. Disabilitalo per AWS DocumentDB, che non supporta scritture ripetibili.",
+ mongoSrvHostHint: "Sembra il nome di un cluster MongoDB Atlas, che ha solo record DNS SRV e non è raggiungibile come host:port.",
+ mongoUseSrvUrl: "Usa URL mongodb+srv://",
color: "Colore",
colorNone: "Nessun colore",
colorGreen: "Verde",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 9643044e05..976b1b1148 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1484,6 +1484,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "tlsAllowInvalidCertificates=true に対応し、ホスト名だけでなくすべての証明書検証を無効化します。MITM 攻撃のリスクが高まります。SSH トンネル経由の AWS DocumentDB では通常必要です。",
mongoRetryWrites: "書き込み再試行",
mongoRetryWritesHint: "retryWrites に対応します。AWS DocumentDB は再試行可能な書き込みをサポートしないため、無効にしてください。",
+ mongoSrvHostHint: "これは MongoDB Atlas のクラスター名のようです。SRV DNS レコードしかないため、host:port では接続できません。",
+ mongoUseSrvUrl: "mongodb+srv:// URL を使用",
color: "色",
colorNone: "色なし",
colorGreen: "緑",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 359a5281cc..1d6bb21fd9 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1686,6 +1686,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "tlsAllowInvalidCertificates=true에 매핑되며 호스트 이름 확인뿐만 아니라 모든 인증서 검증을 비활성화합니다. 이는 MITM 위험을 증가시킵니다. SSH 터널을 통한 AWS DocumentDB에 일반적으로 필요합니다.",
mongoRetryWrites: "쓰기 재시도",
mongoRetryWritesHint: "retryWrites에 매핑됩니다. 재시도 가능한 쓰기를 지원하지 않는 AWS DocumentDB의 경우 비활성화하세요.",
+ mongoSrvHostHint: "MongoDB Atlas 클러스터 이름으로 보입니다. SRV DNS 레코드만 있어 host:port로는 연결할 수 없습니다.",
+ mongoUseSrvUrl: "mongodb+srv:// URL 사용",
color: "색상",
colorNone: "색상 없음",
colorGreen: "초록",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 930ebd8b44..569b3a70cd 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1515,6 +1515,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "Corresponde a tlsAllowInvalidCertificates=true e desativa toda a validação de certificados, não apenas a do hostname. Aumenta o risco de MITM. Geralmente é necessário para AWS DocumentDB via túnel SSH.",
mongoRetryWrites: "Repetir gravações",
mongoRetryWritesHint: "Corresponde a retryWrites. Desative para AWS DocumentDB, que não suporta gravações repetíveis.",
+ mongoSrvHostHint: "Parece o nome de um cluster do MongoDB Atlas, que só tem registros DNS SRV e não pode ser acessado como host:port.",
+ mongoUseSrvUrl: "Usar URL mongodb+srv://",
color: "Cor",
colorNone: "Sem cor",
colorGreen: "Verde",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 95cb7b224d..d2e76debe1 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1786,6 +1786,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "Соответствует tlsAllowInvalidCertificates=true и отключает всю проверку сертификатов, а не только проверку имени хоста. Это повышает риск MITM. Часто требуется для AWS DocumentDB через SSH-туннель.",
mongoRetryWrites: "Повторять записи",
mongoRetryWritesHint: "Соответствует retryWrites. Отключите для AWS DocumentDB, который не поддерживает повторяемые записи.",
+ mongoSrvHostHint: "Похоже на имя кластера MongoDB Atlas: у него есть только DNS-записи SRV, и подключиться к нему как host:port нельзя.",
+ mongoUseSrvUrl: "Использовать URL mongodb+srv://",
color: "Цвет",
colorNone: "Без цвета",
colorGreen: "Зелёный",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 24242e4362..ee1ebdabb2 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -1985,6 +1985,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "แมปไปยัง tlsAllowInvalidCertificates=true และปิดการตรวจสอบใบรับรองทั้งหมด ไม่ใช่แค่การตรวจสอบ Hostname ซึ่งเพิ่มความเสี่ยง MITM โดยทั่วไปจำเป็นสำหรับ AWS DocumentDB ผ่าน SSH Tunnel",
mongoRetryWrites: "ลองเขียนอีกครั้ง",
mongoRetryWritesHint: "แมปไปยัง retryWrites ปิดใช้สำหรับ AWS DocumentDB ซึ่งไม่รองรับการเขียนแบบลองใหม่ได้",
+ mongoSrvHostHint: "ดูเหมือนเป็นชื่อคลัสเตอร์ MongoDB Atlas ซึ่งมีเฉพาะระเบียน DNS แบบ SRV และเชื่อมต่อแบบ host:port ไม่ได้",
+ mongoUseSrvUrl: "ใช้ URL mongodb+srv://",
color: "สี",
colorNone: "ไม่มีสี",
colorGreen: "เขียว",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index e22b92452a..9049e57c36 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -1384,6 +1384,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "tlsAllowInvalidCertificates=true ayarına karşılık gelir ve yalnızca sunucu adı denetimini değil, tüm sertifika doğrulamasını kapatır. Bu, MITM riskini artırır. SSH tüneli üzerinden AWS DocumentDB için genellikle gereklidir.",
mongoRetryWrites: "Yazmaları yeniden dene",
mongoRetryWritesHint: "retryWrites ayarına karşılık gelir. Yeniden denenebilir yazmaları desteklemeyen AWS DocumentDB için kapatın.",
+ mongoSrvHostHint: "Bu bir MongoDB Atlas küme adına benziyor; yalnızca SRV DNS kayıtları olduğundan host:port olarak erişilemez.",
+ mongoUseSrvUrl: "mongodb+srv:// URL kullan",
color: "Renk",
colorNone: "Renk yok",
colorGreen: "Yeşil",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 37e0da08ba..9cbb447546 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1962,6 +1962,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "对应 tlsAllowInvalidCertificates=true,会禁用全部证书校验(不仅是主机名),存在中间人攻击风险。经 SSH 隧道访问 AWS DocumentDB 时通常需要开启。",
mongoRetryWrites: "重试写入",
mongoRetryWritesHint: "对应 retryWrites。AWS DocumentDB 不支持可重试写入,请关闭。",
+ mongoSrvHostHint: "这看起来是 MongoDB Atlas 集群名称,它只有 SRV DNS 记录,无法以 host:port 方式连接。",
+ mongoUseSrvUrl: "改用 mongodb+srv:// URL",
color: "颜色",
colorNone: "无颜色",
colorGreen: "绿色",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 95206a2173..ab98091d08 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1524,6 +1524,8 @@ export default withEnglishFallback({
mongoTlsAllowInvalidCertificatesHint: "對應 tlsAllowInvalidCertificates=true,會停用全部憑證校驗(不只是主機名),存在中間人攻擊風險。經 SSH 隧道存取 AWS DocumentDB 時通常需要開啟。",
mongoRetryWrites: "重試寫入",
mongoRetryWritesHint: "對應 retryWrites。AWS DocumentDB 不支援可重試寫入,請關閉。",
+ mongoSrvHostHint: "這看起來是 MongoDB Atlas 叢集名稱,它只有 SRV DNS 記錄,無法以 host:port 方式連線。",
+ mongoUseSrvUrl: "改用 mongodb+srv:// URL",
color: "顏色",
colorNone: "無顏色",
colorGreen: "綠色",
diff --git a/apps/desktop/src/lib/mongo/mongoConnectionOptions.ts b/apps/desktop/src/lib/mongo/mongoConnectionOptions.ts
index 78783a946e..789bbbc928 100644
--- a/apps/desktop/src/lib/mongo/mongoConnectionOptions.ts
+++ b/apps/desktop/src/lib/mongo/mongoConnectionOptions.ts
@@ -54,6 +54,34 @@ export function normalizeMongoTlsFormState(ssl: boolean, urlParams: string | und
return { urlParams: next, caCertPath: "" };
}
+/**
+ * MongoDB Atlas cluster names (`cluster0.abcde.mongodb.net`) exist only as SRV
+ * records, so a plain `host:port` connection to them fails DNS lookup. Atlas's
+ * per-member hostnames (`…-shard-00-00.abcde.mongodb.net`) resolve normally.
+ */
+export function looksLikeMongoSrvHost(host: string | undefined): boolean {
+ const normalized = host?.trim().toLowerCase() ?? "";
+ return /^[a-z0-9-]+\.[a-z0-9-]+\.mongodb\.net\.?$/.test(normalized) && !normalized.includes("-shard-");
+}
+
+/** The form-mode fields as a `mongodb+srv://` URL; SRV carries no port and turns TLS on by default. */
+export function mongoSrvConnectionString(form: { host: string; username?: string; password?: string; database?: string; url_params?: string; ca_cert_path?: string }): string {
+ const params = parseMongoUrlParams(form.url_params);
+ // SRV discovers the members itself, and DBX's TLS defaults already come from the SRV scheme.
+ const droppedKeys = Array.from(params.keys()).filter((key) => ["directconnection", "tls", "ssl"].includes(key.toLowerCase()));
+ for (const key of droppedKeys) params.delete(key);
+ const caCertPath = form.ca_cert_path?.trim();
+ if (caCertPath && !params.has("tlsCAFile")) params.set("tlsCAFile", caCertPath);
+
+ const username = form.username?.trim() ?? "";
+ const usesOidc = mongoUrlParamCaseInsensitive(params.toString(), "authMechanism").toUpperCase() === "MONGODB-OIDC";
+ const userInfo = username ? `${encodeURIComponent(username)}${usesOidc ? "" : `:${encodeURIComponent(form.password ?? "")}`}@` : "";
+ const host = form.host.trim().replace(/:\d+$/, "");
+ const database = form.database?.trim();
+ const query = params.toString();
+ return `mongodb+srv://${userInfo}${host}/${database ? encodeURIComponent(database) : ""}${query ? `?${query}` : ""}`;
+}
+
export function mongodbAuthFailureHint(message: string): string {
const normalizedMessage = message.toLowerCase();
if (normalizedMessage.includes("tlsallowinvalidhostnames is an invalid option")) {
@@ -72,6 +100,11 @@ export function mongodbAuthFailureHint(message: string): string {
return `${message}\n\nMongoDB SRV URLs require a DNS hostname with SRV records. For an IP address or normal host:port endpoint, use mongodb://host:port instead of mongodb+srv://host.`;
}
+ const unresolvedHost = mongoUnresolvedHost(message);
+ if (unresolvedHost && looksLikeMongoSrvHost(unresolvedHost)) {
+ return `${message}\n\n${unresolvedHost} looks like a MongoDB Atlas cluster name, which only has SRV DNS records. Switch to URL mode and connect with mongodb+srv://${unresolvedHost} instead of host:port.`;
+ }
+
if (message.includes("ReplicaSetNoPrimary") && message.includes("127.0.0.1:27017")) {
return `${message}\n\nThe replica set is advertising 127.0.0.1:27017, which points back to this app machine instead of the MongoDB server. Add directConnection=true for a single reachable endpoint, or reconfigure the replica set members to advertise addresses reachable from this app.`;
}
@@ -95,6 +128,13 @@ export function mongodbAuthFailureHint(message: string): string {
return `${message}\n\n${verificationHint} If the user was created in admin, set Authentication database to admin or add authSource=admin to URL params.`;
}
+/** The host of a server-selection failure whose DNS lookup failed, as the driver reports it on each OS. */
+function mongoUnresolvedHost(message: string): string | null {
+ const lookupFailed = /os error 11001|no such host is known|failed to lookup address|nodename nor servname|name or service not known|不知道这样的主机/i.test(message);
+ if (!lookupFailed) return null;
+ return /Address:\s*([^\s,:]+):\d+/.exec(message)?.[1] ?? null;
+}
+
function parseMongoUrlParams(urlParams: string | undefined): URLSearchParams {
return new URLSearchParams((urlParams || "").trim().replace(/^\?/, ""));
}
diff --git a/packages/app-tests/mongoConnectionOptions.test.ts b/packages/app-tests/mongoConnectionOptions.test.ts
index d35c40191f..f8dbba13dd 100644
--- a/packages/app-tests/mongoConnectionOptions.test.ts
+++ b/packages/app-tests/mongoConnectionOptions.test.ts
@@ -1,6 +1,6 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
-import { mongoUrlParam, mongoUrlParamIsTrue, normalizeMongoTlsFormState, setMongoUrlParam, setMongoUrlParamBoolean, mongodbAuthFailureHint } from "../../apps/desktop/src/lib/mongo/mongoConnectionOptions.ts";
+import { looksLikeMongoSrvHost, mongoSrvConnectionString, mongoUrlParam, mongoUrlParamIsTrue, normalizeMongoTlsFormState, setMongoUrlParam, setMongoUrlParamBoolean, mongodbAuthFailureHint } from "../../apps/desktop/src/lib/mongo/mongoConnectionOptions.ts";
test("reads MongoDB authSource from URL params", () => {
assert.equal(mongoUrlParam("?replicaSet=rs0&authSource=admin", "authSource"), "admin");
@@ -110,3 +110,36 @@ test("adds a MongoDB DocumentDB SSH tunnel hostname hint", () => {
assert.match(mongodbAuthFailureHint(message), /tlsAllowInvalidCertificates=true/);
});
+
+test("recognises MongoDB Atlas cluster names that only have SRV records", () => {
+ for (const host of ["cluster0.uqde52q.mongodb.net", " Cluster0.ABCDE.mongodb.net ", "cluster0-pl-0.abcde.mongodb.net"]) {
+ assert.equal(looksLikeMongoSrvHost(host), true, host);
+ }
+ for (const host of ["cluster0-shard-00-00.abcde.mongodb.net", "ac-abc-shard-00-01.abcde.mongodb.net", "mongodb.net", "abcde.mongodb.net", "db.example.com", "127.0.0.1", "", undefined]) {
+ assert.equal(looksLikeMongoSrvHost(host), false, String(host));
+ }
+});
+
+test("builds a mongodb+srv URL from the connection form", () => {
+ assert.equal(
+ mongoSrvConnectionString({ host: "cluster0.uqde52q.mongodb.net", username: "al@ice", password: "p:ss/#", database: "", url_params: "authSource=admin&directConnection=true&tls=true&retryWrites=false" }),
+ "mongodb+srv://al%40ice:p%3Ass%2F%[email protected]/?authSource=admin&retryWrites=false",
+ );
+ assert.equal(mongoSrvConnectionString({ host: "cluster0.abcde.mongodb.net:27017", database: "shop", ca_cert_path: "/certs/ca.pem" }), "mongodb+srv://cluster0.abcde.mongodb.net/shop?tlsCAFile=%2Fcerts%2Fca.pem");
+ assert.equal(
+ mongoSrvConnectionString({ host: "cluster0.abcde.mongodb.net", username: "arn:aws:iam::1:user/x", password: "ignored", url_params: "authMechanism=MONGODB-OIDC" }),
+ "mongodb+srv://arn%3Aaws%3Aiam%3A%3A1%3Auser%[email protected]/?authMechanism=MONGODB-OIDC",
+ );
+});
+
+test("adds an SRV hint when an Atlas cluster name fails DNS lookup as host:port", () => {
+ const windows =
+ "MongoDB connection failed: Kind: Server selection timeout: No available servers. Topology: { Type: Single, Servers: [ { Address: cluster0.uqde52q.mongodb.net:27017, Type: Unknown, Error: Kind: I/O error: 不知道这样的主机。 (os error 11001), labels: {}, source: None, server response: None } ] }, labels: {}, source: None, server response: None";
+ assert.match(mongodbAuthFailureHint(windows), /mongodb\+srv:\/\/cluster0\.uqde52q\.mongodb\.net instead of host:port/);
+ const mac = windows.replace("不知道这样的主机。 (os error 11001)", "failed to lookup address information: nodename nor servname provided, or not known");
+ assert.match(mongodbAuthFailureHint(mac), /Atlas cluster name/);
+
+ // An ordinary host that fails DNS gets no SRV advice.
+ const typo = windows.replaceAll("cluster0.uqde52q.mongodb.net", "db.example.internal");
+ assert.equal(mongodbAuthFailureHint(typo), typo);
+});