Files
dbx/crates/dbx-web/src/routes/table_import.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

168 lines
5.4 KiB
Rust

use std::sync::Arc;
use axum::extract::{Multipart, Path, State};
use axum::response::sse::{Event, Sse};
use axum::Json;
use dbx_core::table_import::{self, TableImportRequest};
use dbx_core::transfer;
use futures::stream::Stream;
use serde::Deserialize;
use crate::error::AppError;
use crate::state::WebState;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecuteImportWrapper {
pub request: TableImportRequest,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelImportRequest {
pub import_id: String,
}
pub async fn preview_import(
State(state): State<Arc<WebState>>,
mut multipart: Multipart,
) -> Result<Json<serde_json::Value>, AppError> {
let tmp_dir = state.data_dir.join("tmp");
std::fs::create_dir_all(&tmp_dir).map_err(|e| AppError(e.to_string()))?;
if let Some(field) = multipart.next_field().await.map_err(|e| AppError(e.to_string()))? {
let file_name = field.file_name().unwrap_or("upload.csv").to_string();
let data = field.bytes().await.map_err(|e| AppError(e.to_string()))?;
if data.len() > 100 * 1024 * 1024 {
return Err(AppError(format!("File too large: {} bytes (max {} bytes)", data.len(), 100 * 1024 * 1024)));
}
let file_path = tmp_dir.join(&file_name);
std::fs::write(&file_path, &data).map_err(|e| AppError(e.to_string()))?;
let file_path_str = file_path.to_string_lossy().to_string();
let preview = table_import::preview_table_import_file_core(&file_path_str).await;
let _ = tokio::fs::remove_file(&file_path).await;
let preview = preview.map_err(AppError)?;
return Ok(Json(serde_json::to_value(preview).map_err(|e| AppError(e.to_string()))?));
}
Err(AppError("No file uploaded".to_string()))
}
pub async fn execute_import(
State(state): State<Arc<WebState>>,
Json(body): Json<ExecuteImportWrapper>,
) -> Result<Json<serde_json::Value>, AppError> {
let req = body.request;
// Reject import early if the connection is read-only
if let Some(name) = dbx_core::query::connection_readonly_name(&state.app, &req.connection_id).await {
return Err(AppError(format!(
"Read-only mode: connection '{}' has read-only protection enabled. Import blocked.",
name
)));
}
let import_id = req.import_id.clone();
let (tx, _) = tokio::sync::broadcast::channel::<String>(256);
state.sse_channels.write().await.insert(import_id.clone(), tx.clone());
let app = state.app.clone();
let state_clone = state.clone();
tokio::spawn(async move {
let db_type = match transfer::get_db_type(&app, &req.connection_id).await {
Ok(t) => t,
Err(e) => {
let _ = tx.send(
serde_json::json!({
"importId": req.import_id,
"status": "error",
"error": e
})
.to_string(),
);
return;
}
};
let pool_key = match app.get_or_create_pool(&req.connection_id, Some(&req.database)).await {
Ok(k) => k,
Err(e) => {
let _ = tx.send(
serde_json::json!({
"importId": req.import_id,
"status": "error",
"error": e
})
.to_string(),
);
return;
}
};
let tx_clone = tx.clone();
let import_id_for_cancel = req.import_id.clone();
let result = table_import::import_table_file_core(
&app,
&req,
&db_type,
&pool_key,
|id: &str| {
let id = id.to_string();
Box::pin(async move { transfer::is_cancelled(&id).await })
},
|progress| {
if let Ok(json) = serde_json::to_string(&progress) {
let _ = tx_clone.send(json);
}
},
)
.await;
match result {
Ok(summary) => {
if let Ok(json) = serde_json::to_string(&summary) {
let _ = tx.send(json);
}
}
Err(e) => {
let _ = tx.send(
serde_json::json!({
"importId": import_id_for_cancel,
"status": "error",
"error": e
})
.to_string(),
);
}
}
state_clone.sse_channels.write().await.remove(&req.import_id);
});
Ok(Json(serde_json::json!({ "importId": import_id })))
}
pub async fn import_progress(
State(state): State<Arc<WebState>>,
Path(import_id): Path<String>,
) -> Result<Sse<impl Stream<Item = Result<Event, std::convert::Infallible>>>, AppError> {
let channels = state.sse_channels.read().await;
let tx = channels.get(&import_id).ok_or_else(|| AppError("Import not found".to_string()))?;
let rx = tx.subscribe();
drop(channels);
Ok(crate::sse::sse_from_channel(rx))
}
pub async fn cancel_import(
State(_state): State<Arc<WebState>>,
Json(req): Json<CancelImportRequest>,
) -> Json<serde_json::Value> {
transfer::set_cancelled(&req.import_id).await;
Json(serde_json::json!({ "cancelled": true }))
}