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(ssh): add ssh-agent authentication support (#1023)

haipengno162655711821f
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index a7de81f529..f93c771260 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -138,6 +138,7 @@ function defaultSshTunnel(): SshTunnelConfig {
key_passphrase: "",
connect_timeout_secs: 5,
expose_lan: false,
+ use_ssh_agent: false,
};
}
@@ -154,6 +155,7 @@ function normalizeSshTunnel(hop: Partial<SshTunnelConfig>): SshTunnelConfig {
key_passphrase: hop.key_passphrase || "",
connect_timeout_secs: Number(hop.connect_timeout_secs) || 5,
expose_lan: !!hop.expose_lan,
+ use_ssh_agent: !!hop.use_ssh_agent,
};
}
@@ -229,6 +231,7 @@ function sshLayersForConfig(config: LegacyConnectionConfig): SshTunnelConfig[] {
key_passphrase: config.ssh_key_passphrase || "",
connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
expose_lan: config.ssh_expose_lan || false,
+ use_ssh_agent: false,
}),
];
}
@@ -1701,7 +1704,7 @@ function validateTransportLayers(config: LegacyConnectionConfig) {
}
if (layer.type === "ssh") {
if (!layer.user?.trim()) throw new Error(t("connection.sshHopInvalidUser", { hop: label }));
- if (!layer.password?.trim() && !layer.key_path?.trim()) {
+ if (!layer.password?.trim() && !layer.key_path?.trim() && !layer.use_ssh_agent) {
throw new Error(t("connection.sshHopInvalidAuth", { hop: label }));
}
const timeout = Number(layer.connect_timeout_secs);
@@ -2991,6 +2994,13 @@ function openExternalUrl(url: string) {
<Label class="text-right text-xs">{{ t("connection.sshKeyPassphrase") }}</Label>
<Input v-model="selectedSshLayer.key_passphrase" type="password" class="col-span-3" :placeholder="t('connection.sshKeyPassphrasePlaceholder')" :disabled="selectedSshLayer.enabled === false" />
</div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <label class="col-span-3 flex items-center gap-2 cursor-pointer">
+ <input type="checkbox" v-model="selectedSshLayer.use_ssh_agent" class="mr-0" :disabled="selectedSshLayer.enabled === false" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.sshUseAgent") }}</span>
+ </label>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 259747b07f..4499e151c9 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -294,7 +294,8 @@
sshHopInvalidHost: "{hop}: SSH host is required",
sshHopInvalidUser: "{hop}: SSH user is required",
sshHopInvalidPort: "{hop}: SSH port must be between 1 and 65535",
- sshHopInvalidAuth: "{hop}: password or key path is required",
+ sshHopInvalidAuth: "{hop}: password, key path, or ssh-agent is required",
+ sshUseAgent: "Use ssh-agent",
sshHopInvalidTimeout: "{hop}: SSH timeout must be between 1 and 300 seconds",
connectTimeout: "Connection Timeout (seconds)",
queryTimeout: "Query Timeout (seconds)",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 39af900392..32349523d0 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -276,7 +276,8 @@
sshHopInvalidHost: "{hop}: el host SSH es obligatorio",
sshHopInvalidUser: "{hop}: el usuario SSH es obligatorio",
sshHopInvalidPort: "{hop}: el puerto SSH debe estar entre 1 y 65535",
- sshHopInvalidAuth: "{hop}: se requiere contraseña o ruta de clave",
+ sshHopInvalidAuth: "{hop}: se requiere contraseña, ruta de clave o ssh-agent",
+ sshUseAgent: "Usar ssh-agent",
sshHopInvalidTimeout: "{hop}: el tiempo de espera SSH debe estar entre 1 y 300 segundos",
connectTimeout: "Tiempo de espera de conexión (segundos)",
queryTimeout: "Tiempo de espera de consulta (segundos)",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 108cfac69f..f901f40e4e 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -281,7 +281,8 @@
sshHopInvalidHost: "{hop}: Host SSH richiesto",
sshHopInvalidUser: "{hop}: Utente SSH richiesto",
sshHopInvalidPort: "{hop}: La porta SSH deve essere compresa tra 1 e 65535",
- sshHopInvalidAuth: "{hop}: password o percorso chiave richiesti",
+ sshHopInvalidAuth: "{hop}: password, percorso chiave o ssh-agent richiesti",
+ sshUseAgent: "Usa ssh-agent",
sshHopInvalidTimeout: "{hop}: Il timeout SSH deve essere compreso tra 1 e 300 secondi",
connectTimeout: "Timeout Connessione (secondi)",
queryTimeout: "Timeout Query (secondi)",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index db5f2c99d6..29d7c705be 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -281,7 +281,8 @@
sshHopInvalidHost: "{hop}: o host SSH é obrigatório",
sshHopInvalidUser: "{hop}: o usuário SSH é obrigatório",
sshHopInvalidPort: "{hop}: a porta SSH deve estar entre 1 e 65535",
- sshHopInvalidAuth: "{hop}: senha ou caminho da chave é obrigatório",
+ sshHopInvalidAuth: "{hop}: senha, caminho da chave ou ssh-agent é obrigatório",
+ sshUseAgent: "Usar ssh-agent",
sshHopInvalidTimeout: "{hop}: o timeout SSH deve estar entre 1 e 300 segundos",
connectTimeout: "Timeout de Conexão (segundos)",
queryTimeout: "Timeout de Consulta (segundos)",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 96ee1ca863..26fe11441d 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -295,7 +295,8 @@
sshHopInvalidHost: "{hop}:SSH 主机不能为空",
sshHopInvalidUser: "{hop}:SSH 用户不能为空",
sshHopInvalidPort: "{hop}:SSH 端口必须在 1 到 65535 之间",
- sshHopInvalidAuth: "{hop}:需要填写密码或密钥路径",
+ sshHopInvalidAuth: "{hop}:需要填写密码、密钥路径或勾选使用 ssh-agent",
+ sshUseAgent: "使用 ssh-agent",
sshHopInvalidTimeout: "{hop}:SSH 超时时间必须在 1 到 300 秒之间",
connectTimeout: "连接超时(秒)",
queryTimeout: "查询超时(秒)",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 648505702d..2250048b9b 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -281,7 +281,8 @@
sshHopInvalidHost: "{hop}:SSH 主機不能為空",
sshHopInvalidUser: "{hop}:SSH 使用者不能為空",
sshHopInvalidPort: "{hop}:SSH 埠必須在 1 到 65535 之間",
- sshHopInvalidAuth: "{hop}:需要填寫密碼或金鑰路徑",
+ sshHopInvalidAuth: "{hop}:需要填寫密碼、金鑰路徑或勾選使用 ssh-agent",
+ sshUseAgent: "使用 ssh-agent",
sshHopInvalidTimeout: "{hop}:SSH 逾時時間必須在 1 到 300 秒之間",
connectTimeout: "連線逾時(秒)",
queryTimeout: "查詢逾時(秒)",
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 753d3eaced..06feeab9a5 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -114,6 +114,7 @@ export interface SshTunnelConfig {
key_passphrase?: string;
connect_timeout_secs?: number;
expose_lan?: boolean;
+ use_ssh_agent?: boolean;
}
export interface ProxyTunnelConfig {
diff --git a/crates/dbx-core/src/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rs
index 742f655a73..78db49d20b 100644
--- a/crates/dbx-core/src/cloud_sync.rs
+++ b/crates/dbx-core/src/cloud_sync.rs
@@ -575,6 +575,7 @@ mod tests {
key_passphrase: "hop-passphrase".to_string(),
connect_timeout_secs: 5,
expose_lan: false,
+ use_ssh_agent: false,
})],
connect_timeout_secs: 5,
query_timeout_secs: 30,
diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rs
index a140a202da..12ad11bc54 100644
--- a/crates/dbx-core/src/connection_secrets.rs
+++ b/crates/dbx-core/src/connection_secrets.rs
@@ -529,6 +529,7 @@ mod tests {
key_passphrase: passphrase.to_string(),
connect_timeout_secs: 5,
expose_lan: false,
+ use_ssh_agent: false,
}
}
diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rs
index 7d215621d8..fd87791d19 100644
--- a/crates/dbx-core/src/db/ssh_tunnel.rs
+++ b/crates/dbx-core/src/db/ssh_tunnel.rs
@@ -5,6 +5,7 @@ use std::sync::Arc;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
use russh::client::{self, Config, Handle};
+use russh::keys::agent::{client::AgentClient, AgentIdentity};
use russh::keys::{decode_secret_key, key::PrivateKeyWithHashAlg, PrivateKey};
use russh::ChannelMsg;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -48,6 +49,7 @@ async fn connect_and_authenticate(
ssh_password: &str,
ssh_key_path: &str,
ssh_key_passphrase: &str,
+ use_ssh_agent: bool,
connect_timeout_secs: u64,
) -> Result<Handle<SshClient>, String> {
let config =
@@ -91,13 +93,75 @@ async fn connect_and_authenticate(
if !auth_res.success() {
return Err("SSH password authentication failed".to_string());
}
+ } else if use_ssh_agent {
+ match try_authenticate_with_agent(&mut session, ssh_user, &connect_timeout).await {
+ Ok(()) => {}
+ Err(agent_err) => return Err(agent_err),
+ }
} else {
- return Err("No SSH password or key provided".to_string());
+ return Err("No SSH authentication method provided (password, key, or ssh-agent)".to_string());
}
Ok(session)
}
+/// Try to authenticate using ssh-agent identities. Returns `Ok(())` on success,
+/// or an error describing why agent auth failed (unavailable, no identities, all rejected).
+async fn try_authenticate_with_agent(
+ session: &mut Handle<SshClient>,
+ ssh_user: &str,
+ connect_timeout: &Duration,
+) -> Result<(), String> {
+ let mut agent = match AgentClient::connect_env().await {
+ Ok(a) => a,
+ Err(e) => {
+ return Err(format!("No SSH password or key provided, and ssh-agent is unavailable: {e}"));
+ }
+ };
+
+ let identities = match agent.request_identities().await {
+ Ok(ids) if ids.is_empty() => {
+ return Err("No SSH password or key provided, and ssh-agent has no identities".to_string());
+ }
+ Ok(ids) => ids,
+ Err(e) => {
+ return Err(format!("No SSH password or key provided, and ssh-agent request failed: {e}"));
+ }
+ };
+
+ let hash_alg = session.best_supported_rsa_hash().await.ok().flatten().flatten();
+
+ let auth_result = tokio::time::timeout(*connect_timeout, async {
+ for identity in identities {
+ let result = match &identity {
+ AgentIdentity::PublicKey { key, .. } => {
+ session.authenticate_publickey_with(ssh_user, key.clone(), hash_alg, &mut agent).await
+ }
+ AgentIdentity::Certificate { certificate, .. } => {
+ session.authenticate_certificate_with(ssh_user, certificate.clone(), hash_alg, &mut agent).await
+ }
+ };
+
+ match result {
+ Ok(auth_res) if auth_res.success() => return Ok(()),
+ Ok(_) => continue,
+ Err(e) => {
+ log::debug!("SSH agent identity ({}) auth failed: {e}", identity.comment());
+ continue;
+ }
+ }
+ }
+ Err("No SSH password or key provided, and no ssh-agent identity was accepted".to_string())
+ })
+ .await;
+
+ match auth_result {
+ Ok(Ok(())) => Ok(()),
+ Ok(Err(e)) => Err(e),
+ Err(_) => Err("No SSH password or key provided, and ssh-agent auth timed out".to_string()),
+ }
+}
+
fn load_ssh_private_key(path: &str, passphrase: Option<&str>) -> Result<PrivateKey, String> {
let secret = fs::read_to_string(path).map_err(|e| e.to_string())?;
match decode_secret_key(&secret, passphrase) {
@@ -342,6 +406,7 @@ async fn tunnel_reconnect_loop(
ssh_password: String,
ssh_key_path: String,
ssh_key_passphrase: String,
+ use_ssh_agent: bool,
connect_timeout_secs: u64,
listener: TcpListener,
remote_host: String,
@@ -375,6 +440,7 @@ async fn tunnel_reconnect_loop(
&ssh_password,
&ssh_key_path,
&ssh_key_passphrase,
+ use_ssh_agent,
connect_timeout_secs,
)
.await
@@ -443,6 +509,7 @@ impl TunnelManager {
ssh_password: &str,
ssh_key_path: &str,
ssh_key_passphrase: &str,
+ use_ssh_agent: bool,
connect_timeout_secs: u64,
remote_host: &str,
remote_port: u16,
@@ -464,6 +531,7 @@ impl TunnelManager {
ssh_password,
ssh_key_path,
ssh_key_passphrase,
+ use_ssh_agent,
connect_timeout_secs,
remote_host,
remote_port,
@@ -532,6 +600,7 @@ impl TunnelManager {
&hop.password,
&hop.key_path,
&hop.key_passphrase,
+ hop.use_ssh_agent,
effective_hop_timeout(hop),
&target_host,
target_port,
@@ -578,6 +647,7 @@ async fn spawn_tunnel(
ssh_password: &str,
ssh_key_path: &str,
ssh_key_passphrase: &str,
+ use_ssh_agent: bool,
connect_timeout_secs: u64,
remote_host: &str,
remote_port: u16,
@@ -597,6 +667,7 @@ async fn spawn_tunnel(
ssh_password,
ssh_key_path,
ssh_key_passphrase,
+ use_ssh_agent,
connect_timeout_secs,
)
.await?;
@@ -609,6 +680,7 @@ async fn spawn_tunnel(
ssh_password.to_string(),
ssh_key_path.to_string(),
ssh_key_passphrase.to_string(),
+ use_ssh_agent,
connect_timeout_secs,
listener,
remote_host.to_string(),
@@ -705,6 +777,7 @@ mod tests {
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
+ use_ssh_agent: false,
}
}
diff --git a/crates/dbx-core/src/db/transport_layer_tunnel.rs b/crates/dbx-core/src/db/transport_layer_tunnel.rs
index 49eac69e92..b895c66a4b 100644
--- a/crates/dbx-core/src/db/transport_layer_tunnel.rs
+++ b/crates/dbx-core/src/db/transport_layer_tunnel.rs
@@ -58,6 +58,7 @@ pub async fn start_transport_layers(
&ssh.password,
&ssh.key_path,
&ssh.key_passphrase,
+ ssh.use_ssh_agent,
effective_ssh_connect_timeout_secs(ssh.connect_timeout_secs),
&target_endpoint.host,
target_endpoint.port,
@@ -185,6 +186,7 @@ mod tests {
key_passphrase: String::new(),
connect_timeout_secs: 5,
expose_lan: false,
+ use_ssh_agent: false,
})
}
diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs
index 60302c9023..6cf07e66c5 100644
--- a/crates/dbx-core/src/models/connection.rs
+++ b/crates/dbx-core/src/models/connection.rs
@@ -138,6 +138,8 @@ pub struct SshTunnelConfig {
pub connect_timeout_secs: u64,
#[serde(default)]
pub expose_lan: bool,
+ #[serde(default)]
+ pub use_ssh_agent: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/packages/node-core/src/connections.ts b/packages/node-core/src/connections.ts
index 1ce9587ce9..ffe652f080 100644
--- a/packages/node-core/src/connections.ts
+++ b/packages/node-core/src/connections.ts
@@ -43,6 +43,7 @@ export interface SshTunnelConfig {
key_passphrase?: string;
connect_timeout_secs?: number;
expose_lan?: boolean;
+ use_ssh_agent?: boolean;
}
export interface ProxyTunnelConfig {
@@ -162,6 +163,7 @@ function normalizeTransportLayers(config: LegacyConnectionConfig): TransportLaye
key_passphrase: config.ssh_key_passphrase || "",
connect_timeout_secs: config.ssh_connect_timeout_secs || 5,
expose_lan: !!config.ssh_expose_lan,
+ use_ssh_agent: false,
});
}
if (config.proxy_enabled && config.proxy_host) {