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。

fix(connection): 支持 Redis TLS CA 与客户端证书 (#12598)

zipgb3e9c5c20c0c
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 1d37c327bc..30fe670aed 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -5317,6 +5317,13 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
throw new Error(t("connection.etcdClientCertPairRequired"));
}
+ } else if (config.db_type === "redis") {
+ config.etcd_endpoints = undefined;
+ config.client_cert_path = config.client_cert_path?.trim() || "";
+ config.client_key_path = config.client_key_path?.trim() || "";
+ if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
+ throw new Error(t("connection.redisClientCertPairRequired"));
+ }
} else if (form.value.db_type !== "consul" && config.db_type !== "elasticsearch" && config.db_type !== "easysearch" && config.db_type !== "solr") {
config.etcd_endpoints = undefined;
config.client_cert_path = undefined;
@@ -5338,6 +5345,7 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
config.db_type !== "doris" &&
config.db_type !== "mongodb" &&
config.db_type !== "victoriametrics" &&
+ config.db_type !== "redis" &&
config.db_type !== "zookeeper" &&
config.db_type !== "elasticsearch" &&
config.db_type !== "easysearch" &&
@@ -6930,6 +6938,29 @@ async function browseEtcdTlsFile(target: "ca" | "cert" | "key") {
}
}
+async function browseRedisTlsFile(target: "ca" | "cert" | "key") {
+ if (isTauriRuntime()) {
+ const { open } = await import("@tauri-apps/plugin-dialog");
+ const selected = await open({
+ title: target === "ca" ? t("connection.redisCaCertBrowse") : target === "cert" ? t("connection.redisClientCertBrowse") : t("connection.redisClientKeyBrowse"),
+ multiple: false,
+ filters: [
+ { name: "PEM", extensions: ["pem", "crt", "cer", "key"] },
+ { name: "All Files", extensions: ["*"] },
+ ],
+ });
+ if (selected && typeof selected === "string") {
+ if (target === "ca") {
+ form.value.ca_cert_path = selected;
+ } else if (target === "cert") {
+ form.value.client_cert_path = selected;
+ } else {
+ form.value.client_key_path = selected;
+ }
+ }
+ }
+}
+
async function browseHiveKerberosFile(target: "krb5" | "jaas") {
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
@@ -9846,6 +9877,55 @@ function openExternalUrl(url: string) {
</label>
</div>
+ <template v-if="form.db_type === 'redis'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.redisCaCert") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="form.ca_cert_path" class="flex-1" :placeholder="t('connection.redisCaCertPlaceholder')" :disabled="!form.ssl" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="!form.ssl" @click="browseRedisTlsFile('ca')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.redisCaCertBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.redisClientCert") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="form.client_cert_path" class="flex-1" :placeholder="t('connection.redisClientCertPlaceholder')" :disabled="!form.ssl" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="!form.ssl" @click="browseRedisTlsFile('cert')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.redisClientCertBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.redisClientKey") }}</Label>
+ <div class="col-span-3 flex items-center gap-1">
+ <Input v-model="form.client_key_path" class="flex-1" :placeholder="t('connection.redisClientKeyPlaceholder')" :disabled="!form.ssl" />
+ <Tooltip v-if="isDesktop">
+ <TooltipTrigger as-child>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :disabled="!form.ssl" @click="browseRedisTlsFile('key')">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("connection.redisClientKeyBrowse") }}</TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.redisTlsCertificateHint") }}</p>
+ </div>
+ </template>
+
<template v-if="form.db_type === 'etcd' || form.db_type === 'consul' || form.db_type === 'zookeeper' || form.db_type === 'elasticsearch' || form.db_type === 'easysearch' || form.db_type === 'nebula'">
<div class="grid grid-cols-4 items-start gap-4">
<Label :class="connectionLabelSmallPaddedClass">
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 7ab281493b..c9bcaa581b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1402,6 +1402,17 @@ export default {
sundbCustomDriverHint: "The SunDB Agent ships the vendor JDBC driver, so no JAR is needed (driver class csii.sundb.jdbc.SundbDriver). Provide a JAR here only to load a newer vendor driver; custom drivers are loaded in isolation inside the Agent.",
redisTlsInsecure: "Skip certificate verification",
redisTlsInsecureHint: "Equivalent to redis-cli --tls --insecure, for self-signed certificates or private CAs.",
+ redisCaCert: "CA certificate (optional)",
+ redisCaCertPlaceholder: "Path to a PEM CA certificate",
+ redisCaCertBrowse: "Select Redis CA certificate",
+ redisClientCert: "Client certificate (optional)",
+ redisClientCertPlaceholder: "Path to a PEM client certificate",
+ redisClientCertBrowse: "Select Redis client certificate",
+ redisClientKey: "Client private key (optional)",
+ redisClientKeyPlaceholder: "Path to a PEM client private key",
+ redisClientKeyBrowse: "Select Redis client private key",
+ redisTlsCertificateHint: "Leave the CA certificate empty to use the system trust store. Configure both the client certificate and key when the server requires mutual TLS (tls-auth-clients yes).",
+ redisClientCertPairRequired: "Redis TLS client certificate and private key must be configured together",
mysqlTlsMode: "TLS Mode",
firebirdCharset: "Charset",
firebirdCharsetHint: "Controls the connection charset and decoding of CHARACTER SET NONE fields. For GBK or other legacy data stored in ISO8859_1 fields, also set Legacy read encoding.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8d5320f044..1bf192c78e 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1913,6 +1913,17 @@ export default withEnglishFallback({
pluginSshKeyPickerEmpty: "No se encontraron claves",
pluginSshKeyEncrypted: "Cifrado",
objectCacheRefreshFailed: "Error al actualizar la caché de objetos: {message}",
+ redisCaCert: "Certificado de CA (opcional)",
+ redisCaCertPlaceholder: "Ruta del certificado CA en formato PEM",
+ redisCaCertBrowse: "Seleccionar certificado CA de Redis",
+ redisClientCert: "Certificado de cliente (opcional)",
+ redisClientCertPlaceholder: "Ruta del certificado de cliente en formato PEM",
+ redisClientCertBrowse: "Seleccionar certificado de cliente de Redis",
+ redisClientKey: "Clave privada de cliente (opcional)",
+ redisClientKeyPlaceholder: "Ruta de la clave privada de cliente en formato PEM",
+ redisClientKeyBrowse: "Seleccionar clave privada de cliente de Redis",
+ redisTlsCertificateHint: "Si el certificado CA se deja vacío, se utiliza el almacén de confianza del sistema; si el servidor requiere autenticación mutua (tls-auth-clients yes), configure también el certificado de cliente y la clave privada.",
+ redisClientCertPairRequired: "El certificado de cliente y la clave privada para TLS de Redis deben configurarse a la vez",
},
editor: {
duckdbDraining: "La consulta anterior de DuckDB aún se está deteniendo. Vuelva a intentarlo en breve.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d8b3e3b0ec..be87ac377c 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1822,6 +1822,17 @@ export default withEnglishFallback({
pluginSshKeyPickerEmpty: "Nessuna chiave trovata",
pluginSshKeyEncrypted: "Crittografata",
objectCacheRefreshFailed: "Aggiornamento della cache degli oggetti non riuscito: {message}",
+ redisCaCert: "Certificato CA (opzionale)",
+ redisCaCertPlaceholder: "Percorso del certificato CA in formato PEM",
+ redisCaCertBrowse: "Seleziona certificato CA Redis",
+ redisClientCert: "Certificato client (opzionale)",
+ redisClientCertPlaceholder: "Percorso del certificato client in formato PEM",
+ redisClientCertBrowse: "Seleziona certificato client Redis",
+ redisClientKey: "Chiave privata client (opzionale)",
+ redisClientKeyPlaceholder: "Percorso della chiave privata client in formato PEM",
+ redisClientKeyBrowse: "Seleziona chiave privata client Redis",
+ redisTlsCertificateHint: "Se il certificato CA viene lasciato vuoto, viene utilizzato il trust store di sistema; se il server richiede l'autenticazione reciproca (tls-auth-clients yes), configurare anche il certificato client e la chiave privata.",
+ redisClientCertPairRequired: "Il certificato client e la chiave privata TLS di Redis devono essere configurati insieme",
},
editor: {
duckdbDraining: "La query DuckDB precedente è ancora in fase di arresto. Riprova a breve.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 4ea0d4d8d7..3b0a6909e9 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1843,6 +1843,17 @@ export default withEnglishFallback({
pluginSshKeyPickerEmpty: "キーが見つかりません",
pluginSshKeyEncrypted: "暗号化済み",
objectCacheRefreshFailed: "オブジェクトキャッシュの更新に失敗しました:{message}",
+ redisCaCert: "CA 証明書(任意)",
+ redisCaCertPlaceholder: "PEM 形式の CA 証明書パス",
+ redisCaCertBrowse: "Redis CA 証明書を選択",
+ redisClientCert: "クライアント証明書(任意)",
+ redisClientCertPlaceholder: "PEM 形式のクライアント証明書パス",
+ redisClientCertBrowse: "Redis クライアント証明書を選択",
+ redisClientKey: "クライアント秘密鍵(任意)",
+ redisClientKeyPlaceholder: "PEM 形式のクライアント秘密鍵パス",
+ redisClientKeyBrowse: "Redis クライアント秘密鍵を選択",
+ redisTlsCertificateHint: "CA 証明書を空欄にするとシステムの信頼ストアを使用します。サーバーが相互認証(tls-auth-clients yes)を要求する場合は、クライアント証明書と秘密鍵も合わせて設定してください。",
+ redisClientCertPairRequired: "Redis TLS のクライアント証明書と秘密鍵は同時に設定する必要があります",
},
editor: {
duckdbDraining: "前回の DuckDB クエリはまだ停止処理中です。しばらくしてから再試行してください。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 33752a2b8c..a1f8123df6 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1745,6 +1745,17 @@ export default withEnglishFallback({
mqttDirectionFilterAll: "전체",
mqttDirectionFilterReceived: "수신됨",
mqttDirectionFilterSent: "발신됨",
+ redisCaCert: "CA 인증서(선택 사항)",
+ redisCaCertPlaceholder: "PEM 형식 CA 인증서 경로",
+ redisCaCertBrowse: "Redis CA 인증서 선택",
+ redisClientCert: "클라이언트 인증서(선택 사항)",
+ redisClientCertPlaceholder: "PEM 형식 클라이언트 인증서 경로",
+ redisClientCertBrowse: "Redis 클라이언트 인증서 선택",
+ redisClientKey: "클라이언트 개인 키(선택 사항)",
+ redisClientKeyPlaceholder: "PEM 형식 클라이언트 개인 키 경로",
+ redisClientKeyBrowse: "Redis 클라이언트 개인 키 선택",
+ redisTlsCertificateHint: "CA 인증서를 비워 두면 시스템 신뢰 저장소를 사용합니다. 서버에서 상호 인증(tls-auth-clients yes)을 요구하는 경우 클라이언트 인증서와 개인 키를 함께 구성하세요.",
+ redisClientCertPairRequired: "Redis TLS 클라이언트 인증서와 개인 키는 반드시 함께 구성해야 합니다",
},
editor: {
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index e80a07de5f..3b648b26f5 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1823,6 +1823,17 @@ export default withEnglishFallback({
pluginSshKeyPickerEmpty: "Nenhuma chave encontrada",
pluginSshKeyEncrypted: "Criptografada",
objectCacheRefreshFailed: "Falha ao atualizar o cache de objetos: {message}",
+ redisCaCert: "Certificado CA (opcional)",
+ redisCaCertPlaceholder: "Caminho do certificado CA no formato PEM",
+ redisCaCertBrowse: "Selecionar certificado CA do Redis",
+ redisClientCert: "Certificado do cliente (opcional)",
+ redisClientCertPlaceholder: "Caminho do certificado do cliente no formato PEM",
+ redisClientCertBrowse: "Selecionar certificado do cliente do Redis",
+ redisClientKey: "Chave privada do cliente (opcional)",
+ redisClientKeyPlaceholder: "Caminho da chave privada do cliente no formato PEM",
+ redisClientKeyBrowse: "Selecionar chave privada do cliente do Redis",
+ redisTlsCertificateHint: "Quando o certificado CA estiver em branco, o repositório de confiança do sistema será usado; se o servidor exigir autenticação mútua (tls-auth-clients yes), configure também o certificado do cliente e a chave privada.",
+ redisClientCertPairRequired: "O certificado do cliente Redis TLS e a chave privada devem ser configurados juntos",
},
editor: {
duckdbDraining: "A consulta anterior do DuckDB ainda está sendo interrompida. Tente novamente em breve.",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 57cad37497..1f2de055ab 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1823,6 +1823,17 @@ export default withEnglishFallback({
cancelConnecting: "Отменить подключение",
connectCancelled: "Подключение отменено",
sshTotpCancelled: "Ввод одноразового кода отменён",
+ redisCaCert: "Сертификат CA (необязательно)",
+ redisCaCertPlaceholder: "Путь к сертификату CA в формате PEM",
+ redisCaCertBrowse: "Выбрать CA-сертификат Redis",
+ redisClientCert: "Клиентский сертификат (необязательно)",
+ redisClientCertPlaceholder: "Путь к клиентскому сертификату в формате PEM",
+ redisClientCertBrowse: "Выбрать клиентский сертификат Redis",
+ redisClientKey: "Закрытый ключ клиента (необязательно)",
+ redisClientKeyPlaceholder: "Путь к закрытому ключу клиента в формате PEM",
+ redisClientKeyBrowse: "Выбрать закрытый ключ клиента Redis",
+ redisTlsCertificateHint: "Если сертификат CA не указан, используется системное хранилище доверенных сертификатов; если сервер требует взаимной аутентификации (tls-auth-clients yes), настройте одновременно клиентский сертификат и закрытый ключ.",
+ redisClientCertPairRequired: "Для Redis TLS необходимо одновременно настроить клиентский сертификат и закрытый ключ",
},
editor: {
duckdbDraining: "Предыдущий запрос DuckDB ещё завершается. Повторите попытку чуть позже.",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index cfef19fb84..d397eeb0b6 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -2020,6 +2020,17 @@ export default withEnglishFallback({
cancelConnecting: "ยกเลิกการเชื่อมต่อ",
connectCancelled: "ยกเลิกการเชื่อมต่อแล้ว",
sshTotpCancelled: "ยกเลิกการป้อน Code แบบใช้ครั้งเดียวแล้ว",
+ redisCaCert: "ใบรับรอง CA (ไม่บังคับ)",
+ redisCaCertPlaceholder: "พาธของใบรับรอง CA ในรูปแบบ PEM",
+ redisCaCertBrowse: "เลือกใบรับรอง CA ของ Redis",
+ redisClientCert: "ใบรับรองไคลเอนต์ (ไม่บังคับ)",
+ redisClientCertPlaceholder: "พาธของใบรับรองไคลเอนต์ในรูปแบบ PEM",
+ redisClientCertBrowse: "เลือกใบรับรองไคลเอนต์ของ Redis",
+ redisClientKey: "คีย์ส่วนตัวของไคลเอนต์ (ไม่บังคับ)",
+ redisClientKeyPlaceholder: "พาธของคีย์ส่วนตัวไคลเอนต์ในรูปแบบ PEM",
+ redisClientKeyBrowse: "เลือกคีย์ส่วนตัวไคลเอนต์ของ Redis",
+ redisTlsCertificateHint: "เมื่อเว้นว่างใบรับรอง CA ระบบจะใช้ที่เก็บความเชื่อถือของระบบ; เมื่อเซิร์ฟเวอร์ต้องการการตรวจสอบสิทธิ์แบบสองทาง (tls-auth-clients yes) กรุณาตั้งค่าใบรับรองไคลเอนต์และคีย์ส่วนตัวพร้อมกัน",
+ redisClientCertPairRequired: "ต้องกำหนดค่าใบรับรองไคลเอนต์และคีย์ส่วนตัวสำหรับ Redis TLS พร้อมกัน",
},
editor: {
duckdbDraining: "Query DuckDB ก่อนหน้ายังหยุดไม่เสร็จ โปรดลองอีกครั้งในไม่ช้า",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index eee059658f..92c5f3514c 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1337,6 +1337,17 @@ export default withEnglishFallback({
sundbCustomDriverHint: "科蓝 SUNDB Agent 已内置厂商 JDBC 驱动,无需指定 JAR(驱动类 csii.sundb.jdbc.SundbDriver)。仅在需要加载更新版厂商驱动时在此指定 JAR;自定义驱动在 Agent 内隔离加载。",
redisTlsInsecure: "跳过证书验证",
redisTlsInsecureHint: "等价于 redis-cli --tls --insecure,适用于自签名证书或私有 CA。",
+ redisCaCert: "CA 证书(可选)",
+ redisCaCertPlaceholder: "PEM 格式 CA 证书路径",
+ redisCaCertBrowse: "选择 Redis CA 证书",
+ redisClientCert: "客户端证书(可选)",
+ redisClientCertPlaceholder: "PEM 格式客户端证书路径",
+ redisClientCertBrowse: "选择 Redis 客户端证书",
+ redisClientKey: "客户端私钥(可选)",
+ redisClientKeyPlaceholder: "PEM 格式客户端私钥路径",
+ redisClientKeyBrowse: "选择 Redis 客户端私钥",
+ redisTlsCertificateHint: "CA 证书留空时使用系统信任库;服务端要求双向认证(tls-auth-clients yes)时,请同时配置客户端证书和私钥。",
+ redisClientCertPairRequired: "Redis TLS 客户端证书和私钥必须同时配置",
mysqlTlsMode: "TLS 模式",
firebirdCharset: "连接字符集",
firebirdCharsetHint: "控制连接字符集及 CHARACTER SET NONE 字段的解码。字段声明为 ISO8859_1、实际存为 GBK 等编码时,还需设置旧库读取编码。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 11126c1db8..e5c5360e52 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1823,6 +1823,17 @@ export default withEnglishFallback({
mqttClientKeyPath: "用戶端私鑰路徑",
mqttNoLocal: "禁止本機轉送",
readOnlyExplanation: "唯讀模式:直接阻止目前連線的寫入操作,需要暫時解鎖後才能寫入。",
+ redisCaCert: "CA 憑證(選填)",
+ redisCaCertPlaceholder: "PEM 格式 CA 憑證路徑",
+ redisCaCertBrowse: "選擇 Redis CA 憑證",
+ redisClientCert: "用戶端憑證(選填)",
+ redisClientCertPlaceholder: "PEM 格式用戶端憑證路徑",
+ redisClientCertBrowse: "選擇 Redis 用戶端憑證",
+ redisClientKey: "用戶端私鑰(選填)",
+ redisClientKeyPlaceholder: "PEM 格式用戶端私鑰路徑",
+ redisClientKeyBrowse: "選擇 Redis 用戶端私鑰",
+ redisTlsCertificateHint: "CA 憑證留空時,將使用系統信任存放區;若伺服器要求雙向驗證(tls-auth-clients yes),請同時設定用戶端憑證與私鑰。",
+ redisClientCertPairRequired: "Redis TLS 用戶端憑證與私鑰必須同時設定",
},
editor: {
duckdbDraining: "上一筆 DuckDB 查詢仍在停止,請稍後重試。",
diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rs
index c4b5ec090f..837658edd7 100644
--- a/crates/dbx-driver-redis/src/lib.rs
+++ b/crates/dbx-driver-redis/src/lib.rs
@@ -9,6 +9,7 @@ use redis::{
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
+ fs,
future::Future,
sync::{Arc, OnceLock},
time::Duration,
@@ -405,6 +406,7 @@ pub fn redis_connection_test_stub() -> RedisConnection {
node_routes: Vec::new(),
tls: false,
tls_insecure: false,
+ tls_certificates: None,
username: String::new(),
password: String::new(),
scan_sessions: Box::new(Mutex::new(RedisClusterScanSessions::default())),
@@ -423,6 +425,7 @@ pub struct RedisClusterPool {
pub node_routes: Vec<RedisNodeRoute>,
pub tls: bool,
pub tls_insecure: bool,
+ pub tls_certificates: Option<Box<redis::TlsCertificates>>,
pub username: String,
pub password: String,
scan_sessions: Box<Mutex<RedisClusterScanSessions>>,
@@ -717,9 +720,10 @@ pub async fn connect_standalone(
port: u16,
timeout: std::time::Duration,
) -> Result<redis::aio::MultiplexedConnection, String> {
+ let certificates = load_redis_tls_certificates(config)?;
let mut last_error = None;
for info in standalone_connection_infos(config, host, port)? {
- let client = redis::Client::open(info).map_err(|e| format!("Redis connection failed: {e}"))?;
+ let client = build_redis_client(info, certificates.as_ref())?;
match connect_client_with_timeout(client, timeout, "Redis").await {
Ok(con) => return Ok(con),
Err(err) if last_error.is_none() || is_redis_auth_error(&err) => {
@@ -813,18 +817,22 @@ async fn sentinel_master_client(
nodes: &[ConnectionInfo],
service_name: &str,
) -> Result<redis::Client, String> {
- let masters = sentinel_masters(nodes).await.map_err(|error| error.to_string())?;
+ let certificates = load_redis_tls_certificates(config)?;
+ let masters = sentinel_masters(nodes, certificates.as_ref()).await.map_err(|error| error.to_string())?;
for master in masters {
let Some(endpoint) = sentinel_eligible_master(&master, service_name) else { continue };
- let client = redis::Client::open(connection_info(
- &endpoint.host,
- endpoint.port,
- config.ssl,
- config.redis_tls_insecure(),
- &config.username,
- &config.password,
- 0,
- )?)
+ let client = build_redis_client(
+ connection_info(
+ &endpoint.host,
+ endpoint.port,
+ config.ssl,
+ config.redis_tls_insecure(),
+ &config.username,
+ &config.password,
+ 0,
+ )?,
+ certificates.as_ref(),
+ )
.map_err(|error| error.to_string())?;
let mut con = client
.get_multiplexed_async_connection_with_config(&redis_async_connection_config())
@@ -837,22 +845,30 @@ async fn sentinel_master_client(
Err(format!("Master '{service_name}' not found among healthy Sentinel masters"))
}
-async fn sentinel_masters(nodes: &[ConnectionInfo]) -> redis::RedisResult<Vec<HashMap<String, String>>> {
+async fn sentinel_masters(
+ nodes: &[ConnectionInfo],
+ certificates: Option<&redis::TlsCertificates>,
+) -> Result<Vec<HashMap<String, String>>, String> {
let mut last_error = None;
for info in nodes {
let result = async {
- let client = redis::Client::open(info.clone())?;
- let mut con = client.get_multiplexed_async_connection_with_config(&redis_async_connection_config()).await?;
+ let client = build_redis_client(info.clone(), certificates)?;
+ let mut con = client
+ .get_multiplexed_async_connection_with_config(&redis_async_connection_config())
+ .await
+ .map_err(|error| error.to_string())?;
let result = redis::cmd("SENTINEL").arg("MASTERS").query_async(&mut con).await;
match result {
// Match the old Sentinel client's single reconnect on an I/O
// query failure, followed by trying the next configured node.
Err(error) if error.is_io_error() || error.is_unrecoverable_error() => {
- let mut con =
- client.get_multiplexed_async_connection_with_config(&redis_async_connection_config()).await?;
- redis::cmd("SENTINEL").arg("MASTERS").query_async(&mut con).await
+ let mut con = client
+ .get_multiplexed_async_connection_with_config(&redis_async_connection_config())
+ .await
+ .map_err(|error| error.to_string())?;
+ redis::cmd("SENTINEL").arg("MASTERS").query_async(&mut con).await.map_err(|error| error.to_string())
}
- result => result,
+ result => result.map_err(|error| error.to_string()),
}
}
.await;
@@ -861,9 +877,7 @@ async fn sentinel_masters(nodes: &[ConnectionInfo]) -> redis::RedisResult<Vec<Ha
Err(error) => last_error = Some(error),
}
}
- Err(last_error.unwrap_or_else(|| {
- redis::RedisError::from((redis::ErrorKind::EmptySentinelList, "At least one Sentinel is required"))
- }))
+ Err(last_error.unwrap_or_else(|| "At least one Sentinel is required".to_string()))
}
fn sentinel_eligible_master(metadata: &HashMap<String, String>, service_name: &str) -> Option<RedisNodeEndpoint> {
@@ -916,15 +930,19 @@ pub async fn discover_sentinel_master(
return Err("Redis Sentinel master name is required".to_string());
}
- let client = redis::Client::open(connection_info(
- host,
- port,
- config.redis_sentinel_tls,
- config.redis_tls_insecure(),
- &config.redis_sentinel_username,
- &config.redis_sentinel_password,
- 0,
- )?)
+ let certificates = load_redis_tls_certificates(config)?;
+ let client = build_redis_client(
+ connection_info(
+ host,
+ port,
+ config.redis_sentinel_tls,
+ config.redis_tls_insecure(),
+ &config.redis_sentinel_username,
+ &config.redis_sentinel_password,
+ 0,
+ )?,
+ certificates.as_ref(),
+ )
.map_err(|e| format!("Redis Sentinel connect failed: {e}"))?;
let mut con = connect_client_with_timeout(client, connection_timeout(), "Redis Sentinel").await?;
let raw = tokio::time::timeout(
@@ -941,6 +959,7 @@ pub async fn discover_sentinel_master(
pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPool, String> {
let seed_nodes = redis_cluster_seed_nodes(config)?;
let timeout = Duration::from_secs(config.effective_connect_timeout_secs());
+ let certificates = load_redis_tls_certificates(config)?;
let mut last_error = None;
for auth in redis_auth_candidates(&config.username, &config.password) {
let cluster_nodes: Vec<ConnectionInfo> = seed_nodes
@@ -957,10 +976,11 @@ pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPo
)
})
.collect::<Result<_, _>>()?;
- let client = ClusterClient::builder(cluster_nodes)
- .connection_timeout(timeout)
- .build()
- .map_err(|e| format!("Redis cluster connection failed: {e}"))?;
+ let mut builder = ClusterClient::builder(cluster_nodes).connection_timeout(timeout);
+ if let Some(certificates) = &certificates {
+ builder = builder.certs(certificates.clone());
+ }
+ let client = builder.build().map_err(|e| format!("Redis cluster connection failed: {e}"))?;
let mut con = match tokio::time::timeout(timeout, client.get_async_connection())
.await
.map_err(|_| format!("Redis cluster connection timed out ({}s)", timeout.as_secs()))?
@@ -993,6 +1013,7 @@ pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPo
&seed_routes,
config.ssl,
config.redis_tls_insecure(),
+ certificates.as_ref(),
&auth.username,
&auth.password,
)
@@ -1009,6 +1030,7 @@ pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPo
node_routes,
tls: config.ssl,
tls_insecure: config.redis_tls_insecure(),
+ tls_certificates: certificates.clone().map(Box::new),
username: auth.username,
password: auth.password,
scan_sessions: Box::new(Mutex::new(RedisClusterScanSessions::default())),
@@ -1032,11 +1054,13 @@ pub async fn discover_cluster_slot_ranges_from_routes(
seed_routes: &[RedisNodeRoute],
) -> Result<(RedisClusterAuth, Vec<RedisClusterSlotRange>), String> {
let mut last_error = None;
+ let certificates = load_redis_tls_certificates(config)?;
for auth in redis_auth_candidates(&config.username, &config.password) {
match cluster_slot_ranges_from_routes(
seed_routes,
config.ssl,
config.redis_tls_insecure(),
+ certificates.as_ref(),
&auth.username,
&auth.password,
)
@@ -1079,6 +1103,7 @@ pub async fn connect_routed_cluster(
node_routes,
tls: config.ssl,
tls_insecure: config.redis_tls_insecure(),
+ tls_certificates: load_redis_tls_certificates(config)?.map(Box::new),
username: auth.username,
password: auth.password,
scan_sessions: Box::new(Mutex::new(RedisClusterScanSessions::default())),
@@ -1246,6 +1271,50 @@ fn redis_sentinel_master_endpoint(value: RedisRawValue) -> Result<RedisNodeEndpo
Ok(RedisNodeEndpoint { host, port })
}
+/// Loads Redis TLS material from the connection's certificate paths.
+///
+/// `None` keeps redis-rs on its default trust store. A CA file adds a private
+/// root without disabling verification, and a client cert/key pair enables
+/// mutual TLS (Redis 6+ `tls-auth-clients yes`). The paths are loaded whenever
+/// they are configured because Sentinel nodes can use their own TLS switch
+/// (`redis_sentinel_tls`) independently of the data connection.
+fn load_redis_tls_certificates(config: &ConnectionConfig) -> Result<Option<redis::TlsCertificates>, String> {
+ let ca_path = config.ca_cert_path.trim();
+ let client_cert_path = config.client_cert_path.trim();
+ let client_key_path = config.client_key_path.trim();
+ if client_cert_path.is_empty() != client_key_path.is_empty() {
+ return Err("Redis TLS client certificate and key must be configured together".to_string());
+ }
+ if ca_path.is_empty() && client_cert_path.is_empty() {
+ return Ok(None);
+ }
+ let read = |path: &str, label: &str| {
+ fs::read(path).map_err(|error| format!("Failed to read Redis TLS {label} '{path}': {error}"))
+ };
+ let root_cert = if ca_path.is_empty() { None } else { Some(read(ca_path, "CA certificate")?) };
+ let client_tls = if client_cert_path.is_empty() {
+ None
+ } else {
+ Some(redis::ClientTlsConfig {
+ client_cert: read(client_cert_path, "client certificate")?,
+ client_key: read(client_key_path, "client key")?,
+ })
+ };
+ Ok(Some(redis::TlsCertificates { client_tls, root_cert }))
+}
+
+fn build_redis_client(
+ info: ConnectionInfo,
+ certificates: Option<&redis::TlsCertificates>,
+) -> Result<redis::Client, String> {
+ let tls_addr = matches!(info.addr(), ConnectionAddr::TcpTls { .. });
+ let result = match (tls_addr, certificates) {
+ (true, Some(certificates)) => redis::Client::build_with_tls(info, certificates.clone()),
+ _ => redis::Client::open(info),
+ };
+ result.map_err(|error| format!("Redis connection failed: {error}"))
+}
+
fn connection_info(
host: &str,
port: u16,
@@ -1363,30 +1432,26 @@ pub async fn connect_direct_node(
endpoint: &RedisNodeEndpoint,
tls: bool,
insecure: bool,
+ certificates: Option<&redis::TlsCertificates>,
username: &str,
password: &str,
) -> Result<redis::aio::MultiplexedConnection, String> {
- connect_direct_node_in_db(endpoint, tls, insecure, username, password, 0).await
+ connect_direct_node_in_db(endpoint, tls, insecure, certificates, username, password, 0).await
}
async fn connect_direct_node_in_db(
endpoint: &RedisNodeEndpoint,
tls: bool,
insecure: bool,
+ certificates: Option<&redis::TlsCertificates>,
username: &str,
password: &str,
db: u32,
) -> Result<redis::aio::MultiplexedConnection, String> {
- let client = redis::Client::open(connection_info(
- &endpoint.host,
- endpoint.port,
- tls,
- insecure,
- username,
- password,
- i64::from(db),
- )?)
- .map_err(|e| format!("Redis connection failed: {e}"))?;
+ let client = build_redis_client(
+ connection_info(&endpoint.host, endpoint.port, tls, insecure, username, password, i64::from(db))?,
+ certificates,
+ )?;
connect_client(client).await
}
@@ -1397,8 +1462,9 @@ pub async fn connect_monitor(
timeout: std::time::Duration,
) -> Result<redis::aio::Monitor, String> {
let mut last_error = String::new();
+ let certificates = load_redis_tls_certificates(config)?;
for info in standalone_connection_infos(config, host, port)? {
- let client = redis::Client::open(info).map_err(|error| error.to_string())?;
+ let client = build_redis_client(info, certificates.as_ref())?;
let connect = async {
let mut validation =
client.get_multiplexed_async_connection_with_config(&redis_async_connection_config()).await?;
@@ -1427,17 +1493,20 @@ pub async fn connect_pubsub(
timeout: std::time::Duration,
) -> Result<redis::aio::PubSub, String> {
let mut last_error = None;
+ let certificates = load_redis_tls_certificates(config)?;
for auth in redis_auth_candidates(&config.username, &config.password) {
- let client = redis::Client::open(connection_info(
- host,
- port,
- config.ssl,
- config.redis_tls_insecure(),
- &auth.username,
- &auth.password,
- redis_database_index(config),
- )?)
- .map_err(|e| format!("Redis connection failed: {e}"))?;
+ let client = build_redis_client(
+ connection_info(
+ host,
+ port,
+ config.ssl,
+ config.redis_tls_insecure(),
+ &auth.username,
+ &auth.password,
+ redis_database_index(config),
+ )?,
+ certificates.as_ref(),
+ )?;
match tokio::time::timeout(timeout, client.get_async_pubsub()).await {
Ok(Ok(pubsub)) => return Ok(pubsub),
Ok(Err(err)) => {
@@ -2175,15 +2244,23 @@ pub async fn cluster_master_nodes(pool: &RedisClusterPool) -> Result<Vec<RedisNo
&pool.seed_routes,
pool.tls,
pool.tls_insecure,
+ pool.tls_certificates.as_deref(),
&pool.username,
&pool.password,
)
.await
.map(|slot_ranges| unique_master_nodes(&slot_ranges));
}
- cluster_slot_ranges_from_seeds(&pool.seed_nodes, pool.tls, pool.tls_insecure, &pool.username, &pool.password)
- .await
- .map(|slot_ranges| unique_master_nodes(&slot_ranges))
+ cluster_slot_ranges_from_seeds(
+ &pool.seed_nodes,
+ pool.tls,
+ pool.tls_insecure,
+ pool.tls_certificates.as_deref(),
+ &pool.username,
+ &pool.password,
+ )
+ .await
+ .map(|slot_ranges| unique_master_nodes(&slot_ranges))
}
pub async fn flush_cluster(pool: &RedisClusterPool) -> Result<(), String> {
@@ -2204,23 +2281,25 @@ async fn cluster_slot_ranges_from_seeds(
seed_nodes: &[RedisNodeEndpoint],
tls: bool,
insecure: bool,
+ certificates: Option<&redis::TlsCertificates>,
username: &str,
password: &str,
) -> Result<Vec<RedisClusterSlotRange>, String> {
let seed_routes = identity_routes(seed_nodes);
- cluster_slot_ranges_from_routes(&seed_routes, tls, insecure, username, password).await
+ cluster_slot_ranges_from_routes(&seed_routes, tls, insecure, certificates, username, password).await
}
async fn cluster_slot_ranges_from_routes(
seed_routes: &[RedisNodeRoute],
tls: bool,
insecure: bool,
+ certificates: Option<&redis::TlsCertificates>,
username: &str,
password: &str,
) -> Result<Vec<RedisClusterSlotRange>, String> {
let mut last_error = None;
for route in seed_routes {
- let mut con = match connect_direct_node(&route.connect, tls, insecure, username, password).await {
+ let mut con = match connect_direct_node(&route.connect, tls, insecure, certificates, username, password).await {
Ok(con) => con,
Err(err) => {
last_error = Some(err);
@@ -2345,7 +2424,11 @@ async fn native_cluster_database_connection(pool: &RedisClusterPool, db: u32) ->
)
})
.collect::<Result<Vec<_>, _>>()?;
- let client = ClusterClient::builder(nodes).database_id(i64::from(db)).build().map_err(|error| error.to_string())?;
+ let mut builder = ClusterClient::builder(nodes).database_id(i64::from(db));
+ if let Some(certificates) = &pool.tls_certificates {
+ builder = builder.certs((**certificates).clone());
+ }
+ let client = builder.build().map_err(|error| error.to_string())?;
let initialized = tokio::time::timeout(connection_timeout(), client.get_async_connection())
.await
.map_err(|_| format!("Redis cluster db{db} connection timed out"))?
@@ -2409,8 +2492,10 @@ pub async fn connect_cluster_node_in_db(
advertised_endpoint: &RedisNodeEndpoint,
db: u32,
) -> Result<redis::aio::MultiplexedConnection, String> {
- let client = redis::Client::open(cluster_node_connection_info(pool, advertised_endpoint, db)?)
- .map_err(|error| format!("Redis connection failed: {error}"))?;
+ let client = build_redis_client(
+ cluster_node_connection_info(pool, advertised_endpoint, db)?,
+ pool.tls_certificates.as_deref(),
+ )?;
connect_client(client).await
}
@@ -5448,16 +5533,16 @@ mod tests {
use super::{
classify_command, connection_info, decode_cluster_cursor, encode_cluster_cursor, is_redis_auth_error,
- is_redis_command_denied_error, is_redis_json_type, parse_cluster_slots, parse_command_argv,
- parse_database_count, parse_redis_endpoint, parse_scan_keys, parse_stream_consumers, parse_stream_entries,
- parse_stream_groups, parse_stream_pending_entries, redis_auth_candidates, redis_blob_display_text,
- redis_blob_from_bytes, redis_cluster_slot, redis_command_raw_to_json, redis_database_index,
- redis_key_bytes_to_display, redis_key_bytes_to_raw, redis_key_matches_query, redis_key_raw_to_bytes,
- redis_key_value_preview, redis_sentinel_master_endpoint, redis_value_matches_query, redis_value_to_bytes,
- standalone_connection_infos, RedisAuthCandidate, RedisBlob, RedisBlobEncoding, RedisClusterSlotRange,
- RedisCollectionPage, RedisCommandSafety, RedisHashItem, RedisListItem, RedisNodeEndpoint, RedisNodeRoute,
- RedisRawValue, RedisSetItem, RedisStreamConsumer, RedisStreamEntry, RedisStreamField, RedisStreamGroup,
- RedisStreamPendingEntry, RedisValue, RedisValueData, RedisZsetItem,
+ is_redis_command_denied_error, is_redis_json_type, load_redis_tls_certificates, parse_cluster_slots,
+ parse_command_argv, parse_database_count, parse_redis_endpoint, parse_scan_keys, parse_stream_consumers,
+ parse_stream_entries, parse_stream_groups, parse_stream_pending_entries, redis_auth_candidates,
+ redis_blob_display_text, redis_blob_from_bytes, redis_cluster_slot, redis_command_raw_to_json,
+ redis_database_index, redis_key_bytes_to_display, redis_key_bytes_to_raw, redis_key_matches_query,
+ redis_key_raw_to_bytes, redis_key_value_preview, redis_sentinel_master_endpoint, redis_value_matches_query,
+ redis_value_to_bytes, standalone_connection_infos, RedisAuthCandidate, RedisBlob, RedisBlobEncoding,
+ RedisClusterSlotRange, RedisCollectionPage, RedisCommandSafety, RedisHashItem, RedisListItem,
+ RedisNodeEndpoint, RedisNodeRoute, RedisRawValue, RedisSetItem, RedisStreamConsumer, RedisStreamEntry,
+ RedisStreamField, RedisStreamGroup, RedisStreamPendingEntry, RedisValue, RedisValueData, RedisZsetItem,
};
use dbx_types::models::connection::ConnectionConfig;
use redis::{aio::ConnectionLike, Cmd, ConnectionAddr, Pipeline, RedisFuture};
@@ -7106,7 +7191,7 @@ mod tests {
.into_iter()
.map(|node| connection_info("127.0.0.1", node.port(), false, false, "", "", 0).unwrap())
.collect::<Vec<_>>();
- assert!(super::sentinel_masters(&nodes).await.unwrap().is_empty());
+ assert!(super::sentinel_masters(&nodes, None).await.unwrap().is_empty());
first_server.await.unwrap();
second_server.await.unwrap();
}
@@ -8772,6 +8857,7 @@ mod tests {
node_routes: vec![RedisNodeRoute { advertised: advertised.clone(), connect: forwarded.clone() }],
tls: false,
tls_insecure: false,
+ tls_certificates: None,
username: String::new(),
password: String::new(),
scan_sessions: Box::new(tokio::sync::Mutex::new(super::RedisClusterScanSessions::default())),
@@ -10797,6 +10883,54 @@ mod tests {
assert_eq!(redis::cmd("PING").query_async::<String>(&mut tls).await.unwrap(), "PONG");
}
+ #[test]
+ fn redis_tls_certificates_are_loaded_from_configured_paths() {
+ let dir = std::env::temp_dir().join(format!("dbx-redis-tls-{}-{}", std::process::id(), "load"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let ca = dir.join("ca.pem");
+ let cert = dir.join("client.pem");
+ let key = dir.join("client-key.pem");
+ std::fs::write(&ca, b"ca").unwrap();
+ std::fs::write(&cert, b"cert").unwrap();
+ std::fs::write(&key, b"key").unwrap();
+
+ let mut config = redis_test_connection_config();
+ assert!(super::load_redis_tls_certificates(&config).unwrap().is_none());
+
+ config.ca_cert_path = ca.to_string_lossy().to_string();
+ config.client_cert_path = cert.to_string_lossy().to_string();
+ config.client_key_path = key.to_string_lossy().to_string();
+ // Sentinel nodes can enable TLS without enabling it for the data connection.
+ assert!(load_redis_tls_certificates(&config).unwrap().is_some());
+ config.ssl = true;
+ let certificates = load_redis_tls_certificates(&config).unwrap().unwrap();
+ assert_eq!(certificates.root_cert.as_deref(), Some(b"ca".as_slice()));
+ let client_tls = certificates.client_tls.unwrap();
+ assert_eq!(client_tls.client_cert, b"cert");
+ assert_eq!(client_tls.client_key, b"key");
+
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn redis_tls_certificates_require_both_client_files() {
+ let mut config = redis_test_connection_config();
+ config.ssl = true;
+ config.client_cert_path = "/tmp/only-cert.pem".to_string();
+ let error = load_redis_tls_certificates(&config).err().expect("expected certificate error");
+ assert!(error.contains("configured together"), "{error}");
+ }
+
+ #[test]
+ fn redis_tls_certificates_report_unreadable_files() {
+ let mut config = redis_test_connection_config();
+ config.ssl = true;
+ config.ca_cert_path = "/tmp/dbx-missing-ca-certificate.pem".to_string();
+ let error = load_redis_tls_certificates(&config).err().expect("expected certificate error");
+ assert!(error.contains("Failed to read Redis TLS CA certificate"), "{error}");
+ assert!(error.contains("/tmp/dbx-missing-ca-certificate.pem"), "{error}");
+ }
+
fn redis_test_connection_config() -> ConnectionConfig {
ConnectionConfig {
oracle_oci_nls_lang: None,