feat(sqlserver): support legacy TLS compatibility

This commit is contained in:
zipg authored and GitHub committed 2026-07-09 22:45:54 +08:00
1 parent 63ef26b25a
commit 67edb94b1d
30 files changed
+738 -117

No files matched your search

+10 -2
View File
@@ -36,7 +36,10 @@ const MONGODB_PROFILES: &[AgentDriverProfile] = &[AgentDriverProfile {
store_visible: false,
}];
const EXTRA_DRIVER_STORE_ENTRIES: &[(&str, &str)] = &[("kafka", "Apache Kafka")];
const EXTRA_AGENT_LABELS: &[(&str, &str)] =
&[("kafka", "Apache Kafka"), ("sqlserver-legacy", "SQL Server legacy compatibility component")];
const EXTRA_DRIVER_STORE_ENTRIES: &[(&str, &str)] =
&[("kafka", "Apache Kafka"), ("sqlserver-legacy", "SQL Server legacy compatibility component")];
const AGENT_CATALOG: &[AgentCatalogEntry] = &[
AgentCatalogEntry {
@@ -297,6 +300,11 @@ pub fn agent_key(db_type: &DatabaseType, driver_profile: Option<&str>) -> Option
if *db_type == DatabaseType::MessageQueue {
return (driver_profile == Some("kafka")).then_some("kafka");
}
if *db_type == DatabaseType::SqlServer {
return driver_profile
.is_some_and(|profile| profile.eq_ignore_ascii_case("sqlserver-legacy"))
.then_some("sqlserver-legacy");
}
let entry = entry_for_db_type(db_type)?;
if let Some(driver_profile) = driver_profile {
if let Some(profile) = entry.profiles.iter().find(|profile| profile.profile == driver_profile) {
@@ -328,7 +336,7 @@ pub fn driver_store_entries() -> impl Iterator<Item = (&'static str, &'static st
}
pub fn label_for_key(agent_key: &str) -> Option<&'static str> {
if let Some((_, label)) = EXTRA_DRIVER_STORE_ENTRIES.iter().find(|(key, _)| *key == agent_key) {
if let Some((_, label)) = EXTRA_AGENT_LABELS.iter().find(|(key, _)| *key == agent_key) {
return Some(label);
}
for entry in entries() {
+138 -13
View File
@@ -32,6 +32,8 @@ use crate::storage::{normalize_duckdb_worker_max_processes, Storage, DUCKDB_WORK
pub const JDBC_PLUGIN_NOT_INSTALLED: &str =
"JDBC plugin is not installed. Install the optional JDBC plugin to use this connection.";
pub const PRESTOSQL_JDBC_DRIVER_CLASS: &str = "io.prestosql.jdbc.PrestoDriver";
const SQLSERVER_LEGACY_DRIVER_INSTALL_HINT: &str =
"Install the SQL Server legacy compatibility component from Driver Manager, or open the connection settings and enable SQL Server legacy compatibility mode again.";
const DEFAULT_AGENT_CONNECT_TIMEOUT_SECS: u64 = 30;
const ACCESS_AGENT_CONNECT_TIMEOUT_SECS: u64 = 30;
const POOL_CLOSE_TIMEOUT_SECS: u64 = 3;
@@ -257,6 +259,24 @@ pub fn prestosql_jdbc_config_for_endpoint(config: &ConnectionConfig, host: &str,
jdbc_config
}
pub fn sqlserver_legacy_agent_config(config: &ConnectionConfig) -> ConnectionConfig {
let mut legacy_config = config.clone();
legacy_config.driver_profile = Some(db::sqlserver::SQLSERVER_LEGACY_DRIVER_PROFILE.to_string());
legacy_config.driver_label = Some(db::sqlserver::SQLSERVER_LEGACY_DRIVER_LABEL.to_string());
legacy_config
}
pub fn sqlserver_legacy_agent_error(native_error: &str, agent_error: &str) -> String {
let install_hint = if agent_error.contains("driver is not installed") {
format!("\n\n{SQLSERVER_LEGACY_DRIVER_INSTALL_HINT}")
} else {
String::new()
};
format!(
"{native_error}\n\nFallback with SQL Server legacy compatibility component failed: {agent_error}{install_hint}"
)
}
pub async fn connect_mysql_metadata_pool(
config: &ConnectionConfig,
db_config: &ConnectionConfig,
@@ -607,6 +627,95 @@ impl AppState {
Ok(PoolKind::ExternalDriver { driver_id: driver_id.to_string(), config: Arc::new(config.clone()), session })
}
pub async fn test_sqlserver_connection_with_legacy_fallback(
&self,
config: &ConnectionConfig,
host: &str,
port: u16,
connect_timeout: Duration,
) -> Result<String, String> {
match db::sqlserver::connect(
host,
port,
&config.username,
&config.password,
config.database.as_deref(),
config.url_params.as_deref(),
connect_timeout,
)
.await
{
Ok(_) => Ok("Connection successful".to_string()),
Err(native_error)
if db::sqlserver::sqlserver_legacy_compatibility_enabled(config.url_params.as_deref()) =>
{
let legacy_config = sqlserver_legacy_agent_config(config);
let connect_params =
agent_connect_params(&legacy_config, host, port, legacy_config.effective_database().unwrap_or(""));
let mut client = self
.agent_manager
.spawn(&legacy_config.db_type, legacy_config.driver_profile.as_deref())
.await
.map_err(|err| sqlserver_legacy_agent_error(&native_error, &err))?;
client
.call_method_with_timeout::<serde_json::Value>(
AgentMethod::TestConnection,
connect_params,
Some(agent_connect_timeout(&legacy_config)),
)
.await
.map_err(|err| sqlserver_legacy_agent_error(&native_error, &err))?;
client.disconnect().await.ok();
Ok("Connection successful (via SQL Server legacy compatibility driver)".to_string())
}
Err(err) => Err(err),
}
}
pub async fn connect_sqlserver_pool_with_legacy_fallback(
&self,
config: &ConnectionConfig,
host: &str,
port: u16,
connect_timeout: Duration,
) -> Result<PoolKind, String> {
match db::sqlserver::connect(
host,
port,
&config.username,
&config.password,
config.database.as_deref(),
config.url_params.as_deref(),
connect_timeout,
)
.await
{
Ok(client) => Ok(PoolKind::SqlServer(Arc::new(tokio::sync::Mutex::new(client)))),
Err(native_error)
if db::sqlserver::sqlserver_legacy_compatibility_enabled(config.url_params.as_deref()) =>
{
let legacy_config = sqlserver_legacy_agent_config(config);
let connect_params =
agent_connect_params(&legacy_config, host, port, legacy_config.effective_database().unwrap_or(""));
let mut client = self
.agent_manager
.spawn(&legacy_config.db_type, legacy_config.driver_profile.as_deref())
.await
.map_err(|err| sqlserver_legacy_agent_error(&native_error, &err))?;
client
.call_method_with_timeout::<serde_json::Value>(
AgentMethod::Connect,
connect_params,
Some(agent_connect_timeout(&legacy_config)),
)
.await
.map_err(|err| sqlserver_legacy_agent_error(&native_error, &err))?;
Ok(PoolKind::Agent(Arc::new(tokio::sync::Mutex::new(client))))
}
Err(err) => Err(err),
}
}
pub fn external_driver_runtime_env(&self, driver_id: &str) -> Result<PluginRuntimeEnv, String> {
if driver_id != "jdbc" {
return Ok(PluginRuntimeEnv::default());
@@ -1130,17 +1239,7 @@ impl AppState {
PoolKind::ClickHouse(client)
}
DatabaseType::SqlServer => {
let client = db::sqlserver::connect(
&host,
port,
&db_config.username,
&db_config.password,
db_config.database.as_deref(),
db_config.url_params.as_deref(),
connect_timeout,
)
.await?;
PoolKind::SqlServer(Arc::new(tokio::sync::Mutex::new(client)))
self.connect_sqlserver_pool_with_legacy_fallback(&db_config, &host, port, connect_timeout).await?
}
DatabaseType::Elasticsearch => {
let mut client = db::elasticsearch_driver::EsClient::from_config(
@@ -2986,8 +3085,9 @@ mod tests {
agent_connect_timeout, connection_remote_endpoint, connection_url_for_endpoint, database_connection_config,
metadata_connection_config, mysql_metadata_fallback_url, oceanbase_mysql_query_timeout_sql,
oceanbase_mysql_setup_queries, prestosql_jdbc_config_for_endpoint, redacted_connection_url_for_endpoint,
redis_sentinel_transport_id, redis_sentinel_transport_prefix, uses_bare_mysql_pool, uses_tcp_probe,
validate_h2_database_path, AppState, PoolKind, PRESTOSQL_JDBC_DRIVER_CLASS,
redis_sentinel_transport_id, redis_sentinel_transport_prefix, sqlserver_legacy_agent_config,
sqlserver_legacy_agent_error, uses_bare_mysql_pool, uses_tcp_probe, validate_h2_database_path, AppState,
PoolKind, PRESTOSQL_JDBC_DRIVER_CLASS,
};
use crate::agent_connection::{
agent_connect_params, mongo_legacy_error_with_auth_hint, mongo_uses_legacy_driver,
@@ -3102,6 +3202,31 @@ mod tests {
assert_eq!(jdbc_config.jdbc_driver_paths, vec!["D:\\software\\jar\\presto-jdbc-350.jar"]);
}
#[test]
fn sqlserver_legacy_agent_config_marks_hidden_profile() {
let mut config = mysql_config(Some("master"));
config.db_type = DatabaseType::SqlServer;
let legacy = sqlserver_legacy_agent_config(&config);
assert_eq!(legacy.db_type, DatabaseType::SqlServer);
assert_eq!(legacy.driver_profile.as_deref(), Some(crate::db::sqlserver::SQLSERVER_LEGACY_DRIVER_PROFILE));
assert_eq!(legacy.driver_label.as_deref(), Some(crate::db::sqlserver::SQLSERVER_LEGACY_DRIVER_LABEL));
}
#[test]
fn sqlserver_legacy_agent_error_mentions_driver_manager_when_missing() {
let message = sqlserver_legacy_agent_error(
"native failed",
"sqlserver-legacy driver is not installed. Please install it from the Driver Manager.",
);
assert!(message.contains("native failed"));
assert!(message.contains("Fallback with SQL Server legacy compatibility component failed"));
assert!(message.contains("Driver Manager"));
assert!(message.contains("enable SQL Server legacy compatibility mode again"));
}
#[test]
fn agent_connect_params_include_url_params() {
let mut config = mysql_config(Some("testdb"));
+16 -19
View File
@@ -16,6 +16,8 @@ use tokio_util::sync::CancellationToken;
pub type SqlServerClient = Client<Compat<TcpStream>>;
pub const SQLSERVER_DRIVER_PANIC_ERROR_PREFIX: &str = "SQL Server driver panic:";
pub const SQLSERVER_LEGACY_DRIVER_PROFILE: &str = "sqlserver-legacy";
pub const SQLSERVER_LEGACY_DRIVER_LABEL: &str = "SQL Server legacy compatibility component";
const SIMPLE_QUERY_MODULE_KEYWORDS: &[&str] = &["FUNCTION", "PROC", "PROCEDURE", "TRIGGER", "VIEW"];
// Match JDBC/tiberius `encrypt=false`: encrypt only login, then drop back to raw TDS.
const SQLSERVER_LEGACY_ENCRYPTION_LEVEL: tiberius::EncryptionLevel = tiberius::EncryptionLevel::Off;
@@ -53,13 +55,9 @@ pub async fn connect(
user: &str,
pass: &str,
database: Option<&str>,
url_params: Option<&str>,
_url_params: Option<&str>,
timeout: Duration,
) -> Result<SqlServerClient, String> {
if sqlserver_legacy_encryption_disabled(url_params) {
return try_connect_legacy_sqlserver_encryption(host, port, user, pass, database, timeout).await;
}
match try_connect(host, port, user, pass, database, tiberius::EncryptionLevel::Required, timeout).await {
Ok(client) => Ok(client),
Err(encrypted_error) => try_connect_legacy_sqlserver_encryption(host, port, user, pass, database, timeout)
@@ -69,12 +67,11 @@ pub async fn connect(
format!(
"{encrypted_error}\n\nThis may be caused by an old SQL Server TLS/encryption configuration. \
If you are connecting to SQL Server 2008/2008 R2/2012 or another legacy instance, \
try SQL Server legacy unencrypted mode. It behaves like encrypt=false and only helps \
when the server allows unencrypted transport or login-only encryption. It will still fail \
if the server requires encrypted transport that the embedded driver cannot negotiate. \
Only use this mode on trusted networks, VPNs, \
try SQL Server legacy compatibility mode. It first behaves like encrypt=false and, \
when explicitly enabled, DBX can also fall back to the SQL Server legacy compatibility \
driver for TLS 1.0 encrypted transport. Only use this mode on trusted networks, VPNs, \
or SSH tunnels.\n\n\
Automatic legacy unencrypted fallback also failed: {plain_error}"
Automatic native legacy fallback also failed: {plain_error}"
)
} else {
plain_error
@@ -102,7 +99,7 @@ async fn try_connect_legacy_sqlserver_encryption(
Err(errors.join("\n"))
}
fn sqlserver_legacy_encryption_disabled(url_params: Option<&str>) -> bool {
pub fn sqlserver_legacy_compatibility_enabled(url_params: Option<&str>) -> bool {
let Some(params) = url_params.map(str::trim).filter(|params| !params.is_empty()) else {
return false;
};
@@ -1903,14 +1900,14 @@ mod tests {
}
#[test]
fn sqlserver_legacy_encryption_flag_accepts_dbx_and_jdbc_params() {
assert!(!super::sqlserver_legacy_encryption_disabled(None));
assert!(!super::sqlserver_legacy_encryption_disabled(Some("encrypt=true")));
assert!(super::sqlserver_legacy_encryption_disabled(Some("sqlserverEncryption=disabled")));
assert!(super::sqlserver_legacy_encryption_disabled(Some("applicationName=dbx;sqlserverEncryption=off")));
assert!(super::sqlserver_legacy_encryption_disabled(Some("?sqlserverEncryption=false&applicationName=dbx")));
assert!(super::sqlserver_legacy_encryption_disabled(Some("applicationName=dbx;encrypt=false")));
assert!(super::sqlserver_legacy_encryption_disabled(Some("?Encrypt=0&applicationName=dbx")));
fn sqlserver_legacy_compatibility_flag_accepts_dbx_and_jdbc_params() {
assert!(!super::sqlserver_legacy_compatibility_enabled(None));
assert!(!super::sqlserver_legacy_compatibility_enabled(Some("encrypt=true")));
assert!(super::sqlserver_legacy_compatibility_enabled(Some("sqlserverEncryption=disabled")));
assert!(super::sqlserver_legacy_compatibility_enabled(Some("applicationName=dbx;sqlserverEncryption=off")));
assert!(super::sqlserver_legacy_compatibility_enabled(Some("?sqlserverEncryption=false&applicationName=dbx")));
assert!(super::sqlserver_legacy_compatibility_enabled(Some("applicationName=dbx;encrypt=false")));
assert!(super::sqlserver_legacy_compatibility_enabled(Some("?Encrypt=0&applicationName=dbx")));
}
#[test]