feat(mcp): centralize connection access policies
This commit is contained in:
56 files changed
+6393
-617
No files matched your search
@@ -1,4 +1,4 @@
|
||||
use std::sync::Arc;
|
||||
use std::{ffi::OsString, sync::Arc};
|
||||
|
||||
use dbx_core::{models::connection::ConnectionConfig, storage::Storage};
|
||||
use dbx_mcp::{DbxMcpServer, LocalBackend, McpScope};
|
||||
@@ -6,6 +6,29 @@ use rmcp::{model::CallToolRequestParams, ServiceExt};
|
||||
use serde_json::{json, Map, Value};
|
||||
use tempfile::tempdir;
|
||||
|
||||
struct EnvVarGuard {
|
||||
name: &'static str,
|
||||
original: Option<OsString>,
|
||||
}
|
||||
|
||||
impl EnvVarGuard {
|
||||
fn set(name: &'static str, value: &str) -> Self {
|
||||
let original = std::env::var_os(name);
|
||||
std::env::set_var(name, value);
|
||||
Self { name, original }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EnvVarGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(value) = self.original.take() {
|
||||
std::env::set_var(self.name, value);
|
||||
} else {
|
||||
std::env::remove_var(self.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_backend_reads_dbx_storage_without_desktop_process() {
|
||||
let directory = tempdir().expect("temporary data directory");
|
||||
@@ -42,6 +65,51 @@ async fn local_backend_reads_dbx_storage_without_desktop_process() {
|
||||
server_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_read_only_config_applies_before_settings_are_opened() {
|
||||
let _allow_writes = EnvVarGuard::set("DBX_MCP_ALLOW_WRITES", "0");
|
||||
let directory = tempdir().expect("temporary data directory");
|
||||
let db_path = directory.path().join("dbx.db");
|
||||
let storage = Storage::open(&db_path).await.expect("open storage");
|
||||
assert!(!storage.load_mcp_global_policy().await.expect("load MCP policy").configured);
|
||||
let connection: ConnectionConfig = serde_json::from_value(json!({
|
||||
"id": "legacy-read-only",
|
||||
"name": "legacy-read-only",
|
||||
"db_type": "sqlite",
|
||||
"host": "",
|
||||
"port": 0,
|
||||
"username": "",
|
||||
"password": "",
|
||||
"database": directory.path().join("legacy.sqlite").to_string_lossy(),
|
||||
"ssl": false
|
||||
}))
|
||||
.expect("minimal connection config");
|
||||
storage.save_connections(&[connection]).await.expect("save connection");
|
||||
|
||||
let backend = Arc::new(LocalBackend::open(&db_path).await.expect("open local backend"));
|
||||
let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
|
||||
let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
|
||||
let server_task = tokio::spawn(async move { server.serve(server_transport).await });
|
||||
let client = ().serve(client_transport).await.expect("initialize client");
|
||||
let arguments = json!({
|
||||
"connection_id": "legacy-read-only",
|
||||
"sql": "INSERT INTO items (name) VALUES ('blocked')",
|
||||
})
|
||||
.as_object()
|
||||
.cloned()
|
||||
.unwrap_or_else(Map::<String, Value>::new);
|
||||
let result = client
|
||||
.peer()
|
||||
.call_tool(CallToolRequestParams::new("dbx_execute_query").with_arguments(arguments))
|
||||
.await
|
||||
.expect("execute query");
|
||||
let text = result.content[0].as_text().expect("text result");
|
||||
assert_eq!(result.is_error, Some(true));
|
||||
assert!(text.text.contains("MCP_READ_ONLY"), "unexpected MCP response: {}", text.text);
|
||||
client.cancel().await.expect("close client");
|
||||
server_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DBX_MCP_TEST_MONGO_HOST and DBX_MCP_TEST_MONGO_PASSWORD"]
|
||||
async fn executes_mongo_shell_commands_without_desktop_process() {
|
||||
@@ -74,8 +142,6 @@ async fn executes_mongo_shell_commands_without_desktop_process() {
|
||||
let (server_transport, client_transport) = tokio::io::duplex(32 * 1024);
|
||||
let server_task = tokio::spawn(async move { server.serve(server_transport).await });
|
||||
let client = ().serve(client_transport).await.expect("initialize client");
|
||||
let original_writes = std::env::var_os("DBX_MCP_ALLOW_WRITES");
|
||||
std::env::set_var("DBX_MCP_ALLOW_WRITES", "1");
|
||||
|
||||
call_query(&client, "db.items.deleteOne({_id: 'rust-mcp-e2e'})").await;
|
||||
call_query(&client, "db.items.insert({_id: 'rust-mcp-e2e', name: 'Ada'})").await;
|
||||
@@ -83,10 +149,6 @@ async fn executes_mongo_shell_commands_without_desktop_process() {
|
||||
assert!(result.contains("Ada"), "unexpected MongoDB result: {result}");
|
||||
call_query(&client, "db.items.deleteOne({_id: 'rust-mcp-e2e'})").await;
|
||||
|
||||
match original_writes {
|
||||
Some(value) => std::env::set_var("DBX_MCP_ALLOW_WRITES", value),
|
||||
None => std::env::remove_var("DBX_MCP_ALLOW_WRITES"),
|
||||
}
|
||||
client.cancel().await.expect("close client");
|
||||
server_task.abort();
|
||||
}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use dbx_core::{agent_events::ToolResult, agent_tools::AgentSqlPermissions, models::connection::ConnectionConfig};
|
||||
use dbx_core::{
|
||||
agent_events::ToolResult, agent_tools::AgentSqlPermissions, models::connection::ConnectionConfig,
|
||||
storage::McpGlobalPolicy,
|
||||
};
|
||||
use dbx_mcp::{DbxBackend, DbxMcpServer, McpScope};
|
||||
use rmcp::{model::CallToolRequestParams, ServiceExt};
|
||||
use serde_json::Value;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
struct EmptyBackend;
|
||||
|
||||
#[async_trait]
|
||||
impl DbxBackend for EmptyBackend {
|
||||
async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {
|
||||
Ok(McpGlobalPolicy::default())
|
||||
}
|
||||
|
||||
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
@@ -31,9 +38,69 @@ impl DbxBackend for EmptyBackend {
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_connections(&self, _connections: &[ConnectionConfig]) -> Result<(), String> {
|
||||
Ok(())
|
||||
async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
struct PolicyBackend {
|
||||
policy: McpGlobalPolicy,
|
||||
connections: Vec<ConnectionConfig>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DbxBackend for PolicyBackend {
|
||||
async fn load_mcp_global_policy(&self) -> Result<McpGlobalPolicy, String> {
|
||||
Ok(self.policy.clone())
|
||||
}
|
||||
|
||||
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
|
||||
Ok(self.connections.clone())
|
||||
}
|
||||
|
||||
async fn execute_agent_tool(
|
||||
&self,
|
||||
_connection: &ConnectionConfig,
|
||||
_database: &str,
|
||||
tool_name: &str,
|
||||
_arguments: Value,
|
||||
_permissions: AgentSqlPermissions,
|
||||
) -> ToolResult {
|
||||
ToolResult {
|
||||
tool_call_id: "policy-test".to_string(),
|
||||
tool_name: tool_name.to_string(),
|
||||
content: "query should have been blocked".to_string(),
|
||||
is_error: true,
|
||||
explain_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
async fn remove_connection_for_mcp(&self, _connection_id: &str) -> Result<bool, String> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn test_connection(id: &str, name: &str) -> ConnectionConfig {
|
||||
serde_json::from_value(json!({
|
||||
"id": id,
|
||||
"name": name,
|
||||
"db_type": "sqlite",
|
||||
"host": "",
|
||||
"port": 0,
|
||||
"username": "",
|
||||
"password": "",
|
||||
"database": ":memory:",
|
||||
"ssl": false
|
||||
}))
|
||||
.expect("test connection")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -57,3 +124,53 @@ async fn initializes_lists_tools_and_calls_a_tool() {
|
||||
client.cancel().await.expect("close MCP client");
|
||||
server_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enforces_global_connection_scope_and_read_only_policy() {
|
||||
let backend = PolicyBackend {
|
||||
policy: McpGlobalPolicy {
|
||||
read_only: true,
|
||||
allow_dangerous_sql: false,
|
||||
allowed_connection_ids: Some(vec!["allowed".to_string()]),
|
||||
},
|
||||
connections: vec![test_connection("allowed", "allowed-db"), test_connection("blocked", "blocked-db")],
|
||||
};
|
||||
let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
|
||||
let server = DbxMcpServer::with_runtime_options(Arc::new(backend), McpScope::default(), false);
|
||||
let server_task = tokio::spawn(async move { server.serve(server_transport).await });
|
||||
let client = ().serve(client_transport).await.expect("initialize MCP client");
|
||||
|
||||
let listed =
|
||||
client.peer().call_tool(CallToolRequestParams::new("dbx_list_connections")).await.expect("list connections");
|
||||
let listed_text = listed.content[0].as_text().expect("list result").text.clone();
|
||||
assert!(listed_text.contains("allowed-db"));
|
||||
assert!(!listed_text.contains("blocked-db"));
|
||||
|
||||
let blocked = client
|
||||
.peer()
|
||||
.call_tool(CallToolRequestParams::new("dbx_execute_query").with_arguments(
|
||||
json!({ "connection_id": "blocked", "sql": "SELECT 1" }).as_object().cloned().unwrap_or_else(Map::new),
|
||||
))
|
||||
.await
|
||||
.expect("call blocked connection");
|
||||
assert_eq!(blocked.is_error, Some(true));
|
||||
assert!(blocked.content[0].as_text().expect("blocked result").text.contains("CONNECTION_OUT_OF_SCOPE"));
|
||||
|
||||
let read_only = client
|
||||
.peer()
|
||||
.call_tool(
|
||||
CallToolRequestParams::new("dbx_execute_query").with_arguments(
|
||||
json!({ "connection_id": "allowed", "sql": "DELETE FROM users" })
|
||||
.as_object()
|
||||
.cloned()
|
||||
.unwrap_or_else(Map::new),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("call read-only policy");
|
||||
assert_eq!(read_only.is_error, Some(true));
|
||||
assert!(read_only.content[0].as_text().expect("read-only result").text.contains("MCP_READ_ONLY"));
|
||||
|
||||
client.cancel().await.expect("close MCP client");
|
||||
server_task.abort();
|
||||
}
|
||||
Reference in new issue
Block a user