дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
feat(mcp): add read-only database tools (#8275)
The built-in MCP server gets five database tools: list_database_connections, list_database_schemas, list_schema_objects, get_database_object_description and execute_sql_query. They reuse the project's data sources and credential store, never expose URLs, hosts, users or passwords, and need a trusted project; plugin-owned sources stay out. execute_sql_query runs one SELECT/WITH/EXPLAIN statement after a confirmation showing the exact SQL, in a driver-enforced read-only session that is verified before the statement runs (SQLite PRAGMA query_only, PostgreSQL BEGIN READ ONLY with pinned client_encoding, MySQL/MariaDB read-only transaction with utf8mb4 and safe sql_mode, Oracle SET TRANSACTION READ ONLY), rolls it back, refuses drivers without such a session and multi-statement SQL, and caps rows, cell size and run time. MCP guide (en/zh) updated. Closes #8176 Co-authored-by: aLIEz1 <[email protected]>
Цей коміт міститься в:
1 джерело
4650d88b73
коміт
98ffcf5919
15 files changed
+2224
-20
No files matched your search
@@ -1433,6 +1433,83 @@ impl Pool {
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs exactly one statement in a driver-enforced read-only session: a write (including one
|
||||
/// in a `WITH` clause) fails in the database, whatever the statement text looks like. Drivers
|
||||
/// without such a session are refused rather than guarded by a keyword check. SQL that
|
||||
/// [`split`](crate::split::split) reads as more than one statement is refused here as well, so
|
||||
/// a direct caller cannot hand a MySQL/PostgreSQL multi-statement batch to the session.
|
||||
pub async fn execute_read_only(
|
||||
&self,
|
||||
sql: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let driver = self.driver();
|
||||
let statements = crate::split::split(sql, driver);
|
||||
if statements.len() != 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"read-only execution runs exactly one statement, but this SQL has {}",
|
||||
statements.len()
|
||||
)));
|
||||
}
|
||||
if self.transaction_read_only() {
|
||||
// The pool runs every statement in a verified `BEGIN READ ONLY` transaction.
|
||||
return self.execute_from(sql, 0, max_rows, cancel).await;
|
||||
}
|
||||
if !matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_) | Pool::Oracle(_)) {
|
||||
return Err(read_only_unsupported(driver));
|
||||
}
|
||||
if driver == DbDriver::Mysql {
|
||||
// The server runs executable comments and further statements that `split` reads as
|
||||
// comments; the client cannot turn its multi-statement handling off.
|
||||
crate::split::mysql_guard(sql)?;
|
||||
}
|
||||
if let Pool::Oracle(_) = self {
|
||||
// Oracle commits a statement through `Held::command`, which would end the read-only
|
||||
// transaction before the user's statement runs. It has its own non-committing path.
|
||||
let started = Instant::now();
|
||||
let mut conn = Held::acquire_own(self).await?;
|
||||
let result = match &mut conn {
|
||||
Held::Oracle(c) => crate::oracle::execute_read_only(c, sql, max_rows, cancel).await,
|
||||
_ => unreachable!("acquired an Oracle connection"),
|
||||
};
|
||||
conn.discard().await;
|
||||
return result.map(|fetched| query_result(sql, fetched, started));
|
||||
}
|
||||
// A dedicated connection keeps the transaction or PRAGMA off every pooled connection.
|
||||
let mut conn = Held::acquire_own(self).await?;
|
||||
if let Held::Sqlite(c) = &mut conn {
|
||||
// A future dropped mid-session (a timeout, a shutdown) must close this connection
|
||||
// instead of returning one with `PRAGMA query_only` still on to the pool.
|
||||
c.close_on_drop();
|
||||
}
|
||||
if let Err(e) = open_read_only_session(&mut conn, driver, sql).await {
|
||||
conn.discard().await;
|
||||
return Err(e);
|
||||
}
|
||||
let result = match conn.execute_from(self, sql, 0, max_rows, cancel).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
// A failed or cancelled statement must not return an open transaction or query_only.
|
||||
conn.discard().await;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
match close_read_only_session(&mut conn, driver).await {
|
||||
Ok(()) => {
|
||||
if let Held::Sqlite(c) = &mut conn {
|
||||
// The PRAGMA is off again: this connection may go back to the pool.
|
||||
c.return_to_pool().await;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
Err(e) => {
|
||||
conn.discard().await;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `statements` in one transaction; each must change `expect_one`
|
||||
/// row when flagged (table editor submits).
|
||||
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
@@ -1530,6 +1607,161 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
fn driver_name(driver: DbDriver) -> &'static str {
|
||||
driver.display_name()
|
||||
}
|
||||
|
||||
pub(crate) fn read_only_unsupported(driver: DbDriver) -> IdeError {
|
||||
IdeError::invalid(format!(
|
||||
"{} has no read-only session: OpenIDEA refuses to run statements on it without one",
|
||||
driver_name(driver)
|
||||
))
|
||||
}
|
||||
|
||||
/// Opens the driver's read-only session, then checks that the server took it.
|
||||
async fn open_read_only_session(conn: &mut Held, driver: DbDriver, sql: &str) -> IdeResult<()> {
|
||||
match driver {
|
||||
DbDriver::Sqlite => {
|
||||
conn.command("PRAGMA query_only = ON").await?;
|
||||
if read_only_setting(conn, "PRAGMA query_only").await?.as_deref() != Some("1") {
|
||||
return Err(IdeError::invalid("SQLite did not enter a read-only session: PRAGMA query_only is not 1"));
|
||||
}
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
conn.command("BEGIN READ ONLY").await?;
|
||||
if read_only_setting(conn, "SHOW transaction_read_only").await?.as_deref() != Some("on") {
|
||||
return Err(IdeError::invalid(
|
||||
"PostgreSQL did not enter a read-only transaction: transaction_read_only is not on",
|
||||
));
|
||||
}
|
||||
if let Held::Postgres(c) = conn {
|
||||
// sqlx sends the statement as the UTF-8 bytes of the Rust string and decodes text
|
||||
// results as UTF-8, but the server converts those bytes from `client_encoding`
|
||||
// before parsing them, and the source's startup script can change that (and
|
||||
// `standard_conforming_strings`) on every connection. Pin and verify both, as the
|
||||
// MySQL path pins utf8mb4.
|
||||
pg_read_only::pin_encoding(c).await.map_err(db_err)?;
|
||||
// No transaction guard checks this dedicated session's statement, so let the
|
||||
// server parse it as one command before the simple query protocol runs it.
|
||||
pg_read_only::check_single_always(c, sql).await.map_err(db_err)?;
|
||||
}
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
// sqlx sends a statement as the UTF-8 bytes of the Rust string and decodes text
|
||||
// results as UTF-8, but the server's parser reads those bytes as
|
||||
// `character_set_client`. Pin that connection to utf8mb4 (over the source's
|
||||
// `charset` and any startup script) and verify it: in an East-Asian multibyte
|
||||
// charset an ASCII backslash or quote can be swallowed as the second byte of a
|
||||
// character, so the server would split a statement differently than `split` does.
|
||||
conn.command("SET NAMES utf8mb4").await?;
|
||||
let (client, connection) = mysql_connection_charsets(conn).await?;
|
||||
for (name, value) in
|
||||
[("character_set_client", client.as_str()), ("character_set_connection", connection.as_str())]
|
||||
{
|
||||
if !mysql_charset_is_safe(value) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"this MySQL/MariaDB connection reads SQL as {value} ({name}): the server could read \
|
||||
the statement's quotes or backslashes differently than the statement splitter, so \
|
||||
a hidden second statement could run"
|
||||
)));
|
||||
}
|
||||
}
|
||||
// MySQL has no per-transaction flag to read back (`transaction_read_only` is the
|
||||
// session default, which `START TRANSACTION READ ONLY` does not change). Set and
|
||||
// verify the session default first, so a vendor that ignores the clause is refused;
|
||||
// the statement boundary above is what keeps a second, overriding transaction out.
|
||||
conn.command("SET SESSION TRANSACTION READ ONLY").await?;
|
||||
if !mysql_session_read_only(conn).await? {
|
||||
return Err(IdeError::invalid(
|
||||
"MySQL/MariaDB did not take the read-only session: its transaction_read_only setting is off",
|
||||
));
|
||||
}
|
||||
let mode = read_only_setting(conn, "SELECT @@SESSION.sql_mode").await?.unwrap_or_default();
|
||||
if let Some(flag) = mysql_quote_mode_unsupported(&mode) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"this MySQL/MariaDB session sets {flag}: its quotes no longer read like the statement splitter's, \
|
||||
so a hidden second statement could run"
|
||||
)));
|
||||
}
|
||||
conn.command("START TRANSACTION READ ONLY").await?;
|
||||
if !mysql_session_read_only(conn).await? {
|
||||
return Err(IdeError::invalid(
|
||||
"MySQL/MariaDB did not keep the read-only session: its transaction_read_only setting is off",
|
||||
));
|
||||
}
|
||||
}
|
||||
DbDriver::Oracle => unreachable!("Oracle read-only sessions run in oracle::execute_read_only"),
|
||||
_ => return Err(read_only_unsupported(driver)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The session's read-only default: `transaction_read_only` (MySQL 5.7+, MariaDB 11+), then
|
||||
/// MariaDB's older `tx_read_only`. A server with neither has no read-only session to verify.
|
||||
async fn mysql_session_read_only(conn: &mut Held) -> IdeResult<bool> {
|
||||
for name in ["transaction_read_only", "tx_read_only"] {
|
||||
let sql = format!("SELECT @@SESSION.{name}");
|
||||
match read_only_setting(conn, &sql).await {
|
||||
Ok(Some(value)) => {
|
||||
return match value.trim().to_ascii_lowercase().as_str() {
|
||||
"1" | "on" => Ok(true),
|
||||
"0" | "off" => Ok(false),
|
||||
other => Err(IdeError::invalid(format!("MySQL/MariaDB reported {name} as {other}"))),
|
||||
};
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) if error.message.contains("Unknown system variable") => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(IdeError::invalid(
|
||||
"this MySQL-compatible server has no transaction_read_only (or tx_read_only) setting, \
|
||||
so its read-only session cannot be verified",
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether a MySQL connection charset decodes every ASCII byte as itself, so the server reads a
|
||||
/// statement the way [`split`](crate::split::split) and `mysql_guard` do. UTF-8 charsets, ASCII,
|
||||
/// latin1 and binary qualify; East-Asian multibyte charsets (GBK, Big5, SJIS, CP932, GB18030,
|
||||
/// EUC-KR…) can consume an ASCII byte as part of a multibyte character.
|
||||
fn mysql_charset_is_safe(name: &str) -> bool {
|
||||
matches!(name.trim().to_ascii_lowercase().as_str(), "utf8mb4" | "utf8mb3" | "utf8" | "ascii" | "latin1" | "binary")
|
||||
}
|
||||
|
||||
/// The session's `character_set_client` and `character_set_connection`; `SET NAMES` sets both.
|
||||
async fn mysql_connection_charsets(conn: &mut Held) -> IdeResult<(String, String)> {
|
||||
let (_, rows, _, _, _) =
|
||||
conn.fetch_rows("SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection", 1).await?;
|
||||
let row = rows
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| IdeError::invalid("MySQL/MariaDB did not report its connection character set"))?;
|
||||
let mut columns = row.into_iter();
|
||||
Ok((columns.next().flatten().unwrap_or_default(), columns.next().flatten().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// The sql_mode values that change how the server reads quotes; the statement splitter assumes
|
||||
/// MySQL's defaults, so a session with either could split differently than the server parses.
|
||||
fn mysql_quote_mode_unsupported(mode: &str) -> Option<&'static str> {
|
||||
["NO_BACKSLASH_ESCAPES", "ANSI_QUOTES"]
|
||||
.into_iter()
|
||||
.find(|flag| mode.split(',').any(|value| value.trim().eq_ignore_ascii_case(flag)))
|
||||
}
|
||||
|
||||
async fn read_only_setting(conn: &mut Held, sql: &str) -> IdeResult<Option<String>> {
|
||||
let (_, rows, _, _, _) = conn.fetch_rows(sql, 1).await?;
|
||||
Ok(rows.into_iter().next().and_then(|row| row.into_iter().next().flatten()))
|
||||
}
|
||||
|
||||
/// Ends the read-only session a successful statement ran in.
|
||||
async fn close_read_only_session(conn: &mut Held, driver: DbDriver) -> IdeResult<()> {
|
||||
match driver {
|
||||
DbDriver::Sqlite => conn.command("PRAGMA query_only = OFF").await,
|
||||
DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle => conn.command("ROLLBACK").await,
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection of a pool, or one opened beside it that closes when dropped.
|
||||
pub enum Lease<M: ManageConnection> {
|
||||
Pooled(bb8::PooledConnection<'static, M>),
|
||||
@@ -1654,7 +1886,7 @@ impl Held {
|
||||
fn before_statement(&mut self, sql: &str) {
|
||||
let control = sql.trim().trim_end_matches(';').trim().to_ascii_uppercase();
|
||||
if let Held::Mysql(c) = self {
|
||||
if matches!(control.as_str(), "BEGIN" | "START TRANSACTION") {
|
||||
if control == "BEGIN" || control == "START TRANSACTION" || control.starts_with("START TRANSACTION ") {
|
||||
c.in_transaction = true;
|
||||
return;
|
||||
}
|
||||
@@ -2284,4 +2516,75 @@ mod tests {
|
||||
assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE");
|
||||
assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_only_execution_refuses_writes_and_leaves_the_pool_usable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("read-only.db");
|
||||
std::fs::File::create(&file).unwrap();
|
||||
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
pool.execute("CREATE TABLE t (x INTEGER)", 1, &cancel).await.unwrap();
|
||||
|
||||
let result = pool.execute_read_only("SELECT 1", 1, &cancel).await.unwrap();
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
|
||||
|
||||
let refused = pool.execute_read_only("INSERT INTO t VALUES (1)", 10, &cancel).await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::InvalidInput);
|
||||
assert!(refused.message.to_lowercase().contains("readonly"), "{}", refused.message);
|
||||
|
||||
// The guarded statement changed nothing, and the PRAGMA did not stay on the pool.
|
||||
pool.execute("INSERT INTO t VALUES (2)", 1, &cancel).await.unwrap();
|
||||
let rows = pool.execute("SELECT x FROM t", 10, &cancel).await.unwrap().rows;
|
||||
assert_eq!(rows, vec![vec![Some("2".into())]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_quote_modes_that_change_lexing_are_named() {
|
||||
assert_eq!(mysql_quote_mode_unsupported("ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES"), None);
|
||||
assert_eq!(mysql_quote_mode_unsupported("ANSI_QUOTES,STRICT_TRANS_TABLES"), Some("ANSI_QUOTES"));
|
||||
assert_eq!(mysql_quote_mode_unsupported("no_backslash_escapes"), Some("NO_BACKSLASH_ESCAPES"));
|
||||
assert_eq!(mysql_quote_mode_unsupported(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_connection_charsets_that_can_swallow_ascii_are_refused() {
|
||||
for safe in ["utf8mb4", "utf8mb3", "utf8", "ascii", "latin1", "binary", "UTF8MB4", " utf8mb4 "] {
|
||||
assert!(mysql_charset_is_safe(safe), "{safe}");
|
||||
}
|
||||
for unsafe_charset in ["gbk", "big5", "sjis", "cp932", "gb18030", "euckr", "ujis", ""] {
|
||||
assert!(!mysql_charset_is_safe(unsafe_charset), "{unsafe_charset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_only_execution_refuses_a_second_statement() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("read-only-statements.db");
|
||||
std::fs::File::create(&file).unwrap();
|
||||
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
for sql in
|
||||
["SELECT 1; SELECT 2", "SELECT 1; START TRANSACTION READ WRITE; DELETE FROM t", "SELECT 1; DELETE FROM t"]
|
||||
{
|
||||
let refused = pool.execute_read_only(sql, 1, &cancel).await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::InvalidInput, "{sql}");
|
||||
assert!(refused.message.contains("exactly one statement"), "{sql}: {}", refused.message);
|
||||
}
|
||||
// One statement with a trailing `;` (and comments) is still one statement.
|
||||
let result = pool.execute_read_only("SELECT 1; -- done", 1, &cancel).await.unwrap();
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drivers_without_a_read_only_session_are_refused() {
|
||||
for driver in [DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Snowflake, DbDriver::Jdbc] {
|
||||
let error = read_only_unsupported(driver);
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert!(error.message.contains(driver_name(driver)), "{}", error.message);
|
||||
assert!(error.message.contains("no read-only session"), "{}", error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use sqlx::{Executor, SqlSafeStr};
|
||||
use sqlx::{Executor, Row, SqlSafeStr};
|
||||
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
@@ -110,11 +110,64 @@ pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>
|
||||
// validates that the text denotes a single command, including under the server's quoting rules.
|
||||
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
|
||||
if sql.contains(';') {
|
||||
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
|
||||
check_single_always(conn, sql).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prepares `sql` whatever it contains, so the server parses it as one command with its own
|
||||
/// lexer before the simple query protocol runs it. The dedicated read-only connection has no
|
||||
/// transaction guard; a difference between the splitter's lexing and the server's (an encoding,
|
||||
/// a newline or an escape rule) then becomes a parse error instead of a hidden second statement.
|
||||
pub(super) async fn check_single_always(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
|
||||
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the server reports a client encoding that reads the statement's UTF-8 bytes as UTF-8
|
||||
/// (it spells UTF-8 `UTF8`, and some servers `UNICODE`).
|
||||
pub(super) fn utf8_client_encoding(name: &str) -> bool {
|
||||
matches!(name.trim().to_ascii_uppercase().as_str(), "UTF8" | "UNICODE")
|
||||
}
|
||||
|
||||
/// Pins the settings the statement splitter assumes and verifies the server took them. A
|
||||
/// PostgreSQL server converts the statement text from `client_encoding` before parsing it, so a
|
||||
/// multibyte client encoding could end a string at a different quote than `split` did; with
|
||||
/// `standard_conforming_strings` off, a plain `'…'` literal takes backslash escapes `split` does
|
||||
/// not read. A startup script can set either on every connection, so both are pinned per session.
|
||||
pub(super) async fn pin_encoding(conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
// `SET LOCAL`: both callers are inside the read-only transaction, so the source's own
|
||||
// session settings come back when it ends.
|
||||
sqlx::raw_sql("SET LOCAL client_encoding TO 'UTF8'").execute(&mut *conn).await?;
|
||||
let encoding = pg_show(conn, "SHOW client_encoding").await?;
|
||||
if !utf8_client_encoding(&encoding) {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
format!(
|
||||
"PostgreSQL reports client_encoding {encoding}, not UTF8: the server could read the statement's \
|
||||
quotes or escapes differently than the statement splitter, so a hidden second statement could run"
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
sqlx::raw_sql("SET LOCAL standard_conforming_strings TO on").execute(&mut *conn).await?;
|
||||
let conforming = pg_show(conn, "SHOW standard_conforming_strings").await?;
|
||||
if !conforming.trim().eq_ignore_ascii_case("on") {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
format!(
|
||||
"PostgreSQL reports standard_conforming_strings {conforming}, not on: the server could read a \
|
||||
string's backslash differently than the statement splitter, so a hidden second statement could run"
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pg_show(conn: &mut PgConnection, sql: &'static str) -> Result<String, sqlx::Error> {
|
||||
let row = sqlx::raw_sql(sql).fetch_one(conn).await?;
|
||||
row.try_get(0)
|
||||
}
|
||||
|
||||
impl PgHandle {
|
||||
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
|
||||
self.in_transaction = true;
|
||||
@@ -125,6 +178,8 @@ impl PgHandle {
|
||||
check_single(self, sql).await.map_err(db_err)?;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
|
||||
}
|
||||
// After the startup settings: one of them may have changed either setting.
|
||||
pin_encoding(self).await.map_err(db_err)?;
|
||||
self.apply_local_path().await
|
||||
}
|
||||
.await;
|
||||
@@ -220,7 +275,17 @@ impl Held {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::validate;
|
||||
use super::{utf8_client_encoding, validate};
|
||||
|
||||
#[test]
|
||||
fn only_utf8_spellings_pass_the_client_encoding_check() {
|
||||
for name in ["UTF8", "utf8", "Unicode", " UNICODE "] {
|
||||
assert!(utf8_client_encoding(name), "{name}");
|
||||
}
|
||||
for name in ["GBK", "SJIS", "BIG5", "LATIN1", "SQL_ASCII", ""] {
|
||||
assert!(!utf8_client_encoding(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_transaction_control_and_accepts_quoted_text() {
|
||||
|
||||
@@ -1992,6 +1992,27 @@ impl DbManager {
|
||||
self.execute_from(id, statement, 0, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
/// Runs `statement` in a driver-enforced read-only session (see [`Pool::execute_read_only`]).
|
||||
/// Exactly one statement is required: SQL that splits into several is refused at the
|
||||
/// connection layer, so a direct caller cannot smuggle in a second one. Not recorded in the
|
||||
/// query history: it runs outside the console, only after the caller confirmed the exact
|
||||
/// statement. `id` is one data source id; callers that expose this to agents must also require
|
||||
/// one unqualified id and a source that is not plugin-owned.
|
||||
pub async fn execute_read_only_query(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
// Refuse a driver without a read-only session before opening (and connecting) its pool.
|
||||
let source = self.source(id)?;
|
||||
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
|
||||
return Err(conn::read_only_unsupported(source.driver));
|
||||
}
|
||||
self.pool(id).await?.execute_read_only(statement, max_rows, cancel).await
|
||||
}
|
||||
|
||||
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
|
||||
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
|
||||
self.validate_console_script(id, statements, None).await
|
||||
|
||||
@@ -315,8 +315,10 @@ fn open(state: &State) -> Result<OracleHandle, OracleError> {
|
||||
Ok(OracleHandle { conn: Some(conn), context })
|
||||
}
|
||||
|
||||
/// Runs `f` with the connection on the blocking pool. Cancelling drops the
|
||||
/// connection instead of returning it (its statement keeps running server-side).
|
||||
/// Runs `f` with the connection on the blocking pool. Cancelling stops the wait and drops the
|
||||
/// connection instead of returning it, but only when the blocking call ends: the driver has no
|
||||
/// break API, so the statement keeps running server-side until it finishes, and closing the
|
||||
/// connection then rolls its transaction back.
|
||||
async fn with_conn<T>(
|
||||
c: &mut OracleConnection,
|
||||
cancel: &CancellationToken,
|
||||
@@ -367,6 +369,53 @@ pub(crate) async fn run(
|
||||
with_conn(c, cancel, move |conn| statements(conn, &state, &sql, skip, max, mode)).await
|
||||
}
|
||||
|
||||
/// Runs one statement in a verified read-only transaction on its own connection. Auto-commit is
|
||||
/// off whatever the source's mode: [`statement`] must not commit the transaction away, and the
|
||||
/// transaction is always rolled back (a dropped connection rolls it back server-side too).
|
||||
pub(crate) async fn execute_read_only(
|
||||
c: &mut OracleConnection,
|
||||
sql: &str,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Fetched> {
|
||||
let sql = sql.to_owned();
|
||||
with_conn(c, cancel, move |conn| {
|
||||
// `SET TRANSACTION READ ONLY` must be the first statement of its transaction; a startup
|
||||
// script may have left one open.
|
||||
conn.rollback().map_err(|e| oracle_err(&e))?;
|
||||
statement(conn, "SET TRANSACTION READ ONLY", 0, 0, Cells::Text, false)?;
|
||||
verify_read_only(conn)?;
|
||||
// The user's statement is the only other statement in the transaction; `split` is not
|
||||
// used here, so a `;` cannot smuggle in a second one.
|
||||
let result = statement(conn, &sql, 0, max, Cells::Display, false);
|
||||
let rollback = conn.rollback().map_err(|e| oracle_err(&e));
|
||||
match (result, rollback) {
|
||||
(Ok(fetched), Ok(())) => Ok(fetched),
|
||||
(Err(error), _) => Err(error),
|
||||
(Ok(_), Err(error)) => Err(error),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Proves the server took `SET TRANSACTION READ ONLY`: a locking read is refused in a read-only
|
||||
/// transaction (`ORA-01456`). `NOWAIT` keeps the probe from waiting on another session's DUAL
|
||||
/// lock if the transaction did not take; no row is locked when it did.
|
||||
fn verify_read_only(conn: &mut oracledb::Connection) -> IdeResult<()> {
|
||||
match conn.query_row("SELECT 1 FROM DUAL FOR UPDATE NOWAIT", &[]) {
|
||||
Ok(_) => Err(IdeError::invalid("Oracle did not enter a read-only transaction: a locking read succeeded")),
|
||||
Err(e) if read_only_violation(&e) => Ok(()),
|
||||
Err(e) => Err(IdeError::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
format!("Oracle did not confirm the read-only transaction: {}", oracle_err(&e).message),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_only_violation(e: &oracledb::Error) -> bool {
|
||||
matches!(e.kind(), oracledb::ErrorKind::DbError(db) if db.code() as u32 == 1456)
|
||||
}
|
||||
|
||||
/// The table editor's edits in one transaction.
|
||||
pub(crate) async fn transaction(c: &mut OracleConnection, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
if c.state.read_only {
|
||||
@@ -1028,6 +1077,50 @@ mod tests {
|
||||
drop(raw);
|
||||
}
|
||||
|
||||
/// The read-only session `execute_read_only` opens: a write and `EXPLAIN PLAN` (which writes
|
||||
/// `PLAN_TABLE`) are refused by the database, and no change is left behind. Skipped unless
|
||||
/// `OPENIDEA_ORACLE_TEST` names a live server.
|
||||
#[tokio::test]
|
||||
async fn a_read_only_session_refuses_writes_and_leaves_no_change() {
|
||||
let Some(spec) = std::env::var("OPENIDEA_ORACLE_TEST").ok().filter(|s| !s.is_empty()) else { return };
|
||||
let (source, password) = live_source(&spec);
|
||||
let secrets = vec![source.user.clone(), source.host.clone(), source.database.clone()];
|
||||
let pool = crate::conn::Pool::connect(&source, Some(&password), None).await.expect("connect");
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
|
||||
let _ = drop_if_present(&pool, &format!("table {table}")).await;
|
||||
pool.rows(&format!("create table {table} (id number)"), 0).await.expect("create table");
|
||||
pool.rows(&format!("insert into {table} values (1)"), 0).await.expect("insert a row");
|
||||
|
||||
let selected =
|
||||
pool.execute_read_only(&format!("select count(*) from {table}"), 1, &c).await.expect("a query runs");
|
||||
assert_eq!(selected.rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
|
||||
|
||||
let write = pool
|
||||
.execute_read_only(&format!("insert into {table} values (2)"), 1, &c)
|
||||
.await
|
||||
.expect_err("a write is refused in the read-only transaction");
|
||||
assert!(
|
||||
write.message.contains("1456") || write.message.to_ascii_lowercase().contains("read only"),
|
||||
"{}",
|
||||
write.message
|
||||
);
|
||||
let explain = pool
|
||||
.execute_read_only("explain plan for select 1 from dual", 1, &c)
|
||||
.await
|
||||
.expect_err("EXPLAIN PLAN writes PLAN_TABLE, so the read-only transaction refuses it");
|
||||
assert!(
|
||||
explain.message.contains("1456") || explain.message.to_ascii_lowercase().contains("read only"),
|
||||
"{}",
|
||||
explain.message
|
||||
);
|
||||
|
||||
let rows = pool.rows(&format!("select count(*) from {table}"), 1).await.expect("count after the refusals");
|
||||
assert_eq!(rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
|
||||
let _ = drop_if_present(&pool, &format!("table {table}")).await;
|
||||
pass("read-only", "a write and EXPLAIN PLAN were refused; the table kept its one row", &secrets);
|
||||
}
|
||||
|
||||
/// An account whose only verifier is `10G` (see `DBA_USERS.PASSWORD_VERSIONS`):
|
||||
/// the thin driver speaks 11G and later verifiers, so the server rejects even
|
||||
/// the correct password with ORA-01017 until the account is reset
|
||||
|
||||
@@ -31,6 +31,20 @@ pub enum DbDriver {
|
||||
}
|
||||
|
||||
impl DbDriver {
|
||||
/// The driver's name in messages and tool output.
|
||||
pub fn display_name(self) -> &'static str {
|
||||
match self {
|
||||
DbDriver::Sqlite => "SQLite",
|
||||
DbDriver::Postgres => "PostgreSQL",
|
||||
DbDriver::Mysql => "MySQL",
|
||||
DbDriver::SqlServer => "SQL Server",
|
||||
DbDriver::Clickhouse => "ClickHouse",
|
||||
DbDriver::Oracle => "Oracle",
|
||||
DbDriver::Snowflake => "Snowflake",
|
||||
DbDriver::Jdbc => "JDBC",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_port(self) -> Option<u16> {
|
||||
match self {
|
||||
DbDriver::Sqlite | DbDriver::Jdbc => None,
|
||||
@@ -766,10 +780,16 @@ fn read(path: &Path) -> IdeResult<Vec<DataSource>> {
|
||||
}
|
||||
|
||||
fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
let mut ids = HashSet::new();
|
||||
for s in sources {
|
||||
if s.id.is_empty() || s.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source needs an id and a name"));
|
||||
}
|
||||
// A connection target resolves an id to the first source with it; duplicates make that
|
||||
// ambiguous (and a crafted file must not redirect a console or a tool to another entry).
|
||||
if !ids.insert(s.id.as_str()) {
|
||||
return Err(IdeError::invalid(format!("duplicate data source id '{}'", s.id)));
|
||||
}
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
@@ -983,6 +1003,15 @@ mod tests {
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_refuses_duplicate_ids() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = DataSource { id: "a".into(), name: "one".into(), ..Default::default() };
|
||||
let duplicate = vec![source.clone(), DataSource { name: "two".into(), ..source }];
|
||||
let error = save(tmp.path(), &duplicate).unwrap_err();
|
||||
assert!(error.message.contains("duplicate data source id 'a'"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() {
|
||||
let mut introspection = DbIntrospection {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
|
||||
|
||||
use crate::DbDriver;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -316,9 +317,7 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
|
||||
package = false;
|
||||
}
|
||||
// MySQL reads `5--1` as a subtraction.
|
||||
'-' if next == Some('-')
|
||||
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
|
||||
{
|
||||
'-' if next == Some('-') && (!mysql || mysql_dash_comment(chars.get(i + 2).map(|c| c.1))) => {
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
@@ -452,7 +451,9 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
|
||||
}
|
||||
}
|
||||
State::LineComment => {
|
||||
if c == '\n' {
|
||||
// PostgreSQL ends a `--` comment at `\r` as well as `\n` (`scan.l`:
|
||||
// `non_newline [^\n\r]`); MySQL and SQLite read a bare `\r` as comment text.
|
||||
if c == '\n' || (postgres && c == '\r') {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
@@ -469,6 +470,128 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
|
||||
(out, delimiter)
|
||||
}
|
||||
|
||||
/// MySQL starts a `--` line comment only when the character after it is an ASCII space or an
|
||||
/// ASCII control character: the server checks the next byte with `my_isspace`/`my_iscntrl`.
|
||||
/// A Unicode space (U+00A0, U+2000…, U+3000…) is an identifier character to the server, so it
|
||||
/// must not start a comment here either. Both [`split`] and [`mysql_guard`] use this rule.
|
||||
fn mysql_dash_comment(next: Option<char>) -> bool {
|
||||
next.is_none_or(|c| c == ' ' || c.is_ascii_control())
|
||||
}
|
||||
|
||||
/// Whether `/*!` or `/*M!`, whose contents a MySQL/MariaDB server runs as SQL, starts at `i`.
|
||||
fn executable_comment_start(chars: &[char], i: usize) -> bool {
|
||||
chars.get(i) == Some(&'/')
|
||||
&& chars.get(i + 1) == Some(&'*')
|
||||
&& (chars.get(i + 2) == Some(&'!')
|
||||
|| (matches!(chars.get(i + 2), Some('M' | 'm')) && chars.get(i + 3) == Some(&'!')))
|
||||
}
|
||||
|
||||
/// Refuses what a MySQL/MariaDB server runs but [`split`] reads as a comment or a literal:
|
||||
/// executable comments (`/*! … */`, `/*M! … */`), whose contents the server tokenizes as SQL,
|
||||
/// and `INTO OUTFILE` / `INTO DUMPFILE`, which write a file on the server. The client cannot
|
||||
/// switch the server's multi-statement handling off, so a statement handed to a MySQL/MariaDB
|
||||
/// read-only session must pass this first (with the default quote modes, see
|
||||
/// `mysql_quote_mode_unsupported` in `conn`).
|
||||
///
|
||||
/// Executable comments are refused wherever they appear outside a string or a quoted identifier,
|
||||
/// even inside a genuine comment: the conservative refusal cannot be bypassed if the comment
|
||||
/// rules of this guard and the server ever diverge.
|
||||
pub fn mysql_guard(sql: &str) -> IdeResult<()> {
|
||||
let chars: Vec<char> = sql.chars().collect();
|
||||
let mut state = State::Code;
|
||||
// The last word outside quotes and comments, so `INTO /* … */ OUTFILE` is one clause.
|
||||
let mut last = String::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
if !matches!(state, State::Single | State::Double | State::Backtick) && executable_comment_start(&chars, i) {
|
||||
return Err(IdeError::invalid(
|
||||
"MySQL executable comments (/*! … */ and /*M! … */) are not allowed here: \
|
||||
the server runs their contents as SQL",
|
||||
));
|
||||
}
|
||||
match state {
|
||||
State::Code => match c {
|
||||
'\'' => state = State::Single,
|
||||
'"' => state = State::Double,
|
||||
'`' => state = State::Backtick,
|
||||
'#' => state = State::LineComment,
|
||||
'-' if next == Some('-') && mysql_dash_comment(chars.get(i + 2).copied()) => {
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
'/' if next == Some('*') => {
|
||||
state = State::BlockComment;
|
||||
i += 1;
|
||||
}
|
||||
c if c.is_alphanumeric() || c == '_' || c == '$' => {
|
||||
let start = i;
|
||||
while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_' || *c == '$') {
|
||||
i += 1;
|
||||
}
|
||||
let word: String = chars[start..i].iter().collect::<String>().to_ascii_uppercase();
|
||||
if matches!(word.as_str(), "OUTFILE" | "DUMPFILE") && last == "INTO" {
|
||||
return Err(IdeError::invalid(
|
||||
"MySQL INTO OUTFILE / INTO DUMPFILE is not allowed here: it writes a file on the server",
|
||||
));
|
||||
}
|
||||
last = word;
|
||||
continue;
|
||||
}
|
||||
c if c.is_whitespace() => {}
|
||||
_ => last.clear(),
|
||||
},
|
||||
State::Single => {
|
||||
if c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '\'' {
|
||||
if next == Some('\'') {
|
||||
i += 1;
|
||||
} else {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Double => {
|
||||
if c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '"' {
|
||||
if next == Some('"') {
|
||||
i += 1;
|
||||
} else {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Backtick => {
|
||||
if c == '`' {
|
||||
if next == Some('`') {
|
||||
i += 1;
|
||||
} else {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
}
|
||||
State::LineComment => {
|
||||
if c == '\n' {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
State::BlockComment => {
|
||||
if c == '*' && next == Some('/') {
|
||||
state = State::Code;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
// MySQL quotes identifiers only with backticks.
|
||||
State::Bracket => unreachable!("MySQL has no bracketed identifiers"),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Unit {
|
||||
Sql,
|
||||
@@ -777,6 +900,82 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mysql_executable_comments_are_refused_outside_literals() {
|
||||
for sql in [
|
||||
"SELECT 1 /*!50000 , 2 */",
|
||||
"/*! START TRANSACTION READ WRITE; DELETE FROM t; */ SELECT 1",
|
||||
"SELECT 1 /*M!100000 , 2 */",
|
||||
"select 1 /*m! , 2 */",
|
||||
// Also inside a genuine comment: the conservative refusal cannot be bypassed by a
|
||||
// future difference between the guard's comment rules and the server's.
|
||||
"SELECT 1 -- /*! hidden in a comment */",
|
||||
"SELECT 1 # /*! hidden in a comment */",
|
||||
"SELECT 1 /* /*! inside a block comment */",
|
||||
] {
|
||||
let error = mysql_guard(sql).unwrap_err();
|
||||
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
|
||||
}
|
||||
// The same text inside a literal or a quoted identifier is data, not code.
|
||||
for sql in [
|
||||
"SELECT '/*! DELETE FROM t */'",
|
||||
"SELECT \"/*M! x */\", `/*! y */` FROM t",
|
||||
"SELECT 'it''s /*! fine */'",
|
||||
"SELECT 'a\\' /*! still text */'",
|
||||
] {
|
||||
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_dash_comment_uses_mysqls_ascii_rule_like_the_splitter() {
|
||||
// U+00A0 (NO-BREAK SPACE) and other Unicode spaces do not start a `--` comment on the
|
||||
// server: `--` is two minus signs and the executable comment that follows is code.
|
||||
for sql in [
|
||||
"SELECT 1 --\u{00a0}/*! x */",
|
||||
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; DELETE FROM users; */",
|
||||
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/x' */",
|
||||
"SELECT 1 --\u{2003}/*M! DELETE FROM users */",
|
||||
] {
|
||||
let error = mysql_guard(sql).unwrap_err();
|
||||
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
|
||||
}
|
||||
// An ASCII space, tab or control character after `--` is a comment, as before.
|
||||
for sql in ["SELECT 1 -- ordinary comment\n+ 1", "SELECT 1 --\tcomment\n+ 1", "SELECT 1 --\n+ 1"] {
|
||||
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
|
||||
}
|
||||
// `split` applies the same rule: the text after `--` is code (and the `;` there splits),
|
||||
// so the guard is the layer that refuses the executable comment.
|
||||
assert_eq!(
|
||||
texts("SELECT 5 --\u{00a0} 1; SELECT 2", DbDriver::Mysql),
|
||||
vec!["SELECT 5 --\u{00a0} 1", "SELECT 2"]
|
||||
);
|
||||
assert_eq!(texts("SELECT 5 -- 1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5 -- 1; SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_into_outfile_is_refused_outside_literals_and_comments() {
|
||||
for sql in [
|
||||
"SELECT * FROM t INTO OUTFILE '/tmp/x'",
|
||||
"SELECT * FROM t INTO DUMPFILE '/tmp/x'",
|
||||
"SELECT * FROM t INTO/**/OUTFILE '/tmp/x'",
|
||||
"SELECT * FROM t INTO /* c */\n OUTFILE '/tmp/x'",
|
||||
"select * from t into outfile '/tmp/x'",
|
||||
] {
|
||||
let error = mysql_guard(sql).unwrap_err();
|
||||
assert!(error.message.contains("INTO OUTFILE"), "{sql}: {}", error.message);
|
||||
}
|
||||
for sql in [
|
||||
"SELECT 'INTO OUTFILE /tmp/x'",
|
||||
"SELECT 1 AS outfile, 2 AS dumpfile FROM t",
|
||||
"SELECT 1 /* INTO OUTFILE '/tmp/x' */",
|
||||
"SELECT 1 -- INTO OUTFILE '/tmp/x'",
|
||||
"SELECT @outfile FROM t",
|
||||
] {
|
||||
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_session_settings_split_after_comments_and_quoted_values() {
|
||||
let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1";
|
||||
@@ -852,6 +1051,17 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_line_comments_end_at_a_carriage_return_like_the_server() {
|
||||
// `scan.l` reads `\r` as a newline, so the `;` after it ends the statement; MySQL and
|
||||
// SQLite keep a bare `\r` inside the comment.
|
||||
let sql = "SELECT 1 --\r; SELECT 2";
|
||||
assert_eq!(texts(sql, DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
|
||||
assert_eq!(texts(sql, DbDriver::Mysql), vec![sql]);
|
||||
assert_eq!(texts(sql, DbDriver::Sqlite), vec![sql]);
|
||||
assert_eq!(texts("SELECT 1 --\r\n; SELECT 2", DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_double_quoted_strings_and_dashes() {
|
||||
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbRowEdit};
|
||||
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit};
|
||||
|
||||
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
|
||||
|
||||
@@ -13,6 +13,14 @@ fn server() -> Option<(String, u16, String, String)> {
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbManager> {
|
||||
manager_with_properties(tmp, startup_script, Vec::new()).await
|
||||
}
|
||||
|
||||
async fn manager_with_properties(
|
||||
tmp: &tempfile::TempDir,
|
||||
startup_script: &str,
|
||||
properties: Vec<DbProperty>,
|
||||
) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
@@ -24,6 +32,7 @@ async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbMana
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
properties,
|
||||
options: DbOptions { startup_script: startup_script.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
}])
|
||||
@@ -435,3 +444,105 @@ async fn table_grants_list_table_privileges() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The MySQL/MariaDB read-only session: a query runs; writes, executable comments and
|
||||
/// `INTO OUTFILE` are refused. Skipped without `OPENIDEA_TEST_MYSQL`.
|
||||
#[tokio::test]
|
||||
async fn the_read_only_session_refuses_writes_and_server_side_escapes() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
|
||||
for stmt in [
|
||||
format!("DROP TABLE IF EXISTS {table}"),
|
||||
format!("CREATE TABLE {table} (id INT PRIMARY KEY)"),
|
||||
format!("INSERT INTO {table} VALUES (1)"),
|
||||
] {
|
||||
db.execute("m", &stmt, 1, &c).await?;
|
||||
}
|
||||
|
||||
let rows = db.execute_read_only_query("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
|
||||
|
||||
let write = db
|
||||
.execute_read_only_query("m", &format!("INSERT INTO {table} VALUES (2)"), 1, &c)
|
||||
.await
|
||||
.expect_err("the read-only transaction refuses a write");
|
||||
assert!(
|
||||
write.message.to_ascii_lowercase().contains("read only") || write.message.contains("1792"),
|
||||
"{}",
|
||||
write.message
|
||||
);
|
||||
let comment = db
|
||||
.execute_read_only_query("m", "SELECT 1 /*! , 2 */", 1, &c)
|
||||
.await
|
||||
.expect_err("an executable comment is refused before the server runs it");
|
||||
assert!(comment.message.contains("executable comment"), "{}", comment.message);
|
||||
let outfile = db
|
||||
.execute_read_only_query("m", &format!("SELECT * FROM {table} INTO OUTFILE '/tmp/openidea-ro'"), 1, &c)
|
||||
.await
|
||||
.expect_err("INTO OUTFILE is refused");
|
||||
assert!(outfile.message.contains("INTO OUTFILE"), "{}", outfile.message);
|
||||
// `--` followed by a non-ASCII space is two minus signs to the server, not a comment; the
|
||||
// guard must read it the same way instead of hiding the executable comment behind it.
|
||||
for payload in [
|
||||
"SELECT 1 --\u{00a0}/*! x */".to_owned(),
|
||||
format!(
|
||||
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; \
|
||||
DELETE FROM {table}; */"
|
||||
),
|
||||
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/openidea-ro' */".to_owned(),
|
||||
] {
|
||||
let error = db
|
||||
.execute_read_only_query("m", &payload, 1, &c)
|
||||
.await
|
||||
.expect_err("the executable comment is refused before the server runs it");
|
||||
assert!(error.message.contains("executable comment"), "{payload}: {}", error.message);
|
||||
}
|
||||
|
||||
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "nothing else was written");
|
||||
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A source configured with an unsafe connection charset (`charset=gbk`) cannot make the server
|
||||
/// read a statement differently than the client: the read-only connection is pinned to utf8mb4,
|
||||
/// so an ASCII backslash is never swallowed as the second byte of a GBK character. Skipped
|
||||
/// without `OPENIDEA_TEST_MYSQL`.
|
||||
#[tokio::test]
|
||||
async fn the_read_only_connection_is_pinned_to_utf8mb4_whatever_the_source_charset() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) =
|
||||
manager_with_properties(&tmp, "", vec![DbProperty { name: "charset".into(), value: "gbk".into() }]).await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let c = CancellationToken::new();
|
||||
let charsets = db
|
||||
.execute_read_only_query(
|
||||
"m",
|
||||
"SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection",
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(charsets.rows, vec![vec![Some("utf8mb4".into()), Some("utf8mb4".into())]]);
|
||||
|
||||
let table = format!("openidea_charset_{}", uuid::Uuid::new_v4().simple());
|
||||
for stmt in [
|
||||
format!("DROP TABLE IF EXISTS {table}"),
|
||||
format!("CREATE TABLE {table} (id INT)"),
|
||||
format!("INSERT INTO {table} VALUES (1)"),
|
||||
] {
|
||||
db.execute("m", &stmt, 1, &c).await?;
|
||||
}
|
||||
// Read as GBK, the `\` would be consumed as the second byte of a character, the string would
|
||||
// end early and the tail would run as two more statements.
|
||||
let payload = format!("SELECT '中\\' ; START TRANSACTION READ WRITE; DELETE FROM {table}; -- '");
|
||||
db.execute_read_only_query("m", &payload, 1, &c).await?;
|
||||
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "no hidden statement ran");
|
||||
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -234,6 +234,90 @@ async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A data-changing statement hidden in a CTE is not a query: the read-only session refuses it
|
||||
/// in the database, whatever the statement text looks like, and the table keeps its rows.
|
||||
#[tokio::test]
|
||||
async fn a_write_hidden_in_a_cte_is_refused_by_the_read_only_session() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_cte_{}", uuid::Uuid::new_v4().simple());
|
||||
for stmt in [
|
||||
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
|
||||
format!("INSERT INTO {table} VALUES (1, 'kept')"),
|
||||
] {
|
||||
db.execute("p", &stmt, 10, &c).await?;
|
||||
}
|
||||
let statement = format!("WITH d AS (DELETE FROM {table} RETURNING *) SELECT * FROM d");
|
||||
let error = db
|
||||
.execute_read_only_query("p", &statement, 10, &c)
|
||||
.await
|
||||
.expect_err("the read-only transaction must refuse a DELETE in a CTE");
|
||||
assert!(error.message.contains("25006"), "{}", error.message);
|
||||
let rows = db.execute("p", &format!("SELECT id, name FROM {table} ORDER BY id"), 10, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
|
||||
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// PostgreSQL's scanner ends a `--` comment at `\r` as well as `\n`; the splitter must agree, so
|
||||
/// a bare CR cannot hide `COMMIT; DELETE …` from the one-statement check. The hidden statements
|
||||
/// would otherwise run on the dedicated `BEGIN READ ONLY` connection.
|
||||
#[tokio::test]
|
||||
async fn a_carriage_return_cannot_hide_a_second_statement() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_cr_{}", uuid::Uuid::new_v4().simple());
|
||||
for stmt in [format!("CREATE TABLE {table} (id INT PRIMARY KEY)"), format!("INSERT INTO {table} VALUES (1)")] {
|
||||
db.execute("p", &stmt, 10, &c).await?;
|
||||
}
|
||||
let payload = format!("SELECT 1 --\r; COMMIT; DELETE FROM {table}; --");
|
||||
let error = db.execute_read_only_query("p", &payload, 10, &c).await.expect_err("the hidden DELETE must not run");
|
||||
assert!(error.message.contains("exactly one statement"), "{}", error.message);
|
||||
let rows = db.execute("p", &format!("SELECT count(*) FROM {table}"), 10, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
|
||||
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A startup script can change the connection's `client_encoding`; the read-only session pins it
|
||||
/// to UTF-8 anyway, so the server reads the statement's bytes exactly as the splitter did.
|
||||
#[tokio::test]
|
||||
async fn a_startup_script_cannot_change_the_read_only_sessions_encoding() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_gbk_{}", uuid::Uuid::new_v4().simple());
|
||||
for stmt in [
|
||||
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
|
||||
format!("INSERT INTO {table} VALUES (1, 'kept')"),
|
||||
] {
|
||||
db.execute("p", &stmt, 10, &c).await?;
|
||||
}
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "gbk".into();
|
||||
source.name = "GBK startup".into();
|
||||
source.read_only = true;
|
||||
source.options.startup_script = "SET client_encoding TO 'GBK'".into();
|
||||
sources.push(source);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("gbk", server().map(|(.., password)| password), false).await?;
|
||||
|
||||
let encoding = db.execute_read_only_query("gbk", "SELECT current_setting('client_encoding')", 1, &c).await?;
|
||||
assert_eq!(encoding.rows, vec![vec![Some("UTF8".into())]]);
|
||||
// In GBK the backslash before the quote is a trail byte of the preceding character, so the
|
||||
// server would end the E-string early and run the hidden `COMMIT; DELETE …`.
|
||||
let payload = format!("SELECT E'中\\' ; COMMIT; DELETE FROM {table}; -- '");
|
||||
let result = db.execute_read_only_query("gbk", &payload, 1, &c).await?;
|
||||
assert_eq!(result.rows.len(), 1, "{:?}", result.rows);
|
||||
let rows = db.execute("p", &format!("SELECT id, name FROM {table}"), 10, &c).await?;
|
||||
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
|
||||
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Introspection, queries and table edits against a real SQLite file.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
|
||||
use ide_db::{
|
||||
CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
|
||||
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -527,3 +528,56 @@ async fn data_sources_edited_on_disk_close_their_connections() -> IdeResult<()>
|
||||
assert!(!db.reconcile_sources().await);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A read-only query whose future is dropped or cancelled mid-flight must not leave
|
||||
/// `PRAGMA query_only` on a pooled connection: a later write through the pool still works.
|
||||
#[tokio::test]
|
||||
async fn a_dropped_or_cancelled_read_only_query_leaves_the_pool_writable() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let pool = db.pool("s1").await?;
|
||||
// CPU-bound and touches no table, so it holds no file lock while it runs. Large enough that
|
||||
// it cannot finish within the 50 ms before the abort, even on a fast machine.
|
||||
let slow = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000000) \
|
||||
SELECT count(*) FROM c";
|
||||
let spawn = |cancel: CancellationToken| {
|
||||
let pool = pool.clone();
|
||||
tokio::spawn(async move { pool.execute_read_only(slow, 1, &cancel).await })
|
||||
};
|
||||
|
||||
// Dropped mid-query, as a timeout used to drop it.
|
||||
let handle = spawn(CancellationToken::new());
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
handle.abort();
|
||||
let _ = handle.await;
|
||||
|
||||
// Cancelled mid-query, as a cancelled MCP request does.
|
||||
let cancel = CancellationToken::new();
|
||||
let handle = spawn(cancel.clone());
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
cancel.cancel();
|
||||
let error = handle.await.unwrap().expect_err("the cancelled query returns an error");
|
||||
assert_eq!(error.kind, ErrorKind::Cancelled);
|
||||
|
||||
// Let either worker finish: a dropped session's connection must close, not return with
|
||||
// query_only still on. Take every connection the pool has (4 pool + 4 console sessions) and
|
||||
// read the PRAGMA, so a poisoned slot cannot hide in the unchecked rest.
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
let c = CancellationToken::new();
|
||||
let mut held = Vec::new();
|
||||
for _ in 0..8 {
|
||||
let mut conn = ide_db::Held::acquire(&pool).await?;
|
||||
let rows = conn.execute(&pool, "PRAGMA query_only", 1, &c).await?.rows;
|
||||
assert_eq!(rows, vec![vec![Some("0".into())]], "a pooled connection kept query_only");
|
||||
held.push(conn);
|
||||
}
|
||||
drop(held);
|
||||
|
||||
// A pool slot that kept query_only would answer SQLITE_READONLY, intermittently.
|
||||
for n in 0..20 {
|
||||
let sql = format!("INSERT INTO users (name) VALUES ('after{n}')");
|
||||
pool.execute(&sql, 1, &c).await?;
|
||||
}
|
||||
let rows = pool.execute("SELECT count(*) FROM users WHERE name LIKE 'after%'", 1, &c).await?.rows;
|
||||
assert_eq!(rows, vec![vec![Some("20".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
//! Database tools: the project's data sources, their schemas and objects, and read-only SQL.
|
||||
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbObjectKind, DbTableKind, SchemaObjects, split};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
const DEFAULT_MAX_ROWS: usize = 100;
|
||||
const MAX_ROWS: usize = 1000;
|
||||
/// UTF-16 units a cell keeps; the rest is reported in `truncated`.
|
||||
const MAX_CELL_UNITS: usize = 4096;
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Catalog reads can be slower than a query on a big schema; they do not run the user's SQL.
|
||||
const METADATA_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// How long a cancelled or timed-out task gets to run its rollback / reset before the tool returns.
|
||||
const STOP_GRACE: Duration = Duration::from_secs(5);
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![
|
||||
list_database_connections(),
|
||||
list_database_schemas(),
|
||||
list_schema_objects(),
|
||||
get_database_object_description(),
|
||||
execute_sql_query(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The connection a tool may use. The id must be exactly one data source's id: `DbManager`
|
||||
/// resolves `<id>:<database>` by prefix and takes the first matching entry, so a colon or a
|
||||
/// duplicate id could reach an entry other than the one checked here (a plugin-owned source and
|
||||
/// its credentials, for example). Plugin-owned sources stay out of these tools entirely.
|
||||
fn connection(call: &Call, id: &str) -> IdeResult<DataSource> {
|
||||
if id.contains(':') {
|
||||
return Err(IdeError::invalid(
|
||||
"connectionId must be one id from list_database_connections, without a `:database` part",
|
||||
));
|
||||
}
|
||||
let mut matches = call.project().db.sources()?.into_iter().filter(|source| source.id == id);
|
||||
let Some(source) = matches.next() else {
|
||||
return Err(IdeError::not_found(format!("no data source {id}")));
|
||||
};
|
||||
if matches.next().is_some() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"more than one data source has the id {id}; rename or remove one in the Database tool window"
|
||||
)));
|
||||
}
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::not_found(format!("no data source {id}")));
|
||||
}
|
||||
source.resolved()
|
||||
}
|
||||
|
||||
/// The `database` value a tool may show: an Oracle Database field can hold a TNS descriptor,
|
||||
/// which embeds the host and port.
|
||||
fn database_field(source: &DataSource) -> String {
|
||||
let database = source.database.trim();
|
||||
if source.driver == DbDriver::Oracle && (database.starts_with('(') || database.contains('=')) {
|
||||
return String::new();
|
||||
}
|
||||
source.database.clone()
|
||||
}
|
||||
|
||||
/// Replaces every ASCII-case-insensitive occurrence of `needle` in `haystack`. ASCII case folding
|
||||
/// keeps byte lengths, so an offset found in the lowered copy is a valid boundary of the original.
|
||||
fn replace_ascii_case_insensitive(haystack: &mut String, needle: &str, replacement: &str) {
|
||||
let lowered = needle.to_ascii_lowercase();
|
||||
let mut from = 0;
|
||||
loop {
|
||||
let Some(at) = haystack[from..].to_ascii_lowercase().find(&lowered) else { return };
|
||||
let start = from + at;
|
||||
haystack.replace_range(start..start + needle.len(), replacement);
|
||||
from = start + replacement.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the data source's URL, host and user in an error before it reaches the agent: driver
|
||||
/// and tunnel errors quote them (auth failures name the user, tunnel failures the host), in
|
||||
/// whatever case the server reports (Oracle upper-cases user names). Percent-encoded forms are
|
||||
/// redacted too, and the plain forms are matched case-insensitively.
|
||||
fn redact_error(mut error: IdeError, source: &DataSource) -> IdeError {
|
||||
let mut secrets = vec![source.url.trim().to_owned(), source.host.trim().to_owned(), source.user.trim().to_owned()];
|
||||
for value in [source.host.trim(), source.user.trim()] {
|
||||
if !value.is_empty() {
|
||||
secrets.push(percent_encode(value));
|
||||
}
|
||||
}
|
||||
for secret in secrets {
|
||||
// Every configured value, however short: the tool text promises the user and host never
|
||||
// appear, and a one- or two-character name is still a name.
|
||||
if !secret.is_empty() {
|
||||
replace_ascii_case_insensitive(&mut error.message, &secret, "<redacted>");
|
||||
}
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
fn percent_encode(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len());
|
||||
for byte in value.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
|
||||
out.push(byte as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs a catalog read with the request's cancellation and a time limit. The `DbManager`
|
||||
/// metadata methods take no token; dropping their future closes the connection they were using.
|
||||
async fn bounded<T>(call: &Call, deadline: Duration, task: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = call.cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
result = tokio::time::timeout(deadline, task) => match result {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(IdeError::new(
|
||||
ErrorKind::TimedOut,
|
||||
format!("the database did not answer within {} seconds", deadline.as_secs()),
|
||||
)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a read-only query until it finishes, the request is cancelled, or `deadline` passes. On
|
||||
/// either stop the driver's token is cancelled and its cleanup (rollback, reset, close) is
|
||||
/// awaited, instead of dropping the future and leaving a driver's work running.
|
||||
async fn until_stopped<T>(
|
||||
deadline: Duration,
|
||||
cancel: &CancellationToken,
|
||||
token: &CancellationToken,
|
||||
task: impl Future<Output = IdeResult<T>>,
|
||||
) -> IdeResult<T> {
|
||||
tokio::pin!(task);
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut task => result,
|
||||
() = cancel.cancelled() => {
|
||||
token.cancel();
|
||||
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
|
||||
Err(IdeError::cancelled())
|
||||
}
|
||||
() = tokio::time::sleep(deadline) => {
|
||||
token.cancel();
|
||||
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
|
||||
Err(IdeError::new(
|
||||
ErrorKind::TimedOut,
|
||||
format!("the statement did not finish within {} seconds", deadline.as_secs()),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ConnectionInfo {
|
||||
id: String,
|
||||
name: String,
|
||||
driver: DbDriver,
|
||||
database: String,
|
||||
read_only: bool,
|
||||
global: bool,
|
||||
}
|
||||
|
||||
fn list_database_connections() -> Tool {
|
||||
Tool::new(
|
||||
"list_database_connections",
|
||||
"Lists the project's database connections (data sources): `id`, `name`, `driver`, `database`,
|
||||
`readOnly` and `global`. Needs a trusted project; in Restricted Mode the call is refused.
|
||||
Use a connection's `id` as `connectionId` in the other database tools.
|
||||
`database` is the source's configured database; it is empty when none is configured, and a source
|
||||
configured only by a URL is not read here, so its URL does not appear. Global data sources are
|
||||
stored app-wide, are listed in every project and carry `\"global\": true`.
|
||||
Never returns passwords, secrets, URLs, hosts or user names.",
|
||||
|call| async move {
|
||||
call.project.require_trust()?;
|
||||
let connections: Vec<_> = call
|
||||
.project()
|
||||
.db
|
||||
.sources()?
|
||||
.into_iter()
|
||||
.filter(|source| source.plugin_owner.is_none())
|
||||
.map(|source| {
|
||||
let database = database_field(&source);
|
||||
ConnectionInfo {
|
||||
id: source.id,
|
||||
name: source.name,
|
||||
driver: source.driver,
|
||||
database,
|
||||
read_only: source.read_only,
|
||||
global: source.global,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Output::json(json!({ "connections": connections }))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn list_database_schemas() -> Tool {
|
||||
Tool::new(
|
||||
"list_database_schemas",
|
||||
"Lists the schemas a database connection exposes (its databases on MySQL and Oracle).
|
||||
Returns `connectionId`, the configured `database`, and `schemas`. Needs a trusted project; in
|
||||
Restricted Mode the call is refused.",
|
||||
|call| async move {
|
||||
call.project.require_trust()?;
|
||||
let connection_id = call.str("connectionId")?;
|
||||
let source = connection(&call, &connection_id)?;
|
||||
let schemas = bounded(&call, METADATA_TIMEOUT, call.project().db.schemas(&connection_id))
|
||||
.await
|
||||
.map_err(|e| redact_error(e, &source))?;
|
||||
Output::json(json!({
|
||||
"connectionId": connection_id,
|
||||
"database": database_field(&source),
|
||||
"schemas": schemas,
|
||||
}))
|
||||
},
|
||||
)
|
||||
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
|
||||
}
|
||||
|
||||
fn list_schema_objects() -> Tool {
|
||||
Tool::new(
|
||||
"list_schema_objects",
|
||||
"Lists a schema's tables, views, materialized views, routines (functions and procedures), packages, sequences
|
||||
and other objects, as `{ kind, name }`; table-like objects and routines also carry `comment`, `arguments` and
|
||||
`returns` when the database has them.
|
||||
Pass `kind` to filter (case-insensitive): `table`, `view`, `materializedView`, `function`, `procedure`, `package`,
|
||||
`sequence`, `routine` (functions and procedures), or another object kind the database reports. An unknown kind
|
||||
returns an empty list. Needs a trusted project; in Restricted Mode the call is refused.",
|
||||
|call| async move {
|
||||
call.project.require_trust()?;
|
||||
let connection_id = call.str("connectionId")?;
|
||||
let schema = call.str("schema")?;
|
||||
let kind = call.opt_str("kind")?;
|
||||
let source = connection(&call, &connection_id)?;
|
||||
let db = &call.project().db;
|
||||
let tables = bounded(&call, METADATA_TIMEOUT, db.tables(&connection_id, &schema))
|
||||
.await
|
||||
.map_err(|e| redact_error(e, &source))?;
|
||||
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
|
||||
.await
|
||||
.map_err(|e| redact_error(e, &source))?;
|
||||
let objects = schema_objects(tables, objects, kind.as_deref());
|
||||
Output::json(json!({
|
||||
"connectionId": connection_id,
|
||||
"schema": schema,
|
||||
"objects": objects,
|
||||
}))
|
||||
},
|
||||
)
|
||||
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
|
||||
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
|
||||
.param(Param::optional(
|
||||
"kind",
|
||||
ParamType::String,
|
||||
"Only objects of this kind: table, view, materializedView, function, procedure, package, sequence, routine",
|
||||
))
|
||||
}
|
||||
|
||||
fn schema_objects(tables: Vec<ide_db::TableInfo>, objects: SchemaObjects, wanted: Option<&str>) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
for table in tables {
|
||||
let kind = match table.kind {
|
||||
DbTableKind::Table => "table",
|
||||
DbTableKind::View => "view",
|
||||
DbTableKind::MaterializedView => "materializedView",
|
||||
};
|
||||
if !kind_matches(wanted, kind) {
|
||||
continue;
|
||||
}
|
||||
let mut object = json!({ "kind": kind, "name": table.name });
|
||||
if let Some(comment) = table.comment {
|
||||
object["comment"] = json!(comment);
|
||||
}
|
||||
out.push(object);
|
||||
}
|
||||
for routine in objects.routines {
|
||||
let kind = if routine.kind == DbObjectKind::Procedure { "procedure" } else { "function" };
|
||||
if !kind_matches(wanted, kind) {
|
||||
continue;
|
||||
}
|
||||
let mut object = json!({ "kind": kind, "name": routine.name });
|
||||
if !routine.arguments.is_empty() {
|
||||
object["arguments"] = json!(routine.arguments);
|
||||
}
|
||||
if let Some(returns) = routine.returns {
|
||||
object["returns"] = json!(returns);
|
||||
}
|
||||
out.push(object);
|
||||
}
|
||||
for package in objects.packages {
|
||||
if kind_matches(wanted, "package") {
|
||||
out.push(json!({ "kind": "package", "name": package.name }));
|
||||
}
|
||||
}
|
||||
for sequence in objects.sequences {
|
||||
if kind_matches(wanted, "sequence") {
|
||||
out.push(json!({ "kind": "sequence", "name": sequence.name }));
|
||||
}
|
||||
}
|
||||
for object in objects.others {
|
||||
if kind_matches(wanted, &object.kind) {
|
||||
out.push(json!({ "kind": object.kind, "name": object.name }));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn kind_matches(wanted: Option<&str>, kind: &str) -> bool {
|
||||
wanted.is_none_or(|wanted| {
|
||||
wanted.eq_ignore_ascii_case(kind)
|
||||
|| (wanted.eq_ignore_ascii_case("routine") && matches!(kind, "function" | "procedure"))
|
||||
})
|
||||
}
|
||||
|
||||
fn get_database_object_description() -> Tool {
|
||||
Tool::new(
|
||||
"get_database_object_description",
|
||||
"Describes a table, view or materialized view: columns (type, nullability, default, primary key and comment),
|
||||
indexes, foreign keys, triggers and the object's comment, plus the owner, tablespace, access method,
|
||||
storage options and partitioning when the database reports them.
|
||||
Describing routines, packages and sequences is not supported yet. Needs a trusted project; in
|
||||
Restricted Mode the call is refused.",
|
||||
|call| async move {
|
||||
call.project.require_trust()?;
|
||||
let connection_id = call.str("connectionId")?;
|
||||
let schema = call.str("schema")?;
|
||||
let object_name = call.str("objectName")?;
|
||||
if let Some(kind) = call.opt_str("kind")?
|
||||
&& !is_table_like_kind(&kind)
|
||||
{
|
||||
return Err(description_unsupported(&kind));
|
||||
}
|
||||
let source = connection(&call, &connection_id)?;
|
||||
let db = &call.project().db;
|
||||
let details = bounded(&call, METADATA_TIMEOUT, db.table_details(&connection_id, &schema, &object_name))
|
||||
.await
|
||||
.map_err(|e| redact_error(e, &source))?;
|
||||
if details.columns.is_empty() {
|
||||
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
|
||||
.await
|
||||
.map_err(|e| redact_error(e, &source))?;
|
||||
if let Some(kind) = schema_object_kind(&objects, &object_name) {
|
||||
return Err(description_unsupported(kind));
|
||||
}
|
||||
return Err(IdeError::not_found(format!("{schema}.{object_name}")));
|
||||
}
|
||||
Output::json(json!({
|
||||
"connectionId": connection_id,
|
||||
"schema": schema,
|
||||
"objectName": object_name,
|
||||
"details": details,
|
||||
}))
|
||||
},
|
||||
)
|
||||
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
|
||||
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
|
||||
.param(Param::required("objectName", ParamType::String, "Table, view or materialized view name"))
|
||||
.param(Param::optional(
|
||||
"kind",
|
||||
ParamType::String,
|
||||
"Object kind from `list_schema_objects`; only table, view and materializedView are described",
|
||||
))
|
||||
}
|
||||
|
||||
fn is_table_like_kind(kind: &str) -> bool {
|
||||
["table", "view", "materializedView"].iter().any(|known| kind.eq_ignore_ascii_case(known))
|
||||
}
|
||||
|
||||
fn schema_object_kind<'a>(objects: &'a SchemaObjects, name: &str) -> Option<&'a str> {
|
||||
if objects.routines.iter().any(|routine| routine.name == name) {
|
||||
return Some("routine");
|
||||
}
|
||||
if objects.packages.iter().any(|package| package.name == name) {
|
||||
return Some("package");
|
||||
}
|
||||
if objects.sequences.iter().any(|sequence| sequence.name == name) {
|
||||
return Some("sequence");
|
||||
}
|
||||
objects.others.iter().find(|object| object.name == name).map(|object| object.kind.as_str())
|
||||
}
|
||||
|
||||
fn description_unsupported(kind: &str) -> IdeError {
|
||||
IdeError::invalid(format!(
|
||||
"describing a {kind} is not supported yet; this tool describes tables, views and materialized views only"
|
||||
))
|
||||
}
|
||||
|
||||
fn execute_sql_query() -> Tool {
|
||||
Tool::new(
|
||||
"execute_sql_query",
|
||||
"Runs one read-only SQL statement (SELECT, WITH or EXPLAIN) against a data source after the user confirms
|
||||
the exact statement. It runs in a driver-enforced read-only session on SQLite, PostgreSQL, MySQL/MariaDB and
|
||||
Oracle; other drivers are refused. Multiple statements, writes and DDL are refused. On Oracle, EXPLAIN is
|
||||
refused (EXPLAIN PLAN writes PLAN_TABLE). On MySQL/MariaDB, executable comments (`/*! … */`, `/*M! … */`) and
|
||||
INTO OUTFILE/INTO DUMPFILE are refused, and the connection is pinned to utf8mb4 so the server reads the
|
||||
statement exactly as the splitter did. MySQL/MariaDB and MySQL-compatible servers are supported only when
|
||||
they accept `SET NAMES utf8mb4` and report a read-only transaction (`transaction_read_only` or
|
||||
`tx_read_only`); otherwise this tool refuses. On PostgreSQL, the connection is pinned to `client_encoding`
|
||||
UTF8 with `standard_conforming_strings = on`, and the server parses the statement as one command before it
|
||||
runs, so a difference from the splitter's lexing is refused rather than executed. The metadata tools are
|
||||
unaffected. \"Read-only\" means no
|
||||
changes to tables, views and schema through the statement; functions with server-side side effects (for
|
||||
example PostgreSQL lo_export, Oracle UTL_FILE, MySQL LOAD_FILE) are outside that guarantee. Use a database
|
||||
account with read-only privileges for agent access: the IDE's read-only session is defense in depth, not a
|
||||
full sandbox.
|
||||
Returns at most `maxRows` rows (default 100, clamped to 1000), each cell cut to 4096 UTF-16 units. The query
|
||||
is cancelled after 30 seconds, with up to 5 seconds more to roll back and close. The result and errors never
|
||||
include the data source URL, host or user.",
|
||||
execute_query,
|
||||
)
|
||||
.write()
|
||||
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
|
||||
.param(Param::required(
|
||||
"sql",
|
||||
ParamType::String,
|
||||
"One read-only statement: SELECT, WITH or EXPLAIN; leading SQL comments are allowed",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"maxRows",
|
||||
ParamType::Integer,
|
||||
"Rows to return at most (default 100, clamped to 1..=1000)",
|
||||
))
|
||||
}
|
||||
|
||||
async fn execute_query(call: Call) -> IdeResult<Output> {
|
||||
let connection_id = call.str("connectionId")?;
|
||||
let sql = call.str("sql")?;
|
||||
let max_rows = match call.opt_i64("maxRows")? {
|
||||
Some(rows) => rows.clamp(1, MAX_ROWS as i64) as usize,
|
||||
None => DEFAULT_MAX_ROWS,
|
||||
};
|
||||
let source = connection(&call, &connection_id)?;
|
||||
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} has no read-only session; execute_sql_query runs on SQLite, PostgreSQL, MySQL/MariaDB and Oracle only",
|
||||
source.driver.display_name()
|
||||
)));
|
||||
}
|
||||
if source.driver == DbDriver::Mysql {
|
||||
// The server executes these even though `split` reads them as comments or literals.
|
||||
split::mysql_guard(&sql)?;
|
||||
}
|
||||
let statements = split::split(&sql, source.driver);
|
||||
let statement = match statements.as_slice() {
|
||||
[] => return Err(IdeError::invalid("the SQL is empty")),
|
||||
[statement] => statement,
|
||||
_ => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"exactly one statement is allowed, but the SQL has {}",
|
||||
statements.len()
|
||||
)));
|
||||
}
|
||||
};
|
||||
match leading_keyword(&statement.text, source.driver) {
|
||||
Some(keyword) if matches!(keyword.as_str(), "SELECT" | "WITH" | "EXPLAIN") => {
|
||||
if source.driver == DbDriver::Oracle && keyword == "EXPLAIN" {
|
||||
return Err(IdeError::invalid("EXPLAIN is not allowed on Oracle: EXPLAIN PLAN writes PLAN_TABLE"));
|
||||
}
|
||||
}
|
||||
Some(keyword) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{keyword} is not allowed: execute_sql_query runs SELECT, WITH and EXPLAIN statements only"
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid("execute_sql_query runs SELECT, WITH and EXPLAIN statements only"));
|
||||
}
|
||||
}
|
||||
let database = database_field(&source);
|
||||
let database = if database.is_empty() { "(default)" } else { database.as_str() };
|
||||
let detail = format!("Driver: {}\nDatabase: {database}\nSQL:\n{}", source.driver.display_name(), statement.text);
|
||||
call.confirm(&format!("SQL on {}", source.name), Some(detail)).await?;
|
||||
|
||||
let token = call.cancel.child_token();
|
||||
let work = call.project().db.execute_read_only_query(&connection_id, &statement.text, max_rows, &token);
|
||||
let mut result =
|
||||
until_stopped(QUERY_TIMEOUT, &call.cancel, &token, work).await.map_err(|e| redact_error(e, &source))?;
|
||||
result.cap_cells(MAX_CELL_UNITS);
|
||||
let row_count = result.rows.len();
|
||||
Output::json(json!({
|
||||
"connectionId": connection_id,
|
||||
"statement": result.statement,
|
||||
"columns": result.columns,
|
||||
"rows": result.rows,
|
||||
"rowCount": row_count,
|
||||
"hasMore": result.has_more,
|
||||
"truncated": result.truncated,
|
||||
"elapsedMs": result.elapsed_ms,
|
||||
"affected": result.affected,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The first keyword of `sql`, past leading whitespace and SQL comments, uppercased.
|
||||
fn leading_keyword(sql: &str, driver: DbDriver) -> Option<String> {
|
||||
let mut text = sql;
|
||||
loop {
|
||||
text = text.trim_start();
|
||||
if let Some(comment) = text.strip_prefix("--") {
|
||||
// PostgreSQL ends a line comment at `\r` as well as `\n` (`scan.l`), as `split` does;
|
||||
// the other drivers keep a bare `\r` in the comment.
|
||||
let end = comment
|
||||
.char_indices()
|
||||
.find(|&(_, c)| c == '\n' || (driver == DbDriver::Postgres && c == '\r'))
|
||||
.map_or(comment.len(), |(at, _)| at);
|
||||
text = &comment[end..];
|
||||
} else if let Some(comment) = text.strip_prefix('#') {
|
||||
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
|
||||
} else if let Some(comment) = text.strip_prefix("/*") {
|
||||
text = after_block_comment(comment);
|
||||
} else {
|
||||
let end = text.find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '$'))).unwrap_or(text.len());
|
||||
return (end > 0).then(|| text[..end].to_ascii_uppercase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The text after a `/*` comment, past nested block comments (`/* /* */ */`).
|
||||
fn after_block_comment(mut text: &str) -> &str {
|
||||
let mut depth = 1usize;
|
||||
while let Some(at) = text.find(['/', '*']) {
|
||||
text = &text[at..];
|
||||
if let Some(rest) = text.strip_prefix("/*") {
|
||||
depth += 1;
|
||||
text = rest;
|
||||
} else if let Some(rest) = text.strip_prefix("*/") {
|
||||
depth -= 1;
|
||||
text = rest;
|
||||
if depth == 0 {
|
||||
return text;
|
||||
}
|
||||
} else {
|
||||
text = &text[1..];
|
||||
}
|
||||
}
|
||||
""
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn exposes_exactly_the_five_database_tools() {
|
||||
let names: Vec<_> = tools().into_iter().map(|tool| tool.metadata.name).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"list_database_connections",
|
||||
"list_database_schemas",
|
||||
"list_schema_objects",
|
||||
"get_database_object_description",
|
||||
"execute_sql_query",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_execute_sql_query_is_not_read_only() {
|
||||
for tool in tools() {
|
||||
assert_eq!(tool.metadata.read_only, tool.metadata.name != "execute_sql_query", "{}", tool.metadata.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execute_sql_query_requires_a_connection_and_a_statement() {
|
||||
let tool = tools().into_iter().find(|tool| tool.metadata.name == "execute_sql_query").unwrap();
|
||||
let required = tool.metadata.input_schema["required"].as_array().unwrap();
|
||||
for name in ["connectionId", "sql"] {
|
||||
assert!(required.iter().any(|value| value == name), "{name}");
|
||||
assert_eq!(tool.metadata.input_schema["properties"][name]["type"], "string", "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_select_with_and_explain_past_comments() {
|
||||
for sql in [
|
||||
"SELECT 1",
|
||||
"-- note\nSELECT 1",
|
||||
"/* outer /* nested */ comment */ WITH x AS (SELECT 1) SELECT * FROM x",
|
||||
" \n\t EXPLAIN SELECT 1",
|
||||
] {
|
||||
assert!(
|
||||
matches!(leading_keyword(sql, DbDriver::Postgres).as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")),
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// PostgreSQL ends a leading `--` comment at `\r` too, like the fixed splitter.
|
||||
#[test]
|
||||
fn a_carriage_return_ends_a_postgres_leading_comment() {
|
||||
assert_eq!(leading_keyword("-- note\rSELECT 1", DbDriver::Postgres).as_deref(), Some("SELECT"));
|
||||
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::SqlServer] {
|
||||
assert_eq!(leading_keyword("-- note\rSELECT 1", driver), None, "{driver:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_other_leading_keywords() {
|
||||
for sql in [
|
||||
"INSERT INTO t VALUES (1)",
|
||||
"UPDATE t SET x = 1",
|
||||
"DELETE FROM t",
|
||||
"CREATE TABLE t (x INT)",
|
||||
"CALL p()",
|
||||
"COPY t FROM stdin",
|
||||
"PRAGMA query_only = ON",
|
||||
"# comment\nUPDATE t SET x = 1",
|
||||
] {
|
||||
let keyword = leading_keyword(sql, DbDriver::Postgres);
|
||||
assert!(!matches!(keyword.as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")), "{sql}: {keyword:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_hide_the_url_host_and_user() {
|
||||
let source = DataSource {
|
||||
driver: DbDriver::Postgres,
|
||||
host: "db.example.invalid".into(),
|
||||
user: "[email protected]".into(),
|
||||
url_only: true,
|
||||
url: "postgres://alice%40example.com:[email protected]:5432/app".into(),
|
||||
..Default::default()
|
||||
};
|
||||
for message in [
|
||||
"[28P01] password authentication failed for user \"[email protected]\"".to_owned(),
|
||||
"connection to server at db.example.invalid (10.0.0.5), port 5432 failed".to_owned(),
|
||||
"user alice%40example.com cannot log in".to_owned(),
|
||||
"ALICE%40EXAMPLE.COM cannot log in".to_owned(),
|
||||
"Alice%40Example.com cannot log in".to_owned(),
|
||||
"DB.EXAMPLE.INVALID refused the connection".to_owned(),
|
||||
"could not open postgres://alice%40example.com:[email protected]:5432/app".to_owned(),
|
||||
] {
|
||||
let error = redact_error(IdeError::invalid(message.clone()), &source);
|
||||
let lower = error.message.to_ascii_lowercase();
|
||||
for secret in ["alice", "db.example.invalid", "pw@db"] {
|
||||
assert!(!lower.contains(secret), "{message} -> {}", error.message);
|
||||
}
|
||||
}
|
||||
// However short: a one- or two-character name is still a configured name.
|
||||
let short = DataSource { host: "q".into(), user: "ab".into(), ..Default::default() };
|
||||
let error =
|
||||
redact_error(IdeError::invalid("password authentication failed for user \"ab\" at q".to_owned()), &short);
|
||||
assert!(!error.message.to_ascii_lowercase().contains("ab"), "{}", error.message);
|
||||
assert!(!error.message.contains('q'), "{}", error.message);
|
||||
assert!(error.message.contains("<redacted>"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oracle_tns_descriptor_is_not_shown_as_the_database() {
|
||||
let mut source = DataSource {
|
||||
driver: DbDriver::Oracle,
|
||||
database: "(DESCRIPTION=(HOST=db.local))".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(database_field(&source), "");
|
||||
source.database = "PROD=(DESCRIPTION=(HOST=db.local))".into();
|
||||
assert_eq!(database_field(&source), "");
|
||||
source.database = "ORCLPDB1".into();
|
||||
assert_eq!(database_field(&source), "ORCLPDB1");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_deadline_cancels_the_task_and_awaits_its_cleanup() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let token = cancel.child_token();
|
||||
let cleaned = Arc::new(AtomicBool::new(false));
|
||||
let task = {
|
||||
let (token, cleaned) = (token.clone(), cleaned.clone());
|
||||
async move {
|
||||
token.cancelled().await;
|
||||
cleaned.store(true, Ordering::SeqCst);
|
||||
Err::<(), _>(IdeError::cancelled())
|
||||
}
|
||||
};
|
||||
let error = until_stopped(Duration::from_millis(20), &cancel, &token, task).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::TimedOut);
|
||||
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the timeout returned");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_the_request_cancels_the_task() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let token = cancel.child_token();
|
||||
let cleaned = Arc::new(AtomicBool::new(false));
|
||||
let task = {
|
||||
let (token, cleaned) = (token.clone(), cleaned.clone());
|
||||
async move {
|
||||
token.cancelled().await;
|
||||
cleaned.store(true, Ordering::SeqCst);
|
||||
Err::<(), _>(IdeError::cancelled())
|
||||
}
|
||||
};
|
||||
let canceller = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
canceller.cancel();
|
||||
});
|
||||
let error = until_stopped(Duration::from_secs(30), &cancel, &token, task).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Cancelled);
|
||||
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the call returned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kind_filter_is_case_insensitive_and_routine_covers_functions_and_procedures() {
|
||||
assert!(kind_matches(None, "table"));
|
||||
assert!(kind_matches(Some("materializedview"), "materializedView"));
|
||||
assert!(kind_matches(Some("ROUTINE"), "function"));
|
||||
assert!(kind_matches(Some("routine"), "procedure"));
|
||||
assert!(!kind_matches(Some("routine"), "table"));
|
||||
assert!(!kind_matches(Some("stage"), "table"));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
mod automations;
|
||||
mod background;
|
||||
mod check;
|
||||
mod database;
|
||||
mod debug;
|
||||
mod devcontainer;
|
||||
mod edit;
|
||||
@@ -55,6 +56,7 @@ fn tools(local_desktop: bool) -> Vec<tool::Tool> {
|
||||
tools.extend(run::tools());
|
||||
tools.extend(vcs::tools());
|
||||
tools.extend(http::tools());
|
||||
tools.extend(database::tools());
|
||||
if local_desktop {
|
||||
tools.extend(devcontainer::tools());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::common;
|
||||
use ide_core::{
|
||||
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
|
||||
};
|
||||
use ide_db::{DataSource, DbDriver};
|
||||
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_mcp::ToolRegistry;
|
||||
@@ -3144,3 +3145,479 @@ async fn automation_tools_enforce_trust_mandatory_confirm_even_in_brave_mode_and
|
||||
assert_eq!(del_res["deletedId"], imported_id);
|
||||
assert!(h.host.automations.get(&imported_id).is_none());
|
||||
}
|
||||
|
||||
/// The project's SQLite data source `db`: `users` with 150 rows and a foreign key to itself,
|
||||
/// the `users_name` unique index and the `named` view.
|
||||
async fn sqlite_fixture(h: &Harness) {
|
||||
std::fs::File::create(h.root.join("data.sqlite")).unwrap();
|
||||
let db = h.host.project("main").unwrap().db.clone();
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "db".into(),
|
||||
name: "Test DB".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some(h.root.join("data.sqlite").into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, manager_id INTEGER REFERENCES users(id))",
|
||||
"CREATE UNIQUE INDEX users_name ON users(name)",
|
||||
"CREATE VIEW named AS SELECT name FROM users",
|
||||
] {
|
||||
db.execute("db", stmt, 100, &c).await.unwrap();
|
||||
}
|
||||
let rows: Vec<String> = (1..=150).map(|id| format!("({id}, 'user{id:03}')")).collect();
|
||||
db.execute("db", &format!("INSERT INTO users (id, name) VALUES {}", rows.join(", ")), 100, &c).await.unwrap();
|
||||
}
|
||||
|
||||
/// Writes `.openidea/data-sources.toml` as a crafted repository might: `save_sources` rejects
|
||||
/// duplicate ids, so a test of the tool boundary needs the file itself.
|
||||
fn write_sources_file(root: &Path, sources: &[DataSource]) {
|
||||
let tables: Vec<toml::Value> = sources
|
||||
.iter()
|
||||
.map(|source| {
|
||||
let mut value = toml::Value::try_from(source).unwrap();
|
||||
value.as_table_mut().unwrap().remove("global");
|
||||
value
|
||||
})
|
||||
.collect();
|
||||
let doc = toml::Value::Table(toml::map::Map::from_iter([("data-source".to_owned(), toml::Value::Array(tables))]));
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
std::fs::write(root.join(".openidea/data-sources.toml"), toml::to_string_pretty(&doc).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
/// Runs `name` in the project's window and allows the confirmation it asks there; the window
|
||||
/// must be ready (`h.host.mcp_requests.set_ready("main", true)`).
|
||||
async fn confirmed(h: &Harness, name: &str, args: Value) -> String {
|
||||
h.events.lock().unwrap().clear();
|
||||
let call = h.call(name, args);
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
h.host.mcp_requests.answer("main", id, true, None).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(call, allow);
|
||||
result
|
||||
}
|
||||
|
||||
/// Like [`confirmed`], for a call that must fail after the confirmation.
|
||||
async fn confirmed_error(h: &Harness, name: &str, args: Value) -> String {
|
||||
h.events.lock().unwrap().clear();
|
||||
let call = h.error(name, args);
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
h.host.mcp_requests.answer("main", id, true, None).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(call, allow);
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn database_connections_are_listed_without_urls_hosts_or_credentials() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
assert!(!h.host.project("main").unwrap().is_trusted(), "the metadata tools need a trusted project");
|
||||
let refused = h.error("list_database_connections", json!({})).await;
|
||||
assert!(refused.contains("Restricted Mode"), "{refused}");
|
||||
h.trust().await;
|
||||
let raw = h.call("list_database_connections", json!({})).await;
|
||||
let listed: Value = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(
|
||||
listed["connections"],
|
||||
json!([{ "id": "db", "name": "Test DB", "driver": "sqlite", "database": "", "readOnly": false, "global": false }])
|
||||
);
|
||||
for key in ["url", "host", "user", "password"] {
|
||||
assert!(!raw.contains(&format!("\"{key}\"")), "`{key}` in {raw}");
|
||||
}
|
||||
// A URL-only source's URL, host and user never reach the agent either.
|
||||
let db = h.host.project("main").unwrap().db.clone();
|
||||
let mut sources = db.sources().unwrap();
|
||||
sources.push(DataSource {
|
||||
id: "remote".into(),
|
||||
name: "Remote".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
url_only: true,
|
||||
url: "postgres://db.example.invalid:5432/app".into(),
|
||||
..Default::default()
|
||||
});
|
||||
db.save_sources(sources).await.unwrap();
|
||||
let raw = h.call("list_database_connections", json!({})).await;
|
||||
assert!(raw.contains("\"remote\""), "{raw}");
|
||||
for secret in ["db.example.invalid", "5432", "app"] {
|
||||
assert!(!raw.contains(secret), "`{secret}` in {raw}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Global data sources are stored app-wide and listed in every project; the list marks them.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn global_data_sources_are_listed_with_a_global_flag() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
ide_db::source::save_global(
|
||||
&h.host.data_dir,
|
||||
&[DataSource {
|
||||
id: "shared".into(),
|
||||
name: "Shared".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some(h.root.join("data.sqlite").into()),
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
h.trust().await;
|
||||
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
|
||||
let connections = listed["connections"].as_array().unwrap();
|
||||
let project = connections.iter().find(|c| c["id"] == "db").expect("the project source");
|
||||
assert_eq!(project["global"], false, "{listed}");
|
||||
let global = connections.iter().find(|c| c["id"] == "shared").expect("the global source");
|
||||
assert_eq!(global["global"], true, "{listed}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn database_schemas_and_objects_are_listed_in_a_trusted_project() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
for (name, args) in [
|
||||
("list_database_schemas", json!({"connectionId": "db"})),
|
||||
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
|
||||
] {
|
||||
let refused = h.error(name, args).await;
|
||||
assert!(refused.contains("Restricted Mode"), "{name}: {refused}");
|
||||
}
|
||||
h.trust().await;
|
||||
let schemas = h.json("list_database_schemas", json!({"connectionId": "db"})).await;
|
||||
assert_eq!(schemas["connectionId"], "db");
|
||||
assert_eq!(schemas["schemas"], json!(["main"]));
|
||||
// Tables and views are objects; the unique index is not.
|
||||
let all = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main"})).await;
|
||||
assert_eq!(all["objects"], json!([{"kind": "view", "name": "named"}, {"kind": "table", "name": "users"}]), "{all}");
|
||||
assert!(!all.to_string().contains("users_name"), "{all}");
|
||||
let views = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main", "kind": "view"})).await;
|
||||
assert_eq!(views["objects"], json!([{"kind": "view", "name": "named"}]), "{views}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn database_object_description_reads_columns_indexes_and_foreign_keys() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
let args = json!({"connectionId": "db", "schema": "main", "objectName": "users"});
|
||||
let refused = h.error("get_database_object_description", args.clone()).await;
|
||||
assert!(refused.contains("Restricted Mode"), "{refused}");
|
||||
h.trust().await;
|
||||
let described = h.json("get_database_object_description", args).await;
|
||||
assert_eq!(
|
||||
(&described["connectionId"], &described["schema"], &described["objectName"]),
|
||||
(&json!("db"), &json!("main"), &json!("users"))
|
||||
);
|
||||
let details = &described["details"];
|
||||
let columns = details["columns"].as_array().unwrap();
|
||||
let names: Vec<&str> = columns.iter().map(|c| c["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["id", "name", "manager_id"]);
|
||||
assert_eq!(columns[0]["primaryKey"], true);
|
||||
assert_eq!(columns[1]["nullable"], false);
|
||||
let index = details["indexes"].as_array().unwrap().iter().find(|i| i["name"] == "users_name").expect("users_name");
|
||||
assert_eq!(index["unique"], true);
|
||||
assert_eq!(index["columns"], json!(["name"]));
|
||||
let keys = details["foreignKeys"].as_array().unwrap();
|
||||
assert_eq!(keys.len(), 1, "{described}");
|
||||
assert_eq!(keys[0]["columns"], json!(["manager_id"]));
|
||||
assert_eq!(keys[0]["refSchema"], "main");
|
||||
assert_eq!(keys[0]["refTable"], "users");
|
||||
assert_eq!(keys[0]["refColumns"], json!(["id"]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_is_a_write_tool_that_needs_trust() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
let untrusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
|
||||
for name in
|
||||
["list_database_connections", "list_database_schemas", "list_schema_objects", "get_database_object_description"]
|
||||
{
|
||||
assert!(untrusted.iter().any(|t| t.name == name && t.read_only), "{name} is a read tool");
|
||||
}
|
||||
assert!(untrusted.iter().all(|t| t.name != "execute_sql_query"), "a write tool is hidden until trust");
|
||||
// The metadata tools are still listed, but their calls need trust too, not only the write tool.
|
||||
for (name, args) in [
|
||||
("list_database_connections", json!({})),
|
||||
("list_database_schemas", json!({"connectionId": "db"})),
|
||||
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
|
||||
("get_database_object_description", json!({"connectionId": "db", "schema": "main", "objectName": "users"})),
|
||||
] {
|
||||
let message = h.error(name, args).await;
|
||||
assert!(message.contains("Restricted Mode"), "{name}: {message}");
|
||||
}
|
||||
// Calling it directly is refused too, not only hidden from the list.
|
||||
let refused = Registry::new(h.host.clone()).call(
|
||||
&h.root,
|
||||
"execute_sql_query",
|
||||
&json!({"connectionId": "db", "sql": "SELECT 1"}).to_string(),
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let message = match refused.expect_err("a write tool is refused in Restricted Mode") {
|
||||
ide_mcp::ToolCallError::Failed(message) | ide_mcp::ToolCallError::UnknownTool(message) => message,
|
||||
};
|
||||
assert!(message.contains("Restricted Mode"), "{message}");
|
||||
h.trust().await;
|
||||
let trusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
|
||||
let tool = trusted.iter().find(|t| t.name == "execute_sql_query").expect("offered once trusted");
|
||||
assert!(!tool.read_only);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_pages_rows_and_cuts_long_cells() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
|
||||
let page: Value = serde_json::from_str(
|
||||
&confirmed(
|
||||
&h,
|
||||
"execute_sql_query",
|
||||
json!({"connectionId": "db", "sql": "SELECT id, name FROM users ORDER BY id", "maxRows": 10}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(page["rowCount"], 10, "{page}");
|
||||
assert_eq!(page["rows"].as_array().unwrap().len(), 10);
|
||||
assert_eq!(page["hasMore"], true);
|
||||
assert_eq!(page["rows"][0], json!(["1", "user001"]));
|
||||
// The dialog showed the exact statement, not the raw arguments or a truncated form.
|
||||
let detail = h
|
||||
.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|(_, event)| match event {
|
||||
IdeEvent::McpRequest { request: McpUiRequest::Confirm { detail, .. }, .. } => {
|
||||
Some(detail.clone().unwrap_or_default())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("a confirmation was asked");
|
||||
assert!(detail.contains("SQL:\nSELECT id, name FROM users ORDER BY id"), "{detail}");
|
||||
assert!(detail.contains("Driver: SQLite"), "{detail}");
|
||||
let columns: Vec<&str> = page["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(columns, ["id", "name"]);
|
||||
|
||||
// Without `maxRows` the result stops at the default of 100, and says more rows exist.
|
||||
let default: Value = serde_json::from_str(
|
||||
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT id FROM users ORDER BY id"}))
|
||||
.await,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(default["rowCount"], 100, "{default}");
|
||||
assert_eq!(default["rows"].as_array().unwrap().len(), 100);
|
||||
assert_eq!(default["hasMore"], true);
|
||||
|
||||
// A cell longer than 4096 UTF-16 units is cut and reported in `truncated`.
|
||||
let sql = format!("SELECT '{}' AS long", "x".repeat(5000));
|
||||
let long: Value =
|
||||
serde_json::from_str(&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": sql})).await)
|
||||
.unwrap();
|
||||
assert_eq!(long["rows"][0][0].as_str().unwrap().chars().count(), 4096);
|
||||
let truncated = long["truncated"].as_array().unwrap();
|
||||
assert_eq!(truncated.len(), 1, "{long}");
|
||||
assert_eq!(truncated[0]["length"], 5000);
|
||||
assert_eq!((&truncated[0]["row"], &truncated[0]["column"]), (&json!(0), &json!(0)));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_refuses_several_statements_and_writes_before_asking() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
let several = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT 1; SELECT 2"})).await;
|
||||
assert!(several.contains("exactly one statement"), "{several}");
|
||||
let write = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "DELETE FROM users"})).await;
|
||||
assert!(write.contains("DELETE is not allowed"), "{write}");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
let count = h
|
||||
.host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.db
|
||||
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_refuses_a_driver_without_a_read_only_session_before_asking() {
|
||||
let h = Harness::new();
|
||||
let db = h.host.project("main").unwrap().db.clone();
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "mssql".into(),
|
||||
name: "SQL Server".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(1),
|
||||
user: "sa".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
h.events.lock().unwrap().clear();
|
||||
// The refusal happens before a connection is opened, so no server is needed.
|
||||
let error = h.error("execute_sql_query", json!({"connectionId": "mssql", "sql": "SELECT 1"})).await;
|
||||
assert!(error.contains("SQL Server has no read-only session"), "{error}");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
/// A statement that passes the `SELECT`/`WITH` allowlist but writes through a CTE is refused by the
|
||||
/// driver-enforced read-only session (`PRAGMA query_only`), not by the keyword check. Unlike the
|
||||
/// gated PostgreSQL test, this runs everywhere SQLite does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_refuses_a_cte_write_through_the_read_only_session() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let error = confirmed_error(
|
||||
&h,
|
||||
"execute_sql_query",
|
||||
json!({"connectionId": "db", "sql": "WITH d AS (SELECT 1) DELETE FROM users"}),
|
||||
)
|
||||
.await;
|
||||
assert!(error.to_ascii_lowercase().contains("readonly"), "{error}");
|
||||
let count = h
|
||||
.host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.db
|
||||
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count.rows, vec![vec![Some("150".into())]], "the session refused the write before it ran");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_can_be_denied_without_changing_the_database() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let denied =
|
||||
h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT name FROM users ORDER BY id"}));
|
||||
let deny = async {
|
||||
let id = h.request().await;
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, deny);
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
let count = h
|
||||
.host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.db
|
||||
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
|
||||
}
|
||||
|
||||
/// A crafted project file cannot route a tool to a plugin-owned source: its id is refused when
|
||||
/// plugin-owned, a `:database` suffix is refused, and two entries with one id are refused.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn database_tools_refuse_plugin_and_ambiguous_connection_ids() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
let file: ide_core::IpcPath = h.root.join("data.sqlite").into();
|
||||
let plugin = |id: &str| DataSource {
|
||||
id: id.into(),
|
||||
name: "Plugin source".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some(file.clone()),
|
||||
plugin_owner: Some("sample".into()),
|
||||
plugin_source_id: Some("owned".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let user = |id: &str| DataSource {
|
||||
id: id.into(),
|
||||
name: "User source".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some(file.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
write_sources_file(
|
||||
&h.root,
|
||||
&[
|
||||
plugin("plugin-owned"),
|
||||
user("plugin-owned:database"),
|
||||
// The plugin entry first: `DbManager` takes the first matching prefix.
|
||||
plugin("dup"),
|
||||
user("dup"),
|
||||
],
|
||||
);
|
||||
|
||||
let colon = h.error("list_database_schemas", json!({"connectionId": "plugin-owned:database"})).await;
|
||||
assert!(colon.contains("without a `:database` part"), "{colon}");
|
||||
let owned = h.error("list_database_schemas", json!({"connectionId": "plugin-owned"})).await;
|
||||
assert!(owned.contains("no data source plugin-owned"), "{owned}");
|
||||
let duplicate = h.error("list_database_schemas", json!({"connectionId": "dup"})).await;
|
||||
assert!(duplicate.contains("more than one data source"), "{duplicate}");
|
||||
// `list_database_connections` keeps its own filter: only the user entries appear.
|
||||
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
|
||||
let ids: Vec<&str> = listed["connections"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();
|
||||
assert!(!ids.contains(&"plugin-owned"), "{listed}");
|
||||
}
|
||||
|
||||
/// Driver and tunnel errors can name the user or the host; no database tool may pass them on.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn database_tool_errors_hide_the_user_host_and_url() {
|
||||
let h = Harness::new();
|
||||
let db = h.host.project("main").unwrap().db.clone();
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "remote".into(),
|
||||
name: "Remote".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
user: "alice".into(),
|
||||
host: "127.0.0.1".into(),
|
||||
url_only: true,
|
||||
url: "postgres://alice:[email protected]:1/app".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
let assert_hidden = |text: &str| {
|
||||
for secret in ["alice", "127.0.0.1", "postgres://"] {
|
||||
assert!(!text.contains(secret), "`{secret}` in {text}");
|
||||
}
|
||||
};
|
||||
h.trust().await;
|
||||
let listed = h.call("list_database_connections", json!({})).await;
|
||||
assert_hidden(&listed);
|
||||
let schemas = h.error("list_database_schemas", json!({"connectionId": "remote"})).await;
|
||||
assert_hidden(&schemas);
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let query = confirmed_error(&h, "execute_sql_query", json!({"connectionId": "remote", "sql": "SELECT 1"})).await;
|
||||
assert_hidden(&query);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_sql_query_still_answers_a_select_on_a_read_only_data_source() {
|
||||
let h = Harness::new();
|
||||
sqlite_fixture(&h).await;
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
// The data source's own read-only setting is respected: queries still run, and it is listed as such.
|
||||
let db = h.host.project("main").unwrap().db.clone();
|
||||
let mut sources = db.sources().unwrap();
|
||||
sources.iter_mut().find(|s| s.id == "db").unwrap().read_only = true;
|
||||
db.save_sources(sources).await.unwrap();
|
||||
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
|
||||
assert_eq!(listed["connections"][0]["readOnly"], true, "{listed}");
|
||||
let result: Value = serde_json::from_str(
|
||||
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT count(*) AS n FROM users"}))
|
||||
.await,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result["rows"], json!([["150"]]), "{result}");
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "MCP server"
|
||||
description: "Let Claude Code, Codex and other MCP clients use OpenIDEA's search, code insight, editing, run and Git tools on your open projects."
|
||||
description: "Let Claude Code, Codex and other MCP clients use OpenIDEA's search, code insight, editing, run, Git and database tools on your open projects."
|
||||
---
|
||||
|
||||
OpenIDEA has a built-in [Model Context Protocol](https://modelcontextprotocol.io) server. With it on, AI agents running outside the IDE, such as Claude Code in a terminal, Codex or Cursor, can call the IDE's tools on the projects you have open: search with the project index, look up symbols through the language servers, read the Problems view, rename, reformat, build, run configurations and read Git status.
|
||||
@@ -98,6 +98,7 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i
|
||||
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
|
||||
| Git | `get_repositories`, `git_status`, `git_diff` |
|
||||
| HTTP Client | `http_list_requests`, `http_run_request` |
|
||||
| Database | `list_database_connections`, `list_database_schemas`, `list_schema_objects`, `get_database_object_description`, `execute_sql_query` |
|
||||
| Automations | `list_automations`, `preview_automation_schedule`, `save_automation`, `control_automation`, `schedule_next_run` |
|
||||
|
||||
Notes on what they do:
|
||||
@@ -117,6 +118,7 @@ Notes on what they do:
|
||||
- `apply_patch` accepts the Codex `apply_patch` format and unified diffs. Paths must stay inside the project.
|
||||
- `git_diff` compares files on disk, so unsaved editor text is not included.
|
||||
- `http_list_requests` lists requests in a project `.http` / `.rest` file; `http_run_request` sends one by index (optional `env` from `http-client.env.json`), asks first, and returns status plus a truncated body — not request headers or body.
|
||||
- The database tools work on the project's data sources in the **Database** tool window and reuse its credential store, so credentials never cross MCP. All five need a trusted project: in Restricted Mode their calls are refused, and the four read-only tools stay listed while `execute_sql_query` is hidden. `list_database_connections` returns only each data source's id, name, driver, database, read-only and global flags, never URLs, users or passwords (`database` is empty when none is configured; a source configured only by a URL is not read); global data sources are stored app-wide, are listed in every project and carry `"global": true`; data sources owned by plugins are not exposed in this first version, and `connectionId` must be one listed id (a `:database` suffix is refused). `list_database_schemas` lists schemas; `list_schema_objects` lists tables, views, materialized views, routines, packages and sequences; `get_database_object_description` describes the columns, keys, indexes, foreign keys and comments of a table, view or materialized view, and the owner, tablespace, storage options and partitioning the database reports. `execute_sql_query` runs one `SELECT`, `WITH` or `EXPLAIN` statement after a confirmation dialog that shows the exact SQL, and runs in a driver-enforced read-only session that ends afterwards (a transaction rolled back, SQLite's `query_only` reset): a write hidden in a CTE is refused by the session, and multiple statements or non-read statements are refused. It supports SQLite, PostgreSQL, MySQL/MariaDB and Oracle; this first version refuses SQL Server, ClickHouse, Snowflake and custom JDBC. On Oracle, `EXPLAIN` is refused because `EXPLAIN PLAN` writes `PLAN_TABLE`. On MySQL/MariaDB and MySQL-compatible servers, executable comments (`/*! … */`, `/*M! … */`) and `INTO OUTFILE`/`INTO DUMPFILE` are refused, the connection is pinned to `utf8mb4` so the server reads the statement exactly as the statement splitter did, and the tool is supported only when the server accepts `SET NAMES utf8mb4` and reports a read-only transaction through `transaction_read_only` or `tx_read_only`; a server that cannot be verified, or whose `sql_mode` sets `NO_BACKSLASH_ESCAPES` or `ANSI_QUOTES`, is refused. On PostgreSQL, the read-only session is pinned to `client_encoding` UTF8 with `standard_conforming_strings = on`, and the server parses the statement as one command before it runs, so a server that reports another encoding or string-escape setting is refused. Metadata tools are unaffected. "Read-only" means no changes to tables, views and schema through the statement; functions with server-side side effects (for example PostgreSQL `lo_export`, Oracle `UTL_FILE`, MySQL `LOAD_FILE`) are outside that guarantee. Use a database account with read-only privileges for agent access: the IDE's read-only session is defense in depth, not a full sandbox. Rows default to 100 and are capped at 1000, cells are capped at 4096 UTF-16 units, and a query is cancelled after 30 seconds, with up to 5 seconds more to roll back and close.
|
||||
- `list_automations` lists the project's Agent Automations, recent run history, active in-session schedules (`Send Later` and `/loop`), and scheduler status (optional `.automation.md` text with `includeMarkdown: true`); `preview_automation_schedule` validates a trigger and previews upcoming zoned firing times. `save_automation` creates or updates a project automation (including from `.automation.md` text; non-schedule updates preserve any valid future agent override unless `clearOverride: true`), and `control_automation` enables, pauses (`pause` / `pause_all`), runs now or deletes one. Both project-mutating tools always ask in an open trusted project window — even when brave mode is on — never change login-service or approval-ceiling settings, and refuse calls from unattended scheduled runs. When **Allow agent to schedule its next run (unattended)** (`allowAgentSchedule`) is enabled on an automation, its active scheduled runs (authenticated by an unguessable per-session capability nonce, including in `ChatOnly`, headless, or `oneShot` seed runs) can call `schedule_next_run` without confirmation to store a one-time `nextRunOverrideMs` and optional `nextPromptOverride` (`done: true` clears the override and lets the regular schedule continue, leaving `manual` automations idle and auto-disabling elapsed `oneShot` automations once a run completes without scheduling another), subject to a 60-second minimum delay and any `maxRuns` or `disableAfter` limits.
|
||||
- The `xdebug_*` tools expose the IDE's debugger (JetBrains' Debugger MCP toolset). `xdebug_get_debugger_status` lists the active sessions; pass its `id` (the session name, or `name#id` when names collide) as `sessionId` to the other tools. `xdebug_start_debugger_session` uses the same run configurations and run points as `execute_run_configuration`, asks first, and then lets the IDE's own Debug action build the launch and open the session in the Debug tool window; program output goes there rather than into the tool result. It needs a project window.
|
||||
- Breakpoints set with `xdebug_set_breakpoint` are the editor's breakpoints: they show in the gutter and View Breakpoints, are persisted with the project, and are mirrored to the backend for sessions to use. `xdebug_list_breakpoints` reads that same list and returns canonical `id`s for updating and removing breakpoints. `temporary`, `isLogStack` and `suspendPolicy` are accepted for compatibility but are not implemented. After `RESUME`, call `xdebug_control_session(action=WAIT_FOR_PAUSE)` and then `xdebug_get_stack` / `xdebug_get_frame_values`; frame indices and value paths from an earlier pause must not be reused.
|
||||
@@ -187,7 +189,7 @@ When a project loads and unloads:
|
||||
|
||||
While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**.
|
||||
|
||||
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools.
|
||||
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools; the database metadata tools are listed, but their calls need trust.
|
||||
|
||||
A background project has no window, so some tools differ:
|
||||
|
||||
@@ -198,10 +200,10 @@ A background project has no window, so some tools differ:
|
||||
|
||||
## Safety
|
||||
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
|
||||
- **Untrusted projects** expose only the read-only tools; the database metadata tools are listed, but their calls need trust. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command`, `http_run_request`, `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` and `devcontainer_exec` ask in the project window you used last, and the dialog names the project.
|
||||
- Tools that write refuse paths outside the project.
|
||||
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
|
||||
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools; the database metadata tools are listed, but their calls need trust. Keep the list to folders you want agents to reach.
|
||||
|
||||
## Remote development
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "MCP Server"
|
||||
description: "让 Claude Code、Codex 等 MCP 客户端在你打开的项目上使用 OpenIDEA 的搜索、代码洞察、编辑、运行和 Git 工具。"
|
||||
description: "让 Claude Code、Codex 等 MCP 客户端在你打开的项目上使用 OpenIDEA 的搜索、代码洞察、编辑、运行、Git 和数据库工具。"
|
||||
---
|
||||
|
||||
OpenIDEA 内置了一个 [Model Context Protocol](https://modelcontextprotocol.io)(MCP)服务器。打开后,在 IDE 之外运行的 AI agent(例如终端里的 Claude Code、Codex 或 Cursor)就能对你打开的项目调用 IDE 的工具:借助项目索引搜索、通过语言服务器查询符号、读取问题视图、重命名、重新格式化、构建、执行运行配置以及查看 Git 状态。
|
||||
@@ -97,6 +97,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
|
||||
| Git | `get_repositories`、`git_status`、`git_diff` |
|
||||
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
|
||||
| 数据库 | `list_database_connections`、`list_database_schemas`、`list_schema_objects`、`get_database_object_description`、`execute_sql_query` |
|
||||
| 自动化 | `list_automations`、`preview_automation_schedule`、`save_automation`、`control_automation`、`schedule_next_run` |
|
||||
|
||||
几点说明:
|
||||
@@ -116,6 +117,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
- `apply_patch` 接受 Codex 的 `apply_patch` 格式和 unified diff,路径必须在项目内。
|
||||
- `git_diff` 比较的是磁盘上的文件,不包含编辑器中尚未保存的内容。
|
||||
- `http_list_requests` 列出项目中 `.http` / `.rest` 文件里的请求;`http_run_request` 按索引发送其中一个(可选 `env`,来自 `http-client.env.json`),会先询问,并返回状态和截断后的响应体——不含请求头或请求体。
|
||||
- 数据库工具作用于 **数据库** 工具窗口中的项目数据源,并复用它的凭据存储,凭据不会跨 MCP 传递。五个工具都需要项目已被信任:在受限模式下调用会被拒绝,四个只读工具仍会列出,而 `execute_sql_query` 会被隐藏。`list_database_connections` 只返回每个数据源的 id、名称、驱动、数据库、只读标记和全局标记,绝不返回 URL、用户名或密码(`database` 未配置时为空;仅用 URL 配置的数据源的 URL 不会被读取);全局数据源存储在应用级,会在每个项目中列出,并带有 `"global": true`;插件自己的数据源在首个版本中不会暴露,并且 `connectionId` 必须是列表中的一个 id(带 `:database` 后缀会被拒绝)。`list_database_schemas` 列出架构;`list_schema_objects` 列出表、视图、物化视图、例程、包和序列;`get_database_object_description` 描述表、视图或物化视图的列、键、索引、外键和注释,以及数据库报告的属主、表空间、存储选项和分区信息。`execute_sql_query` 在显示完整 SQL 的确认对话框之后执行一条 `SELECT`、`WITH` 或 `EXPLAIN` 语句,并在驱动强制的只读会话中运行,结束后关闭(事务会回滚,SQLite 的 `query_only` 会复位):隐藏在 CTE 中的写入会被该会话拒绝,多条语句和非只读语句也会被拒绝。它支持 SQLite、PostgreSQL、MySQL/MariaDB 和 Oracle;首个版本会拒绝 SQL Server、ClickHouse、Snowflake 和自定义 JDBC。在 Oracle 上会拒绝 `EXPLAIN`,因为 `EXPLAIN PLAN` 会写入 `PLAN_TABLE`。在 MySQL/MariaDB 及 MySQL 兼容服务器上会拒绝可执行注释(`/*! … */`、`/*M! … */`)和 `INTO OUTFILE`/`INTO DUMPFILE`,查询连接会固定为 `utf8mb4`,使服务器按与语句拆分器相同的方式读取语句;只有当服务器接受 `SET NAMES utf8mb4` 并通过 `transaction_read_only` 或 `tx_read_only` 报告只读事务时该工具才可用,无法验证的服务器、或 `sql_mode` 含 `NO_BACKSLASH_ESCAPES`、`ANSI_QUOTES` 的服务器会被拒绝。在 PostgreSQL 上,只读会话会固定为 `client_encoding` UTF8 和 `standard_conforming_strings = on`,服务器还会在执行前把语句解析为一条命令;报告其他编码或字符串转义设置的服务器会被拒绝。元数据工具不受影响。“只读”意味着语句不会更改表、视图和架构;带服务器端副作用的函数(例如 PostgreSQL 的 `lo_export`、Oracle 的 `UTL_FILE`、MySQL 的 `LOAD_FILE`)不在该保证范围内。建议为智能体访问使用只读权限的数据库账号:IDE 的只读会话是纵深防御,而不是完整的沙箱。结果默认返回 100 行、最多 1000 行,单元格上限为 4096 个 UTF-16 单元,查询超过 30 秒会被取消,并最多再等 5 秒回滚和关闭。
|
||||
- `list_automations` 列出项目的智能体自动化、近期运行记录、活动会话计划(`Send Later` 与 `/loop`)以及调度器状态(`includeMarkdown: true` 可附带便携 `.automation.md` 文本);`preview_automation_schedule` 校验触发器并预览后续带时区的触发时间。`save_automation` 创建或更新项目自动化(支持导入 `.automation.md`;非计划项更新默认保留有效的未来智能体覆盖,传入 `clearOverride: true` 可显式清除),`control_automation` 用于启用、暂停(`pause` / `pause_all`)、立即运行或删除自动化。这两个项目级写入工具即使开启勇敢模式也始终在已打开的受信任项目窗口中请求确认,绝不修改开机自启服务或审批上限设置,并拒绝来自无人值守计划运行的调用。当自动化开启 **允许智能体自行安排下一次运行(无人值守)**(`allowAgentSchedule`)时,其正在执行的计划运行(通过每会话不可猜测的能力随机数认证,包括纯对话 `ChatOnly`、无头后台及 `oneShot` 一次性起链运行)可调用 `schedule_next_run`,无需确认即可写入一次性 `nextRunOverrideMs` 与可选 `nextPromptOverride`(`done: true` 会清除覆盖并恢复常规计划,`manual` 自动化保持空闲,`oneShot` 自动化在运行结束且未续排下一次时自动停用),同时强制执行最短 60 秒延迟并遵循 `maxRuns` 与 `disableAfter` 限制。
|
||||
- `xdebug_*` 工具把 IDE 的调试器开放给智能体(对应 JetBrains 的 Debugger MCP 工具集)。`xdebug_get_debugger_status` 列出当前会话;把返回的 `id`(会话名,重名时为 `名称#编号`)作为其他工具的 `sessionId`。`xdebug_start_debugger_session` 与 `execute_run_configuration` 使用相同的运行配置和代码运行点,询问后由 IDE 自己的 Debug 操作构建启动配置并在调试工具窗口中打开会话;程序输出在那里,而不在工具结果中。此工具需要项目窗口。
|
||||
- `xdebug_set_breakpoint` 设置的是编辑器的断点:它们显示在边栏和“查看断点”中,随项目一起持久化,并同步到后端供调试会话使用。`xdebug_list_breakpoints` 读取同一份列表,返回可用于更新和删除的规范 `id`。为兼容而接受 `temporary`、`isLogStack` 和 `suspendPolicy`,但未实现。`RESUME` 之后调用 `xdebug_control_session(action=WAIT_FOR_PAUSE)`,再用 `xdebug_get_stack` / `xdebug_get_frame_values`;上一次暂停得到的帧索引和值路径不能复用。
|
||||
@@ -186,7 +188,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
|
||||
|
||||
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
|
||||
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具;数据库元数据工具会列出,但其调用需要信任。
|
||||
|
||||
后台项目没有窗口,所以有些工具不同:
|
||||
|
||||
@@ -197,10 +199,10 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
## 安全
|
||||
|
||||
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
|
||||
- **未受信任的项目** 只开放只读工具;数据库元数据工具会列出,但其调用需要信任。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
|
||||
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command`、`http_run_request`、`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 和 `devcontainer_exec` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
|
||||
- 会写入的工具拒绝项目之外的路径。
|
||||
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
|
||||
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具;数据库元数据工具会列出,但其调用需要信任。列表里只放你愿意让智能体访问的文件夹。
|
||||
|
||||
## 远程开发
|
||||
|
||||
|
||||
@@ -321,6 +321,11 @@ class FakeMcpBackend implements McpBackend {
|
||||
name: "dengliu_kubernetes__get_pod_logs",
|
||||
description: "Fetch pod logs (plugin: Kubernetes [dengliu.kubernetes])",
|
||||
},
|
||||
{ name: "list_database_connections", description: "Lists the configured database data sources" },
|
||||
{ name: "list_database_schemas", description: "Lists the schemas visible to a data source" },
|
||||
{ name: "list_schema_objects", description: "Lists tables, views, routines and sequences" },
|
||||
{ name: "get_database_object_description", description: "Describes a table's columns, keys and indexes" },
|
||||
{ name: "execute_sql_query", description: "Runs one SELECT, WITH or EXPLAIN statement after confirmation" },
|
||||
],
|
||||
}));
|
||||
|
||||
@@ -451,6 +456,24 @@ describe("McpServersPage & IdeMcpServerPage (Agents › MCP)", () => {
|
||||
expect(await screen.findByText("check_files")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists the database tools under Exposed IDE Tools", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
render(<IdeMcpServerPage backend={backend} />);
|
||||
|
||||
expect(await screen.findByTestId("mcp-ide-server-page")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Inspect Tools" }));
|
||||
|
||||
expect(await screen.findByText("list_database_connections")).toBeInTheDocument();
|
||||
for (const name of [
|
||||
"list_database_schemas",
|
||||
"list_schema_objects",
|
||||
"get_database_object_description",
|
||||
"execute_sql_query",
|
||||
]) {
|
||||
expect(screen.getByText(name)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("labels MCP servers contributed by a plugin", async () => {
|
||||
const backend = new FakeMcpBackend();
|
||||
backend.servers = [server({ id: "plugin:slack", name: "slack", scope: "user", pluginId: "slack" })];
|
||||
|
||||
Reference in new issue
Заблокувати користувача