From 0f6f3d3a8180aab7b61000aaef0257e66f38831e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 16:24:08 +0000 Subject: [PATCH 1/5] feat(auth): mandatory OIDC token exchange (BYOT federation) Wrap the base auth provider (PAT / M2M / U2M) with a FederationProvider that exchanges a foreign-issuer JWT for an in-house Databricks token at {host}/oidc/v1/token before use. - jwt.rs: decode the JWT payload (no signature verification) to read the iss claim, using the existing base64 + serde_json deps. - federation.rs: blocking exchange via block_on_in_runtime (matching the M2M provider's sync-trait-over-async bridge), cached per source token, with non-breaking fallback to the original token on any failure. Wire contract follows the BYOT spec / ADBC: grant_type=jwt-bearer, assertion, scope=sql, and identity_federation_client_id XOR return_original_token_if_authenticated=true. - Gated internally by the iss-vs-host check: non-JWT (PAT) and same-host tokens pass through with no HTTP call, so the wrapper is always-on and needs no enable flag. - New optional SessionConfig::identity_federation_client_id (+ builder setter) selects SP-wide WIF. Verified: cargo build, clippy -D warnings, fmt --check, and tests all pass (8 federation integration tests + full 768-test lib suite). Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 11 + src/auth/mod.rs | 2 +- src/auth/oauth/federation.rs | 408 +++++++++++++++++++++++++++++ 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 | 288 ++++++++++++++++++++ 8 files changed, 874 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..83ba8408 --- /dev/null +++ b/src/auth/oauth/federation.rs @@ -0,0 +1,408 @@ +// 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 sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, RwLock}; +use tokio::runtime::Handle as RuntimeHandle; + +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, + /// Exchanged tokens keyed by a hash of the *source* token, so a rotated + /// upstream credential is exchanged fresh and an expired exchanged token + /// is re-exchanged. + cache: RwLock>, + /// Serializes concurrent exchanges (double-checked against `cache`). + exchange_lock: Mutex<()>, +} + +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(HashMap::new()), + exchange_lock: Mutex::new(()), + }) + } + + /// 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` gives it the Auth-category + // retry ladder (backoff on 408/502/503/504 + timeouts). + 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. + fn exchanged_or_original(&self, source_token: &str) -> String { + let key = cache_key(source_token); + + // Fast path: a fresh cached exchange for this exact source token. + if let Ok(cache) = self.cache.read() { + if let Some(tok) = cache.get(&key) { + if !tok.is_expired() { + return tok.access_token.clone(); + } + } + } + + // Slow path: serialize so concurrent callers don't all hit the + // endpoint, then double-check the cache. + let _guard = self.exchange_lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Ok(cache) = self.cache.read() { + if let Some(tok) = cache.get(&key) { + if !tok.is_expired() { + return tok.access_token.clone(); + } + } + } + + match block_on_in_runtime(&self.runtime_handle, self.exchange(source_token)) { + Ok(token) => { + let access_token = token.access_token.clone(); + if let Ok(mut cache) = self.cache.write() { + cache.insert(key, token); + } + debug!("Token federation: exchanged foreign-issuer token for in-house token"); + access_token + } + Err(e) => { + // Non-breaking fallback: use the original token. Cache the + // original (short-lived) under the same key so a burst of + // requests doesn't hammer the endpoint after a failure. + warn!( + "Token federation: exchange failed, falling back to original token: {}", + e + ); + if let Ok(mut cache) = self.cache.write() { + cache.insert( + key, + OAuthToken::new( + source_token.to_string(), + "Bearer".to_string(), + 60, + None, + vec![], + ), + ); + } + source_token.to_string() + } + } + } +} + +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), + } + } +} + +/// SHA-256 hex digest of a token, used as the cache key so raw tokens are not +/// held as map keys. +fn cache_key(token: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(token.as_bytes()); + hex::encode(hasher.finalize()) +} + +/// 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(HashMap::new()), + exchange_lock: Mutex::new(()), + } + } + + // 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..23905a26 --- /dev/null +++ b/tests/token_federation_wiremock.rs @@ -0,0 +1,288 @@ +// 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 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"), + ) +} + +/// 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"); + } +} From 4acf18bceb6c1aeccbf172608942df8d472e1c9a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 18:19:30 +0000 Subject: [PATCH 2/5] feat(bindings): expose identity_federation_client_id on all boundaries The SP-wide WIF selector for mandatory token exchange was reachable only from the Rust SessionBuilder. Thread it through every consumer boundary so Python, Node, ODBC, Go, and C callers can select SP-wide WIF (the exchange itself, and BYOT / account-wide WIF, already worked everywhere since it is gated by the token issuer, not config). - C ABI: new kernel_session_config_set_identity_federation_client_id setter, stored on KernelSessionConfig and forwarded to the builder; declared in include/databricks_kernel.h. Consumed by ODBC and Go. - pyo3: new optional identity_federation_client_id kwarg on Session(...). - napi: new optional identityFederationClientId field on ConnectionOptions; index.d.ts updated. Tests: C ABI setter unit test (records value, rejects NULL) + C smoke check; pyo3 kwarg-accepted boundary test; napi options-boundary test. Verified build + clippy -D warnings + fmt --check + tests across core, pyo3, and napi. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- include/databricks_kernel.h | 12 ++++++ napi/NEXT_CHANGELOG.md | 7 ++++ napi/index.d.ts | 10 +++++ napi/src/database.rs | 32 +++++++++++++++ pyo3/NEXT_CHANGELOG.md | 7 ++++ pyo3/src/session.rs | 13 +++++++ pyo3/tests/test_auth.py | 25 ++++++++++++ src/c_abi/session.rs | 77 +++++++++++++++++++++++++++++++++++++ tests/c/session_smoke.c | 16 ++++++++ 9 files changed, 199 insertions(+) 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/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 Date: Tue, 11 Aug 2026 19:46:41 +0000 Subject: [PATCH 3/5] fix(auth): don't hold lock across token exchange; single-slot cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review findings on the federation provider's concurrency and cache. H1: the resolver no longer holds a lock across the exchange network call. get_auth_header is sync and runs on a tokio worker, so holding a std Mutex across block_on_in_runtime(exchange) parked that worker for the whole retry budget and, under contention, could starve the runtime. Now: cache hit under a brief read lock; miss runs the exchange lock-free (idempotent — concurrent cold-start callers race and the last writer wins) and takes a brief write lock only to store. Each exchange's latency is already bounded by the Auth-category retry budget (30s / 3 retries), not the global ladder. M2: replace the insert-only HashMap with a single-slot RwLock>. A provider tracks one active source token, so the slot is overwritten on rotation/expiry rather than leaking an entry per rotated credential; it also drops the per-request sha256 on the cache-hit path (compare the source token directly). M1: guard block_on_in_runtime against a current-thread runtime. It uses block_in_place, which panics there; the resolver now detects the flavor and falls back to the original token (same non-breaking posture as a failed exchange) instead of panicking. Tests: retries-enabled bounded-latency test (8 concurrent callers vs an always-503 endpoint finish in parallel, not serialized) guarding H1; a non-circular representative-Databricks-issuer pass-through test (M3). Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 128 +++++++++++++++++------------ tests/token_federation_wiremock.rs | 118 ++++++++++++++++++++++++++ 2 files changed, 193 insertions(+), 53 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index 83ba8408..96865677 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -61,10 +61,8 @@ use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; use crate::util::runtime::block_on_in_runtime; use serde::Deserialize; -use sha2::{Digest, Sha256}; -use std::collections::HashMap; -use std::sync::{Arc, Mutex, RwLock}; -use tokio::runtime::Handle as RuntimeHandle; +use std::sync::{Arc, RwLock}; +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"; @@ -109,12 +107,21 @@ pub struct FederationProvider { /// Runtime handle captured at construction so the sync `get_auth_header` /// can drive the async exchange (see [`block_on_in_runtime`]). runtime_handle: RuntimeHandle, - /// Exchanged tokens keyed by a hash of the *source* token, so a rotated - /// upstream credential is exchanged fresh and an expired exchanged token - /// is re-exchanged. - cache: RwLock>, - /// Serializes concurrent exchanges (double-checked against `cache`). - exchange_lock: Mutex<()>, + /// 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>, +} + +/// 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 { @@ -139,8 +146,7 @@ impl FederationProvider { identity_federation_client_id, http_client, runtime_handle: RuntimeHandle::current(), - cache: RwLock::new(HashMap::new()), - exchange_lock: Mutex::new(()), + cache: RwLock::new(None), }) } @@ -206,62 +212,87 @@ impl FederationProvider { /// Resolves the token to use: the cached/exchanged in-house token on /// success, or `source_token` unchanged on any failure. + /// + /// No lock is held across the network call. A cache hit for the current + /// source token returns under a short read lock; a miss performs the + /// exchange lock-free (so a degraded `/oidc/v1/token` can never block other + /// callers or park the tokio worker pool), then takes a brief write lock + /// only to store the result. Concurrent first-use callers may each run an + /// exchange — those calls are idempotent and the redundancy is bounded by + /// how many threads race the cold start; the single cache slot collapses to + /// the last writer. The Auth-category retry budget (see + /// `build_retry_configs_for_session`: 30s / 3 retries, not the global + /// ladder) bounds each exchange's own latency. fn exchanged_or_original(&self, source_token: &str) -> String { - let key = cache_key(source_token); - // Fast path: a fresh cached exchange for this exact source token. if let Ok(cache) = self.cache.read() { - if let Some(tok) = cache.get(&key) { - if !tok.is_expired() { - return tok.access_token.clone(); + if let Some(entry) = cache.as_ref() { + if entry.source_token == source_token && !entry.exchanged.is_expired() { + return entry.exchanged.access_token.clone(); } } } - // Slow path: serialize so concurrent callers don't all hit the - // endpoint, then double-check the cache. - let _guard = self.exchange_lock.lock().unwrap_or_else(|e| e.into_inner()); - if let Ok(cache) = self.cache.read() { - if let Some(tok) = cache.get(&key) { - if !tok.is_expired() { - return tok.access_token.clone(); - } - } + // 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(); } + // Miss (empty, rotated source, or expired): exchange WITHOUT holding + // any lock, then store the outcome. match block_on_in_runtime(&self.runtime_handle, self.exchange(source_token)) { Ok(token) => { let access_token = token.access_token.clone(); - if let Ok(mut cache) = self.cache.write() { - cache.insert(key, token); - } + self.store(source_token, token); debug!("Token federation: exchanged foreign-issuer token for in-house token"); access_token } Err(e) => { // Non-breaking fallback: use the original token. Cache the - // original (short-lived) under the same key so a burst of - // requests doesn't hammer the endpoint after a failure. + // original (short-lived) so a burst of requests with the same + // source doesn't hammer the endpoint after a failure. warn!( "Token federation: exchange failed, falling back to original token: {}", e ); - if let Ok(mut cache) = self.cache.write() { - cache.insert( - key, - OAuthToken::new( - source_token.to_string(), - "Bearer".to_string(), - 60, - None, - vec![], - ), - ); - } + self.store( + source_token, + OAuthToken::new( + source_token.to_string(), + "Bearer".to_string(), + 60, + None, + vec![], + ), + ); source_token.to_string() } } } + + /// 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, + }); + } + } } impl AuthProvider for FederationProvider { @@ -288,14 +319,6 @@ impl AuthProvider for FederationProvider { } } -/// SHA-256 hex digest of a token, used as the cache key so raw tokens are not -/// held as map keys. -fn cache_key(token: &str) -> String { - let mut hasher = Sha256::new(); - hasher.update(token.as_bytes()); - hex::encode(hasher.finalize()) -} - /// 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. @@ -373,8 +396,7 @@ mod tests { identity_federation_client_id: None, http_client, runtime_handle: RuntimeHandle::current(), - cache: RwLock::new(HashMap::new()), - exchange_lock: Mutex::new(()), + cache: RwLock::new(None), } } diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index 23905a26..f2c10d13 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -21,6 +21,7 @@ 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; @@ -61,6 +62,27 @@ fn no_retry_http_client() -> Arc { ) } +/// 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. @@ -286,3 +308,99 @@ async fn exchanged_token_is_cached_across_calls() { 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}") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn degraded_endpoint_does_not_serialize_concurrent_callers() { + // With retries ENABLED and the exchange endpoint always failing, each + // exchange spends ~real backoff time (2 retries × 200ms ≈ 0.4s+). Fire + // many concurrent callers: because the resolver holds no lock across the + // network call, they run their exchanges in parallel and every call still + // returns (falling back to the original token). Total wall-time must stay + // close to a single exchange's budget, NOT N × it — which is what a lock + // held across the retry ladder would produce. + 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"), + ); + + // Spawn concurrent callers on separate OS threads (get_auth_header is sync + // and blocks the thread), each entering the runtime context. + const N: usize = 8; + let handle = tokio::runtime::Handle::current(); + let start = Instant::now(); + let mut threads = Vec::with_capacity(N); + for _ in 0..N { + let p = provider.clone(); + let h = handle.clone(); + threads.push(std::thread::spawn(move || { + let _guard = h.enter(); + p.get_auth_header() + })); + } + let results: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + let elapsed = start.elapsed(); + + // All calls succeed via the non-breaking fallback (original token). + for r in &results { + assert_eq!(r.as_deref().unwrap(), format!("Bearer {inner_token}")); + } + + // A single exchange's budget is ~0.4s (2 × 200ms) plus overhead. If callers + // serialized behind a shared lock across the retry ladder, 8 of them would + // take 8× that (~3.2s+). Assert well under that serialized floor — generous + // enough to avoid CI flakiness while still failing a serialized regression. + assert!( + elapsed < Duration::from_secs(2), + "concurrent exchanges took {elapsed:?}; expected them to run in parallel \ + (a lock held across the retry ladder would serialize to ~N× a single \ + exchange)" + ); +} From c2b369065d27aab203b9a02fff204e2b07268b40 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 20:50:16 +0000 Subject: [PATCH 4/5] refactor(auth): coalesce concurrent token exchanges single-flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the let-concurrent-callers-race resolver with single-flight coalescing, mirroring the kernel's own TokenStore refresh coordination (and Go's CachedTokenProvider): concurrent cache misses elect one leader via a lock-free AtomicBool that runs the exchange; followers sleep-poll the cache slot and read the leader's published result. Still holds no lock across the network call. The win over racing: on a rotated/expired token a busy shared session can miss on many threads at once, and for SP-wide WIF each exchange mints a distinct server token — coalescing keeps it to one instead of N (N-1 orphaned). It also keeps only the leader in the runtime (block_in_place), not all N callers. Followers verify the published entry is for their own source token (the inner credential may rotate mid-wait) and fall back otherwise; the leader always publishes an outcome — on failure the original token (short TTL), so failures stay non-breaking per spec and followers never spin to their timeout. An RAII guard clears the flag if the leader panics. Test: the concurrency case now asserts exactly one exchange for 10 concurrent cold callers (mock .expect(1)) — the real parity check — plus a degraded-endpoint case asserting all concurrent callers fall back. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 159 +++++++++++++++++++++++------ tests/token_federation_wiremock.rs | 100 ++++++++++++------ 2 files changed, 195 insertions(+), 64 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index 96865677..5d6260dc 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -61,7 +61,9 @@ 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"; @@ -114,8 +116,19 @@ pub struct FederationProvider { /// 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)] @@ -147,6 +160,7 @@ impl FederationProvider { http_client, runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), + exchanging: AtomicBool::new(false), }) } @@ -213,28 +227,25 @@ impl FederationProvider { /// Resolves the token to use: the cached/exchanged in-house token on /// success, or `source_token` unchanged on any failure. /// - /// No lock is held across the network call. A cache hit for the current - /// source token returns under a short read lock; a miss performs the - /// exchange lock-free (so a degraded `/oidc/v1/token` can never block other - /// callers or park the tokio worker pool), then takes a brief write lock - /// only to store the result. Concurrent first-use callers may each run an - /// exchange — those calls are idempotent and the redundancy is bounded by - /// how many threads race the cold start; the single cache slot collapses to - /// the last writer. The Auth-category retry budget (see - /// `build_retry_configs_for_session`: 30s / 3 retries, not the global - /// ladder) bounds each exchange's own latency. + /// **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 Ok(cache) = self.cache.read() { - if let Some(entry) = cache.as_ref() { - if entry.source_token == source_token && !entry.exchanged.is_expired() { - return entry.exchanged.access_token.clone(); - } - } + 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 + // 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 @@ -251,8 +262,36 @@ impl FederationProvider { return source_token.to_string(); } - // Miss (empty, rotated source, or expired): exchange WITHOUT holding - // any lock, then store the outcome. + // 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(); @@ -261,28 +300,68 @@ impl FederationProvider { access_token } Err(e) => { - // Non-breaking fallback: use the original token. Cache the - // original (short-lived) so a burst of requests with the same - // source doesn't hammer the endpoint after a failure. warn!( "Token federation: exchange failed, falling back to original token: {}", e ); - self.store( - source_token, - OAuthToken::new( - source_token.to_string(), - "Bearer".to_string(), - 60, - None, - vec![], - ), - ); + // 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) { @@ -295,6 +374,19 @@ impl FederationProvider { } } +/// 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()?; @@ -397,6 +489,7 @@ mod tests { http_client, runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), + exchanging: AtomicBool::new(false), } } diff --git a/tests/token_federation_wiremock.rs b/tests/token_federation_wiremock.rs index f2c10d13..3ef391b9 100644 --- a/tests/token_federation_wiremock.rs +++ b/tests/token_federation_wiremock.rs @@ -343,15 +343,69 @@ async fn representative_databricks_issuer_passes_through() { ); } +/// 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 degraded_endpoint_does_not_serialize_concurrent_callers() { - // With retries ENABLED and the exchange endpoint always failing, each - // exchange spends ~real backoff time (2 retries × 200ms ≈ 0.4s+). Fire - // many concurrent callers: because the resolver holds no lock across the - // network call, they run their exchanges in parallel and every call still - // returns (falling back to the original token). Total wall-time must stay - // close to a single exchange's budget, NOT N × it — which is what a lock - // held across the retry ladder would produce. +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")) @@ -371,36 +425,20 @@ async fn degraded_endpoint_does_not_serialize_concurrent_callers() { .expect("provider"), ); - // Spawn concurrent callers on separate OS threads (get_auth_header is sync - // and blocks the thread), each entering the runtime context. - const N: usize = 8; - let handle = tokio::runtime::Handle::current(); let start = Instant::now(); - let mut threads = Vec::with_capacity(N); - for _ in 0..N { - let p = provider.clone(); - let h = handle.clone(); - threads.push(std::thread::spawn(move || { - let _guard = h.enter(); - p.get_auth_header() - })); - } - let results: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + let results = concurrent_auth_headers(provider, 8); let elapsed = start.elapsed(); - // All calls succeed via the non-breaking fallback (original token). for r in &results { assert_eq!(r.as_deref().unwrap(), format!("Bearer {inner_token}")); } - - // A single exchange's budget is ~0.4s (2 × 200ms) plus overhead. If callers - // serialized behind a shared lock across the retry ladder, 8 of them would - // take 8× that (~3.2s+). Assert well under that serialized floor — generous - // enough to avoid CI flakiness while still failing a serialized regression. + // 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 exchanges took {elapsed:?}; expected them to run in parallel \ - (a lock held across the retry ladder would serialize to ~N× a single \ - exchange)" + "concurrent degraded-endpoint calls took {elapsed:?}; expected the leader \ + to bound the wait and followers to read its fallback" ); } From 152edd8117249a750dc3c9fae619697d1b8c4a6e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 11 Aug 2026 20:59:49 +0000 Subject: [PATCH 5/5] docs: correct Auth-category retry description in doc and code comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AuthTokenRequest is classified idempotent, so the exchange ladder retries all 5xx/429/408/timeouts except the fixed non-retryable 4xx set — not just 408/502/503/504 as the doc and the federation.rs comment previously said (which understated it: 500 and 429 are retried too). Comment-only change in federation.rs; behavior unchanged. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/auth/oauth/federation.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index 5d6260dc..0cca64d1 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -203,8 +203,9 @@ impl FederationProvider { })?; // No auth header: the request authenticates via the `assertion`, not - // the kernel bearer. `AuthTokenRequest` gives it the Auth-category - // retry ladder (backoff on 408/502/503/504 + timeouts). + // 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)