feat(readonly): add read-only mode for all database connections

## Background
Add a read-only toggle for database connections that blocks all write
operations (INSERT, UPDATE, DELETE, DROP, etc.) when enabled, allowing
only read queries (SELECT, SHOW, EXPLAIN, etc.). Closes #889.

## Changes

### Data Model
- Added `read_only: bool` field to ConnectionConfig (Rust struct, TS
  interfaces, and ConnectionConfigData deserialization layer)
- Used `#[serde(default, skip_serializing_if = "is_false")]` for
  backward/forward compatibility with existing configs

### Frontend UI
- Added "Read Only" checkbox in connection dialog
- 7-language i18n support (en/es/it/pt-BR/zh-CN/zh-TW)

### SQL Classification (query_execution_sql.rs)
- Added `is_write_sql()` with two-layer defense:
  - Layer 1: First-keyword check (must start with known read keyword)
  - Layer 2: Embedded dangerous keyword detection (catches CTE-wrapped
    writes like `WITH ... AS (DELETE FROM ...)`)
  - `FROM` keyword supported as DuckDB SELECT-less syntax indicator
- Added `check_read_only()` returning descriptive error with connection name
- Added 16 unit tests covering: pure reads/writes, CTE, case insensitivity,
  string literal masking, comment stripping, stored procedure calls, edge cases

### SQL Execution Guards (query.rs / transfer.rs)
- Added `check_read_only_for_connection()` and `_multi()` helper functions
  with lazy name clone (only allocates when read_only is true)
- 6 interception points: `do_execute`, MySQL batch, SQL Server batch,
  DuckDB batch, transaction execution, transfer execution

### Non-SQL Write Guards — Tauri Commands
- Added `ensure_connection_writable()` helper (connection.rs)
- Mongo: 6 write entry points (insert/update/delete, single + batch)
- Redis: 15 write entry points (SET, DEL, HSET, HDEL, LPUSH, LSET, LREM,
  SADD, SREM, ZADD, ZREM, EXPIRE, FLUSHDB, delete_keys, execute_command)
  - execute_command uses RedisCommandSafety classification to allow
    safe read commands through raw command interface
- etcd: 2 write entry points (put, delete)
- sql_file: SQL file execution guarded
- MCP Bridge: 4 write entry points (Insert/Update/Delete/SQL query)

### Non-SQL Write Guards — Web API
- Local `ensure_writable()` helper in each route module
- Redis: 12 write endpoints including classified execute_command
- Mongo: 6 write endpoints
- etcd: 2 write endpoints
- sql_file, table_import, transfer: early rejection

### Test Updates
- Updated ConnectionConfig construction in 7 test files with
  `read_only: false` initialization

## Defense-in-Depth
- Layer 1: Command/Route-level early rejection (saves resources)
- Layer 2: Core SQL classifier (`is_write_sql` — first keyword + embedded scan)
- Layer 3: Core execution-time interception (do_execute/transfer/transaction)
This commit is contained in:
runstone committed 2026-06-10 10:58:52 +08:00
1 parent 7798f2231e
commit a440415e86
35 files changed
+597 -24

No files matched your search

+34 -8
View File
@@ -6,6 +6,8 @@ use tokio::net::TcpListener;
use super::connection::AppState;
use super::connection::ensure_connection_writable;
const BIND_ADDR: &str = "127.0.0.1:0";
#[derive(Deserialize)]
@@ -225,7 +227,7 @@ async fn resolve_mongo_pool_key(
connection_name: &str,
database: Option<String>,
stream: &mut tokio::net::TcpStream,
) -> Option<(String, String)> {
) -> Option<(String, String, String)> {
let config = match resolve_connection(state, connection_name).await {
Ok(c) => c,
Err(e) => {
@@ -233,6 +235,7 @@ async fn resolve_mongo_pool_key(
return None;
}
};
let connection_id = config.id.clone();
let database = database.unwrap_or_else(|| config.database.clone().unwrap_or_default());
let pool_key = match state.get_or_create_pool(&config.id, Some(&database)).await {
Ok(key) => key,
@@ -241,7 +244,7 @@ async fn resolve_mongo_pool_key(
return None;
}
};
Some((pool_key, database))
Some((pool_key, database, connection_id))
}
async fn handle_open_table(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {
@@ -365,7 +368,8 @@ async fn handle_mongo_list_collections_data(state: &Arc<AppState>, body: &str, s
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, _connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
@@ -383,7 +387,8 @@ async fn handle_mongo_find_documents_data(state: &Arc<AppState>, body: &str, str
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, _connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
@@ -412,7 +417,8 @@ async fn handle_mongo_aggregate_documents_data(state: &Arc<AppState>, body: &str
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, _connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
@@ -439,10 +445,15 @@ async fn handle_mongo_insert_documents_data(state: &Arc<AppState>, body: &str, s
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
if let Err(e) = ensure_connection_writable(state, &connection_id, "Insert").await {
respond_error(stream, "403 Forbidden", &e).await;
return;
}
match dbx_core::mongo_ops::mongo_insert_documents_core(state, &pool_key, &database, &req.collection, &req.docs_json)
.await
{
@@ -459,10 +470,15 @@ async fn handle_mongo_update_documents_data(state: &Arc<AppState>, body: &str, s
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
if let Err(e) = ensure_connection_writable(state, &connection_id, "Update").await {
respond_error(stream, "403 Forbidden", &e).await;
return;
}
match dbx_core::mongo_ops::mongo_update_documents_core(
state,
&pool_key,
@@ -487,10 +503,15 @@ async fn handle_mongo_delete_documents_data(state: &Arc<AppState>, body: &str, s
return;
}
};
let Some((pool_key, database)) = resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
let Some((pool_key, database, connection_id)) =
resolve_mongo_pool_key(state, &req.connection_name, req.database, stream).await
else {
return;
};
if let Err(e) = ensure_connection_writable(state, &connection_id, "Delete").await {
respond_error(stream, "403 Forbidden", &e).await;
return;
}
match dbx_core::mongo_ops::mongo_delete_documents_core(
state,
&pool_key,
@@ -526,6 +547,11 @@ async fn handle_execute_query_data(state: &Arc<AppState>, body: &str, stream: &m
respond_error(stream, "403 Forbidden", &e).await;
return;
}
// Read-only check: reject if the connection has read-only protection and the SQL is a write
if let Err(e) = dbx_core::query::check_read_only_for_connection(state, &config.id, &req.sql).await {
respond_error(stream, "403 Forbidden", &e).await;
return;
}
match dbx_core::query::execute_sql_statement(state, &config.id, &database, &req.sql, req.schema.as_deref(), None)
.await
{