diff --git a/CHANGELOG.md b/CHANGELOG.md index b3ad6284a..dab54a593 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,14 @@ determines whether text boxes get drawn and additional settings `padding`, results in an in-memory cache of its own within one byte budget (`--results-max-bytes`, default 1 GB, or the `ggsql.resultsMemory` setting) and never changes the session's reader or dialect (#595). +- ODBC connections to Databricks now pick up Posit Workbench managed + credentials, as Snowflake ones already did: when a connection string names + the Workbench workspace in `Host=` and has no credentials of its own, the + Workbench OAuth token is added. + These tokens last about an hour; when a statement, a catalog lookup for the + Connections pane, or registering or unregistering a table fails because its + token has expired, ggsql reconnects with the current Workbench token and + tries once more. Tables registered before the reconnect are gone after it. ### Changed @@ -40,6 +48,13 @@ determines whether text boxes get drawn and additional settings `padding`, `SCALE ... LABEL`. - **Breaking**: The `LABEL` clause is renamed to `TITLE`. The keyword `title` is now `main` and the `subtitle` keyword is now `sub`. +- On Posit Workbench, ODBC connections to Snowflake get the Workbench OAuth + token only when `Server=` names the Workbench account (its public or + PrivateLink hostname, or the host Workbench names) and the string sets no + `Token=`, `UID=` with `PWD=`, or `Authenticator=` other than `oauth`. A + string for another account no longer receives the token. +- ODBC connection strings are read with braced values (`{...}`) kept whole + and keys matched exactly, so `ProxyUID=` is no longer read as `UID=`. - Registering a DataFrame of more than 2,048 rows with the DuckDB reader appends it with DuckDB's Arrow appender rather than one `INSERT` per 2,048-row chunk, about twice as fast on large frames (#617). diff --git a/src/reader/connection.rs b/src/reader/connection.rs index ccbe49abf..cbf8df4de 100644 --- a/src/reader/connection.rs +++ b/src/reader/connection.rs @@ -643,25 +643,125 @@ pub(crate) fn take_odbc_ggsql_params(conn_str: &str) -> (String, ConnectParams) (kept.join(";"), ggsql) } -/// Extract a value from an ODBC connection string by key, stripping braces. -pub fn extract_odbc_value(conn_str: &str, key: &str) -> Option { - let lower = conn_str.to_lowercase(); - let prefix = format!("{}=", key); - let start = lower.find(&prefix)?; - let rest = &conn_str[start + prefix.len()..]; - let value = rest.split(';').next().unwrap_or(""); - let value = value.trim().trim_matches(|c| c == '{' || c == '}'); - if value.is_empty() { - None - } else { - Some(value.to_string()) +/// Every value of `key` (case-insensitive, whole key) in an ODBC connection +/// string, in order. A value wrapped in `{...}` is read whole, including any +/// `;` or `=` inside it, with `}}` standing for a literal `}`. +pub fn odbc_values(conn_str: &str, key: &str) -> Vec { + odbc_pairs(conn_str) + .into_iter() + .filter(|(k, _)| k.eq_ignore_ascii_case(key)) + .map(|(_, v)| v) + .collect() +} + +/// Splits an ODBC connection string into `(key, value)` pairs, honoring +/// braced values. +pub(crate) fn odbc_pairs(conn_str: &str) -> Vec<(String, String)> { + let mut pairs = Vec::new(); + let mut chars = conn_str.chars().peekable(); + while chars.peek().is_some() { + let mut key = String::new(); + let mut has_value = false; + for c in chars.by_ref() { + match c { + '=' => { + has_value = true; + break; + } + ';' => break, + _ => key.push(c), + } + } + if !has_value { + // A bare attribute with no `=` (e.g. `UseProxy;`). + if !key.trim().is_empty() { + pairs.push((key.trim().to_string(), String::new())); + } + continue; + } + while chars.peek().is_some_and(|c| c.is_whitespace()) { + chars.next(); + } + let mut value = String::new(); + if chars.peek() == Some(&'{') { + chars.next(); + while let Some(c) = chars.next() { + if c == '}' { + if chars.peek() == Some(&'}') { + chars.next(); + } else { + break; + } + } + value.push(c); + } + // Anything between the closing brace and the next `;` is ignored. + for c in chars.by_ref() { + if c == ';' { + break; + } + } + } else { + for c in chars.by_ref() { + if c == ';' { + break; + } + value.push(c); + } + } + if !key.trim().is_empty() { + pairs.push((key.trim().to_string(), value.trim().to_string())); + } } + pairs +} + +/// The first non-empty value of `key` in an ODBC connection string, with +/// braces removed (see [`odbc_values`]). +pub fn extract_odbc_value(conn_str: &str, key: &str) -> Option { + odbc_values(conn_str, key) + .into_iter() + .next() + .filter(|value| !value.is_empty()) } #[cfg(test)] mod tests { use super::*; + #[test] + fn test_extract_odbc_value_reads_braced_values_whole() { + let conn = "Driver={My;Driver};HTTPPath={/x;Host=evil};Host=h;PWD={p}}q}"; + assert_eq!( + extract_odbc_value(conn, "driver").as_deref(), + Some("My;Driver") + ); + assert_eq!( + extract_odbc_value(conn, "httppath").as_deref(), + Some("/x;Host=evil") + ); + assert_eq!(extract_odbc_value(conn, "host").as_deref(), Some("h")); + assert_eq!(extract_odbc_value(conn, "pwd").as_deref(), Some("p}q")); + assert_eq!(odbc_values(conn, "host"), vec!["h".to_string()]); + assert_eq!(odbc_values("Host=a;host=b", "HOST").len(), 2); + assert_eq!( + extract_odbc_value("UseProxy;Host=h", "host").as_deref(), + Some("h") + ); + } + + #[test] + fn test_extract_odbc_value_matches_whole_keys_only() { + let conn = "Driver=X;ProxyHost=p;ProxyUID=pu;Host=h; uid = u "; + assert_eq!(extract_odbc_value(conn, "host").as_deref(), Some("h")); + assert_eq!(extract_odbc_value(conn, "uid").as_deref(), Some("u")); + assert_eq!(extract_odbc_value(conn, "pwd"), None); + assert_eq!( + extract_odbc_value("Driver={My Driver}", "driver").as_deref(), + Some("My Driver") + ); + } + #[test] fn test_take_odbc_ggsql_params() { let (conn, ggsql) = take_odbc_ggsql_params("Driver=X;Server=h;Dialect=ansi;UID=u"); diff --git a/src/reader/mod.rs b/src/reader/mod.rs index babd69830..4d3f53b7b 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1373,6 +1373,12 @@ impl RegisteredTables { self.0.borrow_mut().remove(name); } + /// Forget every name, for a reader whose connection was replaced and + /// took its temp tables with it. + pub(crate) fn clear(&self) { + self.0.borrow_mut().clear(); + } + pub(crate) fn is_registered(&self, name: &str) -> bool { self.0.borrow().contains(name) } @@ -1550,6 +1556,17 @@ mod helper_tests { t.note_unregistered("a"); assert!(!t.is_registered("a")); } + + #[test] + fn registered_tables_clear_forgets_every_name() { + let t = RegisteredTables::new(); + t.note_registered("a"); + t.note_registered("b"); + t.clear(); + assert!(!t.is_registered("a")); + assert!(!t.is_registered("b")); + assert!(t.names().is_empty()); + } } // ============================================================================ diff --git a/src/reader/odbc/databricks.rs b/src/reader/odbc/databricks.rs new file mode 100644 index 000000000..048f2207f --- /dev/null +++ b/src/reader/odbc/databricks.rs @@ -0,0 +1,237 @@ +//! Databricks Workbench credential detection. + +use super::{has_odbc_key, normalize_host}; + +/// Profile read when `DATABRICKS_CONFIG_PROFILE` is unset; the one Posit +/// Workbench writes. +const DEFAULT_PROFILE: &str = "workbench"; + +/// Registry `odbc_credential_provider` hook for Databricks: when Posit +/// Workbench manages Databricks credentials for this session, add its OAuth +/// token to a connection string that carries no credentials of its own. +pub(crate) fn apply_workbench_credentials(conn_str: &mut String) { + let config_file = std::env::var("DATABRICKS_CONFIG_FILE").ok(); + let contents = config_file + .as_deref() + .and_then(|path| std::fs::read_to_string(path).ok()); + let profile = std::env::var("DATABRICKS_CONFIG_PROFILE") + .ok() + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_string()); + if let Some(rewritten) = workbench_credentials( + conn_str, + config_file.as_deref(), + contents.as_deref(), + &profile, + ) { + *conn_str = rewritten; + } +} + +/// The connection string with the Workbench token added, or `None` to leave +/// it unchanged. The token is added only when `config_file_env` (the value of +/// `DATABRICKS_CONFIG_FILE`) is a Workbench-managed path, the string has no +/// credentials, and the profile's host is the string's `Host=`, so the token +/// never goes to a workspace it was not issued for. +pub(super) fn workbench_credentials( + conn_str: &str, + config_file_env: Option<&str>, + config_contents: Option<&str>, + profile: &str, +) -> Option { + if !config_file_env?.contains("posit-workbench") { + return None; + } + // Any `UID`, `PWD`, `AuthMech` or `Auth_*` key means the caller already + // chose how to authenticate. + let chose_auth = has_odbc_key(conn_str, "uid") + || has_odbc_key(conn_str, "pwd") + || crate::reader::connection::odbc_pairs(conn_str) + .iter() + .any(|(key, _)| key.to_ascii_lowercase().starts_with("auth")); + if chose_auth { + return None; + } + let (host, token) = read_profile(config_contents?, profile)?; + // A destination that appears more than once is ambiguous: the token goes + // nowhere rather than to a guess. + let [conn_host] = crate::reader::connection::odbc_values(conn_str, "host") + .try_into() + .ok()?; + if token.is_empty() || normalize_host(&host) != normalize_host(&conn_host) { + return None; + } + Some(format!( + "{};AuthMech=11;Auth_Flow=0;Auth_AccessToken={}", + conn_str.trim_end_matches(';'), + token + )) +} + +/// The `(host, token)` pair from the named section of a Databricks config +/// file. Reads only `[section]` headers and `key = value` lines, which is all +/// the file Workbench writes contains. +pub(super) fn read_profile(contents: &str, profile: &str) -> Option<(String, String)> { + let mut in_profile = false; + let mut host = None; + let mut token = None; + for line in contents.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + in_profile = name.trim() == profile; + } else if in_profile { + if let Some((key, value)) = line.split_once('=') { + match key.trim() { + "host" => host = Some(value.trim().to_string()), + "token" => token = Some(value.trim().to_string()), + _ => {} + } + } + } + } + Some((host?, token?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const WB_FILE: &str = "/home/u/.local/share/posit-workbench/databricks/databricks.cfg"; + const WB_CFG: &str = + "[workbench]\nhost = https://adb-1.azuredatabricks.net\ntoken = dapi-tok\n"; + const LINE: &str = "Driver=/opt/rstudio-drivers/spark/bin/lib/libsparkodbc_sb64.so;Host=adb-1.azuredatabricks.net;Port=443;HTTPPath=/sql/1.0/warehouses/abc"; + + #[test] + fn test_injects_workbench_token() { + assert_eq!( + workbench_credentials(LINE, Some(WB_FILE), Some(WB_CFG), "workbench"), + Some(format!( + "{LINE};AuthMech=11;Auth_Flow=0;Auth_AccessToken=dapi-tok" + )) + ); + } + + #[test] + fn test_host_mismatch_gets_no_token() { + let other = LINE.replace("adb-1", "adb-2"); + assert_eq!( + workbench_credentials(&other, Some(WB_FILE), Some(WB_CFG), "workbench"), + None + ); + } + + #[test] + fn test_host_match_ignores_scheme_case_and_trailing_slash() { + let cfg = "[workbench]\nhost = HTTPS://ADB-1.azuredatabricks.net/\ntoken = t\n"; + assert!(workbench_credentials(LINE, Some(WB_FILE), Some(cfg), "workbench").is_some()); + } + + #[test] + fn test_existing_auth_is_left_alone() { + for extra in [ + ";AuthMech=3", + ";UID=token;PWD=dapi-x", + ";Auth_AccessToken=x", + ] { + let s = format!("{LINE}{extra}"); + assert_eq!( + workbench_credentials(&s, Some(WB_FILE), Some(WB_CFG), "workbench"), + None, + "{extra}" + ); + } + } + + #[test] + fn test_proxy_settings_do_not_count_as_credentials_or_host() { + let proxied = format!("{LINE};ProxyHost=proxy;ProxyUID=pu;ProxyPWD=pp;UseProxy=1"); + assert!( + workbench_credentials(&proxied, Some(WB_FILE), Some(WB_CFG), "workbench").is_some() + ); + + let elsewhere = + "Driver=Databricks;ProxyHost=adb-1.azuredatabricks.net;Host=evil.example;HTTPPath=/p"; + assert_eq!( + workbench_credentials(elsewhere, Some(WB_FILE), Some(WB_CFG), "workbench"), + None + ); + } + + #[test] + fn test_ambiguous_destination_gets_no_token() { + let braced = + "Driver=Databricks;HTTPPath={/x;Host=adb-1.azuredatabricks.net};Host=evil.example"; + let repeated = format!("{LINE};Host=evil.example"); + for s in [braced.to_string(), repeated] { + assert_eq!( + workbench_credentials(&s, Some(WB_FILE), Some(WB_CFG), "workbench"), + None, + "{s}" + ); + } + } + + #[test] + fn test_any_chosen_auth_method_is_left_alone() { + for extra in [ + ";Auth_Flow=1;Auth_Client_ID=c;Auth_Client_Secret=s", + ";Auth_RefreshToken=r", + ";UID=;UID=token", + ] { + let s = format!("{LINE}{extra}"); + assert_eq!( + workbench_credentials(&s, Some(WB_FILE), Some(WB_CFG), "workbench"), + None, + "{extra}" + ); + } + } + + #[test] + fn test_requires_workbench_config_path() { + assert_eq!( + workbench_credentials( + LINE, + Some("/home/u/.databrickscfg"), + Some(WB_CFG), + "workbench" + ), + None + ); + assert_eq!( + workbench_credentials(LINE, None, Some(WB_CFG), "workbench"), + None + ); + } + + #[test] + fn test_missing_or_empty_token_is_none() { + assert_eq!( + workbench_credentials(LINE, Some(WB_FILE), None, "workbench"), + None + ); + let cfg = "[workbench]\nhost = https://adb-1.azuredatabricks.net\ntoken = \n"; + assert_eq!( + workbench_credentials(LINE, Some(WB_FILE), Some(cfg), "workbench"), + None + ); + } + + #[test] + fn test_read_profile_picks_named_section() { + let cfg = "[other]\nhost = https://x\ntoken = a\n\n[dev]\nhost = https://y\ntoken = b\n"; + assert_eq!( + read_profile(cfg, "dev"), + Some(("https://y".into(), "b".into())) + ); + assert_eq!(read_profile(cfg, "missing"), None); + } + + #[test] + fn test_pro_driver_path_dispatches_to_databricks() { + let driver = crate::reader::connection::extract_odbc_value(LINE, "driver"); + let entry = crate::reader::registry::detect(None, driver.as_deref()).unwrap(); + assert_eq!(entry.scheme, "databricks"); + assert!(entry.odbc_credential_provider.is_some()); + } +} diff --git a/src/reader/odbc/mod.rs b/src/reader/odbc/mod.rs index baf11ba13..26431e0f8 100644 --- a/src/reader/odbc/mod.rs +++ b/src/reader/odbc/mod.rs @@ -4,17 +4,43 @@ //! ODBC bindings via `libloading`. The ODBC driver manager (`libodbc`) is //! loaded on first use. +pub(crate) mod databricks; #[allow(dead_code)] pub(crate) mod ffi; pub(crate) mod snowflake; mod wrapper; +/// Whether an ODBC connection string sets `key` at all, even to an empty +/// value. Credential hooks use presence, not value, to decide whether the +/// caller already chose how to authenticate. +pub(super) fn has_odbc_key(conn_str: &str, key: &str) -> bool { + !super::connection::odbc_values(conn_str, key).is_empty() +} + +/// A host without its scheme, port or trailing slash, lowercased, for +/// comparing where a connection goes with where a credential is for. +pub(super) fn normalize_host(host: &str) -> String { + let lower = host.trim().to_lowercase(); + let bare = lower + .strip_prefix("https://") + .or_else(|| lower.strip_prefix("http://")) + .unwrap_or(&lower); + let bare = bare.split('/').next().unwrap_or(bare); + match bare.rsplit_once(':') { + Some((name, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => { + name.to_string() + } + _ => bare.to_string(), + } +} + use crate::reader::Reader; use crate::{DataFrame, GgsqlError, Result}; use arrow::array::*; #[cfg(test)] use arrow::datatypes::DataType; use ffi::*; +use std::cell::RefCell; use std::sync::Arc; use wrapper::{Connection, Statement}; @@ -26,9 +52,57 @@ fn take_dialect_override(conn_str: &str) -> (String, Option) { (conn_str, ggsql.dialect) } +/// Whether a driver error means the credential the registry hook supplied +/// has expired, by the entry's `odbc_expired_credential_errors`. +fn is_expired_credential(entry: &super::registry::DatabaseEntry, error: &str) -> bool { + let error = error.to_lowercase(); + entry + .odbc_expired_credential_errors + .iter() + .any(|needle| error.contains(needle)) +} + +/// Run `attempt`; if it fails with an expired credential for `entry`, run +/// `reconnect` and then `attempt` once more. A second failure, or a failure +/// to reconnect, is returned as is. +fn retry_after_expired_credential( + entry: Option<&super::registry::DatabaseEntry>, + attempt: impl Fn() -> Result, + reconnect: impl FnOnce() -> Result<()>, +) -> Result { + match attempt() { + Err(e) if entry.is_some_and(|entry| is_expired_credential(entry, &e.to_string())) => { + reconnect()?; + attempt() + } + result => result, + } +} + +/// Run `drop` for registered table `name` and forget it. A table that is no +/// longer registered, because a reconnect dropped it, needs no `drop`. +fn drop_registered_table( + tables: &crate::reader::RegisteredTables, + name: &str, + drop: impl FnOnce() -> Result<()>, +) -> Result<()> { + if !tables.is_registered(name) { + return Ok(()); + } + drop()?; + tables.note_unregistered(name); + Ok(()) +} + /// Generic ODBC reader implementing the `Reader` trait. pub struct OdbcReader { - connection: Connection, + /// Replaced by `reconnect` after a credential expires. + connection: RefCell, + /// The connection string before the credential hook ran, so a reconnect + /// can run the hook again and pick up a refreshed credential. + unresolved_conn_str: String, + /// The registry entry for the connected backend, when one matched. + entry: Option<&'static super::registry::DatabaseEntry>, dialect: super::DialectRef, registered_tables: crate::reader::RegisteredTables, batch_size: usize, @@ -73,32 +147,8 @@ impl OdbcReader { (None, None) => None, }; - // Backend-specific credential resolution (Snowflake Workbench OAuth - // tokens, `ConnectionName=` lookup), dispatched through the registry - // on the `Driver=` value — the DBMS name isn't known until after - // connecting, which is too late to supply credentials. - let driver = super::connection::extract_odbc_value(&conn_str, "driver"); - if let Some(apply) = super::registry::detect(None, driver.as_deref()) - .ok() - .and_then(|e| e.odbc_credential_provider) - { - apply(&mut conn_str); - } - - let connection = match Connection::connect(wrapper::odbc_env()?, &conn_str) { - Ok(c) => c, - Err(e) => { - // unixODBC IM005 ("Driver's SQLAllocHandle on - // SQL_HANDLE_DBC failed"): some drivers (MonetDB) refuse - // DBC allocation under an ODBC 3.80 environment. Retry once - // under 3.0 semantics before giving up. - if e.to_string().contains("IM005") { - Connection::connect(wrapper::odbc_env_legacy()?, &conn_str)? - } else { - return Err(e); - } - } - }; + let unresolved_conn_str = conn_str; + let (connection, conn_str) = Self::connect(&unresolved_conn_str)?; let dbms_name = connection.dbms_name(); let driver = super::connection::extract_odbc_value(&conn_str, "driver"); @@ -128,18 +178,69 @@ impl OdbcReader { let numeric_as_double = entry.is_some_and(|e| e.odbc_numeric_as_double); Ok(Self { - connection, + connection: RefCell::new(connection), + unresolved_conn_str, + entry, dialect, registered_tables: crate::reader::RegisteredTables::new(), batch_size, numeric_as_double, }) } -} -impl Reader for OdbcReader { - fn execute_sql(&self, sql: &str) -> Result { - let cursor = self.connection.execute(sql)?; + /// Run the backend's credential hook on `unresolved_conn_str` and + /// connect. Returns the connection and the connection string it used. + fn connect(unresolved_conn_str: &str) -> Result<(Connection, String)> { + let mut conn_str = unresolved_conn_str.to_string(); + + // Backend-specific credential resolution (Snowflake and Databricks + // Workbench OAuth tokens, Snowflake `ConnectionName=` lookup), + // dispatched through the registry + // on the `Driver=` value — the DBMS name isn't known until after + // connecting, which is too late to supply credentials. + let driver = super::connection::extract_odbc_value(&conn_str, "driver"); + if let Some(apply) = super::registry::detect(None, driver.as_deref()) + .ok() + .and_then(|e| e.odbc_credential_provider) + { + apply(&mut conn_str); + } + + let connection = match Connection::connect(wrapper::odbc_env()?, &conn_str) { + Ok(c) => c, + Err(e) => { + // unixODBC IM005 ("Driver's SQLAllocHandle on + // SQL_HANDLE_DBC failed"): some drivers (MonetDB) refuse + // DBC allocation under an ODBC 3.80 environment. Retry once + // under 3.0 semantics before giving up. + if e.to_string().contains("IM005") { + Connection::connect(wrapper::odbc_env_legacy()?, &conn_str)? + } else { + return Err(e); + } + } + }; + Ok((connection, conn_str)) + } + + /// Replace the connection with a new one, re-running the credential + /// hook. Temp tables registered on the old connection are gone, so the + /// reader forgets their names. + fn reconnect(&self) -> Result<()> { + let (connection, _) = Self::connect(&self.unresolved_conn_str)?; + *self.connection.borrow_mut() = connection; + self.registered_tables.clear(); + Ok(()) + } + + /// Run `attempt`; if the credential the hook supplied has expired, + /// reconnect and run it once more. + fn with_credential_retry(&self, attempt: impl Fn() -> Result) -> Result { + retry_after_expired_credential(self.entry, attempt, || self.reconnect()) + } + + fn execute_sql_once(&self, sql: &str) -> Result { + let cursor = self.connection.borrow().execute(sql)?; let Some(cursor) = cursor else { return Ok(DataFrame::empty()); @@ -151,12 +252,11 @@ impl Reader for OdbcReader { }) } - fn register(&self, name: &str, df: DataFrame, replace: bool) -> Result<()> { - super::validate_table_name(name)?; - + /// Create temp table `name` from `df` on the current connection. + fn register_once(&self, name: &str, df: &DataFrame, replace: bool) -> Result<()> { if replace { let drop_sql = self.dialect.drop_table_sql(name); - let _ = self.connection.execute(&drop_sql); + let _ = self.connection.borrow().execute(&drop_sql); } let schema = df.schema(); @@ -170,7 +270,7 @@ impl Reader for OdbcReader { }) .collect(); for create_sql in self.dialect.sql_create_empty_temp_table(name, &col_defs) { - self.connection.execute(&create_sql).map_err(|e| { + self.connection.borrow().execute(&create_sql).map_err(|e| { GgsqlError::ReaderError(format!("Failed to create temp table '{}': {}", name, e)) })?; } @@ -201,7 +301,7 @@ impl Reader for OdbcReader { }) .collect(); - let prepared = self.connection.prepare(&insert_sql).map_err(|e| { + let prepared = self.connection.borrow().prepare(&insert_sql).map_err(|e| { GgsqlError::ReaderError(format!("Failed to prepare INSERT for '{}': {}", name, e)) })?; @@ -248,6 +348,17 @@ impl Reader for OdbcReader { self.registered_tables.note_registered(name); Ok(()) } +} + +impl Reader for OdbcReader { + fn execute_sql(&self, sql: &str) -> Result { + self.with_credential_retry(|| self.execute_sql_once(sql)) + } + + fn register(&self, name: &str, df: DataFrame, replace: bool) -> Result<()> { + super::validate_table_name(name)?; + self.with_credential_retry(|| self.register_once(name, &df, replace)) + } fn unregister(&self, name: &str) -> Result<()> { if !self.registered_tables.is_registered(name) { @@ -258,12 +369,20 @@ impl Reader for OdbcReader { } let sql = self.dialect.drop_table_sql(name); - self.connection.execute(&sql).map_err(|e| { - GgsqlError::ReaderError(format!("Failed to unregister table '{}': {}", name, e)) - })?; - - self.registered_tables.note_unregistered(name); - Ok(()) + self.with_credential_retry(|| { + drop_registered_table(&self.registered_tables, name, || { + self.connection + .borrow() + .execute(&sql) + .map(|_| ()) + .map_err(|e| { + GgsqlError::ReaderError(format!( + "Failed to unregister table '{}': {}", + name, e + )) + }) + }) + }) } fn execute(&self, query: &str) -> Result { @@ -275,23 +394,39 @@ impl Reader for OdbcReader { } fn list_catalogs(&self) -> Result> { - // ODBC spec: CatalogName="%", SchemaName="", TableName="" - let stmt = wrapper::sql_tables(&self.connection, Some("%"), Some(""), Some(""), None)?; - let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; - let mut catalogs = extract_string_column_ci(&df, "TABLE_CAT")?; - catalogs.sort(); - catalogs.dedup(); - Ok(catalogs) + self.with_credential_retry(|| { + // ODBC spec: CatalogName="%", SchemaName="", TableName="" + let stmt = wrapper::sql_tables( + &self.connection.borrow(), + Some("%"), + Some(""), + Some(""), + None, + )?; + let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; + let mut catalogs = extract_string_column_ci(&df, "TABLE_CAT")?; + catalogs.sort(); + catalogs.dedup(); + Ok(catalogs) + }) } fn list_schemas(&self, _catalog: &str) -> Result> { - // ODBC spec: CatalogName="", SchemaName="%", TableName="" - let stmt = wrapper::sql_tables(&self.connection, Some(""), Some("%"), Some(""), None)?; - let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; - let mut schemas = extract_string_column_ci(&df, "TABLE_SCHEM")?; - schemas.sort(); - schemas.dedup(); - Ok(schemas) + self.with_credential_retry(|| { + // ODBC spec: CatalogName="", SchemaName="%", TableName="" + let stmt = wrapper::sql_tables( + &self.connection.borrow(), + Some(""), + Some("%"), + Some(""), + None, + )?; + let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; + let mut schemas = extract_string_column_ci(&df, "TABLE_SCHEM")?; + schemas.sort(); + schemas.dedup(); + Ok(schemas) + }) } fn list_tables(&self, catalog: &str, schema: &str) -> Result> { @@ -305,9 +440,17 @@ impl Reader for OdbcReader { } else { Some(schema) }; - let stmt = wrapper::sql_tables(&self.connection, cat, sch, Some("%"), Some("TABLE,VIEW"))?; - let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; - extract_table_infos_ci(&df) + self.with_credential_retry(|| { + let stmt = wrapper::sql_tables( + &self.connection.borrow(), + cat, + sch, + Some("%"), + Some("TABLE,VIEW"), + )?; + let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; + extract_table_infos_ci(&df) + }) } fn list_columns( @@ -326,9 +469,12 @@ impl Reader for OdbcReader { } else { Some(schema) }; - let stmt = wrapper::sql_columns(&self.connection, cat, sch, Some(table), None)?; - let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; - extract_column_infos_ci(&df) + self.with_credential_retry(|| { + let stmt = + wrapper::sql_columns(&self.connection.borrow(), cat, sch, Some(table), None)?; + let df = cursor_to_dataframe(stmt, self.batch_size, self.numeric_as_double)?; + extract_column_infos_ci(&df) + }) } } @@ -1157,7 +1303,10 @@ mod tests { #[ignore] fn pg_connect_and_detect_dialect() { let reader = try_connect(PG_DSN).expect("Cannot connect to PostgreSQL ODBC DSN"); - assert_eq!(reader.connection.dbms_name().as_deref(), Some("PostgreSQL")); + assert_eq!( + reader.connection.borrow().dbms_name().as_deref(), + Some("PostgreSQL") + ); } #[test] @@ -1663,7 +1812,7 @@ mod tests { #[ignore] fn sqlite_connect_and_detect_dialect() { let reader = try_connect(SQLITE_DSN).expect("Cannot connect to SQLite ODBC DSN"); - let dbms = reader.connection.dbms_name().unwrap_or_default(); + let dbms = reader.connection.borrow().dbms_name().unwrap_or_default(); assert!( dbms.to_lowercase().contains("sqlite"), "Expected SQLite, got: {}", @@ -1782,4 +1931,172 @@ mod tests { reader.unregister("__ggsql_test_reg").unwrap(); } + + /// The error a Databricks statement returned after its Workbench token + /// expired, as recorded on Workbench (Simba Spark ODBC, SQLSTATE 08006). + const DATABRICKS_EXPIRED: &str = "ODBC execute failed: [08006] [RStudio][ThriftExtension] (10) Access token expired: Bearer error=\"invalid_token\", error_description=\"The access token expired\""; + + fn entry(scheme: &str) -> &'static crate::reader::registry::DatabaseEntry { + crate::reader::registry::detect(Some(scheme), None).unwrap() + } + + #[test] + fn test_databricks_expired_token_is_expired_credential() { + assert!(is_expired_credential( + entry("databricks"), + DATABRICKS_EXPIRED + )); + } + + #[test] + fn test_expired_credential_match_ignores_case() { + assert!(is_expired_credential( + entry("databricks"), + "ACCESS TOKEN EXPIRED" + )); + } + + #[test] + fn test_syntax_error_is_not_expired_credential() { + let syntax = + "ODBC execute failed: [42000] [RStudio][Hardy] (80) Syntax or semantic analysis error"; + assert!(!is_expired_credential(entry("databricks"), syntax)); + } + + #[test] + fn test_generic_08006_is_not_expired_credential() { + let dropped = "ODBC execute failed: [08006] Communication link failure"; + assert!(!is_expired_credential(entry("databricks"), dropped)); + } + + #[test] + fn test_snowflake_entry_does_not_match_databricks_expiry() { + assert!(!is_expired_credential( + entry("snowflake"), + DATABRICKS_EXPIRED + )); + } + + #[test] + fn test_retry_reconnects_once_after_expired_credential() { + let attempts = std::cell::Cell::new(0); + let reconnects = std::cell::Cell::new(0); + let result = retry_after_expired_credential( + Some(entry("databricks")), + || { + attempts.set(attempts.get() + 1); + if attempts.get() == 1 { + Err(GgsqlError::ReaderError(DATABRICKS_EXPIRED.into())) + } else { + Ok(42) + } + }, + || { + reconnects.set(reconnects.get() + 1); + Ok(()) + }, + ); + assert_eq!(result.unwrap(), 42); + assert_eq!(attempts.get(), 2); + assert_eq!(reconnects.get(), 1); + } + + #[test] + fn test_retry_returns_second_failure_without_reconnecting_again() { + let attempts = std::cell::Cell::new(0); + let reconnects = std::cell::Cell::new(0); + let result: Result = retry_after_expired_credential( + Some(entry("databricks")), + || { + attempts.set(attempts.get() + 1); + Err(GgsqlError::ReaderError(DATABRICKS_EXPIRED.into())) + }, + || { + reconnects.set(reconnects.get() + 1); + Ok(()) + }, + ); + assert!(result + .unwrap_err() + .to_string() + .contains("Access token expired")); + assert_eq!(attempts.get(), 2); + assert_eq!(reconnects.get(), 1); + } + + #[test] + fn test_retry_leaves_other_errors_alone() { + let attempts = std::cell::Cell::new(0); + let reconnects = std::cell::Cell::new(0); + let result: Result = retry_after_expired_credential( + Some(entry("databricks")), + || { + attempts.set(attempts.get() + 1); + Err(GgsqlError::ReaderError("[42000] Syntax error".into())) + }, + || { + reconnects.set(reconnects.get() + 1); + Ok(()) + }, + ); + assert!(result.is_err()); + assert_eq!(attempts.get(), 1); + assert_eq!(reconnects.get(), 0); + } + + #[test] + fn test_retry_returns_reconnect_failure() { + let result: Result = retry_after_expired_credential( + Some(entry("databricks")), + || Err(GgsqlError::ReaderError(DATABRICKS_EXPIRED.into())), + || { + Err(GgsqlError::ReaderError( + "ODBC connect failed: no token".into(), + )) + }, + ); + assert!(result.unwrap_err().to_string().contains("no token")); + } + + #[test] + fn test_unregister_retry_succeeds_when_reconnect_dropped_the_table() { + let tables = crate::reader::RegisteredTables::new(); + tables.note_registered("t"); + let drops = std::cell::Cell::new(0); + let result = retry_after_expired_credential( + Some(entry("databricks")), + || { + drop_registered_table(&tables, "t", || { + drops.set(drops.get() + 1); + Err(GgsqlError::ReaderError(DATABRICKS_EXPIRED.into())) + }) + }, + || { + tables.clear(); + Ok(()) + }, + ); + assert!(result.is_ok()); + assert_eq!(drops.get(), 1); + assert!(!tables.is_registered("t")); + } + + #[test] + fn test_drop_registered_table_keeps_name_when_drop_fails() { + let tables = crate::reader::RegisteredTables::new(); + tables.note_registered("t"); + let result = drop_registered_table(&tables, "t", || { + Err(GgsqlError::ReaderError("[42000] Syntax error".into())) + }); + assert!(result.is_err()); + assert!(tables.is_registered("t")); + } + + #[test] + fn test_drop_registered_table_forgets_name_after_drop() { + let tables = crate::reader::RegisteredTables::new(); + tables.note_registered("t"); + drop_registered_table(&tables, "t", || Ok(())).unwrap(); + assert!(!tables.is_registered("t")); + } } diff --git a/src/reader/odbc/snowflake.rs b/src/reader/odbc/snowflake.rs index 773a86dfb..d468946bb 100644 --- a/src/reader/odbc/snowflake.rs +++ b/src/reader/odbc/snowflake.rs @@ -3,21 +3,27 @@ /// Registry `odbc_credential_provider` hook for Snowflake: rewrite the /// connection string to supply credentials before connecting. Resolves a /// `ConnectionName=` reference from `~/.snowflake/connections.toml`, then -/// injects a Posit Workbench OAuth token when one is available and the -/// string doesn't carry a token already. +/// injects a Posit Workbench OAuth token when [`workbench_token_for`] finds +/// one for the string. pub(crate) fn apply_workbench_credentials(conn_str: &mut String) { if let Some(resolved) = resolve_connection_name(conn_str) { *conn_str = resolved; } - if !has_token(conn_str) { - if let Some(token) = detect_workbench_token() { - *conn_str = inject_snowflake_token(conn_str, &token); - } + let snowflake_home = std::env::var("SNOWFLAKE_HOME").ok(); + let connections_toml = snowflake_home.as_deref().and_then(|home| { + std::fs::read_to_string(std::path::Path::new(home).join("connections.toml")).ok() + }); + if let Some(token) = workbench_token_for( + conn_str, + snowflake_home.as_deref(), + connections_toml.as_deref(), + ) { + add_token(conn_str, &token); } } pub(super) fn has_token(conn_str: &str) -> bool { - crate::reader::connection::extract_odbc_value(conn_str, "token").is_some() + super::has_odbc_key(conn_str, "token") } fn home_dir() -> Option { @@ -145,27 +151,83 @@ pub(super) fn resolve_connection_name(conn_str: &str) -> Option { Some(parts.join(";")) } -/// Detect Posit Workbench Snowflake OAuth token. -pub(super) fn detect_workbench_token() -> Option { - let snowflake_home = std::env::var("SNOWFLAKE_HOME").ok()?; - - if !snowflake_home.contains("posit-workbench") { +/// The Posit Workbench OAuth token to add to a connection string, or `None`. +/// A token is returned only when `snowflake_home` (the value of +/// `SNOWFLAKE_HOME`) is a Workbench-managed path, the string has no +/// credentials of its own (`Token=`, any `Authenticator=` other than `oauth`, +/// or `UID=` with `PWD=`), and its `Server=` names the `[workbench]` account +/// (or the entry's `host`), so the token never goes to an account it was not +/// issued for. +pub(super) fn workbench_token_for( + conn_str: &str, + snowflake_home: Option<&str>, + connections_toml: Option<&str>, +) -> Option { + use super::{has_odbc_key, normalize_host}; + + if !snowflake_home?.contains("posit-workbench") { + return None; + } + let has_password = has_odbc_key(conn_str, "uid") && has_odbc_key(conn_str, "pwd"); + let other_authenticator = crate::reader::connection::odbc_values(conn_str, "authenticator") + .iter() + .any(|a| !a.eq_ignore_ascii_case("oauth")); + if has_token(conn_str) || has_password || other_authenticator { return None; } - let toml_path = std::path::Path::new(&snowflake_home).join("connections.toml"); - let content = std::fs::read_to_string(&toml_path).ok()?; + let doc = connections_toml?.parse::().ok()?; + let entry = doc.get("workbench")?; + let get_str = |key: &str| entry.get(key)?.as_str().map(str::to_string); + + // A destination that appears more than once is ambiguous: the token goes + // nowhere rather than to a guess. + let [server]: [String; 1] = crate::reader::connection::odbc_values(conn_str, "server") + .try_into() + .ok()?; + let server = normalize_host(&server); + // Snowflake serves an account at its public and PrivateLink hostnames, + // and an account with underscores in its name also at the hostnames with + // hyphens in their place. Account names never contain hyphens, so the + // alias cannot name another account. + let mut allowed = Vec::new(); + if let Some(account) = get_str("account").map(|a| a.to_lowercase()) { + for name in [account.clone(), account.replace('_', "-")] { + allowed.push(format!("{name}.snowflakecomputing.com")); + allowed.push(format!("{name}.privatelink.snowflakecomputing.com")); + } + } + if let Some(host) = get_str("host") { + allowed.push(normalize_host(&host)); + } + if !allowed.contains(&server) { + return None; + } - let doc = content.parse::().ok()?; - let token = doc.get("workbench")?.get("token")?.as_str()?.to_string(); + get_str("token").filter(|token| !token.is_empty()) +} - if token.is_empty() { - None +/// Add the Workbench token to a connection string, along with +/// `Authenticator=oauth` unless the string already names it. +pub(super) fn add_token(conn_str: &mut String, token: &str) { + if is_oauth_authenticator(conn_str) { + let trimmed = conn_str.trim_end_matches(';').len(); + conn_str.truncate(trimmed); + conn_str.push_str(";Token="); + conn_str.push_str(token); } else { - Some(token) + *conn_str = inject_snowflake_token(conn_str, token); } } +fn is_oauth_authenticator(conn_str: &str) -> bool { + let authenticators = crate::reader::connection::odbc_values(conn_str, "authenticator"); + !authenticators.is_empty() + && authenticators + .iter() + .all(|a| a.eq_ignore_ascii_case("oauth")) +} + /// Inject OAuth token into a Snowflake ODBC connection string. pub(super) fn inject_snowflake_token(conn_str: &str, token: &str) -> String { let mut result = conn_str.trim_end_matches(';').to_string(); @@ -268,4 +330,147 @@ account = "otheraccount" std::env::remove_var("SNOWFLAKE_HOME"); } + + const SF_HOME: &str = "/home/u/.local/share/posit-workbench/snowflake"; + const SF_TOML: &str = + "[workbench]\naccount = \"myorg-acct\"\ntoken = \"sf-tok\"\nauthenticator = \"oauth\"\n"; + const SF_DRIVER: &str = + "Driver=/opt/rstudio-drivers/snowflake/bin/lib/libsnowflakeodbc_sb64.so"; + + #[test] + fn test_token_for_matching_account_server() { + let s = format!("{SF_DRIVER};Server=MYORG-ACCT.snowflakecomputing.com"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), + Some("sf-tok".into()) + ); + } + + #[test] + fn test_token_for_matching_spcs_host() { + let toml = "[workbench]\naccount = \"a\"\nhost = \"a.internal.snowflakecomputing.com\"\ntoken = \"t\"\n"; + let s = format!("{SF_DRIVER};Server=a.internal.snowflakecomputing.com"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(toml)), + Some("t".into()) + ); + } + + #[test] + fn test_server_mismatch_gets_no_token() { + let s = format!("{SF_DRIVER};Server=other.snowflakecomputing.com"); + assert_eq!(workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), None); + } + + #[test] + fn test_existing_auth_gets_no_token() { + for extra in [";Authenticator=externalbrowser", ";UID=u;PWD=p", ";Token=x"] { + let s = format!("{SF_DRIVER};Server=myorg-acct.snowflakecomputing.com{extra}"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), + None, + "{extra}" + ); + } + } + + #[test] + fn test_oauth_authenticator_without_token_gets_token() { + let s = format!("{SF_DRIVER};Server=myorg-acct.snowflakecomputing.com;Authenticator=oauth"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), + Some("sf-tok".into()) + ); + let mut conn = s.clone(); + add_token(&mut conn, "sf-tok"); + assert_eq!(conn, format!("{s};Token=sf-tok")); + } + + #[test] + fn test_hyphenated_hostname_alias_for_underscore_account() { + let toml = "[workbench]\naccount = \"myorg-my_acct\"\ntoken = \"t\"\n"; + for server in ["myorg-my_acct", "myorg-my-acct"] { + let s = format!("{SF_DRIVER};Server={server}.snowflakecomputing.com"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(toml)), + Some("t".into()), + "{server}" + ); + } + let other = format!("{SF_DRIVER};Server=myorg-other.snowflakecomputing.com"); + assert_eq!(workbench_token_for(&other, Some(SF_HOME), Some(toml)), None); + } + + #[test] + fn test_ambiguous_server_gets_no_token() { + let s = format!( + "{SF_DRIVER};Warehouse={{w;Server=myorg-acct.snowflakecomputing.com}};Server=other.snowflakecomputing.com" + ); + let repeated = format!( + "{SF_DRIVER};Server=myorg-acct.snowflakecomputing.com;Server=other.snowflakecomputing.com" + ); + for s in [s, repeated] { + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), + None, + "{s}" + ); + } + } + + #[test] + fn test_privatelink_and_url_forms_of_the_account_get_token() { + let toml = "[workbench]\naccount = \"myorg-my_acct\"\ntoken = \"t\"\n"; + for server in [ + "myorg-my_acct.privatelink.snowflakecomputing.com", + "myorg-my-acct.privatelink.snowflakecomputing.com", + "https://myorg-my_acct.snowflakecomputing.com/", + "myorg-my_acct.snowflakecomputing.com:443", + ] { + let s = format!("{SF_DRIVER};Server={server}"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(toml)), + Some("t".into()), + "{server}" + ); + } + let other = format!("{SF_DRIVER};Server=myorg-other.privatelink.snowflakecomputing.com"); + assert_eq!(workbench_token_for(&other, Some(SF_HOME), Some(toml)), None); + } + + #[test] + fn test_empty_or_repeated_auth_keys_count_as_present() { + for extra in [ + ";Authenticator=", + ";Authenticator=oauth;Authenticator=snowflake", + ";UID=;UID=u;PWD=p", + ] { + let s = format!("{SF_DRIVER};Server=myorg-acct.snowflakecomputing.com{extra}"); + assert_eq!( + workbench_token_for(&s, Some(SF_HOME), Some(SF_TOML)), + None, + "{extra}" + ); + } + } + + #[test] + fn test_requires_workbench_home() { + let s = format!("{SF_DRIVER};Server=myorg-acct.snowflakecomputing.com"); + assert_eq!( + workbench_token_for(&s, Some("/home/u/.snowflake"), Some(SF_TOML)), + None + ); + } + + #[test] + fn test_pro_driver_path_dispatches_to_snowflake() { + let driver = crate::reader::connection::extract_odbc_value(SF_DRIVER, "driver"); + assert_eq!( + crate::reader::registry::detect(None, driver.as_deref()) + .unwrap() + .scheme, + "snowflake" + ); + } } diff --git a/src/reader/registry.rs b/src/reader/registry.rs index 2b8efcff5..d33b806c4 100644 --- a/src/reader/registry.rs +++ b/src/reader/registry.rs @@ -176,9 +176,16 @@ pub struct DatabaseEntry { /// Pre-connect hook rewriting the ODBC connection string to supply /// credentials the driver cannot obtain itself (Snowflake: resolve /// `ConnectionName=` from `~/.snowflake/connections.toml`, inject a - /// Posit Workbench OAuth token). Dispatched on the `Driver=` value, so + /// Posit Workbench OAuth token; Databricks: inject a Posit Workbench + /// OAuth token). Dispatched on the `Driver=` value, so /// it fires before the DBMS name is known. pub odbc_credential_provider: Option, + /// Case-insensitive substrings of driver error text that mean the + /// credential the hook supplied has expired. The ODBC reader reconnects, + /// re-running the hook, and retries the statement or catalog call once + /// when an error contains one of these. Databricks: Workbench OAuth tokens last about + /// an hour and the Simba Spark driver does not refresh them. + pub odbc_expired_credential_errors: &'static [&'static str], /// In-process reader to prefer when its cargo feature is compiled in /// (duckdb, sqlite). `None` for backends reached only through external /// ADBC/ODBC drivers. @@ -210,6 +217,7 @@ macro_rules! entry { odbc_row_array_size: None, odbc_numeric_as_double: false, odbc_credential_provider: None, + odbc_expired_credential_errors: &[], native_reader: None, } }; @@ -248,6 +256,14 @@ const SNOWFLAKE_CREDENTIAL_PROVIDER: Option = #[cfg(not(feature = "odbc"))] const SNOWFLAKE_CREDENTIAL_PROVIDER: Option = None; +/// Databricks' ODBC credential hook, present only when the `odbc` feature +/// (and with it the `odbc::databricks` module) is compiled in. +#[cfg(feature = "odbc")] +const DATABRICKS_CREDENTIAL_PROVIDER: Option = + Some(crate::reader::odbc::databricks::apply_workbench_credentials); +#[cfg(not(feature = "odbc"))] +const DATABRICKS_CREDENTIAL_PROVIDER: Option = None; + /// All supported backends. **Order matters for detection**: entries are /// scanned top to bottom, so more specific patterns must precede generic /// ones (`microsoft sql server` before anything matching `sql`, Redshift @@ -321,20 +337,24 @@ pub static REGISTRY: &[DatabaseEntry] = &[ ddl_empty_result_error: Some("no destination table to read") ) ), - entry!( - "databricks", - &["spark"], - "Databricks", - &[Has("databricks"), Has("spark")], - &DatabricksDialect, - adbc!( - "adbc_driver_databricks", + DatabaseEntry { + odbc_credential_provider: DATABRICKS_CREDENTIAL_PROVIDER, + odbc_expired_credential_errors: &["access token expired", "invalid_token"], + ..entry!( "databricks", - Passthrough, - false, - ddl_retry_error: Some("schema bytes are empty") + &["spark"], + "Databricks", + &[Has("databricks"), Has("spark")], + &DatabricksDialect, + adbc!( + "adbc_driver_databricks", + "databricks", + Passthrough, + false, + ddl_retry_error: Some("schema bytes are empty") + ) ) - ), + }, entry!( "clickhouse", &[],