feat(safety): temporary write-unlock window for read-only connections

This commit is contained in:
Farahani authored and GitHub committed 2026-08-27 17:37:54 +08:00
1 parent 7933b7656f
commit 955558c81f
66 files changed
+1176 -124

No files matched your search

+3
View File
@@ -295,6 +295,8 @@ pub struct AppState {
/// Web 端 owner 为已认证会话 token,不同登录会话互不可见。建池/池重建/
/// AI/元数据从它读取,前端通过状态接口查询。
pub session_credentials: SessionCredentialStore,
/// In-memory, never-persisted 1/5 minute write overrides for read-only connections.
pub write_unlock_windows: crate::write_unlock::WriteUnlockWindows,
metadata_gates: Arc<Mutex<HashMap<String, Arc<Semaphore>>>>,
mongo_oidc_browser_opener: std::sync::RwLock<Option<MongoOidcBrowserOpener>>,
#[cfg(feature = "mq-admin")]
@@ -1237,6 +1239,7 @@ impl AppState {
postgres_cancel_contexts: Arc::new(RwLock::new(HashMap::new())),
transaction_sessions: Arc::new(RwLock::new(HashMap::new())),
session_credentials: SessionCredentialStore::new(),
write_unlock_windows: crate::write_unlock::WriteUnlockWindows::default(),
metadata_gates: Arc::new(Mutex::new(HashMap::new())),
mongo_oidc_browser_opener: std::sync::RwLock::new(None),
#[cfg(feature = "mq-admin")]
+1
View File
@@ -106,6 +106,7 @@ pub mod transfer;
pub mod two_phase_commit;
pub mod types;
pub mod update;
pub mod write_unlock;
pub mod xlsx_export;
pub const R2_CDN_BASE: &str = "https://dl.dbxio.com/";
+13 -9
View File
@@ -872,17 +872,21 @@ pub fn resolve_kafka_launch_spec(mqc: &MqAdminConfig, state: &AppState) -> Optio
}
async fn ensure_connection_writable(state: &AppState, conn_id: &str, operation: &str) -> Result<(), String> {
let configs = state.configs.read().await;
if let Some(config) = configs.get(conn_id) {
if config.read_only {
return Err(format!(
"Read-only mode: connection '{}' has read-only protection enabled. {} blocked.",
config.name, operation
));
let (name, read_only) = {
let configs = state.configs.read().await;
match configs.get(conn_id) {
Some(config) => (config.name.clone(), config.read_only),
None => return Ok(()),
}
// Production protection for desktop MQ uses UI confirmation; MCP enforces
// is_production separately. Do not hard-block confirmed desktop writes here.
};
if read_only && !state.write_unlock_windows.is_active(conn_id).await {
return Err(format!(
"Read-only mode: connection '{}' has read-only protection enabled. {} blocked.",
name, operation
));
}
// Production protection for desktop MQ uses UI confirmation; MCP enforces
// is_production separately. Do not hard-block confirmed desktop writes here.
Ok(())
}
+1 -1
View File
@@ -554,7 +554,7 @@ async fn get_admin_with_operation_fingerprint(
pub(crate) async fn ensure_connection_writable(state: &AppState, conn_id: &str, action: &str) -> Result<(), String> {
let cfg = state.configs.read().await.get(conn_id).cloned().ok_or("Connection not found")?;
if cfg.read_only {
if cfg.read_only && !state.write_unlock_windows.is_active(conn_id).await {
Err(format!("{action} is blocked because this connection is read-only"))
} else {
Ok(())
+23 -16
View File
@@ -723,10 +723,12 @@ pub async fn check_read_only_for_connection(state: &AppState, pool_key: &str, sq
let configs = state.configs.read().await;
crate::connection::config_for_pool_key(pool_key, &configs)
.filter(|config| config.read_only)
.map(|config| (config.name.clone(), config.db_type))
.map(|config| (config.id.clone(), config.name.clone(), config.db_type))
};
if let Some((name, database_type)) = connection {
crate::query_execution_sql::check_read_only(sql, &name, database_type)?;
if let Some((connection_id, name, database_type)) = connection {
if !state.write_unlock_windows.is_active(&connection_id).await {
crate::query_execution_sql::check_read_only(sql, &name, database_type)?;
}
}
Ok(())
}
@@ -741,11 +743,13 @@ pub async fn check_read_only_for_connection_multi(
let configs = state.configs.read().await;
crate::connection::config_for_pool_key(pool_key, &configs)
.filter(|config| config.read_only)
.map(|config| (config.name.clone(), config.db_type))
.map(|config| (config.id.clone(), config.name.clone(), config.db_type))
};
if let Some((name, database_type)) = connection {
for sql in statements {
crate::query_execution_sql::check_read_only(sql.as_ref(), &name, database_type)?;
if let Some((connection_id, name, database_type)) = connection {
if !state.write_unlock_windows.is_active(&connection_id).await {
for sql in statements {
crate::query_execution_sql::check_read_only(sql.as_ref(), &name, database_type)?;
}
}
}
Ok(())
@@ -755,7 +759,14 @@ pub async fn check_read_only_for_connection_multi(
/// This uses connection_id directly (not pool_key), so it is safe to call at command entry points
/// before any pool key is constructed.
pub async fn connection_readonly_name(state: &AppState, connection_id: &str) -> Option<String> {
state.configs.read().await.get(connection_id).filter(|c| c.read_only).map(|c| c.name.clone())
let name = {
let configs = state.configs.read().await;
configs.get(connection_id).filter(|c| c.read_only).map(|c| c.name.clone())?
};
if state.write_unlock_windows.is_active(connection_id).await {
return None;
}
Some(name)
}
async fn connection_is_mongodb(state: &AppState, connection_id: &str) -> bool {
@@ -1693,15 +1704,11 @@ async fn do_execute_typed(
let _activity_touch = state.pool_activity_touch(pool_key);
let query_timeout = resolve_query_timeout(options.timeout_secs);
let read_only_connection = {
let configs = state.configs.read().await;
let config = crate::connection::config_for_pool_key(pool_key, &configs);
config.filter(|config| config.read_only).map(|config| (config.name.clone(), config.db_type))
};
// Re-check at statement start so a write that becomes ready after the
// temporary unlock window expires is still blocked, even if an earlier
// statement in the same batch is still running.
check_read_only_for_connection(state, pool_key, sql).await?;
let operation_budget = operation_budget_for_pool_key(state, pool_key, query_timeout).await;
if let Some((name, database_type)) = read_only_connection {
crate::query_execution_sql::check_read_only(sql, &name, database_type)?;
}
let pool_db_type = connection_database_type_for_pool_key(state, pool_key).await;
let mysql_catalog_dialect = connection_mysql_catalog_dialect_for_pool_key(state, pool_key).await;
let connections = state.connections.read().await;
+8 -16
View File
@@ -1209,24 +1209,16 @@ async fn try_export_mysql_query_result_stream(
state.touch_pool_activity(&pool_key).await;
let _activity_touch = state.pool_activity_touch(&pool_key);
let (mysql_dialect, read_only_connection) = {
let mysql_dialect = {
let configs = state.configs.read().await;
let config = configs.get(&request.connection_id);
(
config
.map(|config| {
crate::db::mysql::MySqlQueryDialect::for_connection(
config.db_type,
config.driver_profile.as_deref(),
)
})
.unwrap_or_default(),
config.filter(|config| config.read_only).map(|config| (config.name.clone(), config.db_type)),
)
configs
.get(&request.connection_id)
.map(|config| {
crate::db::mysql::MySqlQueryDialect::for_connection(config.db_type, config.driver_profile.as_deref())
})
.unwrap_or_default()
};
if let Some((name, database_type)) = read_only_connection {
crate::query_execution_sql::check_read_only(&request.sql, &name, database_type)?;
}
crate::query::check_read_only_for_connection(state, &request.connection_id, &request.sql).await?;
let row_limit = effective_row_limit(request);
let stream_row_limit = row_limit;
+203
View File
@@ -0,0 +1,203 @@
//! Temporary per-session write-unlock windows for persistently read-only connections.
//!
//! The saved `ConnectionConfig.read_only` flag is never flipped. A confirmed
//! desktop/web session may allow writes for 1 or 5 minutes; MCP and CLI keep
//! reading the persistent flag and cannot use this window.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use crate::session_credentials::current_credential_owner;
pub const WRITE_UNLOCK_ONE_MINUTE_SECS: u64 = 60;
pub const WRITE_UNLOCK_FIVE_MINUTES_SECS: u64 = 300;
#[derive(Clone, Eq, Hash, PartialEq)]
struct WriteUnlockKey {
owner_scope: String,
connection_id: String,
}
impl WriteUnlockKey {
fn current(connection_id: &str) -> Self {
Self { owner_scope: current_credential_owner().unwrap_or_default(), connection_id: connection_id.to_string() }
}
}
#[derive(Default)]
pub struct WriteUnlockWindows {
inner: RwLock<HashMap<WriteUnlockKey, Instant>>,
}
impl WriteUnlockWindows {
pub fn parse_duration_secs(secs: u64) -> Result<Duration, String> {
match secs {
WRITE_UNLOCK_ONE_MINUTE_SECS => Ok(Duration::from_secs(WRITE_UNLOCK_ONE_MINUTE_SECS)),
WRITE_UNLOCK_FIVE_MINUTES_SECS => Ok(Duration::from_secs(WRITE_UNLOCK_FIVE_MINUTES_SECS)),
_ => Err("Write unlock duration must be 1 minute or 5 minutes.".to_string()),
}
}
pub async fn unlock(&self, connection_id: &str, duration_secs: u64) -> Result<u64, String> {
if connection_id.trim().is_empty() {
return Err("Connection id is required.".to_string());
}
let duration = Self::parse_duration_secs(duration_secs)?;
let expires_at = Instant::now() + duration;
self.inner.write().await.insert(WriteUnlockKey::current(connection_id), expires_at);
Ok(duration.as_millis() as u64)
}
pub async fn lock(&self, connection_id: &str) {
self.inner.write().await.remove(&WriteUnlockKey::current(connection_id));
}
pub async fn remaining_ms(&self, connection_id: &str) -> u64 {
let key = WriteUnlockKey::current(connection_id);
let expires_at = self.inner.read().await.get(&key).copied();
let Some(expires_at) = expires_at else {
return 0;
};
remaining_ms_from(expires_at, Instant::now(), &self.inner, key).await
}
pub async fn is_active(&self, connection_id: &str) -> bool {
self.remaining_ms(connection_id).await > 0
}
#[cfg(test)]
async fn force_expiry(&self, connection_id: &str) {
let key = WriteUnlockKey::current(connection_id);
self.inner
.write()
.await
.insert(key, Instant::now().checked_sub(Duration::from_secs(1)).unwrap_or_else(Instant::now));
}
}
async fn remaining_ms_from(
expires_at: Instant,
now: Instant,
inner: &RwLock<HashMap<WriteUnlockKey, Instant>>,
key: WriteUnlockKey,
) -> u64 {
if now >= expires_at {
inner.write().await.remove(&key);
return 0;
}
expires_at.duration_since(now).as_millis() as u64
}
#[cfg(test)]
mod tests {
use super::*;
use crate::connection::AppState;
use crate::models::connection::ConnectionConfig;
use crate::query::{check_read_only_for_connection, connection_readonly_name};
use crate::session_credentials::with_credential_owner;
use crate::storage::Storage;
fn mysql_config(id: &str, name: &str, read_only: bool) -> ConnectionConfig {
serde_json::from_value(serde_json::json!({
"id": id,
"name": name,
"db_type": "mysql",
"host": "localhost",
"port": 3306,
"username": "tester",
"password": "",
"database": "test",
"read_only": read_only
}))
.unwrap()
}
async fn test_state(configs: &[ConnectionConfig]) -> (AppState, tempfile::TempDir) {
let dir = tempfile::tempdir().unwrap();
let storage = Storage::open(&dir.path().join("storage.db")).await.expect("open storage");
let state = AppState::new_with_plugin_dir(storage, dir.path().join("plugins"));
{
let mut stored = state.configs.write().await;
for config in configs {
stored.insert(config.id.clone(), config.clone());
}
}
(state, dir)
}
#[test]
fn parse_duration_secs_accepts_one_and_five_minutes_only() {
assert_eq!(WriteUnlockWindows::parse_duration_secs(60).unwrap(), Duration::from_secs(60));
assert_eq!(WriteUnlockWindows::parse_duration_secs(300).unwrap(), Duration::from_secs(300));
assert!(WriteUnlockWindows::parse_duration_secs(0).is_err());
assert!(WriteUnlockWindows::parse_duration_secs(120).is_err());
assert!(WriteUnlockWindows::parse_duration_secs(600).is_err());
}
#[tokio::test]
async fn read_only_gate_blocks_until_unlock_and_after_expiry() {
let readonly = mysql_config("prod", "prod-db", true);
let other = mysql_config("other", "other-db", true);
let (state, _dir) = test_state(&[readonly, other]).await;
assert_eq!(connection_readonly_name(&state, "prod").await.as_deref(), Some("prod-db"));
check_read_only_for_connection(&state, "prod", "INSERT INTO t VALUES (1)")
.await
.expect_err("write blocked before unlock");
check_read_only_for_connection(&state, "prod", "SELECT 1").await.expect("reads still allowed");
let remaining = state.write_unlock_windows.unlock("prod", 60).await.expect("unlock");
assert!(remaining > 0 && remaining <= 60_000, "remaining={remaining}");
assert!(state.write_unlock_windows.is_active("prod").await);
assert!(!state.write_unlock_windows.is_active("other").await);
assert!(state.configs.read().await.get("prod").expect("config").read_only);
assert_eq!(connection_readonly_name(&state, "prod").await, None);
assert_eq!(connection_readonly_name(&state, "other").await.as_deref(), Some("other-db"));
check_read_only_for_connection(&state, "prod", "INSERT INTO t VALUES (1)")
.await
.expect("write allowed during window");
check_read_only_for_connection(&state, "other", "DELETE FROM t").await.expect_err("unlock is per connection");
state.write_unlock_windows.force_expiry("prod").await;
assert!(!state.write_unlock_windows.is_active("prod").await);
assert_eq!(connection_readonly_name(&state, "prod").await.as_deref(), Some("prod-db"));
check_read_only_for_connection(&state, "prod", "UPDATE t SET a = 1")
.await
.expect_err("write blocked after expiry");
assert_eq!(state.write_unlock_windows.remaining_ms("prod").await, 0);
assert!(state.configs.read().await.get("prod").expect("config").read_only);
}
#[tokio::test]
async fn lock_now_ends_the_window_without_clearing_read_only() {
let readonly = mysql_config("prod", "prod-db", true);
let (state, _dir) = test_state(&[readonly]).await;
state.write_unlock_windows.unlock("prod", 300).await.unwrap();
assert_eq!(connection_readonly_name(&state, "prod").await, None);
state.write_unlock_windows.lock("prod").await;
assert_eq!(connection_readonly_name(&state, "prod").await.as_deref(), Some("prod-db"));
assert!(state.configs.read().await.get("prod").expect("config").read_only);
}
#[tokio::test]
async fn web_session_owners_cannot_share_an_unlock_window() {
let readonly = mysql_config("prod", "prod-db", true);
let (state, _dir) = test_state(&[readonly]).await;
with_credential_owner(Some("token-a".to_string()), async {
state.write_unlock_windows.unlock("prod", 60).await.unwrap();
assert!(state.write_unlock_windows.is_active("prod").await);
})
.await;
with_credential_owner(Some("token-b".to_string()), async {
assert!(!state.write_unlock_windows.is_active("prod").await);
assert_eq!(connection_readonly_name(&state, "prod").await.as_deref(), Some("prod-db"));
})
.await;
}
}