fix(mongodb-agent): block readonly query misjudged as write

This commit is contained in:
zipg authored and GitHub committed 2026-08-06 20:10:31 +08:00
1 parent fa15eb5707
commit a71c767174
7 files changed
+690 -221

No files matched your search

+141 -1
View File
@@ -191,7 +191,9 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
return vec![list_collections_tool(), browse_collection_tool(), get_current_time_tool()];
}
let mut tools = vec![list_tables_tool(), get_columns_tool(), get_current_time_tool()];
if supports_sql_query(db_type) {
if db_type == DatabaseType::MongoDb {
tools.push(mongo_execute_query_tool(sql_permissions));
} else if supports_sql_query(db_type) {
tools.push(execute_query_tool(sql_permissions));
tools.push(get_sample_data_tool());
}
@@ -201,6 +203,29 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
tools
}
fn mongo_execute_query_tool(_sql_permissions: AgentSqlPermissions) -> ToolDefinition {
ToolDefinition {
name: "execute_query",
description: "Execute a read-only MongoDB shell command and return results (max 50 rows). Use commands such as db.collection.find({}), db.collection.findOne({}), db.collection.aggregate([]), or db.collection.countDocuments({}). Write commands are not available to the MongoDB Agent.",
parameters: json!({
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "The MongoDB shell-style command to execute"
},
"limit": {
"type": "number",
"description": "Max rows to return (default 50, max 100)"
}
},
"required": ["sql"]
}),
read_only: true,
parallel_ok: false,
}
}
/// list_tables tool definition.
fn list_tables_tool() -> ToolDefinition {
ToolDefinition {
@@ -620,6 +645,10 @@ async fn execute_execute_query(
.map(|l| (l as usize).min(MAX_ALLOWED_ROWS))
.unwrap_or(EXECUTE_QUERY_LIMIT);
if *db_type == DatabaseType::MongoDb {
return execute_mongo_query(state, connection_id, database, sql, limit.max(1)).await;
}
// Classify SQL risk using the concrete database dialect.
let risk = crate::sql_risk::classify_sql_risk_for_database(sql, *db_type)?;
let connection_config = state.configs.read().await.get(connection_id).cloned();
@@ -677,6 +706,29 @@ async fn execute_execute_query(
format_query_result_as_text(&result, limit)
}
async fn execute_mongo_query(
state: &Arc<AppState>,
connection_id: &str,
database: &str,
source: &str,
limit: usize,
) -> Result<String, String> {
let command = crate::mongo_shell::parse(source).map_err(|error| {
format!(
"{error} Use MongoDB shell-style commands such as db.collection.find({{}}), db.collection.findOne({{}}), or db.collection.aggregate([])."
)
})?;
if command.is_mutating() {
return Err(
"Blocked: MongoDB Agent queries are read-only. Return the command for the user to review and execute manually in DBX."
.to_string(),
);
}
let result = crate::mongo_ops::execute_mongo_command_core(state, connection_id, database, &command, limit).await?;
format_query_result_as_text(&result, limit)
}
/// Format a QueryResult as a Markdown table for LLM consumption.
fn format_query_result_as_text(result: &QueryResult, limit: usize) -> Result<String, String> {
// A result without columns is a command result, not an empty result set.
@@ -1174,6 +1226,94 @@ for line in sys.stdin:
assert!(names.contains(&"get_current_time"));
}
#[cfg(unix)]
#[tokio::test]
async fn mongodb_agent_registers_shell_query_tool_and_routes_find_one_as_read_only() {
let tools = all_tools(DatabaseType::MongoDb, AgentSqlPermissions::default());
let names = tools.iter().map(|tool| tool.name).collect::<Vec<_>>();
assert!(names.contains(&"execute_query"));
assert!(!names.contains(&"get_sample_data"));
assert!(!names.contains(&"explain_query"));
let execute_query = tools.iter().find(|tool| tool.name == "execute_query").unwrap();
assert!(execute_query.description.contains("MongoDB shell command"));
assert!(!execute_query.description.contains("SQL query"));
assert!(execute_query.description.contains("read-only"));
let confirmed_tools = all_tools(
DatabaseType::MongoDb,
AgentSqlPermissions {
allow_writes: true,
allow_dangerous: true,
confirmed_write_sql: Some("db.items.insertOne({name: 'test'})".to_string()),
},
);
let confirmed_execute_query = confirmed_tools.iter().find(|tool| tool.name == "execute_query").unwrap();
assert!(confirmed_execute_query.description.contains("read-only"));
assert!(!confirmed_execute_query.description.contains("confirmed write"));
let temp_dir = tempfile::tempdir().unwrap();
let storage = Storage::open(&temp_dir.path().join("storage.db")).await.unwrap();
let state = Arc::new(AppState::new(storage));
let call = ToolCall {
id: "mongo-find-one".to_string(),
name: "execute_query".to_string(),
arguments: json!({ "sql": "db.BenchmarkIndex_approved.findOne({})" }),
provider_payload: None,
};
let result = execute_tool(
&call,
&state,
"mongo-1",
"benchmark",
None,
&DatabaseType::MongoDb,
AgentSqlPermissions::default(),
)
.await;
assert!(result.is_error);
assert!(!result.content.contains("Blocked:"), "{}", result.content);
assert!(result.content.contains("Connection") || result.content.contains("connection"), "{}", result.content);
}
#[cfg(unix)]
#[tokio::test]
async fn mongodb_agent_keeps_all_writes_blocked_after_sql_confirmation() {
let temp_dir = tempfile::tempdir().unwrap();
let storage = Storage::open(&temp_dir.path().join("storage.db")).await.unwrap();
let state = Arc::new(AppState::new(storage));
let permissions = AgentSqlPermissions {
allow_writes: true,
allow_dangerous: true,
confirmed_write_sql: Some("SQL confirmation does not grant MongoDB writes".to_string()),
};
for (index, source) in [
"db.items.insertOne({name: 'test'})",
"db.items.updateMany({tenant: 7}, {$set: {active: false}})",
"db.items.deleteMany({tenant: 7})",
"db.items.createIndex({tenant: 1})",
r#"db.items.aggregate([{"$out":"items_backup"}])"#,
]
.into_iter()
.enumerate()
{
let call = ToolCall {
id: format!("mongo-write-{index}"),
name: "execute_query".to_string(),
arguments: json!({ "sql": source }),
provider_payload: None,
};
let result =
execute_tool(&call, &state, "mongo-1", "benchmark", None, &DatabaseType::MongoDb, permissions.clone())
.await;
assert!(result.is_error, "{source}: {}", result.content);
assert!(result.content.contains("read-only"), "{source}: {}", result.content);
}
}
#[test]
fn confirmed_sql_permissions_update_execute_query_contract() {
let tools = all_tools(
+44 -4
View File
@@ -709,6 +709,41 @@ pub async fn find_documents(
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
) -> Result<MongoDocumentResult, String> {
find_documents_with_total(client, database, collection, skip, limit, filter, projection, sort, collation, true)
.await
}
/// Execute a find without the document browser's separate total-count query.
/// Agent callers only consume returned rows, so counting the full result set adds latency
/// without providing any useful output.
pub async fn find_documents_without_total(
client: &Client,
database: &str,
collection: &str,
skip: u64,
limit: i64,
filter: Option<&str>,
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
) -> Result<MongoDocumentResult, String> {
find_documents_with_total(client, database, collection, skip, limit, filter, projection, sort, collation, false)
.await
}
#[allow(clippy::too_many_arguments)]
async fn find_documents_with_total(
client: &Client,
database: &str,
collection: &str,
skip: u64,
limit: i64,
filter: Option<&str>,
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
include_total: bool,
) -> Result<MongoDocumentResult, String> {
let col = client.database(database).collection::<Document>(collection);
@@ -722,14 +757,16 @@ pub async fn find_documents(
let collation = parse_find_collation(collation)?;
let count_is_exact = !filter_doc.is_empty();
let total_result = if count_is_exact {
let total_result = if !include_total {
None
} else if count_is_exact {
let mut count = col.count_documents(filter_doc.clone());
if let Some(collation) = collation.clone() {
count = count.collation(collation);
}
count.await.map_err(|e| e.to_string())
Some(count.await.map_err(|e| e.to_string()))
} else {
col.estimated_document_count().await.map_err(|e| e.to_string())
Some(col.estimated_document_count().await.map_err(|e| e.to_string()))
};
let mut find = col.find(filter_doc).skip(skip).limit(limit);
@@ -761,7 +798,10 @@ pub async fn find_documents(
documents.push(bson_to_json(&Bson::Document(doc.clone())));
extended_documents.push(Bson::Document(doc).into_canonical_extjson());
}
let (total, total_is_exact) = resolve_mongo_find_total(total_result, count_is_exact, skip, documents.len());
let (total, total_is_exact) = match total_result {
Some(total_result) => resolve_mongo_find_total(total_result, count_is_exact, skip, documents.len()),
None => (documents.len() as u64, false),
};
Ok(MongoDocumentResult {
documents,
+347
View File
@@ -4,6 +4,8 @@ use crate::db::mongo_driver::{
self, MongoCollectionStatsResult, MongoDocumentResult, MongoDropIndexFailure, MongoDropIndexesResult,
};
use crate::document_ops::CollectionInfo;
use crate::mongo_shell::MongoCommand;
use crate::types::QueryResult;
async fn ensure_document_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
state.get_or_create_pool(connection_id, None).await.map(|_| ())
@@ -155,6 +157,50 @@ pub async fn mongo_find_documents_core(
.await
}
#[allow(clippy::too_many_arguments)]
async fn mongo_find_documents_without_total_core(
state: &AppState,
connection_id: &str,
database: &str,
collection: &str,
skip: u64,
limit: i64,
filter: Option<&str>,
projection: Option<&str>,
sort: Option<&str>,
collation: Option<&str>,
) -> Result<MongoDocumentResult, String> {
ensure_document_pool(state, connection_id).await?;
let connections = state.connections.read().await;
match connections.get(connection_id).ok_or("Not found")? {
PoolKind::MongoDb(client) => {
mongo_driver::find_documents_without_total(
client, database, collection, skip, limit, filter, projection, sort, collation,
)
.await
}
PoolKind::Agent(client) => {
let mut client = client.lock().await;
let mut params = serde_json::json!({
"database": database,
"collection": collection,
"skip": skip,
"limit": limit,
"filter": filter,
"sort": sort,
});
if let Some(projection) = projection {
params["projection"] = serde_json::json!(projection);
}
if let Some(collation) = collation {
params["collation"] = serde_json::json!(collation);
}
client.mongo_find_documents(params).await
}
_ => Err("Not a MongoDB connection".to_string()),
}
}
pub async fn mongo_find_one_core(
state: &AppState,
connection_id: &str,
@@ -635,10 +681,311 @@ pub async fn mongo_find_one_and_delete_core(
}
}
pub async fn execute_mongo_command_core(
state: &AppState,
connection_id: &str,
database: &str,
command: &MongoCommand,
max_rows: usize,
) -> Result<QueryResult, String> {
use serde_json::Value;
match command {
MongoCommand::Version => mongo_server_version_core(state, connection_id, database)
.await
.map(|version| scalar_query_result("version", Value::String(version))),
MongoCommand::Use { database } => Ok(scalar_query_result("database", Value::String(database.clone()))),
MongoCommand::Find { collection, filter, projection, sort, collation, skip, limit } => {
let limit = bounded_mongo_find_limit(*limit, max_rows);
let result = mongo_find_documents_without_total_core(
state,
connection_id,
database,
collection,
*skip,
limit,
Some(filter),
projection.as_deref(),
sort.as_deref(),
collation.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOne { collection, filter, projection, options } => {
let result = mongo_find_one_core(
state,
connection_id,
database,
collection,
Some(filter),
projection.as_deref(),
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Count { collection, filter, accurate } => {
let mode = if *accurate { "accurate" } else { "legacy" };
let total =
mongo_count_documents_core(state, connection_id, database, collection, Some(filter), Some(mode))
.await?;
Ok(scalar_query_result("count", Value::from(total)))
}
MongoCommand::Aggregate { collection, pipeline, options } => {
let result = mongo_aggregate_documents_core(
state,
connection_id,
database,
collection,
pipeline,
Some(max_rows),
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Distinct { collection, field, filter } => {
let result =
mongo_distinct_core(state, connection_id, database, collection, field, filter.as_deref()).await?;
Ok(mongo_documents_query_result(limit_mongo_documents(result, max_rows).documents))
}
MongoCommand::GetIndexes { collection } => {
let result = mongo_aggregate_documents_core(
state,
connection_id,
database,
collection,
r#"[{"$indexStats":{}}]"#,
Some(max_rows),
None,
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::CollectionStats { collection, metric, scale } => {
let stats = mongo_collection_stats_core(state, connection_id, database, collection, scale.clone()).await?;
let value = serde_json::to_value(stats).map_err(|error| error.to_string())?;
if metric == "stats" {
Ok(mongo_documents_query_result(vec![value]))
} else {
let key = match metric.as_str() {
"dataSize" => "size",
"storageSize" => "storageSize",
"totalIndexSize" => "totalIndexSize",
_ => metric,
};
Ok(scalar_query_result(metric, value.get(key).cloned().unwrap_or(Value::Null)))
}
}
MongoCommand::Insert { collection, documents } => {
let affected = mongo_insert_documents_core(state, connection_id, database, collection, documents).await?;
Ok(affected_query_result(affected))
}
MongoCommand::Update { collection, filter, update, options, many } => {
let affected = mongo_update_documents_core(
state,
connection_id,
database,
collection,
filter,
update,
*many,
options.as_deref(),
)
.await?;
Ok(affected_query_result(affected))
}
MongoCommand::Delete { collection, filter, many } => {
let affected =
mongo_delete_documents_core(state, connection_id, database, collection, filter, *many).await?;
Ok(affected_query_result(affected))
}
MongoCommand::CreateIndex { collection, keys, options } => {
let name =
mongo_create_index_core(state, connection_id, database, collection, keys, options.as_deref()).await?;
Ok(scalar_query_result("name", Value::String(name)))
}
MongoCommand::DropIndexes { collection, indexes, single } => {
let result =
mongo_drop_indexes_core(state, connection_id, database, collection, indexes.as_deref(), *single)
.await?;
Ok(mongo_drop_indexes_query_result(
result.dropped_names,
result.failures.into_iter().map(|failure| (failure.name, failure.message)).collect(),
result.affected_rows,
))
}
MongoCommand::DropCollection { collection } => {
mongo_drop_collection_core(state, connection_id, database, collection).await?;
Ok(affected_query_result(1))
}
MongoCommand::FindOneAndUpdate { collection, filter, update, options } => {
let result = mongo_find_one_and_update_core(
state,
connection_id,
database,
collection,
filter,
update,
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndReplace { collection, filter, replacement, options } => {
let result = mongo_find_one_and_replace_core(
state,
connection_id,
database,
collection,
filter,
replacement,
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndDelete { collection, filter, options } => {
let result =
mongo_find_one_and_delete_core(state, connection_id, database, collection, filter, options.as_deref())
.await?;
Ok(mongo_documents_query_result(result.documents))
}
}
}
fn bounded_mongo_find_limit(command_limit: i64, max_rows: usize) -> i64 {
let max_rows = max_rows.max(1).min(i64::MAX as usize) as i64;
if command_limit == 0 {
return max_rows;
}
command_limit.saturating_abs().min(max_rows).max(1)
}
fn limit_mongo_documents(mut result: MongoDocumentResult, max_rows: usize) -> MongoDocumentResult {
let max_rows = max_rows.max(1);
result.documents.truncate(max_rows);
if let Some(raw_documents) = result.raw_documents.as_mut() {
raw_documents.truncate(max_rows);
}
if let Some(extended_documents) = result.extended_documents.as_mut() {
extended_documents.truncate(max_rows);
}
result
}
fn query_result(columns: Vec<String>, rows: Vec<Vec<serde_json::Value>>, affected_rows: u64) -> QueryResult {
QueryResult {
columns,
column_types: Vec::new(),
column_sortables: Vec::new(),
spatial_columns: Vec::new(),
spatial_values: Vec::new(),
rows,
affected_rows,
execution_time_ms: 0,
truncated: false,
session_id: None,
has_more: false,
elasticsearch_raw_body: None,
}
}
fn scalar_query_result(column: impl Into<String>, value: serde_json::Value) -> QueryResult {
query_result(vec![column.into()], vec![vec![value]], 0)
}
fn affected_query_result(affected_rows: u64) -> QueryResult {
query_result(Vec::new(), Vec::new(), affected_rows)
}
fn mongo_drop_indexes_query_result(
dropped_names: Vec<String>,
failures: Vec<(String, String)>,
affected_rows: u64,
) -> QueryResult {
use serde_json::Value;
if failures.is_empty() {
let rows = dropped_names.into_iter().map(|name| vec![Value::String(name)]).collect::<Vec<_>>();
return query_result(if rows.is_empty() { Vec::new() } else { vec!["name".to_string()] }, rows, affected_rows);
}
let mut rows = dropped_names
.into_iter()
.map(|name| vec![Value::String(name), Value::String("dropped".to_string()), Value::Null])
.collect::<Vec<_>>();
rows.extend(
failures.into_iter().map(|(name, message)| {
vec![Value::String(name), Value::String("failed".to_string()), Value::String(message)]
}),
);
query_result(vec!["name".to_string(), "status".to_string(), "message".to_string()], rows, affected_rows)
}
fn mongo_documents_query_result(documents: Vec<serde_json::Value>) -> QueryResult {
use serde_json::Value;
if documents.is_empty() {
return query_result(Vec::new(), Vec::new(), 0);
}
let mut columns = std::collections::BTreeSet::new();
for document in &documents {
if let Some(object) = document.as_object() {
columns.extend(object.keys().cloned());
} else {
columns.insert("value".to_string());
}
}
let columns = columns.into_iter().collect::<Vec<_>>();
let rows = documents
.into_iter()
.map(|document| {
columns
.iter()
.map(|column| {
document
.as_object()
.and_then(|object| object.get(column))
.cloned()
.or_else(|| (column == "value").then(|| document.clone()))
.unwrap_or(Value::Null)
})
.collect()
})
.collect();
query_result(columns, rows, 0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn agent_find_limit_never_passes_an_unbounded_zero_to_mongodb() {
assert_eq!(bounded_mongo_find_limit(0, 50), 50);
assert_eq!(bounded_mongo_find_limit(0, 0), 1);
assert_eq!(bounded_mongo_find_limit(100, 7), 7);
assert_eq!(bounded_mongo_find_limit(-100, 7), 7);
}
#[test]
fn agent_document_limit_caps_distinct_values() {
let result = MongoDocumentResult {
documents: vec![serde_json::json!(1), serde_json::json!(2), serde_json::json!(3)],
raw_documents: Some(vec!["1".to_string(), "2".to_string(), "3".to_string()]),
extended_documents: Some(vec![serde_json::json!(1), serde_json::json!(2), serde_json::json!(3)]),
total: 3,
total_is_exact: true,
};
let limited = limit_mongo_documents(result, 2);
assert_eq!(limited.documents, vec![serde_json::json!(1), serde_json::json!(2)]);
assert_eq!(limited.raw_documents.unwrap(), vec!["1", "2"]);
assert_eq!(limited.extended_documents.unwrap(), vec![serde_json::json!(1), serde_json::json!(2)]);
}
#[cfg(unix)]
use crate::db::agent_driver::{AgentDriverClient, AgentLaunchSpec};
#[cfg(unix)]