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(sqlite): open SQLCipher databases with configured key (#2807)

Guoyu Su016821122cab
diff --git a/crates/dbx-core/src/db/sqlite.rs b/crates/dbx-core/src/db/sqlite.rs
index 767b952d72..49a54382d1 100644
--- a/crates/dbx-core/src/db/sqlite.rs
+++ b/crates/dbx-core/src/db/sqlite.rs
@@ -108,28 +108,41 @@ fn open_sqlite_handle(
validate_existing_sqlite_file(path)?;
}
- let conn = if is_memory {
- Connection::open_in_memory().map_err(|e| format!("SQLite connection failed: {e}"))?
- } else {
- let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE;
- if create_if_missing {
- flags |= OpenFlags::SQLITE_OPEN_CREATE;
- }
- if is_network_path(path) {
- flags |= OpenFlags::SQLITE_OPEN_URI;
- Connection::open_with_flags(sqlite_network_path_uri(path), flags)
- .map_err(|e| format!("SQLite connection failed: {e}"))?
- } else {
- Connection::open_with_flags(path, flags).map_err(|e| format!("SQLite connection failed: {e}"))?
+ let sqlcipher_attempts: &[Option<i64>] = if encrypted { &[None, Some(3), Some(2), Some(1)] } else { &[None] };
+ let mut unlock_error: Option<String> = None;
+
+ for compatibility in sqlcipher_attempts {
+ let conn = open_sqlite_connection(path, create_if_missing)?;
+ if let Err(err) = apply_sqlcipher_key(&conn, cipher_key.as_deref(), *compatibility) {
+ unlock_error = Some(err);
+ continue;
}
- };
+ conn.busy_timeout(std::time::Duration::from_secs(10)).map_err(|e| e.to_string())?;
+ load_sqlite_extensions(&conn, &extensions)?;
+ register_sqlite_compat_functions(&conn)?;
+
+ return Ok(SqliteHandle { conn: Arc::new(Mutex::new(conn)) });
+ }
- apply_sqlcipher_key(&conn, cipher_key.as_deref())?;
- conn.busy_timeout(std::time::Duration::from_secs(10)).map_err(|e| e.to_string())?;
- load_sqlite_extensions(&conn, &extensions)?;
- register_sqlite_compat_functions(&conn)?;
+ Err(unlock_error.unwrap_or_else(|| "SQLCipher database unlock failed.".to_string()))
+}
+
+fn open_sqlite_connection(path: &str, create_if_missing: bool) -> Result<Connection, String> {
+ if is_memory_database_path(path) {
+ return Connection::open_in_memory().map_err(|e| format!("SQLite connection failed: {e}"));
+ }
- Ok(SqliteHandle { conn: Arc::new(Mutex::new(conn)) })
+ let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE;
+ if create_if_missing {
+ flags |= OpenFlags::SQLITE_OPEN_CREATE;
+ }
+ if is_network_path(path) {
+ flags |= OpenFlags::SQLITE_OPEN_URI;
+ Connection::open_with_flags(sqlite_network_path_uri(path), flags)
+ .map_err(|e| format!("SQLite connection failed: {e}"))
+ } else {
+ Connection::open_with_flags(path, flags).map_err(|e| format!("SQLite connection failed: {e}"))
+ }
}
fn sqlite_cipher_key(cipher_key: &str) -> Option<String> {
@@ -155,7 +168,7 @@ fn ensure_sqlcipher_available(encrypted: bool) -> Result<(), String> {
}
#[cfg(feature = "sqlite-sqlcipher")]
-fn apply_sqlcipher_key(conn: &Connection, cipher_key: Option<&str>) -> Result<(), String> {
+fn apply_sqlcipher_key(conn: &Connection, cipher_key: Option<&str>, compatibility: Option<i64>) -> Result<(), String> {
let Some(cipher_key) = cipher_key.filter(|key| !key.is_empty()) else {
return Ok(());
};
@@ -163,16 +176,29 @@ fn apply_sqlcipher_key(conn: &Connection, cipher_key: Option<&str>) -> Result<()
// SQLCipher requires the key before the first schema read; the verification
// query turns wrong keys into an immediate connection error.
conn.pragma_update(None, "key", cipher_key).map_err(|e| format!("SQLCipher key setup failed: {e}"))?;
- conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(()))
+ if let Some(compatibility) = compatibility {
+ conn.pragma_update(None, "cipher_compatibility", compatibility)
+ .map_err(|e| format!("SQLCipher compatibility setup failed: {e}"))?;
+ }
+ verify_sqlcipher_key(conn)
.map_err(|e| format!("SQLCipher database unlock failed. Check the SQLite password/key and file type: {e}"))?;
Ok(())
}
#[cfg(not(feature = "sqlite-sqlcipher"))]
-fn apply_sqlcipher_key(_conn: &Connection, _cipher_key: Option<&str>) -> Result<(), String> {
+fn apply_sqlcipher_key(
+ _conn: &Connection,
+ _cipher_key: Option<&str>,
+ _compatibility: Option<i64>,
+) -> Result<(), String> {
Ok(())
}
+#[cfg(feature = "sqlite-sqlcipher")]
+fn verify_sqlcipher_key(conn: &Connection) -> Result<(), rusqlite::Error> {
+ conn.query_row("SELECT count(*) FROM sqlite_master", [], |_| Ok(()))
+}
+
fn register_sqlite_compat_functions(conn: &Connection) -> Result<(), String> {
let flags = FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC | FunctionFlags::SQLITE_INNOCUOUS;
@@ -590,6 +616,32 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ #[cfg(feature = "sqlite-sqlcipher")]
+ #[tokio::test]
+ async fn sqlcipher_key_opens_legacy_compatible_database() {
+ let path = std::env::temp_dir().join(format!("dbx-sqlcipher-legacy-{}.db", uuid::Uuid::new_v4()));
+ let key = "legacy key";
+
+ {
+ let conn =
+ Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE)
+ .expect("create legacy-compatible encrypted sqlite");
+ conn.pragma_update(None, "key", key).expect("set SQLCipher key");
+ conn.pragma_update(None, "cipher_compatibility", 3).expect("set SQLCipher compatibility");
+ conn.execute_batch("CREATE TABLE t (name TEXT); INSERT INTO t VALUES ('legacy');")
+ .expect("write legacy-compatible encrypted sqlite");
+ }
+
+ let reopened = connect_path_with_cipher_key_and_extensions(path.to_str().unwrap(), key, Vec::new())
+ .await
+ .expect("reopen legacy-compatible encrypted sqlite");
+ let result =
+ execute_query(&reopened, "SELECT name FROM t").await.expect("read legacy-compatible encrypted sqlite");
+ assert_eq!(result.rows[0][0], serde_json::json!("legacy"));
+
+ let _ = std::fs::remove_file(path);
+ }
+
#[cfg(not(feature = "sqlite-sqlcipher"))]
#[tokio::test]
async fn sqlcipher_key_requires_sqlcipher_feature() {
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 5415d455a6..273b80aac5 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -142,6 +142,8 @@ async fn connect_agent_pool(
#[cfg(test)]
mod tests {
+ #[cfg(feature = "sqlite-sqlcipher")]
+ use super::connect_sqlite_from_config;
use super::{
mark_mongo_legacy_driver, mongo_legacy_connect_params, MONGO_LEGACY_DRIVER_LABEL, MONGO_LEGACY_DRIVER_PROFILE,
};
@@ -204,6 +206,24 @@ mod tests {
}
}
+ #[cfg(feature = "sqlite-sqlcipher")]
+ fn sqlite_config(path: &std::path::Path, password: &str) -> ConnectionConfig {
+ let mut config = mongodb_config();
+ config.id = "sqlite".to_string();
+ config.name = "SQLite".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.driver_profile = None;
+ config.driver_label = None;
+ config.url_params = None;
+ config.host = path.to_string_lossy().to_string();
+ config.port = 0;
+ config.username = String::new();
+ config.password = password.to_string();
+ config.database = None;
+ config.connection_string = None;
+ config
+ }
+
#[cfg(feature = "mq-admin")]
fn mq_config(id: &str, admin_url: &str) -> ConnectionConfig {
let mut config = mongodb_config();
@@ -252,6 +272,51 @@ mod tests {
assert!(!mark_mongo_legacy_driver(&mut config));
}
+ #[cfg(feature = "sqlite-sqlcipher")]
+ #[tokio::test]
+ async fn sqlite_connect_from_config_uses_sqlcipher_key() {
+ let path = std::env::temp_dir().join(format!("dbx-tauri-sqlcipher-{}.db", uuid::Uuid::new_v4()));
+ let key = "dbx-pass";
+
+ {
+ let pool =
+ dbx_core::db::sqlite::connect_path_create_if_missing_with_cipher_key(path.to_str().unwrap(), key)
+ .await
+ .expect("create encrypted sqlite");
+ pool.with_connection(|conn| {
+ conn.execute_batch(
+ "CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT); INSERT INTO users(name) VALUES ('Ada'), ('Grace');",
+ )
+ .map_err(|err| err.to_string())
+ })
+ .expect("write encrypted sqlite");
+ }
+
+ let config = sqlite_config(&path, key);
+ let pool = connect_sqlite_from_config(&config).await.expect("open encrypted sqlite");
+ let count = pool
+ .with_connection(|conn| {
+ conn.query_row("SELECT count(*) FROM users", [], |row| row.get::<_, i64>(0))
+ .map_err(|err| err.to_string())
+ })
+ .expect("read encrypted sqlite");
+ assert_eq!(count, 2);
+
+ let wrong_key = match connect_sqlite_from_config(&sqlite_config(&path, "wrong-key")).await {
+ Ok(_) => panic!("wrong SQLCipher key must fail"),
+ Err(err) => err,
+ };
+ assert!(wrong_key.contains("SQLCipher database unlock failed"));
+
+ let missing_key = match connect_sqlite_from_config(&sqlite_config(&path, "")).await {
+ Ok(_) => panic!("missing SQLCipher key must fail"),
+ Err(err) => err,
+ };
+ assert!(missing_key.contains("not a valid SQLite database"));
+
+ let _ = std::fs::remove_file(path);
+ }
+
#[cfg(feature = "mq-admin")]
#[tokio::test]
async fn save_connection_configs_updates_runtime_cache_and_drops_mq_adapter() {
@@ -487,6 +552,25 @@ pub async fn load_sidebar_layout(state: State<'_, Arc<AppState>>) -> Result<Opti
state.storage.load_sidebar_layout().await
}
+fn sqlite_extension_specs_from_config(config: &ConnectionConfig) -> Vec<db::sqlite::SqliteExtensionSpec> {
+ db::sqlite::sqlite_extension_specs_from_url_params(config.url_params.as_deref())
+ .into_iter()
+ .map(|mut extension| {
+ extension.path = expand_tilde(&extension.path);
+ extension
+ })
+ .collect()
+}
+
+async fn connect_sqlite_from_config(config: &ConnectionConfig) -> Result<db::sqlite::SqliteHandle, String> {
+ db::sqlite::connect_path_with_cipher_key_and_extensions(
+ &expand_tilde(&config.host),
+ &config.password,
+ sqlite_extension_specs_from_config(config),
+ )
+ .await
+}
+
#[tauri::command]
pub async fn test_connection(state: State<'_, Arc<AppState>>, config: ConnectionConfig) -> Result<String, String> {
let tunnel_id = format!("{}:test", config.id);
@@ -564,19 +648,10 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
}
Err(e) => Err(e),
},
- DatabaseType::Sqlite => {
- let extensions = db::sqlite::sqlite_extension_specs_from_url_params(config.url_params.as_deref())
- .into_iter()
- .map(|mut extension| {
- extension.path = expand_tilde(&extension.path);
- extension
- })
- .collect();
- match db::sqlite::connect_path_with_extensions(&expand_tilde(&config.host), extensions).await {
- Ok(_) => Ok("Connection successful".to_string()),
- Err(e) => Err(e),
- }
- }
+ DatabaseType::Sqlite => match connect_sqlite_from_config(&config).await {
+ Ok(_) => Ok("Connection successful".to_string()),
+ Err(e) => Err(e),
+ },
DatabaseType::Redis => {
let con = if config.uses_redis_cluster() {
state.connect_redis_cluster(&tunnel_id, &config).await?;
@@ -843,18 +918,7 @@ pub async fn connect_db(
| DatabaseType::Kwdb
| DatabaseType::Questdb
| DatabaseType::OpenGauss => PoolKind::Postgres(db::postgres::connect(&url, connect_timeout).await?),
- DatabaseType::Sqlite => {
- let extensions = db::sqlite::sqlite_extension_specs_from_url_params(db_config.url_params.as_deref())
- .into_iter()
- .map(|mut extension| {
- extension.path = expand_tilde(&extension.path);
- extension
- })
- .collect();
- PoolKind::Sqlite(
- db::sqlite::connect_path_with_extensions(&expand_tilde(&db_config.host), extensions).await?,
- )
- }
+ DatabaseType::Sqlite => PoolKind::Sqlite(connect_sqlite_from_config(&db_config).await?),
DatabaseType::Redis => {
let con = if db_config.uses_redis_cluster() {
PoolKind::Redis(db::redis_driver::RedisConnection::Cluster(