From 5d7f58f5c8e6a327584bb8daf8e6065146c8fcaa Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 21:54:06 +0000 Subject: [PATCH 1/8] feat(auth): add mandatory OIDC token exchange Exchange foreign-issuer JWTs for workspace tokens while passing through PATs and same-workspace tokens. Cache successful exchanges, coalesce concurrent callers, and fall back to the original token on exchange failures. Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 11 + src/auth/mod.rs | 2 +- src/auth/oauth/federation.rs | 524 +++++++++++++++++++++++++++++ src/auth/oauth/jwt.rs | 113 +++++++ src/auth/oauth/mod.rs | 3 + src/config.rs | 12 + src/session.rs | 41 ++- tests/token_federation_wiremock.rs | 444 ++++++++++++++++++++++++ 8 files changed, 1146 insertions(+), 4 deletions(-) create mode 100644 src/auth/oauth/federation.rs create mode 100644 src/auth/oauth/jwt.rs create mode 100644 tests/token_federation_wiremock.rs diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index d4f1aadb..64fe9e04 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -28,6 +28,17 @@ changes go in their respective binding's NEXT_CHANGELOG. value is ignored (default preserved) with a warning rather than failing session creation. The key is client-only — it is consumed before session creation and never reaches the SEA wire. Benefits ODBC too. +- Auth: mandatory OIDC token exchange (BYOT federation) — when an authenticated + token was issued by a party other than the target workspace (Azure AD, an external + IdP, a Bring-Your-Own-Token, or a Workload Identity Federation token), the kernel + now exchanges it for an in-house Databricks token at `/oidc/v1/token` before + using it, transparently across PAT / M2M / U2M. Gated by the token's `iss` claim + (non-JWT and same-host tokens pass through with no HTTP call) and falls back to the + original token if the exchange fails, so existing flows are unaffected. New optional + `SessionConfig::identity_federation_client_id` (and matching + `SessionBuilder::identity_federation_client_id`) selects SP-wide WIF; unset means + BYOT / account-wide WIF. Follows the ADBC wire contract + (`grant_type=jwt-bearer`, `assertion`, `scope=sql`). ### Updated diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 69b36131..5f200f13 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -19,7 +19,7 @@ pub mod oauth; pub mod pat; pub use config::{AuthConfig, AuthType}; -pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider}; +pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider}; pub use pat::PersonalAccessToken; use crate::kernel_error::Result; diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs new file mode 100644 index 00000000..0cca64d1 --- /dev/null +++ b/src/auth/oauth/federation.rs @@ -0,0 +1,524 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mandatory OIDC token exchange (BYOT federation). +//! +//! [`FederationProvider`] wraps another [`AuthProvider`] and, when the inner +//! provider yields a JWT that was **not** issued by the target Databricks +//! workspace (Azure AD, an external IdP, a Bring-Your-Own-Token, or a Workload +//! Identity Federation token), exchanges it for an in-house Databricks OAuth +//! token at the workspace `/oidc/v1/token` endpoint before it is used on any +//! Databricks API. +//! +//! # When the exchange fires +//! +//! Gated entirely by the inner token's `iss` claim vs. the workspace host, so +//! it is free for the common cases: +//! +//! - PAT (`dapi…`) tokens are not JWTs → pass through, no HTTP call. +//! - Same-host M2M / U2M tokens → `iss == host` → pass through, no HTTP call. +//! - Only genuinely foreign-issuer JWTs are exchanged. +//! +//! # Non-breaking fallback +//! +//! If the exchange fails for any reason, the original token is used instead of +//! surfacing an error. This matches the BYOT spec ("in order to not break +//! existing use cases … if any failure happens we will continue with the +//! existing JWT token instead of throwing right away"). +//! +//! # Wire contract +//! +//! ```text +//! POST {host}/oidc/v1/token +//! Accept: */* +//! Content-Type: application/x-www-form-urlencoded +//! +//! grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer +//! assertion = +//! scope = sql +//! # exactly one of: +//! identity_federation_client_id = (SP-wide WIF) +//! return_original_token_if_authenticated = true (BYOT / account-wide WIF) +//! ``` + +use crate::auth::oauth::jwt; +use crate::auth::oauth::token::OAuthToken; +use crate::auth::AuthProvider; +use crate::client::http::DatabricksHttpClient; +use crate::client::retry::RequestType; +use crate::kernel_error::{Error, Result}; +use crate::klog::{debug, warn}; +use crate::util::runtime::block_on_in_runtime; +use serde::Deserialize; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; +use std::time::Duration; +use tokio::runtime::{Handle as RuntimeHandle, RuntimeFlavor}; + +const TOKEN_EXCHANGE_PATH: &str = "/oidc/v1/token"; +const GRANT_TYPE_JWT_BEARER: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + +/// The token-exchange response fields we consume. +#[derive(Debug, Deserialize)] +struct ExchangeResponse { + access_token: String, + #[serde(default = "default_token_type")] + token_type: String, + /// Lifetime in seconds. Defaults to one hour when the server omits it, + /// matching the M2M provider's handling. + #[serde(default = "default_expires_in")] + expires_in: i64, +} + +fn default_token_type() -> String { + "Bearer".to_string() +} + +fn default_expires_in() -> i64 { + 3600 +} + +/// An [`AuthProvider`] decorator that performs mandatory token exchange for +/// foreign-issuer JWTs. See the [module docs](self). +#[derive(Debug)] +pub struct FederationProvider { + /// The wrapped provider that yields the source token. + inner: Arc, + /// Full token-exchange endpoint URL: `{host}/oidc/v1/token`. + token_endpoint: String, + /// The workspace host (bare `host[:port]`) used to decide whether an + /// issuer is in-house. + workspace_host: String, + /// SP-wide Workload Identity Federation client id. `None` → BYOT / + /// account-wide WIF, where the exchange sends + /// `return_original_token_if_authenticated=true` instead. + identity_federation_client_id: Option, + /// Shared HTTP client used for the exchange request. + http_client: Arc, + /// Runtime handle captured at construction so the sync `get_auth_header` + /// can drive the async exchange (see [`block_on_in_runtime`]). + runtime_handle: RuntimeHandle, + /// The most recent exchange result, as `(source_token, exchanged)`. A + /// provider tracks exactly one active source token at a time, so a single + /// slot suffices: when the upstream credential rotates the slot is replaced + /// (keyed on the source token), and an expired exchanged token is + /// re-exchanged. Holding the source token lets a cache-hit compare directly + /// without hashing on the hot path. + cache: RwLock>, + /// Single-flight leader-election flag. When a cache miss needs an exchange, + /// exactly one caller flips this `false → true` and performs the network + /// call; the others poll [`Self::cache`] until it clears (see + /// `exchanged_or_original`). Mirrors the kernel's `TokenStore` refresh + /// coordination so concurrent callers on a rotated / expired token don't + /// each mint a distinct server token (which SP-wide WIF would otherwise do). + exchanging: AtomicBool, +} + +/// How long a follower sleeps between polls while the leader runs the exchange. +/// Matches `TokenStore`'s 1ms refresh-wait cadence. +const FOLLOWER_POLL_INTERVAL: Duration = Duration::from_millis(1); + +/// A cached exchange outcome: the source token it was derived from, and the +/// resulting in-house token. +#[derive(Debug)] +struct CacheEntry { + source_token: String, + exchanged: OAuthToken, +} + +impl FederationProvider { + /// Wraps `inner` with mandatory token exchange against `host`. + /// + /// `host` is the workspace URL (e.g. + /// `https://my-workspace.cloud.databricks.com`); it is used to build the + /// exchange endpoint and to recognize in-house issuers. `async` so it can + /// capture the current tokio runtime handle, matching the other OAuth + /// providers. + pub async fn new( + inner: Arc, + host: &str, + identity_federation_client_id: Option, + http_client: Arc, + ) -> Result { + let host = host.trim_end_matches('/'); + Ok(Self { + inner, + token_endpoint: format!("{host}{TOKEN_EXCHANGE_PATH}"), + workspace_host: host_of(host).unwrap_or_default(), + identity_federation_client_id, + http_client, + runtime_handle: RuntimeHandle::current(), + cache: RwLock::new(None), + exchanging: AtomicBool::new(false), + }) + } + + /// Whether a token with issuer `iss` needs exchange (i.e. it is foreign to + /// this workspace). An unparseable / empty issuer host is treated as "same + /// host" (no exchange) so malformed values fall back to pass-through. + fn issuer_is_foreign(&self, iss: &str) -> bool { + match host_of(iss) { + Some(issuer_host) => !issuer_host.eq_ignore_ascii_case(&self.workspace_host), + None => false, + } + } + + /// 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 mut form: Vec<(&str, &str)> = vec![ + ("grant_type", GRANT_TYPE_JWT_BEARER), + ("assertion", source_token), + ("scope", "sql"), + ]; + // `identity_federation_client_id` and + // `return_original_token_if_authenticated` are mutually exclusive: the + // server ignores the latter when the former is present. + match self.identity_federation_client_id.as_deref() { + Some(client_id) => form.push(("identity_federation_client_id", client_id)), + None => form.push(("return_original_token_if_authenticated", "true")), + } + + let request = self + .http_client + .inner() + .post(&self.token_endpoint) + .header("Accept", "*/*") + .form(&form) + .build() + .map_err(|e| { + Error::invalid_argument() + .message(format!("Failed to build token-exchange request: {e}")) + })?; + + // No auth header: the request authenticates via the `assertion`, not + // the kernel bearer. `AuthTokenRequest` is idempotent, so the + // Auth-category ladder retries with backoff on all 5xx / 429 / 408 and + // timeouts — everything except the fixed non-retryable 4xx set. + let response = self + .http_client + .execute_without_auth(request, RequestType::AuthTokenRequest) + .await?; + + let body: ExchangeResponse = response.json().await.map_err(|e| { + Error::unauthenticated() + .message(format!("Failed to parse token-exchange response: {e}")) + })?; + + Ok(OAuthToken::new( + body.access_token, + body.token_type, + body.expires_in, + None, + vec!["sql".to_string()], + )) + } + + /// Resolves the token to use: the cached/exchanged in-house token on + /// success, or `source_token` unchanged on any failure. + /// + /// **No lock is ever held across the network call.** A cache hit returns + /// under a short read lock. On a miss, callers coalesce single-flight + /// (mirroring the kernel's `TokenStore`): exactly one *leader* wins a + /// lock-free `AtomicBool` election and runs the exchange, publishing the + /// outcome to the cache slot; *followers* sleep-poll the slot until the + /// leader clears the flag, then read the published result. This matters + /// because on a rotated / expired token a busy session can miss on many + /// threads at once, and for SP-wide WIF each redundant exchange would mint a + /// *distinct* server token — coalescing keeps it to one. The Auth-category + /// retry budget (see `build_retry_configs_for_session`: 30s / 3 retries, not + /// the global ladder) bounds the leader's latency. + fn exchanged_or_original(&self, source_token: &str) -> String { + // Fast path: a fresh cached exchange for this exact source token. + if let Some(hit) = self.cached_for(source_token) { + return hit; + } + + // The exchange bridges sync→async via `block_on_in_runtime`, which uses + // `block_in_place` when a runtime is current — that panics on a + // *current-thread* runtime. Every shipped consumer (pyo3, napi, the C + // ABI) drives the kernel on a multi-thread runtime, but a caller on a + // current-thread runtime would otherwise crash here. Detect that case + // and fall back to the original token rather than panicking — the same + // non-breaking posture as an exchange failure. + if matches!( + self.runtime_handle.runtime_flavor(), + RuntimeFlavor::CurrentThread + ) { + warn!( + "Token federation: skipping exchange on a current-thread runtime \ + (cannot block safely); using original token" + ); + return source_token.to_string(); + } + + // Single-flight election. Winner performs the exchange; losers wait. + if self + .exchanging + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_ok() + { + // Leader. RAII guard clears the flag even if the exchange panics, + // so followers can never spin forever. + let _guard = ExchangeGuard { + exchanging: &self.exchanging, + }; + self.lead_exchange(source_token) + } else { + // Follower: wait for the leader to publish, then read the result. + self.follow_exchange(source_token) + } + } + + /// Leader path: run the exchange (no lock held) and publish the outcome. + /// On failure, publish the original token so followers read the same + /// non-breaking fallback (spec: continue with the existing token rather + /// than throwing). + fn lead_exchange(&self, source_token: &str) -> String { + // Re-check under the flag: a leader that just cleared the flag may have + // published a result for this exact source token between our miss and + // our election win. + if let Some(hit) = self.cached_for(source_token) { + return hit; + } + + match block_on_in_runtime(&self.runtime_handle, self.exchange(source_token)) { + Ok(token) => { + let access_token = token.access_token.clone(); + self.store(source_token, token); + debug!("Token federation: exchanged foreign-issuer token for in-house token"); + access_token + } + Err(e) => { + warn!( + "Token federation: exchange failed, falling back to original token: {}", + e + ); + // Publish the original (short-lived) so a burst with the same + // source doesn't hammer the endpoint, and so followers read the + // same fallback rather than spinning to their timeout. + self.store(source_token, Self::fallback_token(source_token)); + source_token.to_string() + } + } + } + + /// Follower path: poll until the leader clears the flag, then return the + /// published result for our source token. If the slot ends up holding a + /// *different* source token (the upstream credential rotated while we + /// waited) or nothing usable, fall back to the original token rather than + /// returning someone else's — correctness over a marginal extra exchange. + fn follow_exchange(&self, source_token: &str) -> String { + // Bound the wait so a wedged leader can't hang a follower indefinitely; + // the leader's own latency is capped by the Auth retry budget (~30s), + // so a comfortably larger ceiling only trips on a genuine stall. + let deadline = std::time::Instant::now() + Duration::from_secs(60); + while self.exchanging.load(Ordering::SeqCst) { + if std::time::Instant::now() >= deadline { + warn!( + "Token federation: timed out waiting for in-flight exchange; \ + using original token" + ); + return source_token.to_string(); + } + std::thread::sleep(FOLLOWER_POLL_INTERVAL); + } + // Leader has finished. Use its published result if it is for our source + // token; otherwise fall back (don't start a fresh exchange from a + // follower — keeps this path simple and still non-breaking). + self.cached_for(source_token) + .unwrap_or_else(|| source_token.to_string()) + } + + /// Returns the cached access token if the slot holds a non-expired entry + /// for `source_token`, else `None`. A brief read lock, no network. + fn cached_for(&self, source_token: &str) -> Option { + let cache = self.cache.read().ok()?; + let entry = cache.as_ref()?; + (entry.source_token == source_token && !entry.exchanged.is_expired()) + .then(|| entry.exchanged.access_token.clone()) + } + + /// The short-lived fallback entry: the original token wrapped so followers + /// and subsequent callers reuse it briefly instead of re-hitting a failing + /// endpoint on every request. + fn fallback_token(source_token: &str) -> OAuthToken { + OAuthToken::new( + source_token.to_string(), + "Bearer".to_string(), + 60, + None, + vec![], + ) + } + + /// Replace the single cache slot with the outcome for `source_token`. + /// A brief write lock; never held across a network call. + fn store(&self, source_token: &str, exchanged: OAuthToken) { + if let Ok(mut cache) = self.cache.write() { + *cache = Some(CacheEntry { + source_token: source_token.to_string(), + exchanged, + }); + } + } +} + +/// RAII guard that clears the single-flight flag on drop, so a leader that +/// panics or early-returns can't leave followers polling forever. Mirrors +/// `TokenStore`'s `RefreshGuard`. +struct ExchangeGuard<'a> { + exchanging: &'a AtomicBool, +} + +impl Drop for ExchangeGuard<'_> { + fn drop(&mut self) { + self.exchanging.store(false, Ordering::SeqCst); + } +} + +impl AuthProvider for FederationProvider { + fn get_auth_header(&self) -> Result { + let header = self.inner.get_auth_header()?; + + // The inner header is `Bearer `. Only bearer JWTs are + // candidates for exchange; anything else passes through unchanged. + let Some(source_token) = header.strip_prefix("Bearer ") else { + return Ok(header); + }; + + // Re-check the issuer on every call (rather than trusting a cached + // decision) so a fresher in-house token from the inner provider is + // never shadowed by a stale exchange. + match jwt::issuer(source_token) { + Some(iss) if self.issuer_is_foreign(&iss) => { + let token = self.exchanged_or_original(source_token); + Ok(format!("Bearer {token}")) + } + // Not a JWT, or issued by this workspace: use as-is. + _ => Ok(header), + } + } +} + +/// Extracts the bare `host[:port]` from a URL-ish string, lowercased. Accepts +/// values with or without a scheme (JWT `iss` claims and workspace hosts both +/// occur in both forms). Returns `None` if no host can be found. +/// +/// Avoids pulling in a URL-parsing dependency: the kernel already normalizes +/// hosts with plain string ops (see `ConnectionConfig::normalise_host`), and +/// we only need the authority component for a host comparison. +fn host_of(url: &str) -> Option { + // Strip scheme if present. + let after_scheme = match url.find("://") { + Some(idx) => &url[idx + 3..], + None => url, + }; + // Authority ends at the first '/', '?', or '#'. + let authority = after_scheme + .split(['/', '?', '#']) + .next() + .unwrap_or(after_scheme); + // Drop userinfo if present (`user:pass@host`). + let host_port = authority.rsplit('@').next().unwrap_or(authority); + if host_port.is_empty() { + None + } else { + Some(host_port.to_ascii_lowercase()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_of_handles_scheme_and_path() { + assert_eq!( + host_of("https://adb-123.4.azuredatabricks.net/oidc").as_deref(), + Some("adb-123.4.azuredatabricks.net") + ); + assert_eq!( + host_of("adb-123.4.azuredatabricks.net").as_deref(), + Some("adb-123.4.azuredatabricks.net") + ); + assert_eq!( + host_of("https://host.example.com:443/path?q=1").as_deref(), + Some("host.example.com:443") + ); + assert_eq!(host_of("").as_deref(), None); + } + + #[test] + fn host_of_lowercases() { + assert_eq!( + host_of("https://ADB-123.Azuredatabricks.NET/oidc").as_deref(), + Some("adb-123.azuredatabricks.net") + ); + } + + /// A provider stub whose `get_auth_header` returns a canned value. + #[derive(Debug)] + struct StubProvider(String); + impl AuthProvider for StubProvider { + fn get_auth_header(&self) -> Result { + Ok(self.0.clone()) + } + } + + fn provider_for(host: &str, inner_header: &str) -> FederationProvider { + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(Default::default()).expect("http client"), + ); + let host = host.trim_end_matches('/'); + FederationProvider { + inner: Arc::new(StubProvider(inner_header.to_string())), + token_endpoint: format!("{host}{TOKEN_EXCHANGE_PATH}"), + workspace_host: host_of(host).unwrap_or_default(), + identity_federation_client_id: None, + http_client, + runtime_handle: RuntimeHandle::current(), + cache: RwLock::new(None), + exchanging: AtomicBool::new(false), + } + } + + // These use `provider_for`, which calls `RuntimeHandle::current()`, so + // they must run inside a tokio runtime even though the assertions + // themselves are synchronous. + #[tokio::test(flavor = "multi_thread")] + async fn issuer_same_host_is_not_foreign() { + let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); + assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com/oidc")); + } + + #[tokio::test(flavor = "multi_thread")] + async fn issuer_other_host_is_foreign() { + let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); + assert!(p.issuer_is_foreign("https://login.microsoftonline.com/tenant/v2.0")); + } + + #[tokio::test(flavor = "multi_thread")] + async fn non_bearer_header_passes_through() { + let p = provider_for("https://ws.cloud.databricks.com", "Basic abc123"); + assert_eq!(p.get_auth_header().unwrap(), "Basic abc123"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn non_jwt_pat_passes_through() { + // `dapi…` is not a JWT → no issuer → pass through, no HTTP call. + let p = provider_for("https://ws.cloud.databricks.com", "Bearer dapiabc123"); + assert_eq!(p.get_auth_header().unwrap(), "Bearer dapiabc123"); + } +} diff --git a/src/auth/oauth/jwt.rs b/src/auth/oauth/jwt.rs new file mode 100644 index 00000000..e2779cfd --- /dev/null +++ b/src/auth/oauth/jwt.rs @@ -0,0 +1,113 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Minimal JWT claim inspection for token federation. +//! +//! Token federation needs to read the `iss` (issuer) claim of an access +//! token to decide whether it was minted by the target Databricks workspace +//! (pass through) or by a foreign identity provider (exchange it for an +//! in-house token). See [`crate::auth::oauth::federation`]. +//! +//! This module intentionally does **not** verify the JWT signature. The +//! workspace validates the token on the exchange call; here we only peek at +//! the payload to route the decision. Doing our own verification would +//! require the issuer's signing keys and add a JWT dependency for no benefit. + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use serde::Deserialize; + +/// The subset of JWT payload claims federation cares about. +#[derive(Debug, Deserialize)] +struct Claims { + /// Issuer — the party that minted the token, e.g. + /// `https:///oidc` for an in-house Databricks token. + iss: Option, +} + +/// Decodes the payload of a JWT without verifying its signature and returns +/// the `iss` claim. +/// +/// Returns `None` when the input is not a well-formed JWT (e.g. a PAT +/// `dapi…` token, or any opaque string), when the payload is not valid JSON, +/// or when the `iss` claim is absent or empty. Callers treat `None` as "not a +/// federatable token — use it as-is". +pub(crate) fn issuer(token: &str) -> Option { + // A JWT is `header.payload.signature`; the payload is the middle segment. + let payload_b64 = token.split('.').nth(1)?; + let payload_bytes = URL_SAFE_NO_PAD.decode(payload_b64).ok()?; + let claims: Claims = serde_json::from_slice(&payload_bytes).ok()?; + claims.iss.filter(|iss| !iss.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Builds a JWT-shaped string `header.payload.signature` where the payload + /// is `claims` serialized and base64url-encoded (no padding). The header + /// and signature segments are arbitrary since we never inspect them. + fn jwt_with_payload(claims: serde_json::Value) -> String { + let payload = URL_SAFE_NO_PAD.encode(claims.to_string()); + format!("header.{payload}.signature") + } + + #[test] + fn extracts_issuer() { + let token = jwt_with_payload(serde_json::json!({ + "iss": "https://adb-123.4.azuredatabricks.net/oidc", + "exp": 1_736_274_838i64, + })); + assert_eq!( + issuer(&token).as_deref(), + Some("https://adb-123.4.azuredatabricks.net/oidc") + ); + } + + #[test] + fn missing_issuer_claim_is_none() { + let token = jwt_with_payload(serde_json::json!({ "exp": 1_736_274_838i64 })); + assert_eq!(issuer(&token), None); + } + + #[test] + fn empty_issuer_claim_is_none() { + let token = jwt_with_payload(serde_json::json!({ "iss": "" })); + assert_eq!(issuer(&token), None); + } + + #[test] + fn non_jwt_pat_token_is_none() { + // A Databricks PAT is an opaque `dapi…` string, not a JWT. + assert_eq!(issuer("dapi1234567890abcdef"), None); + } + + #[test] + fn two_segment_string_is_none() { + assert_eq!(issuer("header.payload"), None); + } + + #[test] + fn garbage_payload_is_none() { + // Middle segment is not valid base64url / not JSON. + assert_eq!(issuer("header.!!!not-base64!!!.sig"), None); + } + + #[test] + fn valid_base64_but_not_json_is_none() { + let payload = URL_SAFE_NO_PAD.encode("this is not json"); + let token = format!("header.{payload}.sig"); + assert_eq!(issuer(&token), None); + } +} diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index e3918961..24021d84 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -24,6 +24,8 @@ pub mod cache; pub(crate) mod cache_crypto; pub mod callback; +pub mod federation; +pub(crate) mod jwt; pub mod m2m; pub mod oidc; pub mod token; @@ -33,6 +35,7 @@ pub mod u2m; // Re-export the main types pub use cache::TokenCache; pub use callback::CallbackServer; +pub use federation::FederationProvider; pub use m2m::ClientCredentialsProvider; pub use oidc::OidcEndpoints; pub use token::OAuthToken; diff --git a/src/config.rs b/src/config.rs index b53c5487..4f09b8f7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1144,6 +1144,18 @@ pub struct SessionConfig { /// Required: how to authenticate. pub auth: AuthConfig, + /// SP-wide Workload Identity Federation client id, for mandatory OIDC + /// token exchange (BYOT federation). When the authenticated token was + /// issued by a party other than this workspace, the kernel exchanges it + /// for an in-house Databricks token at `/oidc/v1/token`; this value, + /// when set, is sent as `identity_federation_client_id` (SP-wide WIF). + /// `None` → BYOT / account-wide WIF, where + /// `return_original_token_if_authenticated=true` is sent instead. The + /// exchange itself is always attempted (gated only by the token's issuer), + /// and falls back to the original token on failure, so this field is not a + /// feature toggle. See `auth::oauth::federation`. + pub identity_federation_client_id: Option, + /// Server-bound session conf. Maps to SEA `session_confs` / /// Thrift `configuration`. Typed sub-structs above translate /// the *client-side* knobs; this map carries everything else. diff --git a/src/session.rs b/src/session.rs index b7199fe7..31eb2c33 100644 --- a/src/session.rs +++ b/src/session.rs @@ -46,7 +46,8 @@ //! requires catalog-managed tables server-side). use crate::auth::{ - AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, PersonalAccessToken, + AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider, + PersonalAccessToken, }; use crate::client::http::TlsConfig as HttpTlsConfig; use crate::client::retry::{ @@ -304,8 +305,13 @@ 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?; + let auth_provider: Arc = build_auth_provider( + &config.auth, + &host, + config.identity_federation_client_id.clone(), + http_client.clone(), + ) + .await?; http_client.set_auth_provider(auth_provider); // 3. Transport. Two-phase: SeaRestTransport needs an @@ -653,6 +659,7 @@ impl Session { pub struct SessionBuilder { connection: Option, auth: Option, + identity_federation_client_id: Option, defaults: Option, http: Option, proxy: Option, @@ -714,6 +721,14 @@ impl SessionBuilder { self } + /// SP-wide Workload Identity Federation client id for mandatory OIDC + /// token exchange (BYOT federation). Optional: leave unset for BYOT / + /// account-wide WIF. See [`SessionConfig::identity_federation_client_id`]. + pub fn identity_federation_client_id(mut self, client_id: impl Into) -> Self { + self.identity_federation_client_id = Some(client_id.into()); + self + } + /// Default catalog / schema applied to statements that don't /// override. pub fn defaults(mut self, defaults: DefaultOpts) -> Self { @@ -827,6 +842,7 @@ impl SessionBuilder { connection, defaults: self.defaults, auth, + identity_federation_client_id: self.identity_federation_client_id, session_conf: self.session_conf, http: self.http.unwrap_or_default(), proxy: self.proxy, @@ -1060,6 +1076,24 @@ fn result_to_post_process_options( /// Build the auth provider for a given [`AuthConfig`]. `host` is the /// workspace URL — used for OIDC discovery on M2M / U2M flows. async fn build_auth_provider( + auth: &AuthConfig, + host: &str, + identity_federation_client_id: Option, + 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 provider = + FederationProvider::new(base, host, identity_federation_client_id, http_client).await?; + Ok(Arc::new(provider)) +} + +/// Constructs the underlying credential provider for the configured auth flow, +/// before token-federation wrapping. +async fn build_base_auth_provider( auth: &AuthConfig, host: &str, http_client: Arc, @@ -1156,6 +1190,7 @@ mod retry_config_tests { auth: AuthConfig::Pat { token: "dapi-test".to_string(), }, + identity_federation_client_id: None, session_conf: Default::default(), http, proxy: None, diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs new file mode 100644 index 00000000..3ef391b9 --- /dev/null +++ b/tests/token_federation_wiremock.rs @@ -0,0 +1,444 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Integration tests for mandatory OIDC token exchange (BYOT federation). +//! +//! Exercises [`FederationProvider`] end-to-end against a mocked +//! `/oidc/v1/token` endpoint: foreign-issuer JWTs are exchanged, same-host and +//! non-JWT tokens pass through untouched, the WIF-vs-BYOT parameters are sent +//! correctly, and any exchange failure falls back to the original token. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use databricks_sql_kernel::auth::oauth::FederationProvider; +use databricks_sql_kernel::auth::{AuthProvider, PersonalAccessToken}; +use databricks_sql_kernel::client::http::{DatabricksHttpClient, HttpClientConfig}; +use databricks_sql_kernel::client::retry::{build_retry_configs, RetryConfig}; +use wiremock::matchers::{body_string_contains, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +/// Builds a JWT-shaped `header.payload.signature` string whose payload carries +/// the given `iss`. Header and signature are arbitrary — federation only reads +/// the payload's `iss` claim, without verifying the signature. +fn jwt_with_issuer(iss: &str) -> String { + let payload = URL_SAFE_NO_PAD.encode( + serde_json::json!({ + "iss": iss, + "exp": 4_102_444_800i64, // year 2100 + }) + .to_string(), + ); + format!("header.{payload}.signature") +} + +/// HTTP client with retries disabled so a mocked failure doesn't incur the +/// real backoff ladder (minutes of sleeps). +fn no_retry_http_client() -> Arc { + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .expect("http client"), + ) +} + +/// HTTP client with a small-but-real retry budget: enough retries that a +/// failing endpoint takes measurable wall-time per exchange, but bounded so a +/// test finishes quickly. Used to prove that a degraded `/oidc/v1/token` does +/// not serialize concurrent callers behind a shared lock. +fn bounded_retry_http_client() -> Arc { + let retry = RetryConfig { + min_wait: Duration::from_millis(200), + max_wait: Duration::from_millis(200), + max_retries: 2, // 3 attempts total + overall_timeout: Duration::from_secs(5), + ..RetryConfig::default() + }; + Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .expect("http client"), + ) +} + +/// Inner provider that yields `Bearer ` — `PersonalAccessToken` +/// formats exactly that, so it stands in for whatever base auth flow produced +/// the token. +fn inner_bearing(token: &str) -> Arc { + Arc::new(PersonalAccessToken::new(token)) +} + +fn exchange_response(access_token: &str) -> serde_json::Value { + serde_json::json!({ + "access_token": access_token, + "token_type": "Bearer", + "expires_in": 3600, + }) +} + +#[tokio::test(flavor = "multi_thread")] +async fn foreign_issuer_is_exchanged() { + let server = MockServer::start().await; + + // `:` in the grant_type is percent-encoded by the form encoder, so match + // on the stable tail plus the always-present `scope=sql`. + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .and(body_string_contains("grant-type%3Ajwt-bearer")) + .and(body_string_contains("scope=sql")) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("in-house-token"))) + .expect(1) + .mount(&server) + .await; + + let provider = FederationProvider::new( + inner_bearing(&jwt_with_issuer( + "https://login.microsoftonline.com/tenant/v2.0", + )), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, "Bearer in-house-token"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn same_host_issuer_passes_through() { + let server = MockServer::start().await; + + // Any hit on the exchange endpoint is a failure for this case. + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with( + ResponseTemplate::new(200).set_body_json(exchange_response("should-not-be-used")), + ) + .expect(0) + .mount(&server) + .await; + + // Issuer host == workspace host → already an in-house token. + let issuer = format!("{}/oidc", server.uri()); + let inner_token = jwt_with_issuer(&issuer); + + let provider = FederationProvider::new( + inner_bearing(&inner_token), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, format!("Bearer {inner_token}")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn non_jwt_pat_passes_through() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("nope"))) + .expect(0) + .mount(&server) + .await; + + let provider = FederationProvider::new( + inner_bearing("dapiabc123def456"), // opaque PAT, not a JWT + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, "Bearer dapiabc123def456"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn sp_wide_wif_sends_identity_federation_client_id() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .and(body_string_contains( + "identity_federation_client_id=my-sp-client-id", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("wif-token"))) + .expect(1) + .mount(&server) + .await; + + let provider = FederationProvider::new( + inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), + &server.uri(), + Some("my-sp-client-id".to_string()), + no_retry_http_client(), + ) + .await + .expect("provider"); + + assert_eq!(provider.get_auth_header().unwrap(), "Bearer wif-token"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn byot_sends_return_original_token_flag() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .and(body_string_contains( + "return_original_token_if_authenticated=true", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("byot-token"))) + .expect(1) + .mount(&server) + .await; + + let provider = FederationProvider::new( + inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), + &server.uri(), + None, // no client id → BYOT / account-wide WIF + no_retry_http_client(), + ) + .await + .expect("provider"); + + assert_eq!(provider.get_auth_header().unwrap(), "Bearer byot-token"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn exchange_http_401_falls_back_to_original() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(401).set_body_string(r#"{"error":"invalid_token"}"#)) + .mount(&server) + .await; + + let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let provider = FederationProvider::new( + inner_bearing(&inner_token), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + // Non-breaking fallback: the original token is used, no error surfaced. + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, format!("Bearer {inner_token}")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn exchange_http_500_falls_back_to_original() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(500).set_body_string("boom")) + .mount(&server) + .await; + + let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let provider = FederationProvider::new( + inner_bearing(&inner_token), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, format!("Bearer {inner_token}")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn exchanged_token_is_cached_across_calls() { + let server = MockServer::start().await; + + // Same source token on every call → exactly one exchange, then cache hits. + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("cached-token"))) + .expect(1) + .mount(&server) + .await; + + let provider = FederationProvider::new( + inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + for _ in 0..3 { + assert_eq!(provider.get_auth_header().unwrap(), "Bearer cached-token"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn representative_databricks_issuer_passes_through() { + // Non-circular version of the same-host case: use a realistic in-house + // Databricks issuer (`https:///oidc`) and a matching + // workspace host that is NOT the mock URI, proving the host comparison — + // scheme + `/oidc` path stripped — treats a real Databricks-issued token + // as in-house and skips the exchange. + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("unused"))) + .expect(0) + .mount(&server) + .await; + + let workspace = "https://adb-5484724900402942.2.azuredatabricks.net"; + let inner_token = jwt_with_issuer(&format!("{workspace}/oidc")); + + let provider = FederationProvider::new( + inner_bearing(&inner_token), + workspace, + None, + no_retry_http_client(), + ) + .await + .expect("provider"); + + // Same host (modulo scheme + `/oidc`) ⇒ pass through unchanged, no HTTP. + assert_eq!( + provider.get_auth_header().unwrap(), + format!("Bearer {inner_token}") + ); +} + +/// Spawn `n` concurrent `get_auth_header` callers on separate OS threads, each +/// entering the runtime context (get_auth_header is sync and blocks its thread). +/// Returns each caller's result. +fn concurrent_auth_headers( + provider: Arc, + n: usize, +) -> Vec> { + let handle = tokio::runtime::Handle::current(); + let threads: Vec<_> = (0..n) + .map(|_| { + let p = provider.clone(); + let h = handle.clone(); + std::thread::spawn(move || { + let _guard = h.enter(); + p.get_auth_header() + }) + }) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn concurrent_cold_callers_coalesce_to_one_exchange() { + // The real single-flight parity check (mirrors the M2M provider's + // `test_m2m_concurrent_token_fetch` and Go's federation concurrency test): + // N callers miss the cache simultaneously, but exactly ONE exchange hits + // the endpoint — the rest wait for the leader and read its published token. + // `.expect(1)` is what fails a regression that let every caller race; a + // wall-time bound would pass even if all N stampeded. + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("shared-token"))) + .expect(1) + .mount(&server) + .await; + + let provider = Arc::new( + FederationProvider::new( + inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), + &server.uri(), + None, + no_retry_http_client(), + ) + .await + .expect("provider"), + ); + + let results = concurrent_auth_headers(provider, 10); + + // Every caller gets the single exchanged token. + for r in &results { + assert_eq!(r.as_deref().unwrap(), "Bearer shared-token"); + } + // The `.expect(1)` on the mock verifies only one exchange occurred. +} + +#[tokio::test(flavor = "multi_thread")] +async fn degraded_endpoint_falls_back_for_all_concurrent_callers() { + // With retries ENABLED and the endpoint always failing, the single-flight + // leader exhausts its bounded retry budget and publishes the original-token + // fallback; followers read it. Every concurrent caller still returns the + // original token (non-breaking), and no caller surfaces an error. + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(503)) + .mount(&server) + .await; + + let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let provider = Arc::new( + FederationProvider::new( + inner_bearing(&inner_token), + &server.uri(), + None, + bounded_retry_http_client(), + ) + .await + .expect("provider"), + ); + + let start = Instant::now(); + let results = concurrent_auth_headers(provider, 8); + let elapsed = start.elapsed(); + + for r in &results { + assert_eq!(r.as_deref().unwrap(), format!("Bearer {inner_token}")); + } + // Coalesced: only the leader spends the retry budget (~0.4s); followers + // sleep-poll and return as soon as it publishes. A generous bound catches a + // regression where every caller ran the full failing ladder in parallel and + // still guards against accidental serialization. + assert!( + elapsed < Duration::from_secs(2), + "concurrent degraded-endpoint calls took {elapsed:?}; expected the leader \ + to bound the wait and followers to read its fallback" + ); +} From 4aadfc5a5c9d02c7c7a1a3fab25a46be0d2e5990 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 22:27:45 +0000 Subject: [PATCH 2/8] fix(auth): harden token federation edge cases Move follower waits off Tokio workers and normalize explicit default ports during issuer comparison. Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 54 ++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index 0cca64d1..0e797a18 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -276,8 +276,14 @@ impl FederationProvider { }; self.lead_exchange(source_token) } else { - // Follower: wait for the leader to publish, then read the result. - self.follow_exchange(source_token) + // Follower: the wait is synchronous, so tell tokio to move other + // tasks off this worker while the leader publishes its result. + match RuntimeHandle::try_current() { + Ok(handle) if matches!(handle.runtime_flavor(), RuntimeFlavor::MultiThread) => { + tokio::task::block_in_place(|| self.follow_exchange(source_token)) + } + _ => self.follow_exchange(source_token), + } } } @@ -421,9 +427,9 @@ impl AuthProvider for FederationProvider { /// we only need the authority component for a host comparison. fn host_of(url: &str) -> Option { // Strip scheme if present. - let after_scheme = match url.find("://") { - Some(idx) => &url[idx + 3..], - None => url, + let (scheme, after_scheme) = match url.find("://") { + Some(idx) => (&url[..idx], &url[idx + 3..]), + None => ("https", url), }; // Authority ends at the first '/', '?', or '#'. let authority = after_scheme @@ -432,6 +438,13 @@ fn host_of(url: &str) -> Option { .unwrap_or(after_scheme); // Drop userinfo if present (`user:pass@host`). let host_port = authority.rsplit('@').next().unwrap_or(authority); + let host_port = if scheme.eq_ignore_ascii_case("https") { + host_port.strip_suffix(":443").unwrap_or(host_port) + } else if scheme.eq_ignore_ascii_case("http") { + host_port.strip_suffix(":80").unwrap_or(host_port) + } else { + host_port + }; if host_port.is_empty() { None } else { @@ -455,11 +468,31 @@ mod tests { ); assert_eq!( host_of("https://host.example.com:443/path?q=1").as_deref(), - Some("host.example.com:443") + Some("host.example.com") ); assert_eq!(host_of("").as_deref(), None); } + #[test] + fn host_of_normalizes_only_default_ports() { + assert_eq!( + host_of("http://host.example.com:80").as_deref(), + Some("host.example.com") + ); + assert_eq!( + host_of("host.example.com:443").as_deref(), + Some("host.example.com") + ); + assert_eq!( + host_of("https://host.example.com:8443").as_deref(), + Some("host.example.com:8443") + ); + assert_eq!( + host_of("http://host.example.com:443").as_deref(), + Some("host.example.com:443") + ); + } + #[test] fn host_of_lowercases() { assert_eq!( @@ -503,6 +536,15 @@ mod tests { assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com/oidc")); } + #[tokio::test(flavor = "multi_thread")] + async fn issuer_same_host_ignores_explicit_default_port() { + let p = provider_for("https://ws.cloud.databricks.com:443", "Bearer x"); + assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com/oidc")); + + let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); + assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com:443/oidc")); + } + #[tokio::test(flavor = "multi_thread")] async fn issuer_other_host_is_foreign() { let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); From 8ae6c7f62557e4dde24d51043750d35479fd9a80 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 22:36:44 +0000 Subject: [PATCH 3/8] fix(auth): ignore ports in federation issuer comparison Match the Python and Go token federation providers by comparing parsed hostnames independently of port. Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 56 +++++++++++++----------------------- 1 file changed, 20 insertions(+), 36 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index 0e797a18..d9e1f07f 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -97,8 +97,7 @@ pub struct FederationProvider { inner: Arc, /// Full token-exchange endpoint URL: `{host}/oidc/v1/token`. token_endpoint: String, - /// The workspace host (bare `host[:port]`) used to decide whether an - /// issuer is in-house. + /// The workspace hostname used to decide whether an issuer is in-house. workspace_host: String, /// SP-wide Workload Identity Federation client id. `None` → BYOT / /// account-wide WIF, where the exchange sends @@ -418,38 +417,23 @@ impl AuthProvider for FederationProvider { } } -/// Extracts the bare `host[:port]` from a URL-ish string, lowercased. Accepts -/// values with or without a scheme (JWT `iss` claims and workspace hosts both -/// occur in both forms). Returns `None` if no host can be found. -/// -/// Avoids pulling in a URL-parsing dependency: the kernel already normalizes -/// hosts with plain string ops (see `ConnectionConfig::normalise_host`), and -/// we only need the authority component for a host comparison. +/// Extracts the hostname from a URL-ish string, lowercased and without its +/// port. Accepts values with or without a scheme and returns `None` if no host +/// can be found. fn host_of(url: &str) -> Option { - // Strip scheme if present. - let (scheme, after_scheme) = match url.find("://") { - Some(idx) => (&url[..idx], &url[idx + 3..]), - None => ("https", url), - }; - // Authority ends at the first '/', '?', or '#'. - let authority = after_scheme - .split(['/', '?', '#']) - .next() - .unwrap_or(after_scheme); - // Drop userinfo if present (`user:pass@host`). - let host_port = authority.rsplit('@').next().unwrap_or(authority); - let host_port = if scheme.eq_ignore_ascii_case("https") { - host_port.strip_suffix(":443").unwrap_or(host_port) - } else if scheme.eq_ignore_ascii_case("http") { - host_port.strip_suffix(":80").unwrap_or(host_port) + let normalized; + let url = if url.contains("://") { + url } else { - host_port + normalized = format!("https://{url}"); + &normalized }; - if host_port.is_empty() { - None - } else { - Some(host_port.to_ascii_lowercase()) - } + + reqwest::Url::parse(url) + .ok()? + .host_str() + .filter(|host| !host.is_empty()) + .map(str::to_ascii_lowercase) } #[cfg(test)] @@ -474,7 +458,7 @@ mod tests { } #[test] - fn host_of_normalizes_only_default_ports() { + fn host_of_ignores_ports() { assert_eq!( host_of("http://host.example.com:80").as_deref(), Some("host.example.com") @@ -485,11 +469,11 @@ mod tests { ); assert_eq!( host_of("https://host.example.com:8443").as_deref(), - Some("host.example.com:8443") + Some("host.example.com") ); assert_eq!( host_of("http://host.example.com:443").as_deref(), - Some("host.example.com:443") + Some("host.example.com") ); } @@ -537,12 +521,12 @@ mod tests { } #[tokio::test(flavor = "multi_thread")] - async fn issuer_same_host_ignores_explicit_default_port() { + async fn issuer_same_host_ignores_port() { let p = provider_for("https://ws.cloud.databricks.com:443", "Bearer x"); assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com/oidc")); let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); - assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com:443/oidc")); + assert!(!p.issuer_is_foreign("https://ws.cloud.databricks.com:8443/oidc")); } #[tokio::test(flavor = "multi_thread")] From 608214bc73ea918d9db0c7f460606f76419e603f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 23:09:57 +0000 Subject: [PATCH 4/8] fix(auth): preserve federation retry delay Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 25 ++++++++++++++++++++----- src/auth/oauth/token.rs | 2 +- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index d9e1f07f..cb5d9a33 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -53,7 +53,7 @@ //! ``` use crate::auth::oauth::jwt; -use crate::auth::oauth::token::OAuthToken; +use crate::auth::oauth::token::{OAuthToken, EXPIRY_BUFFER_SECONDS}; use crate::auth::AuthProvider; use crate::client::http::DatabricksHttpClient; use crate::client::retry::RequestType; @@ -128,6 +128,9 @@ pub struct FederationProvider { /// Matches `TokenStore`'s 1ms refresh-wait cadence. const FOLLOWER_POLL_INTERVAL: Duration = Duration::from_millis(1); +/// Delay before retrying a failed exchange for the same source token. +const FAILED_EXCHANGE_RETRY_DELAY_SECONDS: i64 = 60; + /// A cached exchange outcome: the source token it was derived from, and the /// resulting in-house token. #[derive(Debug)] @@ -355,14 +358,13 @@ impl FederationProvider { .then(|| entry.exchanged.access_token.clone()) } - /// The short-lived fallback entry: the original token wrapped so followers - /// and subsequent callers reuse it briefly instead of re-hitting a failing - /// endpoint on every request. + /// Cache the original token until the next failed-exchange retry. Add the + /// OAuth expiry buffer so it does not shorten the configured retry delay. fn fallback_token(source_token: &str) -> OAuthToken { OAuthToken::new( source_token.to_string(), "Bearer".to_string(), - 60, + FAILED_EXCHANGE_RETRY_DELAY_SECONDS + EXPIRY_BUFFER_SECONDS, None, vec![], ) @@ -485,6 +487,19 @@ mod tests { ); } + #[test] + fn fallback_cache_retries_after_configured_delay() { + let before = chrono::Utc::now(); + let fallback = FederationProvider::fallback_token("source-token"); + let after = chrono::Utc::now(); + let retry_at = fallback.expires_at - chrono::Duration::seconds(EXPIRY_BUFFER_SECONDS); + + assert!( + retry_at >= before + chrono::Duration::seconds(FAILED_EXCHANGE_RETRY_DELAY_SECONDS) + ); + assert!(retry_at <= after + chrono::Duration::seconds(FAILED_EXCHANGE_RETRY_DELAY_SECONDS)); + } + /// A provider stub whose `get_auth_header` returns a canned value. #[derive(Debug)] struct StubProvider(String); diff --git a/src/auth/oauth/token.rs b/src/auth/oauth/token.rs index f6cd2d65..dc7ceff4 100644 --- a/src/auth/oauth/token.rs +++ b/src/auth/oauth/token.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; /// Expiry buffer: tokens are considered expired when remaining TTL < 40 seconds. /// This 40s buffer matches the Python SDK and accounts for clock skew and network latency. /// Azure rejects tokens within 30s of expiry, so 40s provides a safe margin. -const EXPIRY_BUFFER_SECONDS: i64 = 40; +pub(super) const EXPIRY_BUFFER_SECONDS: i64 = 40; /// Maximum stale threshold: 20 minutes. /// The stale threshold is min(initial_TTL * 0.5, 20 minutes). From dbd90456cd675c8d3657db4afb3aa9365141a101 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 13 Aug 2026 15:55:14 +0000 Subject: [PATCH 5/8] refactor(auth): scope federation client id to auth Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 7 +- docs/designs/token-federation-design.md | 58 ++++---- docs/migration-plan.md | 4 +- napi/src/database.rs | 4 +- pyo3/src/auth.rs | 13 +- src/c_abi/session.rs | 5 +- src/config.rs | 169 ++++++++++++++++++---- src/lib.rs | 5 +- src/session.rs | 37 ++--- tests/common/mod.rs | 5 +- tests/klog_bridge.rs | 1 + tests/token_federation_wiremock.rs | 46 +++++- tests/v0_async_execute_e2e.rs | 5 +- tests/v0_async_execute_wiremock.rs | 1 + tests/v0_execute_e2e.rs | 10 +- tests/v0_execute_wiremock.rs | 2 + tests/v0_logging_wiremock.rs | 2 + tests/v0_metadata_e2e.rs | 5 +- tests/v0_metadata_wiremock.rs | 1 + tests/v0_query_tags_headers_e2e.rs | 10 +- tests/v0_session_e2e.rs | 12 +- tests/v0_session_wiremock.rs | 18 ++- tests/v0_statement_canceller_reexecute.rs | 1 + tests/v0_tls_e2e.rs | 6 +- tests/v0_transactions_e2e.rs | 5 +- 25 files changed, 328 insertions(+), 104 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 64fe9e04..50b12236 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -35,10 +35,9 @@ changes go in their respective binding's NEXT_CHANGELOG. using it, transparently across PAT / M2M / U2M. Gated by the token's `iss` claim (non-JWT and same-host tokens pass through with no HTTP call) and falls back to the original token if the exchange fails, so existing flows are unaffected. New optional - `SessionConfig::identity_federation_client_id` (and matching - `SessionBuilder::identity_federation_client_id`) selects SP-wide WIF; unset means - BYOT / account-wide WIF. Follows the ADBC wire contract - (`grant_type=jwt-bearer`, `assertion`, `scope=sql`). + `identity_federation_client_id` fields on the PAT, M2M, and U2M `AuthConfig` + variants select SP-wide WIF; unset means BYOT / account-wide WIF. Follows the + ADBC wire contract (`grant_type=jwt-bearer`, `assertion`, `scope=sql`). ### Updated diff --git a/docs/designs/token-federation-design.md b/docs/designs/token-federation-design.md index 92880833..f27dfaaf 100644 --- a/docs/designs/token-federation-design.md +++ b/docs/designs/token-federation-design.md @@ -131,7 +131,8 @@ provider construction is split into `build_auth_provider` (which wraps) and `build_base_auth_provider` (which matches the auth flow): ``` -build_auth_provider(auth, host, identity_federation_client_id, http_client) +build_auth_provider(auth, host, http_client) + ├── identity_federation_client_id = auth.identity_federation_client_id() ├── base = build_base_auth_provider(auth, host, http_client) │ └── match auth { Pat | OAuthM2M | OAuthU2M => existing construction } └── FederationProvider::new(base, host, identity_federation_client_id, http_client) @@ -192,11 +193,11 @@ We adapt `TokenStore`'s pattern in two ways it doesn't cover: the follower check the published entry is for **its** source token (if the upstream credential rotated mid-wait, it falls back rather than returning another token's result), and the leader **always publishes an outcome** — on failure it stores the original token -(short TTL) so followers read the same non-breaking fallback instead of spinning to -a timeout. On any exchange failure every caller uses the original token (spec: -"continue with the existing JWT token instead of throwing"). The leader's latency -is bounded by the **Auth-category retry budget** (30s / 3 retries — see -`build_retry_configs_for_session`), not the global ladder; followers additionally +with a 60-second retry delay so followers read the same non-breaking fallback +instead of spinning to a timeout. On any exchange failure every caller uses the +original token (spec: "continue with the existing JWT token instead of throwing"). +The leader's latency is bounded by the **Auth-category retry budget** (30s / 3 +retries — see `build_retry_configs_for_session`), not the global ladder; followers additionally cap their wait so a wedged leader can't hang them indefinitely. --- @@ -265,10 +266,10 @@ impl FederationProvider { the original token. 5. **Leader success** → store `(source, OAuthToken)` (from `expires_in`), return `Bearer `. - **Leader failure** → log at `warn!`, store the original token (short TTL) so - followers and subsequent callers read the same fallback instead of re-hitting a - failing endpoint, and **return the original `header`** (spec's non-breaking - fallback). The error is never surfaced to the caller. + **Leader failure** → log at `warn!`, store the original token with a 60-second + retry delay so followers and subsequent callers read the same fallback instead + of re-hitting a failing endpoint, and **return the original `header`** (spec's + non-breaking fallback). The error is never surfaced to the caller. `block_on_in_runtime` uses `block_in_place`, which panics on a **current-thread** runtime. Every shipped consumer (pyo3, napi, C ABI) drives the kernel on a @@ -297,24 +298,26 @@ Add `pub mod jwt;` and `pub mod federation;`; re-export `FederationProvider`. ### `src/config.rs` -One caller-facing field (no wrapper struct, no `enabled`): +The supported base-auth variants each carry the optional federation selector: ```rust -/// SP-wide Workload Identity Federation client id. `None` → BYOT / -/// account-wide WIF, where the exchange sends -/// `return_original_token_if_authenticated=true` instead. -pub identity_federation_client_id: Option, +AuthConfig::Pat { token, identity_federation_client_id } +AuthConfig::OAuthM2M { ..., identity_federation_client_id } +AuthConfig::OAuthU2M { ..., identity_federation_client_id } ``` -Placed on `SessionConfig` (top level, since it applies across PAT/M2M/U2M) and -threaded through the builder. +`None` selects BYOT / account-wide WIF, where the exchange sends +`return_original_token_if_authenticated=true`. The reserved +`AuthConfig::OAuthFederation` variant is unchanged: it represents a separate, +caller-supplied RFC 8693 flow and is not this mandatory decorator. ### `src/session.rs` Split provider construction into `build_auth_provider` (wraps) and `build_base_auth_provider` (matches the auth flow), as shown in -[Integration point](#integration-point). `SessionBuilder` gains an -`identity_federation_client_id(...)` setter, threaded onto `SessionConfig`. +[Integration point](#integration-point). `build_auth_provider` reads the +federation client id from the selected `AuthConfig` variant before wrapping the +base provider. ### `src/kernel_error.rs` @@ -322,20 +325,19 @@ No new variant. Exchange failures use existing `Error::unauthenticated()` / `Error::network_error()` for the `warn!` log only; they are swallowed into the fallback and never returned. -### Bindings — exposing `identity_federation_client_id` on every boundary +### Bindings — follow-up work The exchange itself works through all consumers unchanged (it is gated by the -token issuer, not config), but the SP-wide WIF *selector* must be reachable from -each surface, or Python / Node / ODBC / Go / C callers can only ever take the -BYOT / account-wide WIF branch. It is threaded through: +token issuer, not config). This core change leaves the bindings passing `None`; +a follow-up will expose the SP-wide WIF selector on each surface: -- **C ABI** (`src/c_abi/session.rs`, consumed by ODBC and Go): new +- **C ABI** (`src/c_abi/session.rs`, consumed by ODBC and Go): add a `kernel_session_config_set_identity_federation_client_id()` setter, stored on - `KernelSessionConfig` and forwarded to the builder; declared in + `KernelSessionConfig` and attached to the selected `AuthConfig`; declared in `include/databricks_kernel.h` (hand-written header). -- **pyo3** (`pyo3/src/session.rs`): new optional `identity_federation_client_id` - keyword on `Session(...)`. -- **napi** (`napi/src/database.rs`): new optional `identityFederationClientId` +- **pyo3** (`pyo3/src/session.rs`): add an optional + `identity_federation_client_id` keyword on `Session(...)`. +- **napi** (`napi/src/database.rs`): add an optional `identityFederationClientId` field on `ConnectionOptions`; the generated `napi/index.d.ts` is updated by hand. Each binding stages its own changelog entry (`pyo3/NEXT_CHANGELOG.md`, diff --git a/docs/migration-plan.md b/docs/migration-plan.md index 4bbf56c8..61899228 100644 --- a/docs/migration-plan.md +++ b/docs/migration-plan.md @@ -239,8 +239,8 @@ follow-ups in a later PR. ### PR 2 — Session **Goal.** -`Session::builder().http_path(host, http_path).auth(AuthConfig::Pat{token}).open().await` -returns a working session against a Databricks workspace. First +A session built with `AuthConfig::Pat { token, identity_federation_client_id: None }` +works against a Databricks workspace. First user-visible piece of the v0 surface; gives us a real E2E test. **What changes.** diff --git a/napi/src/database.rs b/napi/src/database.rs index ddf139df..a4a0a55e 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -355,12 +355,13 @@ pub struct ConnectionOptions { /// session. fn build_auth_config(options: &ConnectionOptions) -> napi::Result { match options.auth_mode.unwrap_or_default() { - AuthMode::Pat => AuthConfig::pat(options.token.clone()).map_err(napi_err_from_kernel), + AuthMode::Pat => AuthConfig::pat(options.token.clone(), None).map_err(napi_err_from_kernel), AuthMode::OAuthM2m => AuthConfig::oauth_m2m( options.oauth_client_id.clone(), options.oauth_client_secret.clone(), options.oauth_scopes.clone(), None, + None, ) .map_err(napi_err_from_kernel), // All U2M fields are optional. Default the OAuth client_id to @@ -399,6 +400,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { // binding exposes no passphrase option. Surfacing one through // `options` would strengthen it further. None, + None, )) } } diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index cca1c74c..8a57da60 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -131,7 +131,10 @@ fn build_auth_config_inner( if token.is_empty() { return Err("access_token must not be empty".to_owned()); } - Ok(AuthConfig::Pat { token }) + Ok(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) } "oauth-m2m" => { // Client credentials grant: both halves are mandatory. @@ -145,6 +148,7 @@ fn build_auth_config_inner( client_secret, scopes: oauth.scopes, token_url_override: oauth.token_url, + identity_federation_client_id: None, }) } "oauth-u2m" => { @@ -229,6 +233,7 @@ fn build_auth_config_inner( // passphrase through `OAuthParams` — the equivalent of JDBC's // TokenCachePassPhrase — would strengthen it further. token_cache: None, + identity_federation_client_id: None, }) } other => Err(format!( @@ -264,7 +269,7 @@ mod tests { fn pat_builds() { let cfg = build_auth_config_inner("pat", Some("dapi123".into()), OAuthParams::default()).unwrap(); - assert!(matches!(cfg, AuthConfig::Pat { token } if token == "dapi123")); + assert!(matches!(cfg, AuthConfig::Pat { token, .. } if token == "dapi123")); } #[test] @@ -327,11 +332,13 @@ mod tests { client_secret, scopes, token_url_override, + identity_federation_client_id, } => { assert_eq!(client_id, "id"); assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_string()])); assert_eq!(token_url_override.as_deref(), Some("https://example/token")); + assert!(identity_federation_client_id.is_none()); } other => panic!("expected OAuthM2M, got {other:?}"), } @@ -357,6 +364,7 @@ mod tests { token_url_override, callback_timeout, token_cache, + identity_federation_client_id, } => { assert_eq!(client_id.as_deref(), Some("databricks-sql-python")); assert!(redirect_port.is_none()); @@ -374,6 +382,7 @@ mod tests { token_cache.is_none(), "Python U2M should defer to the kernel's token-cache default" ); + assert!(identity_federation_client_id.is_none()); } other => panic!("expected OAuthU2M, got {other:?}"), } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index e6d5d8ad..4c46aa4f 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -926,11 +926,11 @@ fn build_session(config: KernelSessionConfig) -> Result AuthConfig::pat(Some(token))?, + AuthSpec::Pat { token } => AuthConfig::pat(Some(token), None)?, AuthSpec::OAuthM2M { client_id, client_secret, - } => AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, + } => AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None, None)?, AuthSpec::OAuthU2M { client_id, redirect_port, @@ -942,6 +942,7 @@ fn build_session(config: KernelSessionConfig) -> Result, + }, /// OAuth 2.0 machine-to-machine (client credentials grant). /// Used for service-principal authentication. @@ -309,6 +314,9 @@ pub enum AuthConfig { /// Token endpoint override. `None` → discover via OIDC at /// `/.well-known/oauth-authorization-server`. token_url_override: Option, + /// SP-wide Workload Identity Federation client id. `None` selects + /// BYOT / account-wide WIF behavior when token exchange is needed. + identity_federation_client_id: Option, }, /// OAuth 2.0 user-to-machine (authorization code + PKCE, browser @@ -336,6 +344,9 @@ pub enum AuthConfig { /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`] /// (enabled, which then requires a passphrase — see that type). token_cache: Option, + /// SP-wide Workload Identity Federation client id. `None` selects + /// BYOT / account-wide WIF behavior when token exchange is needed. + identity_federation_client_id: Option, }, /// OAuth 2.0 token exchange (RFC 8693), for federated identity @@ -367,9 +378,15 @@ impl AuthConfig { /// required-field check lives here so every wrapper rejects a /// missing/empty token identically (`ErrorCode::InvalidArgument`) /// instead of each re-implementing it at the binding boundary. - pub fn pat(token: Option) -> crate::Result { + pub fn pat( + token: Option, + identity_federation_client_id: Option, + ) -> crate::Result { match token { - Some(token) if !token.is_empty() => Ok(AuthConfig::Pat { token }), + Some(token) if !token.is_empty() => Ok(AuthConfig::Pat { + token, + identity_federation_client_id, + }), _ => Err(crate::kernel_error::Error::invalid_argument() .message("PAT auth requires a non-empty access token")), } @@ -384,6 +401,7 @@ impl AuthConfig { client_secret: Option, scopes: Option>, token_url_override: Option, + identity_federation_client_id: Option, ) -> crate::Result { let client_id = client_id.filter(|s| !s.is_empty()).ok_or_else(|| { crate::kernel_error::Error::invalid_argument() @@ -398,6 +416,7 @@ impl AuthConfig { client_secret, scopes, token_url_override, + identity_federation_client_id, }) } @@ -414,6 +433,7 @@ impl AuthConfig { token_url_override: Option, callback_timeout: Option, token_cache: Option, + identity_federation_client_id: Option, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -422,6 +442,26 @@ impl AuthConfig { token_url_override, callback_timeout, token_cache, + identity_federation_client_id, + } + } + + /// SP-wide federation client id attached to the selected base auth flow. + pub(crate) fn identity_federation_client_id(&self) -> Option<&str> { + match self { + Self::Pat { + identity_federation_client_id, + .. + } + | Self::OAuthM2M { + identity_federation_client_id, + .. + } + | Self::OAuthU2M { + identity_federation_client_id, + .. + } => identity_federation_client_id.as_deref(), + Self::OAuthFederation { .. } | Self::External(_) => None, } } } @@ -447,25 +487,47 @@ pub trait TokenProvider: Send + Sync { impl std::fmt::Debug for AuthConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Pat { .. } => f.write_str("Pat { token: }"), + Self::Pat { + identity_federation_client_id, + .. + } => f + .debug_struct("Pat") + .field("token", &"") + .field( + "identity_federation_client_id", + identity_federation_client_id, + ) + .finish(), Self::OAuthM2M { - client_id, scopes, .. + client_id, + scopes, + identity_federation_client_id, + .. } => f .debug_struct("OAuthM2M") .field("client_id", client_id) .field("client_secret", &"") .field("scopes", scopes) + .field( + "identity_federation_client_id", + identity_federation_client_id, + ) .finish(), Self::OAuthU2M { client_id, redirect_port, scopes, + identity_federation_client_id, .. } => f .debug_struct("OAuthU2M") .field("client_id", client_id) .field("redirect_port", redirect_port) .field("scopes", scopes) + .field( + "identity_federation_client_id", + identity_federation_client_id, + ) .finish(), Self::OAuthFederation { subject_token_type, @@ -1144,18 +1206,6 @@ pub struct SessionConfig { /// Required: how to authenticate. pub auth: AuthConfig, - /// SP-wide Workload Identity Federation client id, for mandatory OIDC - /// token exchange (BYOT federation). When the authenticated token was - /// issued by a party other than this workspace, the kernel exchanges it - /// for an in-house Databricks token at `/oidc/v1/token`; this value, - /// when set, is sent as `identity_federation_client_id` (SP-wide WIF). - /// `None` → BYOT / account-wide WIF, where - /// `return_original_token_if_authenticated=true` is sent instead. The - /// exchange itself is always attempted (gated only by the token's issuer), - /// and falls back to the original token on failure, so this field is not a - /// feature toggle. See `auth::oauth::federation`. - pub identity_federation_client_id: Option, - /// Server-bound session conf. Maps to SEA `session_confs` / /// Thrift `configuration`. Typed sub-structs above translate /// the *client-side* knobs; this map carries everything else. @@ -1509,42 +1559,70 @@ mod tests { #[test] fn pat_rejects_missing_or_empty_token() { - let err = AuthConfig::pat(None).unwrap_err(); + let err = AuthConfig::pat(None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("non-empty access token")); - let err = AuthConfig::pat(Some(String::new())).unwrap_err(); + let err = AuthConfig::pat(Some(String::new()), None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); } #[test] fn pat_accepts_non_empty_token() { - match AuthConfig::pat(Some("dapi-x".to_string())).unwrap() { - AuthConfig::Pat { token } => assert_eq!(token, "dapi-x"), + match AuthConfig::pat( + Some("dapi-x".to_string()), + Some("federation-client".to_string()), + ) + .unwrap() + { + AuthConfig::Pat { + token, + identity_federation_client_id, + } => { + assert_eq!(token, "dapi-x"); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); + } other => panic!("expected Pat, got {other:?}"), } } #[test] fn oauth_m2m_rejects_missing_or_empty_client_id() { - let err = AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None).unwrap_err(); + let err = + AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); - let err = AuthConfig::oauth_m2m(Some(String::new()), Some("sec".to_string()), None, None) - .unwrap_err(); + let err = AuthConfig::oauth_m2m( + Some(String::new()), + Some("sec".to_string()), + None, + None, + None, + ) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); } #[test] fn oauth_m2m_rejects_missing_or_empty_client_secret() { - let err = AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None).unwrap_err(); + let err = + AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); - let err = AuthConfig::oauth_m2m(Some("cid".to_string()), Some(String::new()), None, None) - .unwrap_err(); + let err = AuthConfig::oauth_m2m( + Some("cid".to_string()), + Some(String::new()), + None, + None, + None, + ) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); } @@ -1556,6 +1634,7 @@ mod tests { Some("sec".to_string()), Some(vec!["all-apis".to_string()]), None, + Some("federation-client".to_string()), ) .unwrap() { @@ -1564,16 +1643,50 @@ mod tests { client_secret, scopes, token_url_override, + identity_federation_client_id, } => { assert_eq!(client_id, "cid"); assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_string()])); assert!(token_url_override.is_none()); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthM2M, got {other:?}"), } } + #[test] + fn oauth_u2m_carries_identity_federation_client_id() { + let auth = AuthConfig::oauth_u2m( + None, + None, + None, + None, + None, + None, + Some("federation-client".to_string()), + ); + + assert_eq!( + auth.identity_federation_client_id(), + Some("federation-client") + ); + } + + #[test] + fn oauth_federation_has_no_mandatory_federation_client_id() { + let auth = AuthConfig::OAuthFederation { + subject_token: "subject-token".to_string(), + subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(), + audience: "audience".to_string(), + }; + + assert_eq!(auth.identity_federation_client_id(), None); + } + // ─── ConnectionConfig parsing ────────────────────────────────── #[test] @@ -1688,6 +1801,7 @@ mod tests { fn debug_pat_redacts_token() { let c = AuthConfig::Pat { token: "dapi_secret".to_string(), + identity_federation_client_id: None, }; let s = format!("{c:?}"); assert!(!s.contains("dapi_secret"), "token leaked: {s}"); @@ -1701,6 +1815,7 @@ mod tests { client_secret: "supersecret".to_string(), scopes: None, token_url_override: None, + identity_federation_client_id: None, }; let s = format!("{c:?}"); assert!(!s.contains("supersecret"), "secret leaked: {s}"); diff --git a/src/lib.rs b/src/lib.rs index 2e45d3dd..a2da2b4d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,7 +56,10 @@ //! "https://my-workspace.databricks.com", //! "abc123", //! )) -//! .auth(AuthConfig::Pat { token: "dapi...".into() }) +//! .auth(AuthConfig::Pat { +//! token: "dapi...".into(), +//! identity_federation_client_id: None, +//! }) //! .open() //! .await?; //! diff --git a/src/session.rs b/src/session.rs index 31eb2c33..3217309f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -305,13 +305,8 @@ impl Session { // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. - let auth_provider: Arc = build_auth_provider( - &config.auth, - &host, - config.identity_federation_client_id.clone(), - http_client.clone(), - ) - .await?; + let auth_provider: Arc = + build_auth_provider(&config.auth, &host, http_client.clone()).await?; http_client.set_auth_provider(auth_provider); // 3. Transport. Two-phase: SeaRestTransport needs an @@ -659,7 +654,6 @@ impl Session { pub struct SessionBuilder { connection: Option, auth: Option, - identity_federation_client_id: Option, defaults: Option, http: Option, proxy: Option, @@ -721,14 +715,6 @@ impl SessionBuilder { self } - /// SP-wide Workload Identity Federation client id for mandatory OIDC - /// token exchange (BYOT federation). Optional: leave unset for BYOT / - /// account-wide WIF. See [`SessionConfig::identity_federation_client_id`]. - pub fn identity_federation_client_id(mut self, client_id: impl Into) -> Self { - self.identity_federation_client_id = Some(client_id.into()); - self - } - /// Default catalog / schema applied to statements that don't /// override. pub fn defaults(mut self, defaults: DefaultOpts) -> Self { @@ -842,7 +828,6 @@ impl SessionBuilder { connection, defaults: self.defaults, auth, - identity_federation_client_id: self.identity_federation_client_id, session_conf: self.session_conf, http: self.http.unwrap_or_default(), proxy: self.proxy, @@ -1078,7 +1063,6 @@ fn result_to_post_process_options( async fn build_auth_provider( auth: &AuthConfig, host: &str, - identity_federation_client_id: Option, http_client: Arc, ) -> Result> { // Build the base provider for the configured auth flow, then wrap it with @@ -1086,8 +1070,13 @@ async fn build_auth_provider( // 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 provider = - FederationProvider::new(base, host, identity_federation_client_id, http_client).await?; + let provider = FederationProvider::new( + base, + host, + auth.identity_federation_client_id().map(str::to_owned), + http_client, + ) + .await?; Ok(Arc::new(provider)) } @@ -1099,7 +1088,7 @@ async fn build_base_auth_provider( http_client: Arc, ) -> Result> { match auth { - AuthConfig::Pat { token } => { + AuthConfig::Pat { token, .. } => { if token.is_empty() { return Err( Error::invalid_argument().message("AuthConfig::Pat token must not be empty") @@ -1112,6 +1101,7 @@ async fn build_base_auth_provider( client_secret, scopes, token_url_override, + .. } => { if client_id.is_empty() || client_secret.is_empty() { return Err(Error::invalid_argument().message( @@ -1139,6 +1129,7 @@ async fn build_base_auth_provider( token_url_override, callback_timeout, token_cache, + .. } => { let client_id = client_id.as_deref().unwrap_or("databricks-cli"); let redirect_port = redirect_port.unwrap_or(8020); @@ -1189,8 +1180,8 @@ mod retry_config_tests { defaults: None, auth: AuthConfig::Pat { token: "dapi-test".to_string(), + identity_federation_client_id: None, }, - identity_federation_client_id: None, session_conf: Default::default(), http, proxy: None, @@ -1589,6 +1580,7 @@ mod is_open_tests { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .open() .await @@ -1640,6 +1632,7 @@ mod is_open_tests { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) // ignore_transactions defaults to true; be explicit for the test. .defaults(DefaultOpts { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 1cf85fe6..d976b6e3 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -104,7 +104,10 @@ pub async fn live_session() -> Session { Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open against live workspace") diff --git a/tests/klog_bridge.rs b/tests/klog_bridge.rs index 2652cbed..efd36c7a 100644 --- a/tests/klog_bridge.rs +++ b/tests/klog_bridge.rs @@ -178,6 +178,7 @@ async fn empty_logging_config_open_does_not_install_subscriber() { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .http(http) .open() diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index 3ef391b9..3c58cb44 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -29,7 +29,8 @@ use databricks_sql_kernel::auth::oauth::FederationProvider; use databricks_sql_kernel::auth::{AuthProvider, PersonalAccessToken}; use databricks_sql_kernel::client::http::{DatabricksHttpClient, HttpClientConfig}; use databricks_sql_kernel::client::retry::{build_retry_configs, RetryConfig}; -use wiremock::matchers::{body_string_contains, method, path}; +use databricks_sql_kernel::{AuthConfig, ConnectionConfig, HttpConfig, Session}; +use wiremock::matchers::{body_string_contains, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; /// Builds a JWT-shaped `header.payload.signature` string whose payload carries @@ -208,6 +209,49 @@ async fn sp_wide_wif_sends_identity_federation_client_id() { assert_eq!(provider.get_auth_header().unwrap(), "Bearer wif-token"); } +#[tokio::test(flavor = "multi_thread")] +async fn auth_config_federation_client_id_reaches_exchange() { + let server = MockServer::start().await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .and(body_string_contains( + "identity_federation_client_id=my-sp-client-id", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(exchange_response("wif-token"))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .and(header("authorization", "Bearer wif-token")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "session_id": "session-id", + "warehouse_id": "warehouse-id", + }))) + .expect(1) + .mount(&server) + .await; + + let mut http = HttpConfig::default(); + http.retry_max_retries = 0; + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/warehouse-id") + .unwrap(), + ) + .auth(AuthConfig::Pat { + token: jwt_with_issuer("https://external-idp.example.com"), + identity_federation_client_id: Some("my-sp-client-id".to_string()), + }) + .http(http) + .open() + .await + .unwrap(); + + assert_eq!(session.session_id(), "session-id"); +} + #[tokio::test(flavor = "multi_thread")] async fn byot_sends_return_original_token_flag() { let server = MockServer::start().await; diff --git a/tests/v0_async_execute_e2e.rs b/tests/v0_async_execute_e2e.rs index c28c218c..38555daf 100644 --- a/tests/v0_async_execute_e2e.rs +++ b/tests/v0_async_execute_e2e.rs @@ -39,7 +39,10 @@ async fn live_session() -> Session { Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open against live workspace") diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 14cec455..b7f6e0a9 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -46,6 +46,7 @@ async fn open_session(server: &MockServer) -> Session { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .open() .await diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index b3293f00..18285a90 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -39,7 +39,10 @@ async fn live_session() -> Session { Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open against live workspace") @@ -862,7 +865,10 @@ async fn live_session_with_complex_json(complex_types_as_json: bool) -> Session Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .result(result) .open() .await diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 34d4a474..b9cd79a5 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -44,6 +44,7 @@ async fn open_session(server: &MockServer) -> Session { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .open() .await @@ -60,6 +61,7 @@ async fn open_session_with_result(server: &MockServer, result: ResultConfig) -> ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .result(result) .open() diff --git a/tests/v0_logging_wiremock.rs b/tests/v0_logging_wiremock.rs index 77edda6f..69705006 100644 --- a/tests/v0_logging_wiremock.rs +++ b/tests/v0_logging_wiremock.rs @@ -85,6 +85,7 @@ async fn logging_config_file_destination_is_written() { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .http(http) .logging(logging) @@ -122,6 +123,7 @@ async fn logging_config_file_destination_is_written() { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .http(http2) .logging(logging2) diff --git a/tests/v0_metadata_e2e.rs b/tests/v0_metadata_e2e.rs index c70a616c..c5b576b2 100644 --- a/tests/v0_metadata_e2e.rs +++ b/tests/v0_metadata_e2e.rs @@ -48,7 +48,10 @@ async fn live_session() -> Session { Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open against live workspace") diff --git a/tests/v0_metadata_wiremock.rs b/tests/v0_metadata_wiremock.rs index 25de939f..8bb1362c 100644 --- a/tests/v0_metadata_wiremock.rs +++ b/tests/v0_metadata_wiremock.rs @@ -55,6 +55,7 @@ async fn open_session(server: &MockServer) -> Session { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .open() .await diff --git a/tests/v0_query_tags_headers_e2e.rs b/tests/v0_query_tags_headers_e2e.rs index 07ba7399..07ca5a3d 100644 --- a/tests/v0_query_tags_headers_e2e.rs +++ b/tests/v0_query_tags_headers_e2e.rs @@ -62,7 +62,10 @@ async fn live_session() -> Session { let (host, path, token) = host_path_token(); Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open against live workspace") @@ -81,7 +84,10 @@ async fn live_session_with_headers(headers: Vec<(String, String)>) -> Session { http.custom_headers = headers; Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .http(http) .open() .await diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 958039b8..77af49bc 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -53,7 +53,10 @@ async fn open_with_pat_against_live_warehouse() { let session = Session::builder() .http_path(host, http_path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("Session::open should succeed against the live warehouse"); @@ -94,6 +97,7 @@ async fn open_with_oauth_m2m_against_live_warehouse() { client_secret, scopes: None, token_url_override: None, + identity_federation_client_id: None, }) .open() .await @@ -130,6 +134,7 @@ async fn open_with_oauth_u2m_against_live_warehouse() { enabled: false, passphrase: None, }), + identity_federation_client_id: None, }) .open() .await @@ -150,7 +155,10 @@ async fn open_drop_does_not_panic() { let session = Session::builder() .http_path(host, http_path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .open() .await .expect("open"); diff --git a/tests/v0_session_wiremock.rs b/tests/v0_session_wiremock.rs index f736cba8..b3452c97 100644 --- a/tests/v0_session_wiremock.rs +++ b/tests/v0_session_wiremock.rs @@ -47,6 +47,7 @@ async fn open_session_against(server: &MockServer) -> databricks_sql_kernel::Res ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .http(http) .open() @@ -231,7 +232,10 @@ async fn missing_auth_returns_invalid_argument() { async fn malformed_http_path_surfaces_at_open() { let err = Session::builder() .http_path("https://h", "/not/a/sql/path") - .auth(AuthConfig::Pat { token: "x".into() }) + .auth(AuthConfig::Pat { + token: "x".into(), + identity_federation_client_id: None, + }) .open() .await .expect_err("malformed http_path must fail at open()"); @@ -258,7 +262,10 @@ async fn connection_setter_clears_prior_http_path_parse_error() { ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") .expect("override path"), ) - .auth(AuthConfig::Pat { token: "x".into() }) + .auth(AuthConfig::Pat { + token: "x".into(), + identity_federation_client_id: None, + }) .open() .await .expect("override should win — open() must succeed"); @@ -281,7 +288,10 @@ async fn http_path_setter_clears_prior_parse_error_on_success() { let session = Session::builder() .http_path("https://h", "/garbage") .http_path(server.uri(), "/sql/1.0/warehouses/test_wh") - .auth(AuthConfig::Pat { token: "x".into() }) + .auth(AuthConfig::Pat { + token: "x".into(), + identity_federation_client_id: None, + }) .open() .await .expect("recovery http_path call should clear the sentinel"); @@ -335,6 +345,7 @@ async fn open_session_with_result_cfg( ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .result(result) .open() @@ -429,6 +440,7 @@ async fn create_session_drops_user_supplied_can_cloud_download() { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .session_conf(session_conf) .open() diff --git a/tests/v0_statement_canceller_reexecute.rs b/tests/v0_statement_canceller_reexecute.rs index e16d5ba9..26fed249 100644 --- a/tests/v0_statement_canceller_reexecute.rs +++ b/tests/v0_statement_canceller_reexecute.rs @@ -49,6 +49,7 @@ async fn open_session(server: &MockServer) -> Session { ) .auth(AuthConfig::Pat { token: "dapi_test_token".into(), + identity_federation_client_id: None, }) .open() .await diff --git a/tests/v0_tls_e2e.rs b/tests/v0_tls_e2e.rs index 1826446c..ecddc1b0 100644 --- a/tests/v0_tls_e2e.rs +++ b/tests/v0_tls_e2e.rs @@ -92,11 +92,15 @@ fn live_auth() -> AuthConfig { client_secret, scopes: None, token_url_override: None, + identity_federation_client_id: None, } } else { let token = env_var("DATABRICKS_TOKEN") .expect("need DATABRICKS_TEST_CLIENT_ID/SECRET (OAuth M2M) or DATABRICKS_TOKEN (PAT)"); - AuthConfig::Pat { token } + AuthConfig::Pat { + token, + identity_federation_client_id: None, + } } } diff --git a/tests/v0_transactions_e2e.rs b/tests/v0_transactions_e2e.rs index ee6df3ae..1fa0a899 100644 --- a/tests/v0_transactions_e2e.rs +++ b/tests/v0_transactions_e2e.rs @@ -44,7 +44,10 @@ async fn live_session(ignore_transactions: bool) -> Session { Session::builder() .http_path(host, path) - .auth(AuthConfig::Pat { token }) + .auth(AuthConfig::Pat { + token, + identity_federation_client_id: None, + }) .ignore_transactions(ignore_transactions) .open() .await From 4e9409bce6ef7ecc2de2713c121a98737c0dfec3 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 13 Aug 2026 16:49:35 +0000 Subject: [PATCH 6/8] fix(auth): break federation provider ownership cycle Signed-off-by: Vu Anh Phung --- docs/designs/token-federation-design.md | 8 +++- src/auth/oauth/federation.rs | 52 +++++++++++++++++++------ src/session.rs | 2 +- tests/token_federation_wiremock.rs | 43 +++++++++++--------- 4 files changed, 73 insertions(+), 32 deletions(-) diff --git a/docs/designs/token-federation-design.md b/docs/designs/token-federation-design.md index f27dfaaf..30ab258b 100644 --- a/docs/designs/token-federation-design.md +++ b/docs/designs/token-federation-design.md @@ -230,7 +230,7 @@ pub struct FederationProvider { token_endpoint: String, // {host}/oidc/v1/token, built directly workspace_host: String, // normalized host, for iss-host comparison identity_federation_client_id: Option, - http_client: Arc, + http_client: Weak, runtime_handle: tokio::runtime::Handle, cache: RwLock>, // single slot: (source_token, exchanged) exchanging: AtomicBool, // single-flight leader election @@ -241,11 +241,15 @@ impl FederationProvider { inner: Arc, host: &str, identity_federation_client_id: Option, - http_client: Arc, + http_client: &Arc, ) -> Result; } ``` +The HTTP client owns the installed auth provider, so the federation wrapper +retains only a weak client reference and does not introduce a cycle for PAT +sessions. + `get_auth_header()` logic: 1. `let header = self.inner.get_auth_header()?;` → strip `"Bearer "` → `source`. diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index cb5d9a33..d522c727 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -62,7 +62,7 @@ use crate::klog::{debug, warn}; use crate::util::runtime::block_on_in_runtime; use serde::Deserialize; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, RwLock, Weak}; use std::time::Duration; use tokio::runtime::{Handle as RuntimeHandle, RuntimeFlavor}; @@ -103,8 +103,10 @@ pub struct FederationProvider { /// account-wide WIF, where the exchange sends /// `return_original_token_if_authenticated=true` instead. identity_federation_client_id: Option, - /// Shared HTTP client used for the exchange request. - http_client: Arc, + /// Shared HTTP client used for the exchange request. Weak because the + /// client owns this provider after two-phase auth initialization, avoiding + /// a new ownership cycle for PAT sessions. + http_client: Weak, /// Runtime handle captured at construction so the sync `get_auth_header` /// can drive the async exchange (see [`block_on_in_runtime`]). runtime_handle: RuntimeHandle, @@ -146,12 +148,14 @@ impl FederationProvider { /// `https://my-workspace.cloud.databricks.com`); it is used to build the /// exchange endpoint and to recognize in-house issuers. `async` so it can /// capture the current tokio runtime handle, matching the other OAuth - /// providers. + /// providers. The caller must retain `http_client`; the provider stores a + /// weak reference so the PAT wrapper does not introduce a cycle after the + /// client installs the provider. pub async fn new( inner: Arc, host: &str, identity_federation_client_id: Option, - http_client: Arc, + http_client: &Arc, ) -> Result { let host = host.trim_end_matches('/'); Ok(Self { @@ -159,7 +163,7 @@ impl FederationProvider { token_endpoint: format!("{host}{TOKEN_EXCHANGE_PATH}"), workspace_host: host_of(host).unwrap_or_default(), identity_federation_client_id, - http_client, + http_client: Arc::downgrade(http_client), runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), exchanging: AtomicBool::new(false), @@ -179,6 +183,9 @@ 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 mut form: Vec<(&str, &str)> = vec![ ("grant_type", GRANT_TYPE_JWT_BEARER), ("assertion", source_token), @@ -192,8 +199,7 @@ impl FederationProvider { None => form.push(("return_original_token_if_authenticated", "true")), } - let request = self - .http_client + let request = http_client .inner() .post(&self.token_endpoint) .header("Accept", "*/*") @@ -208,8 +214,7 @@ impl FederationProvider { // the kernel bearer. `AuthTokenRequest` is idempotent, so the // Auth-category ladder retries with backoff on all 5xx / 429 / 408 and // timeouts — everything except the fixed non-retryable 4xx set. - let response = self - .http_client + let response = http_client .execute_without_auth(request, RequestType::AuthTokenRequest) .await?; @@ -519,7 +524,7 @@ mod tests { token_endpoint: format!("{host}{TOKEN_EXCHANGE_PATH}"), workspace_host: host_of(host).unwrap_or_default(), identity_federation_client_id: None, - http_client, + http_client: Arc::downgrade(&http_client), runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), exchanging: AtomicBool::new(false), @@ -562,4 +567,29 @@ mod tests { let p = provider_for("https://ws.cloud.databricks.com", "Bearer dapiabc123"); assert_eq!(p.get_auth_header().unwrap(), "Bearer dapiabc123"); } + + #[tokio::test(flavor = "multi_thread")] + async fn pat_wrapper_does_not_retain_http_client() { + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(Default::default()).expect("http client"), + ); + let weak_http_client = Arc::downgrade(&http_client); + let provider = Arc::new( + FederationProvider::new( + Arc::new(StubProvider("Bearer dapiabc123".to_string())), + "https://ws.cloud.databricks.com", + None, + &http_client, + ) + .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 3217309f..a9a19168 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1074,7 +1074,7 @@ async fn build_auth_provider( base, host, auth.identity_federation_client_id().map(str::to_owned), - http_client, + &http_client, ) .await?; Ok(Arc::new(provider)) diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index 3c58cb44..086f6fe3 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -114,13 +114,14 @@ async fn foreign_issuer_is_exchanged() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&jwt_with_issuer( "https://login.microsoftonline.com/tenant/v2.0", )), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -147,11 +148,12 @@ async fn same_host_issuer_passes_through() { let issuer = format!("{}/oidc", server.uri()); let inner_token = jwt_with_issuer(&issuer); + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&inner_token), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -170,11 +172,12 @@ async fn non_jwt_pat_passes_through() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing("dapiabc123def456"), // opaque PAT, not a JWT &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -197,11 +200,12 @@ async fn sp_wide_wif_sends_identity_federation_client_id() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), &server.uri(), Some("my-sp-client-id".to_string()), - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -266,11 +270,12 @@ async fn byot_sends_return_original_token_flag() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), &server.uri(), None, // no client id → BYOT / account-wide WIF - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -289,11 +294,12 @@ async fn exchange_http_401_falls_back_to_original() { .await; let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&inner_token), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -314,11 +320,12 @@ async fn exchange_http_500_falls_back_to_original() { .await; let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&inner_token), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -339,11 +346,12 @@ async fn exchanged_token_is_cached_across_calls() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = FederationProvider::new( inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"); @@ -371,14 +379,11 @@ async fn representative_databricks_issuer_passes_through() { let workspace = "https://adb-5484724900402942.2.azuredatabricks.net"; let inner_token = jwt_with_issuer(&format!("{workspace}/oidc")); - let provider = FederationProvider::new( - inner_bearing(&inner_token), - workspace, - None, - no_retry_http_client(), - ) - .await - .expect("provider"); + let http_client = no_retry_http_client(); + let provider = + FederationProvider::new(inner_bearing(&inner_token), workspace, None, &http_client) + .await + .expect("provider"); // Same host (modulo scheme + `/oidc`) ⇒ pass through unchanged, no HTTP. assert_eq!( @@ -424,12 +429,13 @@ async fn concurrent_cold_callers_coalesce_to_one_exchange() { .mount(&server) .await; + let http_client = no_retry_http_client(); let provider = Arc::new( FederationProvider::new( inner_bearing(&jwt_with_issuer("https://external-idp.example.com")), &server.uri(), None, - no_retry_http_client(), + &http_client, ) .await .expect("provider"), @@ -458,12 +464,13 @@ async fn degraded_endpoint_falls_back_for_all_concurrent_callers() { .await; let inner_token = jwt_with_issuer("https://external-idp.example.com"); + let http_client = bounded_retry_http_client(); let provider = Arc::new( FederationProvider::new( inner_bearing(&inner_token), &server.uri(), None, - bounded_retry_http_client(), + &http_client, ) .await .expect("provider"), From 1190cd7fd61d31f30e5c08c055218b07e968c339 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 13 Aug 2026 19:20:03 +0000 Subject: [PATCH 7/8] fix(auth): redact federation provider debug output Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 73 +++++++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index d522c727..e92fdab9 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -91,7 +91,6 @@ fn default_expires_in() -> i64 { /// An [`AuthProvider`] decorator that performs mandatory token exchange for /// foreign-issuer JWTs. See the [module docs](self). -#[derive(Debug)] pub struct FederationProvider { /// The wrapped provider that yields the source token. inner: Arc, @@ -135,12 +134,37 @@ const FAILED_EXCHANGE_RETRY_DELAY_SECONDS: i64 = 60; /// A cached exchange outcome: the source token it was derived from, and the /// resulting in-house token. -#[derive(Debug)] struct CacheEntry { source_token: String, exchanged: OAuthToken, } +impl std::fmt::Debug for CacheEntry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CacheEntry") + .field("source_token", &"") + .field("exchanged", &"") + .finish() + } +} + +impl std::fmt::Debug for FederationProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FederationProvider") + .field("inner", &"") + .field("token_endpoint", &self.token_endpoint) + .field("workspace_host", &self.workspace_host) + .field( + "identity_federation_client_id", + &self.identity_federation_client_id, + ) + .field("http_client", &"") + .field("cache", &"") + .field("exchanging", &self.exchanging.load(Ordering::Relaxed)) + .finish() + } +} + impl FederationProvider { /// Wraps `inner` with mandatory token exchange against `host`. /// @@ -592,4 +616,49 @@ mod tests { assert!(weak_http_client.upgrade().is_none()); assert!(weak_provider.upgrade().is_none()); } + + #[tokio::test(flavor = "multi_thread")] + async fn debug_redacts_all_credentials() { + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(Default::default()).expect("http client"), + ); + let provider = FederationProvider::new( + Arc::new(StubProvider("Bearer inner-provider-secret".to_string())), + "https://ws.cloud.databricks.com", + Some("federation-client-id".to_string()), + &http_client, + ) + .await + .expect("provider"); + provider.store( + "source-jwt-secret", + OAuthToken::new( + "exchanged-token-secret".to_string(), + "Bearer".to_string(), + 3600, + Some("refresh-token-secret".to_string()), + vec!["sql".to_string()], + ), + ); + + let provider_debug = format!("{provider:?}"); + let cache_debug = format!("{:?}", provider.cache.read().unwrap().as_ref().unwrap()); + for secret in [ + "inner-provider-secret", + "source-jwt-secret", + "exchanged-token-secret", + "refresh-token-secret", + ] { + assert!( + !provider_debug.contains(secret), + "secret leaked: {provider_debug}" + ); + assert!( + !cache_debug.contains(secret), + "secret leaked: {cache_debug}" + ); + } + assert!(provider_debug.contains("")); + assert!(cache_debug.contains("")); + } } From 2ce4b441e73a2ee41ed0f18c8344df6abd32f074 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 13 Aug 2026 20:18:52 +0000 Subject: [PATCH 8/8] fix(config): preserve auth constructor signatures Signed-off-by: Vu Anh Phung --- napi/src/database.rs | 4 +- src/c_abi/session.rs | 5 +- src/config.rs | 111 ++++++++++++++++++++----------------------- 3 files changed, 54 insertions(+), 66 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index a4a0a55e..ddf139df 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -355,13 +355,12 @@ pub struct ConnectionOptions { /// session. fn build_auth_config(options: &ConnectionOptions) -> napi::Result { match options.auth_mode.unwrap_or_default() { - AuthMode::Pat => AuthConfig::pat(options.token.clone(), None).map_err(napi_err_from_kernel), + AuthMode::Pat => AuthConfig::pat(options.token.clone()).map_err(napi_err_from_kernel), AuthMode::OAuthM2m => AuthConfig::oauth_m2m( options.oauth_client_id.clone(), options.oauth_client_secret.clone(), options.oauth_scopes.clone(), None, - None, ) .map_err(napi_err_from_kernel), // All U2M fields are optional. Default the OAuth client_id to @@ -400,7 +399,6 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { // binding exposes no passphrase option. Surfacing one through // `options` would strengthen it further. None, - None, )) } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 4c46aa4f..e6d5d8ad 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -926,11 +926,11 @@ fn build_session(config: KernelSessionConfig) -> Result AuthConfig::pat(Some(token), None)?, + AuthSpec::Pat { token } => AuthConfig::pat(Some(token))?, AuthSpec::OAuthM2M { client_id, client_secret, - } => AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None, None)?, + } => AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, AuthSpec::OAuthU2M { client_id, redirect_port, @@ -942,7 +942,6 @@ fn build_session(config: KernelSessionConfig) -> Result, - identity_federation_client_id: Option, - ) -> crate::Result { + pub fn pat(token: Option) -> crate::Result { match token { Some(token) if !token.is_empty() => Ok(AuthConfig::Pat { token, - identity_federation_client_id, + identity_federation_client_id: None, }), _ => Err(crate::kernel_error::Error::invalid_argument() .message("PAT auth requires a non-empty access token")), @@ -401,7 +398,6 @@ impl AuthConfig { client_secret: Option, scopes: Option>, token_url_override: Option, - identity_federation_client_id: Option, ) -> crate::Result { let client_id = client_id.filter(|s| !s.is_empty()).ok_or_else(|| { crate::kernel_error::Error::invalid_argument() @@ -416,7 +412,7 @@ impl AuthConfig { client_secret, scopes, token_url_override, - identity_federation_client_id, + identity_federation_client_id: None, }) } @@ -433,7 +429,6 @@ impl AuthConfig { token_url_override: Option, callback_timeout: Option, token_cache: Option, - identity_federation_client_id: Option, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -442,7 +437,7 @@ impl AuthConfig { token_url_override, callback_timeout, token_cache, - identity_federation_client_id, + identity_federation_client_id: None, } } @@ -1559,31 +1554,23 @@ mod tests { #[test] fn pat_rejects_missing_or_empty_token() { - let err = AuthConfig::pat(None, None).unwrap_err(); + let err = AuthConfig::pat(None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("non-empty access token")); - let err = AuthConfig::pat(Some(String::new()), None).unwrap_err(); + let err = AuthConfig::pat(Some(String::new())).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); } #[test] fn pat_accepts_non_empty_token() { - match AuthConfig::pat( - Some("dapi-x".to_string()), - Some("federation-client".to_string()), - ) - .unwrap() - { + match AuthConfig::pat(Some("dapi-x".to_string())).unwrap() { AuthConfig::Pat { token, identity_federation_client_id, } => { assert_eq!(token, "dapi-x"); - assert_eq!( - identity_federation_client_id.as_deref(), - Some("federation-client") - ); + assert!(identity_federation_client_id.is_none()); } other => panic!("expected Pat, got {other:?}"), } @@ -1591,38 +1578,24 @@ mod tests { #[test] fn oauth_m2m_rejects_missing_or_empty_client_id() { - let err = - AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None, None).unwrap_err(); + let err = AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); - let err = AuthConfig::oauth_m2m( - Some(String::new()), - Some("sec".to_string()), - None, - None, - None, - ) - .unwrap_err(); + let err = AuthConfig::oauth_m2m(Some(String::new()), Some("sec".to_string()), None, None) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); } #[test] fn oauth_m2m_rejects_missing_or_empty_client_secret() { - let err = - AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None, None).unwrap_err(); + let err = AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); - let err = AuthConfig::oauth_m2m( - Some("cid".to_string()), - Some(String::new()), - None, - None, - None, - ) - .unwrap_err(); + let err = AuthConfig::oauth_m2m(Some("cid".to_string()), Some(String::new()), None, None) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); } @@ -1634,7 +1607,6 @@ mod tests { Some("sec".to_string()), Some(vec!["all-apis".to_string()]), None, - Some("federation-client".to_string()), ) .unwrap() { @@ -1649,31 +1621,50 @@ mod tests { assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_string()])); assert!(token_url_override.is_none()); - assert_eq!( - identity_federation_client_id.as_deref(), - Some("federation-client") - ); + assert!(identity_federation_client_id.is_none()); } other => panic!("expected OAuthM2M, got {other:?}"), } } #[test] - fn oauth_u2m_carries_identity_federation_client_id() { - let auth = AuthConfig::oauth_u2m( - None, - None, - None, - None, - None, - None, - Some("federation-client".to_string()), - ); + fn oauth_u2m_defaults_identity_federation_client_id() { + let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None); - assert_eq!( - auth.identity_federation_client_id(), - Some("federation-client") - ); + assert_eq!(auth.identity_federation_client_id(), None); + } + + #[test] + fn auth_variants_carry_identity_federation_client_id() { + let auths = [ + AuthConfig::Pat { + token: "token".to_string(), + identity_federation_client_id: Some("federation-client".to_string()), + }, + AuthConfig::OAuthM2M { + client_id: "cid".to_string(), + client_secret: "secret".to_string(), + scopes: None, + token_url_override: None, + identity_federation_client_id: Some("federation-client".to_string()), + }, + AuthConfig::OAuthU2M { + client_id: None, + redirect_port: None, + scopes: None, + token_url_override: None, + callback_timeout: None, + token_cache: None, + identity_federation_client_id: Some("federation-client".to_string()), + }, + ]; + + for auth in auths { + assert_eq!( + auth.identity_federation_client_id(), + Some("federation-client") + ); + } } #[test]