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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(dbx-cli): 加固运行时命令参数校验
Illuminated202037eeb8999c90
diff --git a/Cargo.lock b/Cargo.lockindex 2b20b22c74..daf4f16132 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1679,6 +1679,7 @@ version = "0.5.2"dependencies = ["chrono","dbx-core",+ "libc","reqwest 0.12.28","serde","serde_json",diff --git a/crates/dbx-cli/Cargo.toml b/crates/dbx-cli/Cargo.tomlindex a81c00834b..acb34da20f 100644--- a/crates/dbx-cli/Cargo.toml+++ b/crates/dbx-cli/Cargo.toml@@ -15,6 +15,7 @@ serde_json = "1.0"tokio = { version = "1", features = ["full"] }reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }uuid = { version = "1", features = ["v4", "serde"] }+libc = "0.2"[dev-dependencies]tempfile = "3"diff --git a/crates/dbx-cli/src/commands.rs b/crates/dbx-cli/src/commands.rsindex e97350dd6d..a5d6c3f717 100644--- a/crates/dbx-cli/src/commands.rs+++ b/crates/dbx-cli/src/commands.rs@@ -1,5 +1,8 @@use dbx_core::cli::{fail, ok, CliEnvelope, CliErrorCode, CliSource};+const DEFAULT_RESULT_LIMIT: u32 = 50;+const MAX_RESULT_LIMIT: u32 = 1000;+pub(crate) async fn run(args: Vec<String>) -> Result<(), CliEnvelope<()>> {let output = dispatch(args).await;println!("{}", serde_json::to_string_pretty(&output).unwrap());@@ -34,21 +37,44 @@ struct ParsedArgs {positionals: Vec<String>,}+#[derive(Clone, Copy, PartialEq, Eq)]+enum FlagKind {+ Value,+ Bool,+}+fn parse_args(args: Vec<String>) -> Result<ParsedArgs, CliEnvelope<serde_json::Value>> {let mut positionals = Vec::new();let mut index = 0;while index < args.len() {- if args[index] == "--format" {- let Some(format) = args.get(index + 1) else {- return Err(fail(CliSource::Headless, CliErrorCode::InternalError, "--format requires a value", true));+ let arg = &args[index];+ if arg.starts_with("--") {+ let Some(kind) = flag_kind(&args, arg) else {+ return Err(invalid_args(format!("Unknown flag: {arg}")));};- if format != "json" {- return Err(fail(CliSource::Headless, CliErrorCode::InternalError, "Only --format json is supported", true));++ if kind == FlagKind::Value {+ let Some(value) = args.get(index + 1) else {+ return Err(invalid_args(format!("{arg} requires a value")));+ };+ if value.starts_with("--") {+ return Err(invalid_args(format!("{arg} requires a value")));+ }+ if arg == "--format" && value != "json" {+ return Err(invalid_args("Only --format json is supported"));+ }+ if arg != "--format" {+ positionals.push(arg.clone());+ positionals.push(value.clone());+ }+ index += 2;+ } else {+ positionals.push(arg.clone());+ index += 1;}- index += 2;} else {- positionals.push(args[index].clone());+ positionals.push(arg.clone());index += 1;}}@@ -56,6 +82,23 @@ fn parse_args(args: Vec<String>) -> Result<ParsedArgs, CliEnvelope<serde_json::VOk(ParsedArgs { positionals })}+fn flag_kind(args: &[String], flag: &str) -> Option<FlagKind> {+ let first = args.first().map(String::as_str);+ let second = args.get(1).map(String::as_str);+ let value = FlagKind::Value;+ let boolean = FlagKind::Bool;++ match (first, second, flag) {+ (_, _, "--format") => Some(value),+ (Some("conn"), Some("show"), "--redacted") => Some(boolean),+ (Some("schema"), Some("snapshot"), "--conn" | "--db") => Some(value),+ (Some("safe-query"), _, "--conn" | "--sql" | "--db") => Some(value),+ (Some("handoff"), _, "--conn" | "--title" | "--sql" | "--sql-file" | "--description") => Some(value),+ (Some("result"), Some("current"), "--limit") => Some(value),+ _ => None,+ }+}+async fn context(_args: &[String]) -> CliEnvelope<serde_json::Value> {match crate::runtime_client::get_json("/context").await {Ok(data) => ok(CliSource::GuiRuntime, data),@@ -76,7 +119,12 @@ async fn schema_snapshot(args: &[String]) -> CliEnvelope<serde_json::Value> {return fail(CliSource::Headless, CliErrorCode::ConnectionNotFound, "--conn is required", true);};- fail(CliSource::Headless, CliErrorCode::InternalError, "Schema snapshot headless execution is not implemented", true)+ fail(+ CliSource::Headless,+ CliErrorCode::InternalError,+ "Schema snapshot headless execution is not implemented",+ true,+ )}async fn safe_query(args: &[String]) -> CliEnvelope<serde_json::Value> {@@ -91,15 +139,48 @@ async fn safe_query(args: &[String]) -> CliEnvelope<serde_json::Value> {}async fn handoff(args: &[String]) -> CliEnvelope<serde_json::Value> {- let body = serde_json::json!({- "conn": option_value(args, "--conn"),- "title": option_value(args, "--title"),- "sql": option_value(args, "--sql"),- });+ let Some(conn) = required_option(args, "--conn") else {+ return invalid_args("--conn is required");+ };+ let Some(title) = required_option(args, "--title") else {+ return invalid_args("--title is required");+ };+ let sql_inline = option_value(args, "--sql");+ let sql_file = option_value(args, "--sql-file");+ let sql = match (sql_inline, sql_file) {+ (Some(_), Some(_)) => return invalid_args("Use exactly one of --sql or --sql-file"),+ (Some(sql), None) => sql.to_string(),+ (None, Some(path)) => match std::fs::read_to_string(path) {+ Ok(sql) => sql,+ Err(err) => return invalid_args(format!("Failed to read --sql-file: {err}")),+ },+ (None, None) => return invalid_args("Use exactly one of --sql or --sql-file"),+ };- match crate::runtime_client::post_json("/handoff", body).await {- Ok(data) => ok(CliSource::GuiRuntime, data),- Err(_) => fail(CliSource::Headless, CliErrorCode::InternalError, "Handoff payload is required", true),+ if sql.trim().is_empty() {+ return invalid_args("SQL must not be empty");+ }++ let risk = dbx_core::sql_safety::risk_for_connection(&sql, conn, None);+ let item = dbx_core::handoff::HandoffItem::queued(+ conn.to_string(),+ conn.to_string(),+ None,+ title.to_string(),+ option_value(args, "--description").map(str::to_string),+ sql,+ risk.operation_class,+ risk.risk_level,+ risk.is_production,+ );++ if let Ok(data) = crate::runtime_client::post_json("/handoff", serde_json::to_value(&item).unwrap()).await {+ return ok(CliSource::GuiRuntime, data);+ }++ match queue_handoff(&item).await {+ Ok(()) => ok(CliSource::Headless, serde_json::json!({ "id": item.id, "status": "queued" })),+ Err(err) => fail(CliSource::Headless, CliErrorCode::InternalError, err, false),}}@@ -111,9 +192,12 @@ async fn selection(_args: &[String]) -> CliEnvelope<serde_json::Value> {}async fn result_current(args: &[String]) -> CliEnvelope<serde_json::Value> {- let limit = option_value(args, "--limit").unwrap_or("50");+ let limit = match parse_result_limit(args) {+ Ok(limit) => limit,+ Err(err) => return err,+ };- match crate::runtime_client::get_json(&format!("/result/current?limit={limit}")).await {+ match crate::runtime_client::get_json_with_query("/result/current", &[("limit", limit.to_string())]).await {Ok(data) => ok(CliSource::GuiRuntime, data),Err(_) => runtime_required("dbx result current requires DBX GUI runtime."),}@@ -123,19 +207,42 @@ fn runtime_required(message: &str) -> CliEnvelope<serde_json::Value> {fail(CliSource::Headless, CliErrorCode::GuiRuntimeRequired, message, true)}+fn invalid_args(message: impl Into<String>) -> CliEnvelope<serde_json::Value> {+ fail(CliSource::Headless, CliErrorCode::InternalError, message, true)+}+fn option_value<'a>(args: &'a [String], key: &str) -> Option<&'a str> {- args.windows(2)- .find(|pair| pair[0] == key)- .map(|pair| pair[1].as_str())+ args.windows(2).find(|pair| pair[0] == key).map(|pair| pair[1].as_str())+}++fn required_option<'a>(args: &'a [String], key: &str) -> Option<&'a str> {+ option_value(args, key).map(str::trim).filter(|value| !value.is_empty())+}++fn parse_result_limit(args: &[String]) -> Result<u32, CliEnvelope<serde_json::Value>> {+ let default_limit = DEFAULT_RESULT_LIMIT.to_string();+ let raw = option_value(args, "--limit").unwrap_or(&default_limit);+ let limit = raw+ .parse::<u32>()+ .map_err(|_| invalid_args(format!("--limit must be a positive integer between 1 and {MAX_RESULT_LIMIT}")))?;+ if !(1..=MAX_RESULT_LIMIT).contains(&limit) {+ return Err(invalid_args(format!("--limit must be a positive integer between 1 and {MAX_RESULT_LIMIT}")));+ }+ Ok(limit)+}++async fn queue_handoff(item: &dbx_core::handoff::HandoffItem) -> Result<(), String> {+ let app_dir = crate::runtime_client::app_data_dir();+ std::fs::create_dir_all(&app_dir).map_err(|err| err.to_string())?;+ let storage = dbx_core::storage::Storage::open(&app_dir.join("dbx.db")).await?;+ storage.save_handoff(item).await}#[cfg(test)]mod tests {use super::*;+ use crate::runtime_client::ENV_LOCK;use dbx_core::cli::CliErrorCode;- use std::sync::Mutex;-- static ENV_LOCK: Mutex<()> = Mutex::new(());fn assert_failure_code(env: CliEnvelope<serde_json::Value>, expected: CliErrorCode) {match env {@@ -192,10 +299,7 @@ mod tests {let json = serde_json::to_value(&env).unwrap();assert!(json.get("ok").is_some(), "missing ok for args: {args:?}");assert!(json.get("source").is_some(), "missing source for args: {args:?}");- assert!(- json.get("data").is_some() || json.get("error").is_some(),- "missing data/error for args: {args:?}"- );+ assert!(json.get("data").is_some() || json.get("error").is_some(), "missing data/error for args: {args:?}");}std::env::remove_var("DBX_APP_DATA_DIR");@@ -216,4 +320,88 @@ mod tests {CliErrorCode::InternalError,);}++ #[tokio::test]+ async fn rejects_unknown_flags_with_error_envelope() {+ assert_failure_code(+ dispatch(vec!["context".into(), "--unknown".into(), "value".into()]).await,+ CliErrorCode::InternalError,+ );+ }++ #[tokio::test]+ async fn rejects_missing_option_values_with_error_envelope() {+ assert_failure_code(+ dispatch(vec!["safe-query".into(), "--conn".into(), "--sql".into(), "select 1".into()]).await,+ CliErrorCode::InternalError,+ );+ }++ #[tokio::test]+ async fn validates_handoff_required_options_and_sql_source() {+ assert_failure_code(+ dispatch(vec!["handoff".into(), "--title".into(), "Review".into(), "--sql".into(), "select 1".into()])+ .await,+ CliErrorCode::InternalError,+ );+ assert_failure_code(+ dispatch(vec!["handoff".into(), "--conn".into(), "local".into(), "--sql".into(), "select 1".into()]).await,+ CliErrorCode::InternalError,+ );+ assert_failure_code(+ dispatch(vec![+ "handoff".into(),+ "--conn".into(),+ "local".into(),+ "--title".into(),+ "Review".into(),+ "--sql".into(),+ "select 1".into(),+ "--sql-file".into(),+ "query.sql".into(),+ ])+ .await,+ CliErrorCode::InternalError,+ );+ }++ #[tokio::test]+ async fn handoff_queues_sql_file_when_runtime_is_unavailable() {+ let _guard = ENV_LOCK.lock().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let sql_file = dir.path().join("query.sql");+ std::fs::write(&sql_file, "select 1").unwrap();+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());++ let env = dispatch(vec![+ "handoff".into(),+ "--conn".into(),+ "local".into(),+ "--title".into(),+ "Review".into(),+ "--sql-file".into(),+ sql_file.display().to_string(),+ ])+ .await;++ match env {+ CliEnvelope::Success { source, data, .. } => {+ assert_eq!(source, CliSource::Headless);+ assert_eq!(data["status"], "queued");+ }+ CliEnvelope::Failure { error, .. } => panic!("expected queued handoff, got {error:?}"),+ }++ std::env::remove_var("DBX_APP_DATA_DIR");+ }++ #[tokio::test]+ async fn result_current_rejects_non_positive_and_over_limit_values() {+ for limit in ["0", "-1", "1001", "abc"] {+ assert_failure_code(+ dispatch(vec!["result".into(), "current".into(), "--limit".into(), limit.into()]).await,+ CliErrorCode::InternalError,+ );+ }+ }}diff --git a/crates/dbx-cli/src/main.rs b/crates/dbx-cli/src/main.rsindex f34308a758..9a5a19356d 100644--- a/crates/dbx-cli/src/main.rs+++ b/crates/dbx-cli/src/main.rs@@ -4,10 +4,7 @@ mod runtime_client;#[tokio::main]async fn main() {if let Err(err) = commands::run(std::env::args().skip(1).collect()).await {- println!(- "{}",- serde_json::to_string_pretty(&err).unwrap_or_else(|_| "{\"ok\":false}".to_string())- );+ println!("{}", serde_json::to_string_pretty(&err).unwrap_or_else(|_| "{\"ok\":false}".to_string()));std::process::exit(1);}}diff --git a/crates/dbx-cli/src/runtime_client.rs b/crates/dbx-cli/src/runtime_client.rsindex 45cb1898b8..effa954a0a 100644--- a/crates/dbx-cli/src/runtime_client.rs+++ b/crates/dbx-cli/src/runtime_client.rs@@ -1,6 +1,10 @@use serde::{Deserialize, Serialize};+use std::fs::Metadata;use std::path::PathBuf;+#[cfg(test)]+pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RuntimeDiscovery {@@ -13,8 +17,7 @@ pub fn app_data_dir() -> PathBuf {return PathBuf::from(path);}- let home = std::env::var(if cfg!(windows) { "APPDATA" } else { "HOME" })- .unwrap_or_else(|_| ".".to_string());+ let home = std::env::var(if cfg!(windows) { "APPDATA" } else { "HOME" }).unwrap_or_else(|_| ".".to_string());if cfg!(target_os = "macos") {PathBuf::from(home).join("Library/Application Support/com.dbx.app")@@ -27,35 +30,47 @@ pub fn app_data_dir() -> PathBuf {pub fn load_runtime() -> Option<RuntimeDiscovery> {let path = app_data_dir().join("agent-runtime.json");+ let metadata = std::fs::symlink_metadata(&path).ok()?;+ if !is_secure_runtime_file(&metadata) {+ return None;+ }let json = std::fs::read_to_string(path).ok()?;serde_json::from_str(&json).ok()}pub async fn get_json(path: &str) -> Result<serde_json::Value, String> {let runtime = load_runtime().ok_or_else(|| "runtime unavailable".to_string())?;- let url = format!("http://127.0.0.1:{}{}", runtime.port, path);+ let url = runtime_url(&runtime, path, &[])?;- let response = reqwest::Client::new()- .get(url)- .bearer_auth(runtime.token)- .send()- .await- .map_err(|err| err.to_string())?;+ let response =+ reqwest::Client::new().get(url).bearer_auth(runtime.token).send().await.map_err(|err| err.to_string())?;let status = response.status();if !status.is_success() {return Err(format!("runtime request failed with status {status}"));}- response- .json()- .await- .map_err(|err| err.to_string())+ response.json().await.map_err(|err| err.to_string())+}++pub async fn get_json_with_query(path: &str, query: &[(&str, String)]) -> Result<serde_json::Value, String> {+ let runtime = load_runtime().ok_or_else(|| "runtime unavailable".to_string())?;+ let url = runtime_url(&runtime, path, query)?;++ let response =+ reqwest::Client::new().get(url).bearer_auth(runtime.token).send().await.map_err(|err| err.to_string())?;++ let status = response.status();+ if !status.is_success() {+ return Err(format!("runtime request failed with status {status}"));+ }++ response.json().await.map_err(|err| err.to_string())}pub async fn post_json(path: &str, body: serde_json::Value) -> Result<serde_json::Value, String> {let runtime = load_runtime().ok_or_else(|| "runtime unavailable".to_string())?;- let url = format!("http://127.0.0.1:{}{}", runtime.port, path);+ let url = runtime_url(&runtime, path, &[])?;let response = reqwest::Client::new().post(url)@@ -70,8 +85,106 @@ pub async fn post_json(path: &str, body: serde_json::Value) -> Result<serde_jsonreturn Err(format!("runtime request failed with status {status}"));}- response- .json()- .await- .map_err(|err| err.to_string())+ response.json().await.map_err(|err| err.to_string())+}++fn runtime_url(runtime: &RuntimeDiscovery, path: &str, query: &[(&str, String)]) -> Result<reqwest::Url, String> {+ if path.contains('\r') || path.contains('\n') || path.contains("://") {+ return Err("invalid runtime path".to_string());+ }++ let mut url = reqwest::Url::parse(&format!("http://127.0.0.1:{}/", runtime.port)).map_err(|err| err.to_string())?;+ url.set_path(path.trim_start_matches('/'));+ {+ let mut pairs = url.query_pairs_mut();+ for (key, value) in query {+ pairs.append_pair(key, value);+ }+ }+ Ok(url)+}++fn is_secure_runtime_file(metadata: &Metadata) -> bool {+ if metadata.file_type().is_symlink() || !metadata.is_file() {+ return false;+ }+ runtime_file_owner_and_mode_are_secure(metadata)+}++#[cfg(unix)]+fn runtime_file_owner_and_mode_are_secure(metadata: &Metadata) -> bool {+ use std::os::unix::fs::MetadataExt;++ let owner_only = metadata.mode() & 0o077 == 0;+ let owned_by_effective_user = metadata.uid() == unsafe { libc::geteuid() };+ owner_only && owned_by_effective_user+}++#[cfg(not(unix))]+fn runtime_file_owner_and_mode_are_secure(_metadata: &Metadata) -> bool {+ true+}++#[cfg(test)]+mod tests {+ use super::*;++ #[cfg(unix)]+ fn set_mode(path: &std::path::Path, mode: u32) {+ use std::os::unix::fs::PermissionsExt;++ let mut permissions = std::fs::metadata(path).unwrap().permissions();+ permissions.set_mode(mode);+ std::fs::set_permissions(path, permissions).unwrap();+ }++ #[test]+ fn load_runtime_rejects_symlink_discovery_file() {+ let _guard = ENV_LOCK.lock().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("target.json");+ let link = dir.path().join("agent-runtime.json");+ std::fs::write(&target, r#"{"port":4321,"token":"secret"}"#).unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(&target, &link).unwrap();+ #[cfg(not(unix))]+ std::fs::write(&link, r#"{"port":4321,"token":"secret"}"#).unwrap();+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());++ assert!(load_runtime().is_none());++ std::env::remove_var("DBX_APP_DATA_DIR");+ }++ #[cfg(unix)]+ #[test]+ fn load_runtime_rejects_group_or_world_accessible_discovery_file() {+ let _guard = ENV_LOCK.lock().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let discovery = dir.path().join("agent-runtime.json");+ std::fs::write(&discovery, r#"{"port":4321,"token":"secret"}"#).unwrap();+ set_mode(&discovery, 0o644);+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());++ assert!(load_runtime().is_none());++ std::env::remove_var("DBX_APP_DATA_DIR");+ }++ #[cfg(unix)]+ #[test]+ fn load_runtime_accepts_owner_only_discovery_file() {+ let _guard = ENV_LOCK.lock().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let discovery = dir.path().join("agent-runtime.json");+ std::fs::write(&discovery, r#"{"port":4321,"token":"secret"}"#).unwrap();+ set_mode(&discovery, 0o600);+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());++ let runtime = load_runtime().expect("secure runtime discovery should load");+ assert_eq!(runtime.port, 4321);+ assert_eq!(runtime.token, "secret");++ std::env::remove_var("DBX_APP_DATA_DIR");+ }}