From 9ba61756db02986dd74f01a3b7c2ef93b0eef6e7 Mon Sep 17 00:00:00 2001 From: "Spencer.Chang" Date: Fri, 17 Jul 2026 16:05:50 +0800 Subject: [PATCH] feat(jdbc): add user-managed JDBCX support --- README.md | 4 +- README.zh-CN.md | 4 +- apps/desktop/public/icons/database/jdbcx.svg | 3 + apps/desktop/src/App.vue | 2 + .../connection/ConnectionDialog.vue | 63 +++++- .../src/components/icons/DatabaseIcon.vue | 1 + apps/desktop/src/i18n/locales/en.ts | 3 + apps/desktop/src/i18n/locales/es.ts | 3 + apps/desktop/src/i18n/locales/it.ts | 3 + apps/desktop/src/i18n/locales/ja.ts | 3 + apps/desktop/src/i18n/locales/pt-BR.ts | 3 + apps/desktop/src/i18n/locales/zh-CN.ts | 3 + apps/desktop/src/i18n/locales/zh-TW.ts | 3 + .../connection/jdbcxConnectionDialog.spec.ts | 27 +++ .../database/jdbcxBuiltinDriver.spec.ts | 201 ++++++++++++++++++ .../lib/__tests__/imports/jdbcxImport.spec.ts | 54 +++++ .../lib/__tests__/sql/sqlParameters.spec.ts | 10 + .../src/lib/database/jdbcxBuiltinDriver.ts | 114 ++++++++++ apps/desktop/src/lib/imports/dbeaverImport.ts | 7 +- apps/desktop/src/lib/sql/sqlParameters.ts | 15 +- crates/dbx-core/src/models/connection.rs | 69 +++++- plugins/jdbc/README.md | 15 ++ .../main/java/app/dbx/jdbc/DbxJdbcPlugin.java | 76 ++++++- .../java/app/dbx/jdbc/DbxJdbcPluginTest.java | 82 +++++++ 24 files changed, 752 insertions(+), 16 deletions(-) create mode 100644 apps/desktop/public/icons/database/jdbcx.svg create mode 100644 apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts create mode 100644 apps/desktop/src/lib/__tests__/database/jdbcxBuiltinDriver.spec.ts create mode 100644 apps/desktop/src/lib/__tests__/imports/jdbcxImport.spec.ts create mode 100644 apps/desktop/src/lib/database/jdbcxBuiltinDriver.ts diff --git a/README.md b/README.md index 6887e15b3b..6792e61bee 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ ### 60+ Databases, One Tool -MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, and more. Agent/JDBC-oriented profiles extend DBX to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, and custom JDBC connections. New native and agent-driven drivers also cover Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and more. Message queue admin is also available for Pulsar, Kafka, and RocketMQ. All in a single ~20 MB app. No bundled Chromium. +MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, and more. Agent/JDBC-oriented profiles extend DBX to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, and custom JDBC connections. New native and agent-driven drivers also cover Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and more. Message queue admin is also available for Pulsar, Kafka, and RocketMQ. All in a single ~20 MB app. No bundled Chromium. ### Query Editor @@ -413,7 +413,7 @@ DBX is 20 MB with no runtime dependencies (no Java, no Python). It includes AI a
What databases are supported? -MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, and more. Agent/JDBC-oriented profiles extend support to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and custom JDBC connections. Message queue admin (Pulsar, Kafka, RocketMQ) is also supported. +MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, and more. Agent/JDBC-oriented profiles extend support to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and custom JDBC connections. Message queue admin (Pulsar, Kafka, RocketMQ) is also supported.
diff --git a/README.zh-CN.md b/README.zh-CN.md index c3f314e41b..6b7f549c5e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -91,7 +91,7 @@ ### 60+ 种数据库,一个工具搞定 -MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo 等数据库都能直接连接。Agent/JDBC 方向的配置还可扩展到 H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB 和自定义 JDBC。新增的原生与 Agent 驱动还覆盖了 Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、IRIS 等。全部装进约 20 MB 的应用里,不内嵌 Chromium。 +MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo 等数据库都能直接连接。Agent/JDBC 方向的配置还可扩展到 H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX 和自定义 JDBC。新增的原生与 Agent 驱动还覆盖了 Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、IRIS 等。全部装进约 20 MB 的应用里,不内嵌 Chromium。 ### 查询编辑器 @@ -413,7 +413,7 @@ DBX 仅 20 MB,无需运行时依赖(无需 Java、无需 Python)。AI 和
支持哪些数据库? -MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Qdrant、Milvus、Weaviate、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo 等。JDBC 方向配置可扩展到 H2、Snowflake、Trino、PrestoSQL、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase 8a/8s、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、ZooKeeper、Nacos、IRIS 及自定义 JDBC 连接,并支持消息队列管理(Pulsar、Kafka、RocketMQ)。 +MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Qdrant、Milvus、Weaviate、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo 等。JDBC 方向配置可扩展到 H2、Snowflake、Trino、PrestoSQL、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX、Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase 8a/8s、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、ZooKeeper、Nacos、IRIS 及自定义 JDBC 连接,并支持消息队列管理(Pulsar、Kafka、RocketMQ)。
diff --git a/apps/desktop/public/icons/database/jdbcx.svg b/apps/desktop/public/icons/database/jdbcx.svg new file mode 100644 index 0000000000..9bb01be83a --- /dev/null +++ b/apps/desktop/public/icons/database/jdbcx.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue index ec326aa00d..0315b4050d 100644 --- a/apps/desktop/src/App.vue +++ b/apps/desktop/src/App.vue @@ -88,6 +88,7 @@ import { isSchemaAware, isSingleDatabase, usesTreeSchemaMode } from "@/lib/datab import { codeMirrorSqlDialect, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect"; import { sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter"; import { detectDatabaseFileType } from "@/lib/database/databaseFileDetection"; +import { ensureJdbcxRuntimeDrivers } from "@/lib/database/jdbcxBuiltinDriver"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -118,6 +119,7 @@ const connectionStore = useConnectionStore(); const queryStore = useQueryStore(); const settingsStore = useSettingsStore(); const savedSqlStore = useSavedSqlStore(); +connectionStore.setBeforeConnectHandler((config) => ensureJdbcxRuntimeDrivers(config, api).then(() => undefined)); const { message: toastMessage, visible: toastVisible, toast } = useToast(); const { isDark, themeMode, applyTheme, setThemeMode } = useTheme(); const { checkingUpdates, updateInfo, updateCheckMessage, showUpdateDialog, isDownloadingUpdate, downloadProgress, updateReady, hasUpdateAvailable, openUrl, checkUpdates, openLatestRelease, downloadAndInstallUpdate, restartApp } = useAppUpdater(); diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue index a572df84ca..7d073a0380 100644 --- a/apps/desktop/src/components/connection/ConnectionDialog.vue +++ b/apps/desktop/src/components/connection/ConnectionDialog.vue @@ -41,6 +41,7 @@ import { copyToClipboard } from "@/lib/common/clipboard"; import { configuredDatabaseProductName, connectionConfigFingerprint, databaseInfoCopyText, databaseInfoRows, normalizeDatabaseConnectionInfo, type DatabaseInfoField } from "@/lib/connection/connectionDatabaseInfo"; import { agentDriverInstallKey, appendAgentDriverUpdateHint, hasAgentDriverUpdate, showAgentDriverInstallHint, type AgentDriverInstallState, type DriverStoreFocus } from "@/lib/connection/agentDriverInstallHint"; import { prestoSqlBuiltinDriverPaths } from "@/lib/database/prestoSqlBuiltinDriver"; +import { JDBCX_DEFAULT_URL, JDBCX_DRIVER_PROFILE, JDBCX_JDBC_DRIVER_CLASS, ensureJdbcxRuntimeDrivers, isJdbcxRuntimeBundle, isJdbcxRuntimePath, jdbcxHighPrivilegeExtensionsEnabled, setJdbcxHighPrivilegeExtensionsEnabled } from "@/lib/database/jdbcxBuiltinDriver"; import { SQLITE_DATABASE_FILE_EXTENSIONS } from "@/lib/database/databaseFileDetection"; import { connectionAttemptOriginalErrorMessage, connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "@/lib/connection/connectionAttemptTimeout"; import { appendConnectionErrorHints } from "@/lib/connection/connectionErrorHints"; @@ -100,6 +101,7 @@ type JdbcDriverSelectItem = { id: string; label: string; paths: string[]; + jdbcxRuntime: boolean; }; const DREMIO_ARROW_FLIGHT_SQL_JDBC_URL = "jdbc:arrow-flight-sql://127.0.0.1:32010"; @@ -548,11 +550,13 @@ const jdbcDriverSelectItems = computed(() => { id: `local:${bundle.id}`, label: bundle.name, paths: bundle.artifacts.map((artifact) => artifact.path), + jdbcxRuntime: bundle.artifacts.some((artifact) => isJdbcxRuntimePath(artifact.path)), })); const bundles = jdbcMavenBundles.value.map((bundle) => ({ id: `maven:${bundle.id}`, label: bundle.coordinate, paths: bundle.artifacts.map((artifact) => artifact.path), + jdbcxRuntime: isJdbcxRuntimeBundle(bundle), })); const manual = jdbcDrivers.value .filter((driver) => !driver.bundle_id) @@ -560,6 +564,7 @@ const jdbcDriverSelectItems = computed(() => { id: `manual:${driver.path}`, label: driver.name, paths: [driver.path], + jdbcxRuntime: isJdbcxRuntimePath(driver.path), })); return [...localBundles, ...bundles, ...manual].sort((left, right) => left.label.localeCompare(right.label)); }); @@ -723,6 +728,7 @@ const driverProfiles: Record< db2: { type: "db2", port: 50000, user: "db2inst1", label: "IBM DB2", icon: "db2" }, informix: { type: "informix", port: 9088, user: "informix", label: "Informix", icon: "informix" }, dremio: { type: "jdbc", port: 31010, user: "", label: "Dremio", icon: "dremio" }, + jdbcx: { type: "jdbc", port: 0, user: "", label: "JDBCX", icon: "jdbcx" }, neo4j: { type: "neo4j", port: 7687, user: "neo4j", label: "Neo4j", icon: "neo4j" }, cassandra: { type: "cassandra", port: 9042, user: "cassandra", label: "Cassandra", icon: "cassandra" }, bigquery: { @@ -1199,6 +1205,21 @@ async function ensureRequiredAgentDriverInstalled(config: ConnectionConfig): Pro } } +async function ensureRequiredJdbcxDriverInstalled(config: ConnectionConfig): Promise { + const result = await ensureJdbcxRuntimeDrivers(config, api, () => { + testResult.value = { ok: true, message: "Installing JDBC plugin..." }; + }); + if (!result) return; + + jdbcMavenBundles.value = result.bundles; + addJdbcDriverPaths(result.paths); + form.value.jdbc_driver_paths = [...(config.jdbc_driver_paths ?? [])]; + selectedJdbcDriverPath.value = result.runtimeSelectionId; + if (result.paths.length > 0) { + jdbcManualClasspathOpen.value = false; + } +} + async function installSqlServerLegacyCompatibilityComponentIfNeeded(): Promise { if (await api.isAgentInstalled(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY)) return true; @@ -1471,6 +1492,9 @@ function applyProfile(val: string, preserveConnectionFields = false) { if (val === "dremio") { resetDremioConnectionUrls(); applyDremioConnectionMode("legacy"); + } else if (val === JDBCX_DRIVER_PROFILE) { + form.value.connection_string = JDBCX_DEFAULT_URL; + form.value.jdbc_driver_class = JDBCX_JDBC_DRIVER_CLASS; } } if (profile.type === "prestosql") { @@ -1838,6 +1862,7 @@ const iconTypeMap: Record = { db2: "db2", informix: "informix", dremio: "dremio", + jdbcx: "jdbcx", iris: "iris", neo4j: "neo4j", cassandra: "cassandra", @@ -1923,6 +1948,7 @@ const dbOptions: DbOption[] = [ { value: "nacos", label: "Nacos" }, { value: "influxdb", label: "InfluxDB" }, { value: "iris", label: "IRIS" }, + { value: "jdbcx", label: "JDBCX" }, { value: "manticoresearch", label: "Manticore Search" }, { value: "custom_mysql", label: "Custom (MySQL)" }, { value: "custom_postgres", label: "Custom (PostgreSQL)" }, @@ -1956,6 +1982,14 @@ const hasDbPickerResults = computed(() => filteredDbCategories.value.some((categ const selectedDbIcon = computed(() => iconTypeMap[selectedType.value] || selectedProfile().icon || selectedType.value); const jdbcBackedDatabaseTypes = new Set(["jdbc", "prestosql"]); const isJdbcConnection = computed(() => form.value.db_type === "jdbc"); +const isJdbcxConnection = computed(() => isJdbcConnection.value && form.value.driver_profile === JDBCX_DRIVER_PROFILE); +const jdbcxHighPrivilegeExtensionsAllowed = computed({ + get: () => jdbcxHighPrivilegeExtensionsEnabled(form.value), + set: (enabled: boolean) => { + setJdbcxHighPrivilegeExtensionsEnabled(form.value, enabled); + resetTestState(); + }, +}); const isPrestoSqlConnection = computed(() => form.value.db_type === "prestosql"); const isH2FileMode = computed(() => form.value.db_type === "h2" && h2ConnectionMode.value === "file"); const usesLocalFilePathInput = computed(() => isLocalFileTypeDb(form.value.db_type) && (form.value.db_type !== "h2" || isH2FileMode.value)); @@ -2318,6 +2352,7 @@ async function testConnection() { try { config = connectionConfigForSubmit(editingId.value || draftTestConnectionId.value); await ensureRequiredAgentDriverInstalled(config); + await ensureRequiredJdbcxDriverInstalled(config); const result = await testConnectionWithTimeout(config, runId); if (runId !== testRunId) return; let successfulConfig = config; @@ -2549,7 +2584,7 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo }); config.url_params = hiveKerberos.urlParams; config.agent_java_options = hiveKerberos.agentJavaOptions; - } else { + } else if (!(config.db_type === "jdbc" && config.driver_profile === JDBCX_DRIVER_PROFILE)) { config.agent_java_options = undefined; } if (config.db_type === "informix" && config.informix_server) { @@ -2712,6 +2747,11 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo if (config.db_type === "jdbc") { if (config.driver_profile === "dremio") { applyDremioJdbcMetadata(config); + } else if (config.driver_profile === JDBCX_DRIVER_PROFILE) { + config.host = ""; + config.port = 0; + config.connection_string = config.connection_string?.trim() || JDBCX_DEFAULT_URL; + config.jdbc_driver_class = config.jdbc_driver_class?.trim() || JDBCX_JDBC_DRIVER_CLASS; } else { config.host = ""; config.port = 0; @@ -3980,7 +4020,16 @@ function onJdbcDriverSelect(id: any) { const item = jdbcDriverSelectItemById.value.get(id); if (!item) return; selectedJdbcDriverPath.value = id; - addJdbcDriverPaths(item.paths); + if (isJdbcxConnection.value && item.jdbcxRuntime) { + const installedJdbcxRuntimePaths = new Set(jdbcDriverSelectItems.value.filter((candidate) => candidate.jdbcxRuntime).flatMap((candidate) => candidate.paths)); + const existingPaths = jdbcDriverPathsInput.value + .split(/\r?\n/) + .map((path) => path.trim()) + .filter((path) => path && !installedJdbcxRuntimePaths.has(path)); + jdbcDriverPathsInput.value = Array.from(new Set([...existingPaths, ...item.paths])).join("\n"); + } else { + addJdbcDriverPaths(item.paths); + } jdbcManualClasspathOpen.value = false; } @@ -4257,6 +4306,16 @@ function openExternalUrl(url: string) { +
+ +
+
+
{{ t("connection.jdbcxHighPrivilegeExtensions") }}
+

{{ t("connection.jdbcxHighPrivilegeExtensionsWarning") }}

+
+ +
+
diff --git a/apps/desktop/src/components/icons/DatabaseIcon.vue b/apps/desktop/src/components/icons/DatabaseIcon.vue index b99cab5ddd..4de8ccabb6 100644 --- a/apps/desktop/src/components/icons/DatabaseIcon.vue +++ b/apps/desktop/src/components/icons/DatabaseIcon.vue @@ -92,6 +92,7 @@ const assetIcons: Record = { iris: "iris.png", influxdb: "influxdb", zookeeper: "zookeeper", + jdbcx: "jdbcx", }; const letterIcons: Record = { diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 9367196c62..b49712c68e 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -513,6 +513,9 @@ export default { jdbcDriverBrowse: "Choose JDBC driver JAR", jdbcDocs: "View JDBC docs", jdbcPluginHint: "Install the DBX JDBC plugin first, then import the database vendor's JDBC driver JAR.", + jdbcxExtensions: "JDBCX extensions", + jdbcxHighPrivilegeExtensions: "Allow high-privilege extensions", + jdbcxHighPrivilegeExtensionsWarning: "Disabled by default. Enabling allows Shell, Script, Web, MCP, and other extensions to execute local commands or access the network.", dmCompatHint: "Requires DM8 ODBC driver installed on your system.", dmDownload: "Download from Dameng", mongoLegacyHint: "Use Legacy for older MongoDB servers, especially versions below 4.2. If authentication fails and the user was created in admin, set Auth DB to admin.", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index be7578e315..a2690fe2f1 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -418,6 +418,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "Seleccionar JAR del driver JDBC", jdbcDocs: "Ver documentación JDBC", jdbcPluginHint: "Instala primero el plugin JDBC de DBX y luego importa el JAR del driver JDBC del proveedor.", + jdbcxExtensions: "Extensiones JDBCX", + jdbcxHighPrivilegeExtensions: "Permitir extensiones con privilegios elevados", + jdbcxHighPrivilegeExtensionsWarning: "Desactivado de forma predeterminada. Al activarlo, Shell, Script, Web, MCP y otras extensiones pueden ejecutar comandos locales o acceder a la red.", dmCompatHint: "Requiere el driver ODBC DM8 instalado en el sistema.", dmDownload: "Descargar desde Dameng", mongoLegacyHint: "Usa Legacy para servidores MongoDB antiguos, especialmente versiones anteriores a 4.2. Si falla la autenticación y el usuario se creó en admin, define Auth DB como admin.", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 98fe931d3b..35d9ca4c00 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -416,6 +416,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "Scegli file JAR del driver JDBC", jdbcDocs: "Visualizza documentazione JDBC", jdbcPluginHint: "Installa prima il plugin DBX JDBC, quindi importa il file JAR del driver JDBC del fornitore del database.", + jdbcxExtensions: "Estensioni JDBCX", + jdbcxHighPrivilegeExtensions: "Consenti estensioni con privilegi elevati", + jdbcxHighPrivilegeExtensionsWarning: "Disabilitato per impostazione predefinita. Se abilitato, Shell, Script, Web, MCP e altre estensioni possono eseguire comandi locali o accedere alla rete.", dmCompatHint: "Richiede il driver ODBC DM8 installato sul sistema.", dmDownload: "Scarica da Dameng", mongoLegacyHint: "Usa Legacy per server MongoDB meno recenti, specialmente versioni precedenti alla 4.2. Se l'autenticazione fallisce e l'utente è stato creato in admin, imposta DB di Autenticazione su admin.", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 7851868f38..0566b11b60 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -410,6 +410,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "JDBCドライバーJARを選択", jdbcDocs: "JDBCドキュメントを見る", jdbcPluginHint: "最初にDBX JDBCプラグインをインストールし、次にデータベースベンダーのJDBCドライバーJARをインポートしてください。", + jdbcxExtensions: "JDBCX 拡張機能", + jdbcxHighPrivilegeExtensions: "高権限の拡張機能を許可", + jdbcxHighPrivilegeExtensionsWarning: "既定では無効です。有効にすると、Shell、Script、Web、MCP などの拡張機能がローカルコマンドを実行したりネットワークへアクセスしたりできます。", dmCompatHint: "システムにDM8 ODBCドライバーがインストールされている必要があります。", dmDownload: "達夢からダウンロード", mongoLegacyHint: "古いMongoDBサーバー(特に4.2未満)ではレガシーを使用してください。認証に失敗しユーザーがadminで作成された場合は、認証DBをadminに設定してください。", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 145dd8aae7..9defe82a83 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -417,6 +417,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "Escolher JAR do driver JDBC", jdbcDocs: "Ver documentação JDBC", jdbcPluginHint: "Instale primeiro o plugin JDBC do DBX e depois importe o JAR do driver JDBC do fornecedor do banco de dados.", + jdbcxExtensions: "Extensões JDBCX", + jdbcxHighPrivilegeExtensions: "Permitir extensões com privilégios elevados", + jdbcxHighPrivilegeExtensionsWarning: "Desativado por padrão. Ao ativar, Shell, Script, Web, MCP e outras extensões podem executar comandos locais ou acessar a rede.", dmCompatHint: "Requer o driver ODBC DM8 instalado no seu sistema.", dmDownload: "Baixar da Dameng", mongoLegacyHint: "Use Legacy para servidores MongoDB antigos, especialmente versões anteriores à 4.2. Se a autenticação falhar e o usuário foi criado em admin, defina o BD de autenticação como admin.", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 2af3a3490e..2bcdc17af2 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -517,6 +517,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "选择 JDBC 驱动 JAR", jdbcDocs: "查看 JDBC 文档", jdbcPluginHint: "先安装 DBX JDBC 插件,再导入数据库厂商提供的 JDBC 驱动 JAR。", + jdbcxExtensions: "JDBCX 扩展", + jdbcxHighPrivilegeExtensions: "允许高权限扩展", + jdbcxHighPrivilegeExtensionsWarning: "默认禁用。开启后,Shell、Script、Web、MCP 等扩展可以执行本机命令或访问网络。", dmCompatHint: "需要在系统上安装达梦 DM8 ODBC 驱动程序。", dmDownload: "前往达梦官网下载", mongoLegacyHint: "旧版 MongoDB(尤其是 4.2 以下版本)请选择旧版兼容。若账号创建在 admin 且认证失败,请将认证库设为 admin。", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 0a5288039c..5984ad8909 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -417,6 +417,9 @@ export default withEnglishFallback({ jdbcDriverBrowse: "選擇 JDBC 驅動程式 JAR", jdbcDocs: "檢視 JDBC 文件", jdbcPluginHint: "先安裝 DBX JDBC 外掛程式,再匯入資料庫廠商提供的 JDBC 驅動程式 JAR。", + jdbcxExtensions: "JDBCX 擴充功能", + jdbcxHighPrivilegeExtensions: "允許高權限擴充功能", + jdbcxHighPrivilegeExtensionsWarning: "預設停用。啟用後,Shell、Script、Web、MCP 等擴充功能可以執行本機命令或存取網路。", dmCompatHint: "需要在系統上安裝達夢 DM8 ODBC 驅動程式。", dmDownload: "前往達夢官網下載", mongoLegacyHint: "舊版 MongoDB(尤其是 4.2 以下版本)請選擇舊版相容。若帳號建立在 admin 且認證失敗,請將認證庫設為 admin。", diff --git a/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts new file mode 100644 index 0000000000..371bfab2d9 --- /dev/null +++ b/apps/desktop/src/lib/__tests__/connection/jdbcxConnectionDialog.spec.ts @@ -0,0 +1,27 @@ +import { readFileSync } from "node:fs"; +import { parse } from "vue/compiler-sfc"; +import ts from "typescript"; +import { describe, expect, it } from "vitest"; + +const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8"); +const parsedDialog = parse(dialogSource, { filename: "ConnectionDialog.vue" }); + +function findFunction(name: string): ts.FunctionDeclaration { + const script = parsedDialog.descriptor.scriptSetup; + expect(parsedDialog.errors).toEqual([]); + expect(script).toBeDefined(); + + const source = ts.createSourceFile("ConnectionDialog.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name); + expect(declaration).toBeDefined(); + return declaration!; +} + +describe("JDBCX connection dialog", () => { + it("preserves the connection-level high-privilege extension opt-in on submit", () => { + const submitConfig = findFunction("connectionConfigForSubmit").getText(); + + expect(submitConfig).toContain('config.db_type === "jdbc" && config.driver_profile === JDBCX_DRIVER_PROFILE'); + expect(submitConfig).toContain("config.agent_java_options = undefined"); + }); +}); diff --git a/apps/desktop/src/lib/__tests__/database/jdbcxBuiltinDriver.spec.ts b/apps/desktop/src/lib/__tests__/database/jdbcxBuiltinDriver.spec.ts new file mode 100644 index 0000000000..abafec98dc --- /dev/null +++ b/apps/desktop/src/lib/__tests__/database/jdbcxBuiltinDriver.spec.ts @@ -0,0 +1,201 @@ +import { describe, expect, it, vi } from "vitest"; +import { JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION, ensureJdbcxRuntimeDrivers, isJdbcxRuntimePath, jdbcxHighPrivilegeExtensionsEnabled, setJdbcxHighPrivilegeExtensionsEnabled } from "@/lib/database/jdbcxBuiltinDriver"; +import type { ConnectionConfig, JdbcMavenBundleInfo } from "@/types/database"; + +function jdbcxConfig(): ConnectionConfig { + return { + id: "jdbcx-1", + name: "JDBCX database", + db_type: "jdbc", + driver_profile: "jdbcx", + driver_label: "JDBCX", + host: "", + port: 0, + username: "root", + password: "", + connection_string: "jdbcx:prql:vendor://127.0.0.1:1234/test", + jdbc_driver_paths: [], + }; +} + +function runtimeApi(paths: string[], bundles: JdbcMavenBundleInfo[] = []) { + return { + listJdbcMavenBundles: async () => bundles, + listJdbcDrivers: async () => paths.map((path) => ({ name: path.split("/").at(-1) ?? path, path, size: 1 })), + jdbcPluginStatus: async () => ({ installed: true, compatible: true }), + installJdbcPlugin: vi.fn(async () => undefined), + }; +} + +describe("jdbcxBuiltinDriver", () => { + it("requires an explicit opt-in for high-privilege JDBCX extensions", () => { + const config = jdbcxConfig(); + + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(false); + setJdbcxHighPrivilegeExtensionsEnabled(config, true); + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(true); + setJdbcxHighPrivilegeExtensionsEnabled(config, false); + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(false); + }); + + it("canonicalizes whitespace-padded legacy opt-ins across edit round trips", () => { + const config = jdbcxConfig(); + config.agent_java_options = [" -Ddbx.jdbcx.allowHighPrivilegeExtensions=false ", "-Xmx512m", "\t-Ddbx.jdbcx.allowHighPrivilegeExtensions=true\t"]; + + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(true); + + setJdbcxHighPrivilegeExtensionsEnabled(config, true); + expect(config.agent_java_options).toEqual(["-Xmx512m", JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION]); + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(true); + + setJdbcxHighPrivilegeExtensionsEnabled(config, false); + expect(config.agent_java_options).toEqual(["-Xmx512m"]); + expect(jdbcxHighPrivilegeExtensionsEnabled(config)).toBe(false); + }); + + it("recognizes user-installed JDBCX runtime JARs", () => { + expect(isJdbcxRuntimePath("/drivers/jdbcx-driver-0.8.0.jar")).toBe(true); + expect(isJdbcxRuntimePath("C:\\drivers\\jdbcx-core-0.8.0.jar")).toBe(false); + expect(isJdbcxRuntimePath("/drivers/postgresql-42.7.7.jar")).toBe(false); + }); + + it("uses the connection-selected JDBCX runtime without unrelated driver JARs", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/postgresql-42.7.7.jar", "/drivers/jdbcx-driver-0.8.0.jar"]; + const result = await ensureJdbcxRuntimeDrivers(config, runtimeApi(["/drivers/jdbcx-driver-0.8.0.jar", "/drivers/acme-proprietary-driver.jar"])); + + expect(result?.paths).toEqual(["/drivers/postgresql-42.7.7.jar", "/drivers/jdbcx-driver-0.8.0.jar"]); + expect(config.jdbc_driver_paths).toEqual(result?.paths); + }); + + it("honors a connection-selected JDBCX runtime outside the driver store", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/opt/jdbc/mysql-connector.jar", "/opt/jdbc/jdbcx-driver-0.8.0.jar"]; + + const result = await ensureJdbcxRuntimeDrivers(config, runtimeApi([])); + + expect(result?.runtimeSelectionId).toBe("manual:/opt/jdbc/jdbcx-driver-0.8.0.jar"); + expect(result?.paths).toEqual(config.jdbc_driver_paths); + }); + + it("adds the complete installed JDBCX Maven bundle to the selected vendor classpath", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/mysql-connector-j-9.2.0.jar", "/drivers/jdbcx-driver-0.8.0.jar"]; + const bundle: JdbcMavenBundleInfo = { + id: "jdbcx-0.8.0", + coordinate: "io.github.jdbcx:jdbcx-driver:0.8.0", + scope: "runtime", + repositories: ["https://repo.maven.apache.org/maven2/"], + installed_at: "2026-07-15T00:00:00Z", + path: "/drivers/jdbcx", + artifacts: [ + { + group_id: "io.github.jdbcx", + artifact_id: "jdbcx-driver", + version: "0.8.0", + classifier: "", + extension: "jar", + file_name: "jdbcx-driver-0.8.0.jar", + path: "/drivers/jdbcx-driver-0.8.0.jar", + size: 1, + sha256: "abc", + }, + ], + }; + + const result = await ensureJdbcxRuntimeDrivers(config, runtimeApi([], [bundle])); + + expect(result?.paths).toEqual(["/drivers/mysql-connector-j-9.2.0.jar", "/drivers/jdbcx-driver-0.8.0.jar"]); + }); + + it("keeps only the JDBCX runtime bundle explicitly selected by the connection", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/mysql-connector-j-9.2.0.jar", "/drivers/jdbcx-0.9.0/jdbcx-driver-0.9.0.jar"]; + const bundle = (version: string): JdbcMavenBundleInfo => ({ + id: `jdbcx-${version}`, + coordinate: `io.github.jdbcx:jdbcx-driver:${version}`, + scope: "runtime", + repositories: [], + installed_at: "2026-07-15T00:00:00Z", + path: `/drivers/jdbcx-${version}`, + artifacts: [ + { + group_id: "io.github.jdbcx", + artifact_id: "jdbcx-driver", + version, + classifier: "", + extension: "jar", + file_name: `jdbcx-driver-${version}.jar`, + path: `/drivers/jdbcx-${version}/jdbcx-driver-${version}.jar`, + size: 1, + sha256: version, + }, + { + group_id: "org.example", + artifact_id: "runtime-dependency", + version, + classifier: "", + extension: "jar", + file_name: `runtime-dependency-${version}.jar`, + path: `/drivers/jdbcx-${version}/runtime-dependency-${version}.jar`, + size: 1, + sha256: `dependency-${version}`, + }, + ], + }); + + const result = await ensureJdbcxRuntimeDrivers(config, runtimeApi([], [bundle("0.8.0"), bundle("0.9.0")])); + + expect(result?.runtimeSelectionId).toBe("maven:jdbcx-0.9.0"); + expect(result?.paths).toEqual(["/drivers/mysql-connector-j-9.2.0.jar", "/drivers/jdbcx-0.9.0/jdbcx-driver-0.9.0.jar", "/drivers/jdbcx-0.9.0/runtime-dependency-0.9.0.jar"]); + expect(result?.paths.some((path) => path.includes("0.8.0"))).toBe(false); + }); + + it("rejects ambiguous installed JDBCX runtimes until the connection selects one", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/mysql-connector-j-9.2.0.jar"]; + const bundles = ["0.8.0", "0.9.0"].map( + (version): JdbcMavenBundleInfo => ({ + id: `jdbcx-${version}`, + coordinate: `io.github.jdbcx:jdbcx-driver:${version}`, + scope: "runtime", + repositories: [], + installed_at: "2026-07-15T00:00:00Z", + path: `/drivers/jdbcx-${version}`, + artifacts: [ + { + group_id: "io.github.jdbcx", + artifact_id: "jdbcx-driver", + version, + classifier: "", + extension: "jar", + file_name: `jdbcx-driver-${version}.jar`, + path: `/drivers/jdbcx-${version}/jdbcx-driver-${version}.jar`, + size: 1, + sha256: version, + }, + ], + }), + ); + + await expect(ensureJdbcxRuntimeDrivers(config, runtimeApi([], bundles))).rejects.toThrow("Select exactly one JDBCX bundle/runtime"); + }); + + it("requires an explicit connection selection when only one JDBCX runtime is installed", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/mysql-connector-j-9.2.0.jar"]; + + await expect(ensureJdbcxRuntimeDrivers(config, runtimeApi(["/drivers/jdbcx-driver-0.8.0.jar"]))).rejects.toThrow("installed but not selected"); + }); + + it("rejects connections that select more than one JDBCX runtime", async () => { + const config = jdbcxConfig(); + config.jdbc_driver_paths = ["/drivers/jdbcx-driver-0.8.0.jar", "/drivers/jdbcx-driver-0.9.0.jar"]; + + await expect(ensureJdbcxRuntimeDrivers(config, runtimeApi(config.jdbc_driver_paths))).rejects.toThrow("Keep exactly one JDBCX bundle/runtime"); + }); + + it("asks the user to install JDBCX when its runtime is missing", async () => { + await expect(ensureJdbcxRuntimeDrivers(jdbcxConfig(), runtimeApi(["/drivers/mysql-connector-j-9.2.0.jar"]))).rejects.toThrow("Install io.github.jdbcx:jdbcx-driver: in Driver Store"); + }); +}); diff --git a/apps/desktop/src/lib/__tests__/imports/jdbcxImport.spec.ts b/apps/desktop/src/lib/__tests__/imports/jdbcxImport.spec.ts new file mode 100644 index 0000000000..b82a7b099c --- /dev/null +++ b/apps/desktop/src/lib/__tests__/imports/jdbcxImport.spec.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { JDBCX_JDBC_DRIVER_CLASS } from "@/lib/database/jdbcxBuiltinDriver"; +import { parseDbeaverConnections } from "@/lib/imports/dbeaverImport"; + +describe("JDBCX connection import", () => { + it("imports JDBCX connections with the JDBCX profile", async () => { + const dataSources = JSON.stringify({ + connections: { + "jdbcx-1": { + id: "jdbcx-1", + name: "federated-query", + provider: "generic", + driver: "jdbcx", + configuration: { + url: "jdbcx:script:mysql://db.example.com:3306/app", + user: "analyst", + }, + }, + }, + }); + const payload = JSON.stringify({ format: "dbeaver-import", dataSources }); + + const [connection] = await parseDbeaverConnections(payload); + + expect(connection?.db_type).toBe("jdbc"); + expect(connection?.driver_profile).toBe("jdbcx"); + expect(connection?.driver_label).toBe("JDBCX"); + expect(connection?.connection_string).toBe("jdbcx:script:mysql://db.example.com:3306/app"); + expect(connection?.jdbc_driver_class).toBe(JDBCX_JDBC_DRIVER_CLASS); + }); + + it("prioritizes the jdbcx URL scheme for custom driver IDs", async () => { + const dataSources = JSON.stringify({ + connections: { + "jdbcx-custom": { + id: "jdbcx-custom", + name: "custom-jdbcx", + provider: "generic", + driver: "custom-mysql-wrapper", + configuration: { + url: "jdbcx:mysql://db.example.com:3306/app", + }, + }, + }, + }); + + const [connection] = await parseDbeaverConnections(JSON.stringify({ format: "dbeaver-import", dataSources })); + + expect(connection?.db_type).toBe("jdbc"); + expect(connection?.driver_profile).toBe("jdbcx"); + expect(connection?.driver_label).toBe("JDBCX"); + expect(connection?.jdbc_driver_class).toBe(JDBCX_JDBC_DRIVER_CLASS); + }); +}); diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts index 9ce3cadc35..eb708e3d42 100644 --- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts +++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts @@ -31,6 +31,16 @@ describe("extractSqlParameters", () => { expect(extractSqlParameters(sql)).toEqual(["?1", "named", "shell_name", "mybatis_name", "sql_server_name"]); }); + it("ignores npm scoped packages in JDBCX MCP command arguments", () => { + const sql = '{{ mcp(cmd=npx, args=-y @modelcontextprotocol/server-everything, tool=echo): {"message":"hello"} }}'; + expect(extractSqlParameters(sql)).toEqual([]); + expect(substituteSqlParameters(sql, {})).toBe(sql); + }); + + it("keeps SQL Server parameters used in division expressions", () => { + expect(extractSqlParameters("select @amount/2, @total / 4")).toEqual(["amount", "total"]); + }); + it("describes each placeholder syntax for the parameter dialog", () => { const sql = "select ? as a, :named as b, ${shell_name} as c, #{mybatis_name} as d, @sql_server_name as e"; expect(extractSqlParameterDescriptors(sql)).toEqual([ diff --git a/apps/desktop/src/lib/database/jdbcxBuiltinDriver.ts b/apps/desktop/src/lib/database/jdbcxBuiltinDriver.ts new file mode 100644 index 0000000000..fba22a0283 --- /dev/null +++ b/apps/desktop/src/lib/database/jdbcxBuiltinDriver.ts @@ -0,0 +1,114 @@ +import type { ConnectionConfig, JdbcDriverInfo, JdbcMavenBundleInfo } from "@/types/database"; + +export const JDBCX_DRIVER_PROFILE = "jdbcx"; +export const JDBCX_JDBC_DRIVER_CLASS = "io.github.jdbcx.WrappedDriver"; +export const JDBCX_DEFAULT_URL = "jdbcx:"; +export const JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION = "-Ddbx.jdbcx.allowHighPrivilegeExtensions=true"; +const JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION_PREFIX = "-Ddbx.jdbcx.allowHighPrivilegeExtensions="; + +export type JdbcxRuntimeDriverApi = { + listJdbcDrivers: () => Promise; + listJdbcMavenBundles: () => Promise; + jdbcPluginStatus: () => Promise<{ installed: boolean; compatible: boolean }>; + installJdbcPlugin: () => Promise; +}; + +export type JdbcxRuntimeDriverResult = { + bundles: JdbcMavenBundleInfo[]; + paths: string[]; + runtimeSelectionId: string; +}; + +type JdbcxRuntimeCandidate = { + id: string; + paths: string[]; + runtimePaths: string[]; +}; + +export function isJdbcxRuntimePath(path: string): boolean { + return /(?:^|[/\\])jdbcx-driver(?:-|\.)/i.test(path); +} + +export function isJdbcxRuntimeBundle(bundle: JdbcMavenBundleInfo): boolean { + const [groupId, artifactId] = bundle.coordinate.split(":"); + return groupId === "io.github.jdbcx" && artifactId === "jdbcx-driver"; +} + +export function jdbcxHighPrivilegeExtensionsEnabled(config: Pick): boolean { + const option = [...(config.agent_java_options ?? [])] + .reverse() + .map((value) => value.trim()) + .find((value) => value.startsWith(JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION_PREFIX)); + return option?.slice(option.indexOf("=") + 1).toLowerCase() === "true"; +} + +export function setJdbcxHighPrivilegeExtensionsEnabled(config: Pick, enabled: boolean): void { + // Canonicalize this DBX-owned option so legacy whitespace cannot diverge from backend parsing. + const options = (config.agent_java_options ?? []).filter((option) => !option.trim().startsWith(JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION_PREFIX)); + config.agent_java_options = enabled ? [...options, JDBCX_HIGH_PRIVILEGE_EXTENSIONS_JAVA_OPTION] : options; +} + +function runtimeCandidates(bundles: JdbcMavenBundleInfo[], installedDrivers: JdbcDriverInfo[], configuredPaths: string[]): JdbcxRuntimeCandidate[] { + const bundleCandidates = bundles.filter(isJdbcxRuntimeBundle).map((bundle) => { + const paths = bundle.artifacts.map((artifact) => artifact.path).filter(Boolean); + return { + id: `maven:${bundle.id}`, + paths, + runtimePaths: paths.filter(isJdbcxRuntimePath), + }; + }); + const mavenBundleIds = new Set(bundles.map((bundle) => bundle.id)); + const installedBundlePaths = new Map(); + for (const driver of installedDrivers) { + if (!driver.bundle_id || mavenBundleIds.has(driver.bundle_id)) continue; + installedBundlePaths.set(driver.bundle_id, [...(installedBundlePaths.get(driver.bundle_id) ?? []), driver.path]); + } + const localBundleCandidates = [...installedBundlePaths].map(([bundleId, paths]) => ({ + id: `local:${bundleId}`, + paths, + runtimePaths: paths.filter(isJdbcxRuntimePath), + })); + const standaloneCandidates = installedDrivers.filter((driver) => !driver.bundle_id && isJdbcxRuntimePath(driver.path)).map((driver) => ({ id: `manual:${driver.path}`, paths: [driver.path], runtimePaths: [driver.path] })); + const knownRuntimePaths = new Set([...bundleCandidates, ...localBundleCandidates, ...standaloneCandidates].flatMap((candidate) => candidate.runtimePaths)); + const configuredCandidates = configuredPaths.filter((path) => isJdbcxRuntimePath(path) && !knownRuntimePaths.has(path)).map((path) => ({ id: `manual:${path}`, paths: [path], runtimePaths: [path] })); + return [...bundleCandidates, ...localBundleCandidates, ...standaloneCandidates, ...configuredCandidates].filter((candidate) => candidate.runtimePaths.length > 0); +} + +function selectRuntimeCandidate(candidates: JdbcxRuntimeCandidate[], configuredPaths: string[]): JdbcxRuntimeCandidate { + const configured = new Set(configuredPaths); + const selected = candidates.filter((candidate) => candidate.runtimePaths.some((path) => configured.has(path))); + if (selected.length > 1) { + throw new Error("Multiple JDBCX runtimes are selected. Keep exactly one JDBCX bundle/runtime in Driver JARs, then retry."); + } + if (selected.length === 1) return selected[0]; + if (candidates.length > 0) { + throw new Error("JDBCX runtime is installed but not selected. Select exactly one JDBCX bundle/runtime in Driver JARs, then retry."); + } + throw new Error("JDBCX runtime is not installed. Install io.github.jdbcx:jdbcx-driver: in Driver Store, then retry."); +} + +export async function ensureJdbcxRuntimeDrivers(config: ConnectionConfig, api: JdbcxRuntimeDriverApi, onInstalling?: (coordinates: string[]) => void): Promise { + if (config.db_type !== "jdbc" || config.driver_profile !== JDBCX_DRIVER_PROFILE) return undefined; + + config.connection_string = config.connection_string?.trim() || JDBCX_DEFAULT_URL; + config.jdbc_driver_class = config.jdbc_driver_class?.trim() || JDBCX_JDBC_DRIVER_CLASS; + const configuredPaths = (config.jdbc_driver_paths ?? []).map((path) => path.trim()).filter(Boolean); + const pluginStatus = await api.jdbcPluginStatus(); + if (!pluginStatus.installed || !pluginStatus.compatible) { + onInstalling?.([]); + await api.installJdbcPlugin(); + } + + const [bundles, installedDrivers] = await Promise.all([api.listJdbcMavenBundles(), api.listJdbcDrivers()]); + const candidates = runtimeCandidates(bundles, installedDrivers, configuredPaths); + const selectedRuntime = selectRuntimeCandidate(candidates, configuredPaths); + const installedRuntimeArtifacts = new Set(candidates.flatMap((candidate) => candidate.paths)); + const selectedDriverPaths = configuredPaths.filter((path) => !installedRuntimeArtifacts.has(path)); + const paths = Array.from(new Set([...selectedDriverPaths, ...selectedRuntime.paths])); + + // JDBCX discovers the delegate driver through JDBC ServiceLoader/Driver.acceptsURL. + // Keep the classpath scoped to the connection-selected vendor driver and the + // JDBCX runtime so unrelated driver dependencies cannot conflict. + config.jdbc_driver_paths = paths; + return { bundles, paths, runtimeSelectionId: selectedRuntime.id }; +} diff --git a/apps/desktop/src/lib/imports/dbeaverImport.ts b/apps/desktop/src/lib/imports/dbeaverImport.ts index a66d0ac80f..923ad17965 100644 --- a/apps/desktop/src/lib/imports/dbeaverImport.ts +++ b/apps/desktop/src/lib/imports/dbeaverImport.ts @@ -1,5 +1,6 @@ import type { ConnectionConfig, DatabaseType } from "@/types/database"; import { uuid } from "@/lib/common/utils"; +import { JDBCX_JDBC_DRIVER_CLASS } from "@/lib/database/jdbcxBuiltinDriver"; type PartialConnection = Omit; @@ -52,6 +53,7 @@ const profileMap: Record = { opengauss: { dbType: "gaussdb", profile: "opengauss", label: "openGauss", port: 5432, user: "gaussdb" }, questdb: { dbType: "questdb", profile: "questdb", label: "QuestDB", port: 8812, user: "questdb" }, influxdb: { dbType: "influxdb", profile: "influxdb", label: "InfluxDB", port: 8086, user: "" }, + jdbcx: { dbType: "jdbc", profile: "jdbcx", label: "JDBCX", port: 0, user: "" }, }; function normalizeKey(value: unknown) { @@ -70,6 +72,9 @@ function getNumber(value: unknown) { } function inferProfile(entry: DbeaverConnectionEntry): ConnectionProfile { + if (/^jdbcx:/i.test(getString(entry.configuration?.url))) return profileMap.jdbcx; + const driverProfile = profileMap[normalizeKey(entry.driver)]; + if (driverProfile) return driverProfile; const candidates = [entry.provider, entry.driver, entry.configuration?.url, entry.name].map(normalizeKey).join(" "); for (const [needle, profile] of Object.entries(profileMap)) { if (candidates.includes(needle)) return profile; @@ -218,7 +223,7 @@ function buildConnection(entry: DbeaverConnectionEntry, credentials: ReturnType< ssl: false, oracle_connection_type: profile.dbType === "oracle" ? parsedUrl.oracleConnectionType || "service_name" : undefined, connection_string: profile.dbType === "jdbc" || profile.dbType === "mongodb" ? url || undefined : undefined, - jdbc_driver_class: profile.dbType === "jdbc" ? getString(config["driver-class"] || entry.driver) || undefined : undefined, + jdbc_driver_class: profile.dbType === "jdbc" ? getString(config["driver-class"] || (profile.profile === "jdbcx" ? JDBCX_JDBC_DRIVER_CLASS : entry.driver)) || undefined : undefined, jdbc_driver_paths: [], }; diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts index cf94fc0830..bafa3ca827 100644 --- a/apps/desktop/src/lib/sql/sqlParameters.ts +++ b/apps/desktop/src/lib/sql/sqlParameters.ts @@ -167,7 +167,7 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions) } if (ch === "@" && isSyntaxEnabled("sqlserver")) { const name = readParameterName(sql, i + 1); - if (name && next !== "@" && sql[i - 1] !== "@" && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) { + if (name && next !== "@" && sql[i - 1] !== "@" && !isJdbcxMcpScopedPackage(sql, i, i + 1 + name.length) && !nativeSqlServerParameters.declared.has(name.toLowerCase()) && !nativeSqlServerParameters.ignoredStarts.has(i)) { occurrences.push({ key: name, name, @@ -194,6 +194,19 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions) return occurrences; } +// JDBCX MCP commands accept npm scoped packages in their unquoted args value, +// for example `args=-y @modelcontextprotocol/server-everything`. The `@scope` +// prefix is command data, not a SQL Server-style template parameter. +function isJdbcxMcpScopedPackage(sql: string, start: number, nameEnd: number): boolean { + if (sql[nameEnd] !== "/" || !/[\p{L}\p{N}_.-]/u.test(sql[nameEnd + 1] ?? "")) return false; + + const blockStart = sql.lastIndexOf("{{", start); + if (blockStart === -1 || sql.lastIndexOf("}}", start) > blockStart) return false; + + const extensionPrefix = sql.slice(blockStart + 2, start); + return /^\s*mcp\s*\(/i.test(extensionPrefix) && /(?:^|[,\s])args\s*=[^,]*$/i.test(extensionPrefix); +} + // Doris-style complex types use colons between field names and types; those are not bind parameters. function collectComplexTypeFieldSeparators(sql: string): Set { const separators = new Set(); diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs index 0d539c4d4c..423d08108b 100644 --- a/crates/dbx-core/src/models/connection.rs +++ b/crates/dbx-core/src/models/connection.rs @@ -1861,7 +1861,7 @@ fn rewrite_mongo_uri_host(uri: &str, new_host: &str, new_port: u16) -> String { } pub fn parse_jdbc_host_port(url: &str) -> Option<(String, u16)> { - let rest = url.strip_prefix("jdbc:")?; + let rest = jdbc_transport_rest(url)?; // jdbc:oracle:thin:@host:port:SID or jdbc:oracle:thin:@//host:port/service if let Some(after) = rest.strip_prefix("oracle:") { @@ -1903,11 +1903,35 @@ pub fn parse_jdbc_host_port(url: &str) -> Option<(String, u16)> { } } +fn jdbc_transport_rest(url: &str) -> Option<&str> { + if let Some(rest) = url.strip_prefix("jdbc:").or_else(|| url.strip_prefix("JDBC:")) { + return Some(rest); + } + + let rest = url.strip_prefix("jdbcx:").or_else(|| url.strip_prefix("JDBCX:"))?; + if let Some(scheme_end) = rest.find("://") { + let scheme = &rest[..scheme_end]; + return Some(match scheme.rfind(':') { + Some(extension_end) => &rest[extension_end + 1..], + None => rest, + }); + } + + // Oracle's descriptor and thin URL forms do not contain `://`. In an + // extended JDBCX URL the vendor transport follows the first colon. + let tail = rest.split_once(':').map(|(_, tail)| tail); + match tail { + Some(tail) if tail.get(.."oracle:".len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case("oracle:")) => { + Some(tail) + } + _ => Some(rest), + } +} + pub fn rewrite_jdbc_url_host(url: &str, new_host: &str, new_port: u16) -> String { let normalized_url = url.to_ascii_uppercase(); - if normalized_url.starts_with("JDBC:ORACLE:") - && normalized_url.contains("(HOST=") - && normalized_url.contains("(PORT=") + let normalized_rest = jdbc_transport_rest(url).map(str::to_ascii_uppercase).unwrap_or_default(); + if normalized_rest.starts_with("ORACLE:") && normalized_url.contains("(HOST=") && normalized_url.contains("(PORT=") { return rewrite_oracle_descriptor_host(url, new_host, new_port); } @@ -3135,6 +3159,22 @@ mod tests { assert_eq!(p, 3306); } + #[test] + fn parse_jdbcx_host_port_with_and_without_extension() { + assert_eq!( + super::parse_jdbc_host_port("jdbcx:mysql://db.example.com:3306/app"), + Some(("db.example.com".to_string(), 3306)) + ); + assert_eq!( + super::parse_jdbc_host_port("jdbcx:prql:postgresql://pg.example.com:5432/app"), + Some(("pg.example.com".to_string(), 5432)) + ); + assert_eq!( + super::parse_jdbc_host_port("jdbcx:query:sqlserver://sql.example.com:1433;databaseName=app"), + Some(("sql.example.com".to_string(), 1433)) + ); + } + #[test] fn parse_jdbc_host_port_with_userinfo() { let (h, p) = super::parse_jdbc_host_port("jdbc:postgresql://user:pass@pghost:5433/db").unwrap(); @@ -3208,6 +3248,27 @@ mod tests { assert_eq!(rewritten, "jdbc:postgresql://127.0.0.1:54321/mydb"); } + #[test] + fn rewrite_jdbcx_url_preserves_extension() { + let url = "jdbcx:script:mysql://db.example.com:3306/app"; + let rewritten = super::rewrite_jdbc_url_host(url, "127.0.0.1", 13306); + assert_eq!(rewritten, "jdbcx:script:mysql://127.0.0.1:13306/app"); + + let sqlserver = "jdbcx:query:sqlserver://sql.example.com:1433;databaseName=app"; + let rewritten = super::rewrite_jdbc_url_host(sqlserver, "127.0.0.1", 11433); + assert_eq!(rewritten, "jdbcx:query:sqlserver://127.0.0.1:11433;databaseName=app"); + } + + #[test] + fn rewrite_jdbcx_oracle_descriptor() { + let url = "jdbcx:web:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=orahost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))"; + let rewritten = super::rewrite_jdbc_url_host(url, "127.0.0.1", 11521); + assert_eq!( + rewritten, + "jdbcx:web:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=11521))(CONNECT_DATA=(SERVICE_NAME=orcl)))" + ); + } + #[test] fn rewrite_jdbc_url_oracle() { let url = "jdbc:oracle:thin:@orahost:1521:ORCL"; diff --git a/plugins/jdbc/README.md b/plugins/jdbc/README.md index f69d3c029b..6e2436166c 100644 --- a/plugins/jdbc/README.md +++ b/plugins/jdbc/README.md @@ -36,3 +36,18 @@ lib/dbx-jdbc-plugin.jar ``` DBX does not bundle Java or JDBC drivers. Install Java locally and add database-specific driver JAR paths in the DBX JDBC connection form. + +The first-class JDBCX profile uses `io.github.jdbcx.WrappedDriver` and +`jdbcx:[extension:][vendor://host:port/database]` URLs. Install a JDBCX Maven bundle such as +`io.github.jdbcx:jdbcx-driver:0.8.0` in the DBX JDBC driver store, together with the database vendor's JDBC driver. +JDBCX discovers delegate drivers through JDBC `ServiceLoader`/`Driver.acceptsURL`, without vendor-specific DBX code. +Each connection selects exactly one installed JDBCX runtime bundle; DBX excludes artifacts from every other installed +JDBCX version from that connection's classpath. + +DBX restricts JDBCX to the `help`, `var`, and `version` extensions by default. Shell, Script, Web, MCP, and other +high-privilege extensions can execute local commands or access external resources, so they require an explicit +per-connection opt-in in the connection dialog. + +Some high-privilege extensions require optional runtime libraries that JDBCX deliberately does not bundle. Install +those libraries in the JDBC driver store and select them for the same connection. For JDBCX 0.8.0, MCP requires +`io.github.jdbcx:io.modelcontextprotocol:1.0.1`; use the dependency version declared by the selected JDBCX release. diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java index caec6608d4..ef6893d6fd 100644 --- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java +++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java @@ -50,6 +50,10 @@ import java.util.stream.Collectors; public final class DbxJdbcPlugin { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final int MAX_ROWS = 10_000; + private static final String JDBCX_URL_PREFIX = "jdbcx:"; + private static final String JDBCX_EXTENSION_WHITELIST_PROPERTY = "jdbcx.extension.whitelist"; + private static final String JDBCX_HIGH_PRIVILEGE_EXTENSIONS_OPT_IN = "-Ddbx.jdbcx.allowHighPrivilegeExtensions="; + private static final String JDBCX_SAFE_EXTENSION_WHITELIST = "help,var,version"; private static final String[] DEFAULT_TABLE_TYPES = new String[] { "TABLE", "VIEW", @@ -226,11 +230,45 @@ public final class DbxJdbcPlugin { } private static String throwableMessage(Throwable error) { + List causes = new ArrayList<>(); Throwable cause = error; - while (cause.getCause() != null && cause.getCause() != cause) { + while (cause != null && !causes.contains(cause)) { + causes.add(cause); cause = cause.getCause(); } - return cause.getMessage() == null ? cause.toString() : cause.getMessage(); + for (int i = causes.size() - 1; i >= 0; i--) { + Throwable current = causes.get(i); + String message = informativeThrowableMessage(current); + if (message != null) { + return message; + } + for (Throwable suppressed : current.getSuppressed()) { + message = informativeThrowableMessage(suppressed); + if (message != null) { + return message; + } + } + } + return causes.isEmpty() ? error.toString() : causes.get(causes.size() - 1).toString(); + } + + private static String informativeThrowableMessage(Throwable error) { + String message = error.getMessage(); + if (message == null || message.isBlank()) { + return null; + } + String trimmed = message.trim(); + if (error instanceof ClassNotFoundException || error instanceof NoClassDefFoundError) { + String className = trimmed.replace('/', '.'); + if (className.startsWith("io.modelcontextprotocol.")) { + return "Missing JDBCX MCP runtime class " + className + + ". Install io.github.jdbcx:io.modelcontextprotocol with the version required by the selected JDBCX runtime."; + } + return "Missing Java class " + className + ". Install the required runtime dependency."; + } + return trimmed.equals(error.getClass().getName()) || trimmed.equals(error.getClass().getSimpleName()) + ? null + : trimmed; } private static JsonNode handle(String method, JsonNode params, JsonNode connection) throws Exception { @@ -475,6 +513,7 @@ public final class DbxJdbcPlugin { properties.setProperty("password", password); } applyConnectTimeout(connection, properties); + applyJdbcxExtensionSecurity(connection, url, properties); if (isOracleUrl(url)) { applyOracleProperties(connection, properties); } @@ -483,6 +522,30 @@ public final class DbxJdbcPlugin { return sharedConnection; } + private static void applyJdbcxExtensionSecurity(JsonNode connection, String url, Properties properties) { + if (isJdbcxUrl(url) && !jdbcxHighPrivilegeExtensionsEnabled(connection)) { + properties.setProperty(JDBCX_EXTENSION_WHITELIST_PROPERTY, JDBCX_SAFE_EXTENSION_WHITELIST); + } + } + + private static boolean isJdbcxUrl(String url) { + return url != null && url.regionMatches(true, 0, JDBCX_URL_PREFIX, 0, JDBCX_URL_PREFIX.length()); + } + + private static boolean jdbcxHighPrivilegeExtensionsEnabled(JsonNode connection) { + JsonNode options = connection.path("agent_java_options"); + if (!options.isArray()) { + return false; + } + for (int i = options.size() - 1; i >= 0; i--) { + String option = options.path(i).asText("").trim(); + if (option.startsWith(JDBCX_HIGH_PRIVILEGE_EXTENSIONS_OPT_IN)) { + return Boolean.parseBoolean(option.substring(JDBCX_HIGH_PRIVILEGE_EXTENSIONS_OPT_IN.length())); + } + } + return false; + } + private static void applyConnectTimeout(JsonNode connection, Properties properties) { int connectTimeoutSecs = positiveInt(connection, "connect_timeout_secs", 30); DriverManager.setLoginTimeout(connectTimeoutSecs); @@ -1999,11 +2062,16 @@ public final class DbxJdbcPlugin { } private static String connectionKey(JsonNode connection) { - return optionalText(connection, "connection_string") + String connectionString = optionalText(connection, "connection_string"); + String jdbcxSecurityKey = isJdbcxUrl(connectionString) + ? "|jdbcxHighPrivilegeExtensions=" + jdbcxHighPrivilegeExtensionsEnabled(connection) + : ""; + return connectionString + "|" + optionalText(connection, "url_params") + "|" + optionalText(connection, "username") + "|" + optionalText(connection, "password") - + "|" + connection.path("sysdba").asBoolean(false); + + "|" + connection.path("sysdba").asBoolean(false) + + jdbcxSecurityKey; } private static Set primaryKeys(DatabaseMetaData meta, String database, String schema, String table) throws SQLException { diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java index 8aa44fdd8c..23f971340a 100644 --- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java +++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java @@ -29,6 +29,7 @@ import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; final class DbxJdbcPluginTest { private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -82,6 +83,29 @@ final class DbxJdbcPluginTest { assertEquals("linkage boom", response.path("error").path("message").asText()); } + @Test + void reportsInformativeOuterMessageWhenRootCauseHasNoMessage() throws Exception { + Method method = DbxJdbcPlugin.class.getDeclaredMethod("throwableMessage", Throwable.class); + method.setAccessible(true); + RuntimeException root = new RuntimeException(); + SQLException outer = new SQLException("MCP initialization failed: Cannot run program npx", root); + + assertEquals("MCP initialization failed: Cannot run program npx", method.invoke(null, outer)); + } + + @Test + void reportsActionableMessageForMissingJdbcxMcpRuntime() throws Exception { + Method method = DbxJdbcPlugin.class.getDeclaredMethod("throwableMessage", Throwable.class); + method.setAccessible(true); + SQLException outer = new SQLException(new ClassNotFoundException("io.modelcontextprotocol.spec.McpError")); + + assertEquals( + "Missing JDBCX MCP runtime class io.modelcontextprotocol.spec.McpError. " + + "Install io.github.jdbcx:io.modelcontextprotocol with the version required by the selected JDBCX runtime.", + method.invoke(null, outer) + ); + } + @Test void testConnectionAndConnectionInfoExposeH2Metadata() throws Exception { JsonNode tested = request("testConnection", """ @@ -461,6 +485,64 @@ final class DbxJdbcPluginTest { assertEquals("45", properties.getProperty("connectTimeout")); } + @Test + void jdbcxHighPrivilegeExtensionsAreDisabledByDefault() throws Exception { + Method method = DbxJdbcPlugin.class.getDeclaredMethod( + "applyJdbcxExtensionSecurity", + JsonNode.class, + String.class, + Properties.class + ); + method.setAccessible(true); + Properties properties = new Properties(); + method.invoke(null, MAPPER.createObjectNode(), "jdbcx:shell:mysql://127.0.0.1:3306/test", properties); + + String whitelist = properties.getProperty("jdbcx.extension.whitelist"); + assertEquals("help,var,version", whitelist); + assertFalse(whitelist.contains("shell")); + assertFalse(whitelist.contains("script")); + assertFalse(whitelist.contains("web")); + assertFalse(whitelist.contains("mcp")); + } + + @Test + void jdbcxHighPrivilegeExtensionsRequireExplicitConnectionOptIn() throws Exception { + Method method = DbxJdbcPlugin.class.getDeclaredMethod( + "applyJdbcxExtensionSecurity", + JsonNode.class, + String.class, + Properties.class + ); + method.setAccessible(true); + Properties properties = new Properties(); + ObjectNode connection = MAPPER.createObjectNode(); + connection.putArray("agent_java_options").add("-Ddbx.jdbcx.allowHighPrivilegeExtensions=true"); + + method.invoke(null, connection, "jdbcx:script:mysql://127.0.0.1:3306/test", properties); + + assertFalse(properties.containsKey("jdbcx.extension.whitelist")); + } + + @Test + void jdbcxHighPrivilegeExtensionChangeInvalidatesOnlyJdbcxConnections() throws Exception { + Method method = DbxJdbcPlugin.class.getDeclaredMethod("connectionKey", JsonNode.class); + method.setAccessible(true); + ObjectNode jdbcxConnection = MAPPER.createObjectNode(); + jdbcxConnection.put("connection_string", "jdbcx:mysql://127.0.0.1:3306/test"); + String jdbcxDisabledKey = (String) method.invoke(null, jdbcxConnection); + jdbcxConnection.putArray("agent_java_options").add("-Ddbx.jdbcx.allowHighPrivilegeExtensions=true"); + String jdbcxEnabledKey = (String) method.invoke(null, jdbcxConnection); + + ObjectNode regularConnection = MAPPER.createObjectNode(); + regularConnection.put("connection_string", "jdbc:mysql://127.0.0.1:3306/test"); + String regularDefaultKey = (String) method.invoke(null, regularConnection); + regularConnection.putArray("agent_java_options").add("-Ddbx.jdbcx.allowHighPrivilegeExtensions=true"); + String regularWithOptionKey = (String) method.invoke(null, regularConnection); + + assertNotEquals(jdbcxDisabledKey, jdbcxEnabledKey); + assertEquals(regularDefaultKey, regularWithOptionKey); + } + @Test void prestoConnectTimeoutDoesNotSetUnsupportedDriverProperties() throws Exception { Method method = DbxJdbcPlugin.class.getDeclaredMethod("applyConnectTimeout", JsonNode.class, Properties.class);