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/include/databricks_kernel.h b/include/databricks_kernel.h index d9edbfb5..3be4f35e 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -346,6 +346,18 @@ KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* con KernelStatusCode kernel_session_config_set_ignore_transactions(KernelSessionConfig* config, bool ignore); +/* SP-wide Workload Identity Federation client id for mandatory OIDC token + * exchange. Optional. When the authenticated token is issued by a party other + * than the target workspace, the kernel exchanges it for an in-house + * Databricks token; setting this makes that exchange send + * `identity_federation_client_id` (SP-wide WIF). Unset takes the BYOT / + * account-wide WIF path (`return_original_token_if_authenticated=true`). Not a + * feature toggle — the exchange is always attempted, gated only by the token's + * issuer. `client_id` must be non-NULL. Shared by all drivers (ODBC / Go). */ +KernelStatusCode +kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* config, + const char* client_id); + /* Configure the on-disk OAuth token cache for U2M (browser) auth. Mirrors * the EnableTokenCache / TokenCachePassPhrase pair exposed by the reference * ODBC driver and JDBC. diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 762d3e8d..39717015 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,13 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions`: new optional `identityFederationClientId` field — selects + SP-wide Workload Identity Federation for mandatory OIDC token exchange. When the + authenticated token is issued by a party other than the target workspace, the + kernel exchanges it for an in-house Databricks token, sending this client id. + Omit for BYOT / account-wide WIF. Not a feature toggle — the exchange is always + attempted, gated only by the token's issuer. + ### Updated ### Fixed diff --git a/napi/index.d.ts b/napi/index.d.ts index 0b042121..453d9cd6 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -205,6 +205,16 @@ export interface ConnectionOptions { * (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M). */ oauthScopes?: Array + /** + * SP-wide Workload Identity Federation client id for mandatory OIDC + * token exchange. Optional. When the authenticated token is issued by + * a party other than the target workspace, the kernel exchanges it for + * an in-house Databricks token; setting this sends + * `identity_federation_client_id` (SP-wide WIF). Omitted ⇒ BYOT / + * account-wide WIF. Not a feature toggle — the exchange is always + * attempted, gated only by the token's issuer. + */ + identityFederationClientId?: string /** * Default catalog for statements executed on this session. * Routed through the kernel's `DefaultOpts` and onto the SEA diff --git a/napi/src/database.rs b/napi/src/database.rs index ddf139df..1fe775c1 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -178,6 +178,15 @@ pub struct ConnectionOptions { /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults /// (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M). pub oauth_scopes: Option>, + /// SP-wide Workload Identity Federation client id for mandatory OIDC + /// token exchange. Optional. When the authenticated token is issued by + /// a party other than the target workspace, the kernel exchanges it for + /// an in-house Databricks token; setting this sends + /// `identity_federation_client_id` (SP-wide WIF). Omitted ⇒ BYOT / + /// account-wide WIF. Not a feature toggle — the exchange is always + /// attempted, gated only by the token's issuer. Maps onto the kernel + /// [`SessionBuilder::identity_federation_client_id`]. + pub identity_federation_client_id: Option, /// Default catalog for statements executed on this session. /// Routed through the kernel's `DefaultOpts` and onto the SEA /// `CreateSession.catalog` wire field. @@ -544,6 +553,11 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result, redirect_port: Option, oauth_callback_timeout_secs: Option, + identity_federation_client_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -288,6 +298,9 @@ impl Session { let mut builder = KSession::builder() .http_path(host, http_path) .auth(auth_config); + if let Some(client_id) = identity_federation_client_id { + builder = builder.identity_federation_client_id(client_id); + } if let Some(tls) = tls_config { builder = builder.tls(tls); } diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py index 3e2cee99..312cae19 100644 --- a/pyo3/tests/test_auth.py +++ b/pyo3/tests/test_auth.py @@ -59,3 +59,28 @@ def test_unknown_auth_type_raises_value_error(): auth_type="something-else", access_token="x", ) + + +def test_identity_federation_client_id_is_accepted_kwarg(): + # The SP-wide WIF selector is a recognized keyword (not a TypeError): + # paired with missing auth it reaches the pre-network auth rejection, + # which proves the signature accepts it without opening a connection. + with pytest.raises(ValueError, match="access_token"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + identity_federation_client_id="sp-client-abc", + ) + + +def test_unknown_kwarg_raises_type_error(): + # Guards the test above: a genuinely unknown kwarg is a TypeError, so + # the ValueError in the test above really does mean the kwarg was + # accepted by the signature. + with pytest.raises(TypeError): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + access_token="x", + not_a_real_kwarg="nope", + ) 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/c_abi/session.rs b/src/c_abi/session.rs index e6d5d8ad..ef7a3948 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -112,6 +112,12 @@ pub struct KernelSessionConfig { /// real transactions via `kernel_session_config_set_ignore_transactions` /// with `false`. Maps to [`DefaultOpts::ignore_transactions`]. ignore_transactions: bool, + /// SP-wide Workload Identity Federation client id for mandatory OIDC token + /// exchange (populated by + /// `kernel_session_config_set_identity_federation_client_id`). `None` ⇒ + /// BYOT / account-wide WIF. Maps to + /// [`SessionConfig::identity_federation_client_id`]. + identity_federation_client_id: Option, /// On-disk U2M token-cache policy (populated by /// `kernel_session_config_set_u2m_token_cache_config`). Defaults to enabled with /// no passphrase, in which case the cache is encrypted under a @@ -203,6 +209,8 @@ pub unsafe extern "C" fn kernel_session_config_new( retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. ignore_transactions: true, + // No SP-wide WIF client id by default (BYOT / account-wide WIF). + identity_federation_client_id: None, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), // Kernel result defaults (CloudFetch enabled, Arrow-native types). @@ -669,6 +677,31 @@ pub unsafe extern "C" fn kernel_session_config_set_ignore_transactions( }) } +/// Set the SP-wide Workload Identity Federation client id for mandatory OIDC +/// token exchange. +/// +/// Optional. When the authenticated token is issued by a party other than the +/// target workspace, the kernel exchanges it for an in-house Databricks token; +/// setting this makes that exchange send `identity_federation_client_id` (the +/// SP-wide WIF scenario). Leaving it unset takes the BYOT / account-wide WIF +/// path (`return_original_token_if_authenticated=true`). It is not a feature +/// toggle — the exchange is always attempted, gated only by the token's issuer. +/// Maps to [`SessionConfig::identity_federation_client_id`]. +/// +/// # Safety +/// `config` must be a live config handle; `client_id` must be a NUL-terminated +/// C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_identity_federation_client_id( + config: *mut KernelSessionConfig, + client_id: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.identity_federation_client_id = Some(required_str(client_id, "client_id")?); + Ok(()) + }) +} + /// Configure the on-disk OAuth token cache for U2M (browser) auth. /// /// Mirrors the `EnableTokenCache` / `TokenCachePassPhrase` pair exposed by @@ -900,6 +933,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result/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/c/session_smoke.c b/tests/c/session_smoke.c index ca55e1ae..ced83aa4 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -205,6 +205,21 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } +/* SP-wide WIF setter: a valid client id succeeds; NULL → InvalidArgument. */ +static void test_identity_federation_client_id_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + KernelStatusCode rc = + kernel_session_config_set_identity_federation_client_id(config, "sp-client-abc"); + CHECK(rc == KernelStatusCode_Success, "set_identity_federation_client_id succeeds"); + rc = kernel_session_config_set_identity_federation_client_id(config, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_identity_federation_client_id(NULL) → InvalidArgument"); + + kernel_session_config_free(config); +} + /* Client-conf setter accepts known keys, clamps, and rejects bad input. */ static void test_client_conf_setter(void) { KernelSessionConfig* config = NULL; @@ -300,6 +315,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters(); + test_identity_federation_client_id_setter(); test_client_conf_setter(); test_init_logging(); test_is_open_null_guards(); 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" + ); +}