From 11097c4fbecba8c2d621877fa8ec1e8cc8d5422d Mon Sep 17 00:00:00 2001 From: cathleeny <58714163+cathleeny@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:49:33 +0000 Subject: [PATCH 1/3] fix(auth): hold the HTTP client weakly in OAuth providers `DatabricksHttpClient` owns its auth provider, and the M2M, M2M private-key and U2M providers (and the Azure service principal provider built on M2M) each held a strong `Arc` back to it. The pair formed a reference cycle, so closing an OAuth session leaked the HTTP client, the provider and the tokio runtime handle the provider captures. In the Python binding, which runs one runtime per session, that handle keeps the runtime's FDs open, the same symptom as the transport cycle fixed in #434. The providers now store a `Weak` and upgrade it only when a token fetch runs, matching `FederationProvider`. Their constructors take `&Arc` so the caller keeps ownership, and a shared `upgrade_http_client` helper replaces federation's inline upgrade. Signed-off-by: cathleeny <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 5 ++ src/auth/oauth/azure.rs | 10 +-- src/auth/oauth/federation.rs | 4 +- src/auth/oauth/jwt_m2m.rs | 70 +++++++++++++++---- src/auth/oauth/m2m.rs | 121 +++++++++++++++++++++++++-------- src/auth/oauth/mod.rs | 15 ++++ src/auth/oauth/u2m.rs | 65 ++++++++++++++---- src/session.rs | 12 ++-- tests/oauth_u2m_integration.rs | 8 +-- 9 files changed, 235 insertions(+), 75 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..39253feb 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,12 +20,17 @@ changes go in their respective binding's NEXT_CHANGELOG. with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. +- `ClientCredentialsProvider`, `JwtClientCredentialsProvider` and + `AuthorizationCodeProvider` constructors take `&Arc` + and hold it weakly, matching `FederationProvider`. Callers must keep the + client alive for as long as they use the provider. ### Updated ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. +- Closing an OAuth session (M2M, M2M private key, U2M or Azure service principal) now frees its HTTP client and auth provider. The provider held the HTTP client strongly while the client owned the provider, so the pair and the provider's tokio runtime handle leaked for every closed session. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 5636e64d..1a111ffa 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -161,7 +161,7 @@ impl AzureServicePrincipalProvider { azure_client_secret: &str, tenant: &str, workspace_resource_id: Option, - http_client: std::sync::Arc, + http_client: &std::sync::Arc, ) -> crate::kernel_error::Result { Self::new_with_token_url( host, @@ -185,13 +185,13 @@ impl AzureServicePrincipalProvider { azure_client_secret: &str, token_url: String, workspace_resource_id: Option, - http_client: std::sync::Arc, + http_client: &std::sync::Arc, ) -> crate::kernel_error::Result { let data = super::m2m::ClientCredentialsProvider::new_with_full_config( host, azure_client_id, azure_client_secret, - http_client.clone(), + http_client, vec![sp_m2m_scope(host)], Some(token_url.clone()), ) @@ -586,7 +586,7 @@ mod tests { "sp-client-secret", token_url, Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_string()), - http_client, + &http_client, ) .await .expect("provider builds"); @@ -619,7 +619,7 @@ mod tests { "sp-client-secret", token_url, None, - http_client, + &http_client, ) .await .expect("provider builds"); diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index ed239bb4..a7eed7ba 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -207,9 +207,7 @@ impl FederationProvider { /// Performs the token exchange and returns the in-house token. Errors here /// are turned into the pass-through fallback by the caller. async fn exchange(&self, source_token: &str) -> Result { - let http_client = self.http_client.upgrade().ok_or_else(|| { - Error::invalid_state().message("Token federation HTTP client is no longer available") - })?; + let http_client = super::upgrade_http_client(&self.http_client)?; let mut form: Vec<(&str, &str)> = vec![ ("grant_type", GRANT_TYPE_JWT_BEARER), ("assertion", source_token), diff --git a/src/auth/oauth/jwt_m2m.rs b/src/auth/oauth/jwt_m2m.rs index 2375fbfe..8f4b8102 100644 --- a/src/auth/oauth/jwt_m2m.rs +++ b/src/auth/oauth/jwt_m2m.rs @@ -34,7 +34,7 @@ //! M2M tokens are not cached to disk (same rationale as [`super::m2m`]): //! the private key is always available for re-authentication. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use oauth2::basic::BasicTokenType; use oauth2::{EmptyExtraTokenFields, StandardTokenResponse, TokenResponse as _}; @@ -112,8 +112,9 @@ pub struct JwtClientCredentialsProvider { signing_key: Arc, /// Thread-safe token store managing the token lifecycle. token_store: TokenStore, - /// HTTP client for token endpoint requests. - http_client: Arc, + /// HTTP client for token endpoint requests. Weak; see + /// [`super::upgrade_http_client`]. + http_client: Weak, /// OAuth scopes to request. scopes: Vec, /// Tokio runtime handle captured at construction so the sync @@ -152,7 +153,8 @@ impl JwtClientCredentialsProvider { /// * `jwt_kid` — key id for the JWT header. /// * `jwt_passphrase` — passphrase for an encrypted PKCS#8 key, else `None`. /// * `jwt_algorithm` — JWT algorithm name (`None` → `RS256`). - /// * `http_client` — shared HTTP client. + /// * `http_client` — shared HTTP client. The caller must keep it alive; + /// the provider holds only a weak reference. /// * `scopes` — OAuth scopes to request. /// * `token_endpoint_override` — token endpoint URL, or `None` to discover via OIDC. #[allow(clippy::too_many_arguments)] @@ -163,7 +165,7 @@ impl JwtClientCredentialsProvider { jwt_kid: &str, jwt_passphrase: Option<&str>, jwt_algorithm: Option<&str>, - http_client: Arc, + http_client: &Arc, scopes: Vec, token_endpoint_override: Option, ) -> Result { @@ -178,7 +180,7 @@ impl JwtClientCredentialsProvider { let token_endpoint = match token_endpoint_override { Some(endpoint) => endpoint, None => { - OidcEndpoints::discover(host, &http_client) + OidcEndpoints::discover(host, http_client) .await? .token_endpoint } @@ -190,7 +192,7 @@ impl JwtClientCredentialsProvider { token_endpoint, signing_key, token_store: TokenStore::new(), - http_client, + http_client: Arc::downgrade(http_client), scopes, runtime_handle: RuntimeHandle::current(), }) @@ -246,6 +248,7 @@ impl AuthProvider for JwtClientCredentialsProvider { let jwt_kid = self.jwt_kid.clone(); let token = self.token_store.get_or_refresh(move || { + let http_client = super::upgrade_http_client(&http_client)?; // Sign a fresh assertion only now that a refresh is actually // running (fresh-token calls return before reaching here). let client_assertion = @@ -379,6 +382,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -386,7 +390,7 @@ mod tests { "test-kid", None, Some("RS256"), - http_client(), + &client, vec!["all-apis".to_string()], None, ) @@ -423,6 +427,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -430,7 +435,7 @@ mod tests { "test-kid", None, Some("RS256"), - http_client(), + &client, vec!["all-apis".to_string()], None, ) @@ -491,6 +496,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -498,7 +504,7 @@ mod tests { "test-kid", None, None, - http_client(), + &client, vec!["all-apis".to_string()], None, ) @@ -527,6 +533,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -534,7 +541,7 @@ mod tests { "test-kid", None, None, - http_client(), + &client, vec!["all-apis".to_string()], Some(token_url), ) @@ -560,7 +567,7 @@ mod tests { "test-kid", None, Some("ES512"), - http_client(), + &http_client(), vec!["all-apis".to_string()], None, ) @@ -582,7 +589,7 @@ mod tests { "test-kid", None, None, - http_client(), + &http_client(), vec!["all-apis".to_string()], None, ) @@ -605,6 +612,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -612,7 +620,7 @@ mod tests { "test-kid", None, None, - http_client(), + &client, vec!["all-apis".to_string()], None, ) @@ -650,6 +658,7 @@ mod tests { .await; let (_dir, key_path) = write_test_key(); + let client = http_client(); let provider = JwtClientCredentialsProvider::new( &server.uri(), "test-client-id", @@ -657,7 +666,7 @@ mod tests { "test-kid", None, None, - http_client(), + &client, vec!["all-apis".to_string()], None, ) @@ -668,4 +677,35 @@ mod tests { assert_eq!(err.code, crate::kernel_error::ErrorCode::Unauthenticated); assert_eq!(err.http_status, Some(400)); } + + /// The HTTP client owns its auth provider, so a provider holding the client + /// strongly would leak both, plus the provider's tokio runtime handle. + #[tokio::test(flavor = "multi_thread")] + async fn provider_does_not_retain_http_client() { + let (_dir, key_path) = write_test_key(); + let client = http_client(); + let weak_client = Arc::downgrade(&client); + let provider = Arc::new( + JwtClientCredentialsProvider::new( + "https://ws.cloud.databricks.com", + "test-client-id", + &key_path, + "test-kid", + None, + None, + &client, + vec!["all-apis".to_string()], + Some("https://ws.cloud.databricks.com/oidc/v1/token".to_string()), + ) + .await + .expect("provider"), + ); + let weak_provider = Arc::downgrade(&provider); + client.set_auth_provider(provider); + + drop(client); + + assert!(weak_client.upgrade().is_none()); + assert!(weak_provider.upgrade().is_none()); + } } diff --git a/src/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 36fd9c31..48dcd4c6 100644 --- a/src/auth/oauth/m2m.rs +++ b/src/auth/oauth/m2m.rs @@ -40,7 +40,7 @@ use oauth2::{ AuthUrl, ClientId, ClientSecret, HttpRequest, HttpResponse, RequestTokenError, Scope, TokenResponse, TokenUrl, }; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use tokio::runtime::Handle as RuntimeHandle; /// OAuth provider for M2M (Machine-to-Machine) authentication. @@ -73,7 +73,7 @@ use tokio::runtime::Handle as RuntimeHandle; /// "https://my-workspace.cloud.databricks.com", /// "my-client-id", /// "my-client-secret", -/// http_client, +/// &http_client, /// ).await?; /// /// // Get auth header (will trigger initial token fetch) @@ -92,8 +92,9 @@ pub struct ClientCredentialsProvider { auth_endpoint: String, /// Thread-safe token store managing the token lifecycle token_store: TokenStore, - /// HTTP client for token endpoint requests - http_client: Arc, + /// HTTP client for token endpoint requests. Weak; see + /// [`super::upgrade_http_client`]. + http_client: Weak, /// OAuth scopes to request (typically "all-apis"). Empty when `resource` /// is set (a v1.0 `resource=` grant). scopes: Vec, @@ -125,7 +126,8 @@ impl ClientCredentialsProvider { /// * `host` - Databricks workspace URL (e.g., "https://my-workspace.cloud.databricks.com") /// * `client_id` - OAuth client ID for the service principal /// * `client_secret` - OAuth client secret for the service principal - /// * `http_client` - Shared HTTP client for token endpoint requests + /// * `http_client` - Shared HTTP client for token endpoint requests. The + /// caller must keep it alive; the provider holds only a weak reference. /// /// # Returns /// @@ -145,7 +147,7 @@ impl ClientCredentialsProvider { /// "https://my-workspace.cloud.databricks.com", /// "client-id", /// "client-secret", - /// http_client, + /// &http_client, /// ).await?; /// # Ok(()) /// # } @@ -154,7 +156,7 @@ impl ClientCredentialsProvider { host: &str, client_id: &str, client_secret: &str, - http_client: Arc, + http_client: &Arc, ) -> Result { Self::new_with_scopes( host, @@ -174,7 +176,7 @@ impl ClientCredentialsProvider { host: &str, client_id: &str, client_secret: &str, - http_client: Arc, + http_client: &Arc, scopes: Vec, ) -> Result { Self::new_with_full_config(host, client_id, client_secret, http_client, scopes, None).await @@ -190,7 +192,8 @@ impl ClientCredentialsProvider { /// * `host` - Databricks workspace URL /// * `client_id` - OAuth client ID for the service principal /// * `client_secret` - OAuth client secret for the service principal - /// * `http_client` - Shared HTTP client for token endpoint requests + /// * `http_client` - Shared HTTP client for token endpoint requests. The + /// caller must keep it alive; the provider holds only a weak reference. /// * `scopes` - OAuth scopes to request /// * `token_endpoint_override` - Optional token endpoint URL override /// @@ -203,7 +206,7 @@ impl ClientCredentialsProvider { host: &str, client_id: &str, client_secret: &str, - http_client: Arc, + http_client: &Arc, scopes: Vec, token_endpoint_override: Option, ) -> Result { @@ -218,7 +221,7 @@ impl ClientCredentialsProvider { let (token_endpoint, auth_endpoint) = match token_endpoint_override { Some(token_endpoint) => (token_endpoint.clone(), token_endpoint), None => { - let endpoints = OidcEndpoints::discover(host, &http_client).await?; + let endpoints = OidcEndpoints::discover(host, http_client).await?; (endpoints.token_endpoint, endpoints.authorization_endpoint) } }; @@ -229,7 +232,7 @@ impl ClientCredentialsProvider { token_endpoint, auth_endpoint, token_store: TokenStore::new(), - http_client, + http_client: Arc::downgrade(http_client), scopes, resource: None, // `new_with_full_config` is `async`, so we're guaranteed @@ -254,7 +257,7 @@ impl ClientCredentialsProvider { pub async fn new_with_resource_v1( client_id: &str, client_secret: &str, - http_client: Arc, + http_client: &Arc, resource: String, token_endpoint: String, ) -> Result { @@ -264,7 +267,7 @@ impl ClientCredentialsProvider { auth_endpoint: token_endpoint.clone(), token_endpoint, token_store: TokenStore::new(), - http_client, + http_client: Arc::downgrade(http_client), scopes: Vec::new(), resource: Some(resource), runtime_handle: RuntimeHandle::current(), @@ -302,6 +305,7 @@ impl AuthProvider for ClientCredentialsProvider { // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); let token = self.token_store.get_or_refresh(move || { + let http_client = super::upgrade_http_client(&http_client)?; // Execute the async token fetch via the kernel's // captured runtime handle. `block_on_in_runtime` // dispatches on `Handle::try_current()`: it uses @@ -540,7 +544,7 @@ mod tests { /// M2M provider pointed straight at `{server}/oidc/v1/token`, skipping discovery. async fn provider_at( mock_server: &MockServer, - http_client: Arc, + http_client: &Arc, ) -> ClientCredentialsProvider { ClientCredentialsProvider::new_with_full_config( &mock_server.uri(), @@ -607,7 +611,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, ) .await .expect("Failed to create provider"); @@ -653,7 +657,7 @@ mod tests { let provider = ClientCredentialsProvider::new_with_resource_v1( "sp-client-id", "sp-client-secret", - http_client, + &http_client, "https://management.core.windows.net/".to_string(), format!("{}/tenant-abc/oauth2/token", mock_server.uri()), ) @@ -721,7 +725,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, ) .await .expect("Failed to create provider"); @@ -773,7 +777,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, ) .await; @@ -815,7 +819,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, ) .await; @@ -861,7 +865,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, ) .await .expect("Failed to create provider"), @@ -937,7 +941,7 @@ mod tests { &mock_server.uri(), "test-client-id", "test-client-secret", - http_client, + &http_client, vec!["custom-scope-1".to_string(), "custom-scope-2".to_string()], ) .await @@ -995,7 +999,7 @@ mod tests { &mock_server.uri(), "azure-client-id", "azure-client-secret", - http_client, + &http_client, vec!["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default".to_string()], Some(token_endpoint), ) @@ -1032,7 +1036,8 @@ mod tests { .mount(&mock_server) .await; - let provider = provider_at(&mock_server, fast_retry_http_client(3)).await; + let http_client = fast_retry_http_client(3); + let provider = provider_at(&mock_server, &http_client).await; assert_eq!( provider @@ -1056,7 +1061,8 @@ mod tests { .mount(&mock_server) .await; - let provider = provider_at(&mock_server, fast_retry_http_client(3)).await; + let http_client = fast_retry_http_client(3); + let provider = provider_at(&mock_server, &http_client).await; let err = provider .get_auth_header() @@ -1076,7 +1082,8 @@ mod tests { .mount(&mock_server) .await; - let provider = provider_at(&mock_server, fast_retry_http_client(2)).await; + let http_client = fast_retry_http_client(2); + let provider = provider_at(&mock_server, &http_client).await; let err = provider .get_auth_header() @@ -1097,7 +1104,8 @@ mod tests { .mount(&mock_server) .await; - let provider = provider_at(&mock_server, fast_retry_http_client(2)).await; + let http_client = fast_retry_http_client(2); + let provider = provider_at(&mock_server, &http_client).await; let err = provider .get_auth_header() @@ -1129,10 +1137,11 @@ mod tests { .mount(&mock_server) .await; + let http_client = fast_retry_http_client(3); let provider = ClientCredentialsProvider::new_with_resource_v1( "sp-client-id", "sp-client-secret", - fast_retry_http_client(3), + &http_client, "https://management.core.windows.net/".to_string(), format!("{}/tenant-abc/oauth2/token", mock_server.uri()), ) @@ -1147,4 +1156,60 @@ mod tests { ); assert_eq!(calls.load(Ordering::SeqCst), 2); } + + /// Never contacted: the tests below reach no token request. + const UNUSED_TOKEN_URL: &str = "https://ws.cloud.databricks.com/oidc/v1/token"; + + /// The HTTP client owns its auth provider, so a provider holding the client + /// strongly would leak both, plus the provider's tokio runtime handle. + #[tokio::test(flavor = "multi_thread")] + async fn provider_does_not_retain_http_client() { + let http_client = fast_retry_http_client(0); + let weak_http_client = Arc::downgrade(&http_client); + let provider = Arc::new( + ClientCredentialsProvider::new_with_full_config( + "https://ws.cloud.databricks.com", + "test-client-id", + "test-client-secret", + &http_client, + vec!["all-apis".to_string()], + Some(UNUSED_TOKEN_URL.to_string()), + ) + .await + .expect("provider"), + ); + let weak_provider = Arc::downgrade(&provider); + http_client.set_auth_provider(provider); + + drop(http_client); + + assert!(weak_http_client.upgrade().is_none()); + assert!(weak_provider.upgrade().is_none()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn token_fetch_fails_cleanly_once_http_client_is_dropped() { + let http_client = fast_retry_http_client(0); + let provider = ClientCredentialsProvider::new_with_full_config( + "https://ws.cloud.databricks.com", + "test-client-id", + "test-client-secret", + &http_client, + vec!["all-apis".to_string()], + Some(UNUSED_TOKEN_URL.to_string()), + ) + .await + .expect("provider"); + + drop(http_client); + + let err = provider + .get_auth_header() + .expect_err("no HTTP client to fetch a token with"); + assert!( + err.message.contains("no longer available"), + "{}", + err.message + ); + } } diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 68053ada..4efb8cd5 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -46,3 +46,18 @@ pub use m2m::ClientCredentialsProvider; pub use oidc::OidcEndpoints; pub use token::OAuthToken; pub use u2m::AuthorizationCodeProvider; + +use crate::client::http::DatabricksHttpClient; +use crate::kernel_error::{Error, Result}; +use std::sync::{Arc, Weak}; + +/// OAuth providers hold the HTTP client weakly because the client owns its +/// auth provider: a strong reference would form a cycle that keeps the client, +/// the provider and its tokio runtime handle alive after the session closes. +pub(crate) fn upgrade_http_client( + http_client: &Weak, +) -> Result> { + http_client + .upgrade() + .ok_or_else(|| Error::invalid_state().message("OAuth HTTP client is no longer available")) +} diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 5a27d3b3..0035724e 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -50,7 +50,7 @@ use oauth2::{ AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, RefreshToken, Scope, TokenResponse, TokenUrl, }; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use std::time::Duration; use tokio::runtime::Handle as RuntimeHandle; @@ -113,7 +113,7 @@ fn save_to_cache( /// let provider = AuthorizationCodeProvider::new( /// "https://my-workspace.cloud.databricks.com", /// "my-client-id", -/// http_client, +/// &http_client, /// ).await?; /// /// // Get auth header (may launch browser on first call if no cached token) @@ -132,8 +132,9 @@ pub struct AuthorizationCodeProvider { auth_endpoint: String, /// Thread-safe token store managing the token lifecycle token_store: TokenStore, - /// HTTP client for token endpoint requests - http_client: Arc, + /// HTTP client for token endpoint requests. Weak; see + /// [`super::upgrade_http_client`]. + http_client: Weak, /// OAuth scopes to request (typically "all-apis offline_access") scopes: Vec, /// Candidate callback-server ports, tried in order (first free binds). @@ -172,7 +173,8 @@ impl AuthorizationCodeProvider { /// /// * `host` - Databricks workspace URL (e.g., "https://my-workspace.cloud.databricks.com") /// * `client_id` - OAuth client ID for the application - /// * `http_client` - Shared HTTP client for token endpoint requests + /// * `http_client` - Shared HTTP client for token endpoint requests. The + /// caller must keep it alive; the provider holds only a weak reference. /// /// # Returns /// @@ -191,7 +193,7 @@ impl AuthorizationCodeProvider { /// let provider = AuthorizationCodeProvider::new( /// "https://my-workspace.cloud.databricks.com", /// "client-id", - /// http_client, + /// &http_client, /// ).await?; /// # Ok(()) /// # } @@ -199,7 +201,7 @@ impl AuthorizationCodeProvider { pub async fn new( host: &str, client_id: &str, - http_client: Arc, + http_client: &Arc, ) -> Result { // Scopes must match the app registered for `DEFAULT_CALLBACK_PORT` // (8030 → `databricks-sql-connector`, whose redirect URI is registered @@ -229,7 +231,7 @@ impl AuthorizationCodeProvider { pub async fn new_with_config( host: &str, client_id: &str, - http_client: Arc, + http_client: &Arc, scopes: Vec, callback_port: u16, callback_timeout: Duration, @@ -261,7 +263,7 @@ impl AuthorizationCodeProvider { pub async fn new_with_full_config( host: &str, client_id: &str, - http_client: Arc, + http_client: &Arc, scopes: Vec, callback_ports: Vec, callback_timeout: Duration, @@ -269,7 +271,7 @@ impl AuthorizationCodeProvider { cache_passphrase: Option, ) -> Result { // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) - let endpoints = OidcEndpoints::discover(host, &http_client).await?; + let endpoints = OidcEndpoints::discover(host, http_client).await?; // Use override if provided, otherwise use discovered endpoint let token_endpoint = token_endpoint_override.unwrap_or(endpoints.token_endpoint); @@ -306,7 +308,7 @@ impl AuthorizationCodeProvider { token_endpoint, auth_endpoint: endpoints.authorization_endpoint, token_store, - http_client, + http_client: Arc::downgrade(http_client), scopes, callback_ports, callback_timeout, @@ -368,6 +370,7 @@ impl AuthProvider for AuthorizationCodeProvider { // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); let token = self.token_store.get_or_refresh(move || { + let http_client = super::upgrade_http_client(&http_client)?; // Execute async token fetch/refresh via the kernel's // captured runtime handle. `block_on_in_runtime` // dispatches on `Handle::try_current()`: `block_in_place` @@ -657,7 +660,7 @@ mod tests { let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![8020], Duration::from_secs(120), @@ -710,7 +713,7 @@ mod tests { let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![8020], Duration::from_secs(120), @@ -779,7 +782,7 @@ mod tests { let mut provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test @@ -803,4 +806,38 @@ mod tests { "Should fail when falling back to browser flow in unit test" ); } + + /// The HTTP client owns its auth provider, so a provider holding the client + /// strongly would leak both, plus the provider's tokio runtime handle. + #[tokio::test(flavor = "multi_thread")] + async fn provider_does_not_retain_http_client() { + let mock_server = MockServer::start().await; + mock_oidc_discovery(&mock_server).await; + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("Failed to create HTTP client"), + ); + let weak_http_client = Arc::downgrade(&http_client); + let provider = Arc::new( + AuthorizationCodeProvider::new_with_full_config( + &mock_server.uri(), + "test-client-id", + &http_client, + vec!["sql".to_string(), "offline_access".to_string()], + vec![0], + Duration::from_secs(5), + None, + None, + ) + .await + .expect("provider"), + ); + let weak_provider = Arc::downgrade(&provider); + http_client.set_auth_provider(provider); + + drop(http_client); + + assert!(weak_http_client.upgrade().is_none()); + assert!(weak_provider.upgrade().is_none()); + } } diff --git a/src/session.rs b/src/session.rs index 1a64a209..fac07c97 100644 --- a/src/session.rs +++ b/src/session.rs @@ -376,7 +376,7 @@ impl Session { // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. let auth_provider: Arc = - build_auth_provider(&config.auth, &host, http_client.clone()).await?; + build_auth_provider(&config.auth, &host, &http_client).await?; http_client.set_auth_provider(auth_provider); // Authenticate before the feature-flag prefetch, which swallows its // errors: otherwise a failed token request is sent again by @@ -1383,18 +1383,18 @@ fn resolve_u2m_bundle( async fn build_auth_provider( auth: &AuthConfig, host: &str, - http_client: Arc, + http_client: &Arc, ) -> Result> { // Build the base provider for the configured auth flow, then wrap it with // mandatory OIDC token exchange (BYOT federation). The wrapper is a no-op // for non-JWT and same-host-issuer tokens, so it is safe to apply // unconditionally across PAT / M2M / U2M. See `auth::oauth::federation`. - let base = build_base_auth_provider(auth, host, http_client.clone()).await?; + let base = build_base_auth_provider(auth, host, http_client).await?; let provider = FederationProvider::new( base, host, auth.identity_federation_client_id().map(str::to_owned), - &http_client, + http_client, ) .await?; Ok(Arc::new(provider)) @@ -1405,7 +1405,7 @@ async fn build_auth_provider( async fn build_base_auth_provider( auth: &AuthConfig, host: &str, - http_client: Arc, + http_client: &Arc, ) -> Result> { match auth { AuthConfig::Pat { token, .. } => { @@ -1508,7 +1508,7 @@ async fn build_base_auth_provider( } let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), - _ => azure::discover_tenant(host, &http_client).await?, + _ => azure::discover_tenant(host, http_client).await?, }; let provider = AzureServicePrincipalProvider::new( host, diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 95b83782..2c04396b 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -116,7 +116,7 @@ async fn test_u2m_refresh_token_full_flow() { let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![8020], Duration::from_secs(120), @@ -190,7 +190,7 @@ async fn test_u2m_refresh_token_stale_immediate_return() { let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-stale", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![8021], Duration::from_secs(120), @@ -270,7 +270,7 @@ async fn test_u2m_refresh_token_expired_fallback() { let mut provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-expired", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test @@ -345,7 +345,7 @@ async fn test_u2m_refresh_updates_cache() { let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-cache", - http_client, + &http_client, vec!["all-apis".to_string(), "offline_access".to_string()], vec![8023], Duration::from_secs(120), From e41bac4e4da5f7da039f7fea5aedf970c1d7e00b Mon Sep 17 00:00:00 2001 From: cathleeny <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:16:18 +0000 Subject: [PATCH 2/3] docs(changelog): mark OAuth provider constructor change as breaking Label the constructor signature change as a Rust API break, as v1.2.0 did for TelemetryConfig::enabled, and note the invalid_state error after the client is dropped. Signed-off-by: cathleeny <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 66308813..8577a424 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,10 +20,12 @@ changes go in their respective binding's NEXT_CHANGELOG. with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. -- `ClientCredentialsProvider`, `JwtClientCredentialsProvider` and - `AuthorizationCodeProvider` constructors take `&Arc` - and hold it weakly, matching `FederationProvider`. Callers must keep the - client alive for as long as they use the provider. +- **Breaking (Rust API):** `ClientCredentialsProvider`, + `JwtClientCredentialsProvider` and `AuthorizationCodeProvider` constructors + take `&Arc` instead of `Arc` and + hold it weakly, matching `FederationProvider`. Callers must keep the client + alive for as long as they use the provider; a token fetch after the client is + dropped fails with `invalid_state`. ### Updated From c7d6a36e9b767619a81f4ab43ed68e1faf37f7eb Mon Sep 17 00:00:00 2001 From: cathleeny <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:38:17 +0000 Subject: [PATCH 3/3] test(auth): assert invalid_state code on dropped HTTP client The changelog promises a token fetch after the client is dropped fails with invalid_state; check the error code, not only the message. Co-authored-by: Isaac Signed-off-by: cathleeny <58714163+cathleeny@users.noreply.github.com> --- src/auth/oauth/m2m.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 48dcd4c6..7c54e476 100644 --- a/src/auth/oauth/m2m.rs +++ b/src/auth/oauth/m2m.rs @@ -1206,6 +1206,7 @@ mod tests { let err = provider .get_auth_header() .expect_err("no HTTP client to fetch a token with"); + assert_eq!(err.code, Error::invalid_state().code); assert!( err.message.contains("no longer available"), "{}",