Files
dbx/crates/dbx-web/src/routes/etcd.rs
T
runstone a440415e86 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)
2026-06-10 10:58:52 +08:00

94 lines
2.7 KiB
Rust

use std::sync::Arc;
use axum::extract::State;
use axum::Json;
use serde::Deserialize;
use crate::error::AppError;
use crate::state::WebState;
/// Check if a connection is read-only and return an error if so.
async fn ensure_writable(
app: &dbx_core::connection::AppState,
connection_id: &str,
action: &str,
) -> Result<(), AppError> {
if let Some(name) = dbx_core::query::connection_readonly_name(app, connection_id).await {
return Err(AppError(format!(
"Read-only mode: connection '{}' has read-only protection enabled. {} blocked.",
name, action
)));
}
Ok(())
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EtcdListPrefixRequest {
pub connection_id: String,
pub prefix: String,
pub limit: usize,
pub continuation: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EtcdKeyRequest {
pub connection_id: String,
pub key: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EtcdPutRequest {
pub connection_id: String,
pub key: String,
pub value: dbx_core::agent_kv::KvValue,
pub lease: Option<i64>,
}
pub async fn list_prefix(
State(state): State<Arc<WebState>>,
Json(req): Json<EtcdListPrefixRequest>,
) -> Result<Json<dbx_core::agent_kv::KvListPrefixResponse>, AppError> {
let result = dbx_core::agent_kv::kv_list_prefix_core(
&state.app,
&req.connection_id,
&req.prefix,
req.limit,
req.continuation.as_deref(),
)
.await
.map_err(AppError)?;
Ok(Json(result))
}
pub async fn get(
State(state): State<Arc<WebState>>,
Json(req): Json<EtcdKeyRequest>,
) -> Result<Json<dbx_core::agent_kv::KvGetResponse>, AppError> {
let result = dbx_core::agent_kv::kv_get_core(&state.app, &req.connection_id, &req.key).await.map_err(AppError)?;
Ok(Json(result))
}
pub async fn put(
State(state): State<Arc<WebState>>,
Json(req): Json<EtcdPutRequest>,
) -> Result<Json<dbx_core::agent_kv::KvPutResponse>, AppError> {
ensure_writable(&state.app, &req.connection_id, "Put").await?;
let result = dbx_core::agent_kv::kv_put_core(&state.app, &req.connection_id, &req.key, req.value, req.lease)
.await
.map_err(AppError)?;
Ok(Json(result))
}
pub async fn delete(
State(state): State<Arc<WebState>>,
Json(req): Json<EtcdKeyRequest>,
) -> Result<Json<dbx_core::agent_kv::KvDeleteResponse>, AppError> {
ensure_writable(&state.app, &req.connection_id, "Delete").await?;
let result =
dbx_core::agent_kv::kv_delete_core(&state.app, &req.connection_id, &req.key).await.map_err(AppError)?;
Ok(Json(result))
}