Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ arrow-ipc = "59"
# (which `native-tls` pulls in on Linux) collides with Node's symbols at
# module load time and segfaults the process before any Rust code runs.
# `rustls` is pure Rust + ring and avoids the conflict entirely.
reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] }
# 0.12.23: first release with `ClientBuilder::retry` (see `client/http.rs`).
reqwest = { version = "0.12.23", default-features = false, features = ["json", "gzip", "stream"] }
native-tls = { version = "0.2", optional = true }
rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] }
# Enforce TLS dependency minimums for consumers with their own lockfiles.
Expand Down
4 changes: 4 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ changes go in their respective binding's NEXT_CHANGELOG.
with an optional partner entry from `adbc.databricks.user_agent_entry`
(`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in
`adbc.databricks.http.headers` is now rejected; use the dedicated entry option.
- Each HTTP request costs less CPU: the client no longer copies every request
for HTTP/2 retries it cannot make, and an unchanged token's `Authorization`
value (and, with token federation, its issuer check) is reused instead of
being rebuilt per request.

### Updated

Expand Down
77 changes: 68 additions & 9 deletions src/auth/oauth/federation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ pub struct FederationProvider {
/// 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,
/// The inner provider's last header and whether its token's issuer is
/// foreign. Keyed on the exact header, so the JWT is decoded once per
/// token rather than on every request, and a fresher token from the inner
/// provider is always checked again.
issuer_decision: RwLock<Option<IssuerDecision>>,
}

struct IssuerDecision {
header: String,
foreign: bool,
}

/// How long a follower sleeps between polls while the leader runs the exchange.
Expand Down Expand Up @@ -191,9 +201,28 @@ impl FederationProvider {
runtime_handle: RuntimeHandle::current(),
cache: RwLock::new(None),
exchanging: AtomicBool::new(false),
issuer_decision: RwLock::new(None),
})
}

/// Whether the bearer token in `header` (`source_token`) needs exchange,
/// decided once per distinct header.
fn token_is_foreign(&self, header: &str, source_token: &str) -> bool {
if let Ok(slot) = self.issuer_decision.read() {
if let Some(decision) = slot.as_ref().filter(|d| d.header == header) {
return decision.foreign;
}
}
let foreign = jwt::issuer(source_token).is_some_and(|iss| self.issuer_is_foreign(&iss));
if let Ok(mut slot) = self.issuer_decision.write() {
*slot = Some(IssuerDecision {
header: header.to_string(),
foreign,
});
}
foreign
}

/// 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.
Expand Down Expand Up @@ -441,16 +470,15 @@ impl AuthProvider for FederationProvider {
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}"))
}
// Check the issuer of every new token (rather than trusting a
// decision made for an earlier one) so a fresher in-house token from
// the inner provider is never shadowed by a stale exchange.
if self.token_is_foreign(&header, source_token) {
let token = self.exchanged_or_original(source_token);
Ok(format!("Bearer {token}"))
} else {
// Not a JWT, or issued by this workspace: use as-is.
_ => Ok(header),
Ok(header)
}
}
}
Expand Down Expand Up @@ -559,6 +587,7 @@ mod tests {
runtime_handle: RuntimeHandle::current(),
cache: RwLock::new(None),
exchanging: AtomicBool::new(false),
issuer_decision: RwLock::new(None),
}
}

Expand Down Expand Up @@ -586,6 +615,36 @@ mod tests {
assert!(p.issuer_is_foreign("https://login.microsoftonline.com/tenant/v2.0"));
}

fn unsigned_jwt(iss: &str) -> String {
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
let part = |v: serde_json::Value| URL_SAFE_NO_PAD.encode(v.to_string());
format!(
"{}.{}.sig",
part(serde_json::json!({"alg": "none"})),
part(serde_json::json!({ "iss": iss }))
)
}

/// The issuer decision is remembered per exact header: repeating a token
/// reuses it, and a different token is checked again.
#[tokio::test(flavor = "multi_thread")]
async fn issuer_decision_follows_the_current_token() {
let p = provider_for("https://ws.cloud.databricks.com", "Bearer x");
let in_house = unsigned_jwt("https://ws.cloud.databricks.com/oidc");
let foreign = unsigned_jwt("https://login.microsoftonline.com/tenant/v2.0");
let header = |t: &str| format!("Bearer {t}");

for _ in 0..2 {
assert!(!p.token_is_foreign(&header(&in_house), &in_house));
}
for _ in 0..2 {
assert!(p.token_is_foreign(&header(&foreign), &foreign));
}
assert!(!p.token_is_foreign(&header(&in_house), &in_house));
assert!(!p.token_is_foreign("Bearer opaque", "opaque"));
}

#[tokio::test(flavor = "multi_thread")]
async fn non_bearer_header_passes_through() {
let p = provider_for("https://ws.cloud.databricks.com", "Basic abc123");
Expand Down
64 changes: 61 additions & 3 deletions src/client/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::client::retry::{
use crate::kernel_error::{Error, Result};
use crate::klog::{debug, warn};
use crate::types::sea::ServiceError;
use reqwest::header::HeaderValue;
use reqwest::{Client, NoProxy, Proxy, Request, Response};
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
Expand Down Expand Up @@ -386,6 +387,36 @@ pub struct DatabricksHttpClient {
config: HttpClientConfig,
auth_provider: OnceLock<Arc<dyn AuthProvider>>,
retry_configs: HashMap<RequestCategory, RetryConfig>,
auth_value: AuthValueCache,
}

/// The last `Authorization` string from the provider and its validated header
/// value, so an unchanged token is not re-validated and copied per request.
/// `Debug` never prints the credential.
#[derive(Default)]
struct AuthValueCache(std::sync::RwLock<Option<(String, HeaderValue)>>);

impl std::fmt::Debug for AuthValueCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("AuthValueCache(<redacted>)")
}
}

impl AuthValueCache {
fn get_or_build(&self, header: String) -> Result<HeaderValue> {
// Requests sharing a token only read, so they don't wait on each other.
if let Some((cached, value)) = self.0.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
if *cached == header {
return Ok(value.clone());
}
}
let mut value = HeaderValue::from_str(&header).map_err(|e| {
Error::invalid_argument().message(format!("Failed to build request: {e}"))
})?;
value.set_sensitive(true);
*self.0.write().unwrap_or_else(|e| e.into_inner()) = Some((header, value.clone()));
Ok(value)
}
}

impl DatabricksHttpClient {
Expand Down Expand Up @@ -502,6 +533,7 @@ impl DatabricksHttpClient {
config,
auth_provider: OnceLock::new(),
retry_configs,
auth_value: AuthValueCache::default(),
})
}

Expand All @@ -522,7 +554,11 @@ impl DatabricksHttpClient {
.timeout(config.read_timeout)
.pool_max_idle_per_host(config.max_connections_per_host)
.user_agent(&config.user_agent)
.redirect(redirect);
.redirect(redirect)
// reqwest's default retry layer copies every request so it can
// replay HTTP/2 or HTTP/3 refusals, neither of which this client
// speaks; `execute_impl` does the kernel's retries.
.retry(reqwest::retry::never().max_retries_per_request(0));
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved

// Apply TLS configuration
if config.tls.enabled == Some(false) {
Expand Down Expand Up @@ -902,8 +938,8 @@ impl DatabricksHttpClient {
if !self.config.sea_response_compression_enabled {
req_builder = req_builder.header("Accept-Encoding", "identity");
}
let auth_header = self.auth_header()?;
req_builder = req_builder.header("Authorization", auth_header);
let auth_value = self.auth_value.get_or_build(self.auth_header()?)?;
req_builder = req_builder.header(reqwest::header::AUTHORIZATION, auth_value);
// Extra auth headers (Azure SP management-token pair). Empty for
// every other provider. Applied only on authenticated requests,
// never on the token/OIDC calls that use `execute_without_auth`.
Expand Down Expand Up @@ -1085,6 +1121,28 @@ mod tests {
build_retry_configs(&RetryConfig::default(), &HashMap::new())
}

#[test]
fn auth_value_cache_reuses_the_value_until_the_header_changes() {
let cache = AuthValueCache::default();
let first = cache.get_or_build("Bearer one".to_string()).unwrap();
assert!(first.is_sensitive());
assert_eq!(first, "Bearer one");
assert_eq!(
cache.get_or_build("Bearer one".to_string()).unwrap(),
"Bearer one"
);
assert_eq!(
cache.get_or_build("Bearer two".to_string()).unwrap(),
"Bearer two"
);
assert!(cache.get_or_build("Bearer bad\nvalue".to_string()).is_err());
assert_eq!(
cache.get_or_build("Bearer two".to_string()).unwrap(),
"Bearer two"
);
assert!(!format!("{cache:?}").contains("two"));
}

#[test]
fn test_http_client_config_default() {
let config = HttpClientConfig::default();
Expand Down
Loading