Skip to content
Closed
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
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Fixed

- Connection custom headers are no longer forwarded to presigned CloudFetch downloads, except a caller `User-Agent`, which remains client-wide. Server-provided storage headers and existing custom-header behavior on SEA, telemetry, M2M/OIDC and feature-flag requests are preserved.
- `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession.
- A timed-out or reset CloudFetch download no longer writes the presigned URL's signature (`sig=`, `X-Amz-Signature`) to the log or the returned error. The request URL in those messages now ends at the path, and debug request lines stop at `?`.

Expand Down
6 changes: 4 additions & 2 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -356,8 +356,10 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con
KernelStatusCode kernel_session_config_set_enable_geospatial_support(
KernelSessionConfig* config, bool enabled);

/* Append one HTTP header sent on every request. Call once per header
* (order preserved); `name` and `value` are both required. */
/* Append one custom HTTP header for SEA, telemetry, feature-flag and M2M/OIDC
* requests, not presigned CloudFetch downloads. A caller User-Agent replaces
* the client-wide UA, including downloads. Call once per header (order
* preserved); `name` and `value` are both required. */
KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config,
const char* name, const char* value);

Expand Down
7 changes: 4 additions & 3 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,9 +491,10 @@ export interface ConnectionOptions {
*/
clientKeyPem?: Buffer
/**
* Extra HTTP headers to send on every request — the route for
* caller-supplied headers (the NodeJS driver's `customHeaders` and
* the composed `User-Agent`). Maps onto the kernel
* Extra HTTP headers for SEA, telemetry, feature-flag and M2M/OIDC
* requests, excluding presigned CloudFetch downloads. A caller
* `User-Agent` replaces the client-wide UA, including downloads.
* Maps the NodeJS driver's `customHeaders` onto the kernel
* [`HttpConfig::custom_headers`].
*
* An **ordered list** of `(name, value)` pairs, mirroring the kernel
Expand Down
7 changes: 4 additions & 3 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,9 +362,10 @@ pub struct ConnectionOptions {
/// kernel's TLS backends supply a PKCS#8 key (`BEGIN PRIVATE KEY`).
/// Maps onto the kernel [`TlsConfig::client_key_pem`].
pub client_key_pem: Option<Buffer>,
/// Extra HTTP headers to send on every request — the route for
/// caller-supplied headers (the NodeJS driver's `customHeaders` and
/// the composed `User-Agent`). Maps onto the kernel
/// Extra HTTP headers for SEA, telemetry, feature-flag and M2M/OIDC
/// requests, excluding presigned CloudFetch downloads. A caller
/// `User-Agent` replaces the client-wide UA, including downloads.
/// Maps the NodeJS driver's `customHeaders` onto the kernel
/// [`HttpConfig::custom_headers`].
///
/// An **ordered list** of `(name, value)` pairs, mirroring the kernel
Expand Down
19 changes: 9 additions & 10 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,12 +326,12 @@ impl Session {
/// `max_connections` sets the maximum idle connections retained per host.
/// Unset keeps the kernel default (100); zero is rejected.
///
/// `http_headers` is a list of `(name, value)` pairs sent on every
/// request — used to forward the connector's caller headers (which
/// also carry the composed `User-Agent`). The kernel applies them
/// before its own `Authorization` / `x-databricks-org-id` headers,
/// which always take precedence; a caller header for either of those
/// names is ignored.
/// `http_headers` is a list of `(name, value)` pairs for SEA, telemetry,
/// feature-flag and M2M/OIDC requests, not presigned CloudFetch downloads.
/// A caller `User-Agent` replaces the client-wide UA, including downloads.
/// Other entries precede the kernel's own `Authorization` /
/// `x-databricks-org-id` headers, which always take precedence;
/// a caller header for either reserved name is ignored.
///
/// `session_conf` is the server-bound session configuration map
/// — passed through to SEA `session_confs` verbatim. Use for
Expand Down Expand Up @@ -556,10 +556,9 @@ impl Session {
// wrappers can pass an intuitive total. `retry_max_attempts = 0`
// or `1` both mean "one attempt, no retries".
//
// `http_headers` are extra headers sent on every request (the
// connector forwards its `http_headers`, which also carries the
// composed `User-Agent`). The kernel applies them before its own
// `Authorization` / `x-databricks-org-id`, which always win.
// `http_headers` apply to SEA, telemetry, feature flags and M2M/OIDC,
// not presigned CloudFetch downloads. A caller User-Agent stays
// client-wide. Kernel Authorization/org-id take precedence.
let http_config = build_http_config(
sea_response_compression_enabled,
request_timeout_secs,
Expand Down
12 changes: 7 additions & 5 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,9 @@ pub struct KernelSessionConfig {
/// TLS relaxations / custom trust (populated by the `..._set_tls_*`
/// setters). Defaults to the kernel's strict validation.
tls: TlsSpec,
/// Extra HTTP headers sent on every request (accumulated by
/// `..._set_custom_header`, one `(name, value)` pair per call).
/// Extra HTTP headers for SEA, telemetry, feature flags and M2M/OIDC,
/// not presigned CloudFetch downloads. User-Agent remains client-wide.
/// Accumulated by `..._set_custom_header`, one pair per call.
custom_headers: Vec<(String, String)>,
/// Whether authenticated SEA responses may use HTTP compression.
sea_response_compression_enabled: bool,
Expand Down Expand Up @@ -589,9 +590,10 @@ pub unsafe extern "C" fn kernel_session_config_set_oauth_scopes(
})
}

/// Append one HTTP header sent on every request (e.g. a partner-supplied
/// `X-…` header). Call once per header; order is preserved. Both `name`
/// and `value` are required. Maps to the kernel's `custom_headers`.
/// Append one custom HTTP header for SEA, telemetry, feature-flag and M2M/OIDC
/// requests, not presigned CloudFetch downloads. A caller `User-Agent` replaces
/// the client-wide UA, including downloads. Call once per header; order is
/// preserved. Both `name` and `value` are required. Maps to `custom_headers`.
///
/// # Safety
/// `config` must be a live config handle; `name` / `value` must be
Expand Down
133 changes: 102 additions & 31 deletions src/client/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,13 +283,16 @@ pub struct HttpClientConfig {
/// TLS configuration.
pub tls: TlsConfig,
/// Databricks organization ID for multi-tenant workspace routing.
/// When set, sent as the `x-databricks-org-id` header on all authenticated requests.
/// When set, added as `x-databricks-org-id` on `execute` /
/// `execute_without_auth` and feature-flag requests, including
/// presigned CloudFetch downloads.
pub org_id: Option<String>,
/// Extra headers applied to every request, before the kernel's own
/// `Authorization` / `x-databricks-org-id` (which are added last and
/// therefore win). A caller `User-Agent` here is folded into the
/// effective UA at construction (it **replaces** the base UA, then is
/// removed from this list). Populated from
/// Extra headers applied by `execute` / `execute_without_auth`
/// (SEA, telemetry, M2M/OIDC auth) and the feature-flag GET, except
/// presigned CloudFetch downloads. The kernel's own `Authorization` /
/// `x-databricks-org-id` take precedence. A caller `User-Agent` instead
/// replaces the client-wide UA, including downloads, and is removed
/// from this list at construction. Populated from
/// [`crate::config::HttpConfig::custom_headers`]; see its docs for
/// the full precedence / reserved-name rules.
pub custom_headers: Vec<(String, String)>,
Expand Down Expand Up @@ -864,34 +867,32 @@ impl DatabricksHttpClient {
// client's effective UA in `new()` (a caller UA replaces the
// base, which then becomes reqwest's default UA header).
//
// Note: this loop runs for BOTH `execute` and
// `execute_without_auth`, so custom headers (and the effective
// User-Agent) also ride OAuth token-endpoint requests. This
// is intentional and matches the Thrift connector, where
// `setCustomHeaders` applies to every request on the
// transport, IdP calls included.
for (name, value) in &self.config.custom_headers {
let lname = name.to_ascii_lowercase();
if lname == "authorization" || lname == "x-databricks-org-id" {
warn!(
header = %name,
"ignoring caller-supplied custom header; this name is \
// M2M token/OIDC requests through `execute_without_auth` retain
// these headers; presigned downloads do not. UA is client-wide.
if request_type != RequestType::CloudFetchDownload {
for (name, value) in &self.config.custom_headers {
let lname = name.to_ascii_lowercase();
if lname == "authorization" || lname == "x-databricks-org-id" {
warn!(
header = %name,
"ignoring caller-supplied custom header; this name is \
managed by the kernel and cannot be overridden"
);
continue;
}
if lname == "accept-encoding"
&& with_auth
&& !self.config.sea_response_compression_enabled
{
warn!(
header = %name,
"ignoring caller-supplied Accept-Encoding header because SEA response \
);
continue;
}
if lname == "accept-encoding"
&& with_auth
&& !self.config.sea_response_compression_enabled
{
warn!(
header = %name,
"ignoring caller-supplied Accept-Encoding header because SEA response \
compression is disabled"
);
continue;
);
continue;
}
req_builder = req_builder.header(name, value);
}
req_builder = req_builder.header(name, value);
}

for (name, value) in headers.iter() {
Expand Down Expand Up @@ -1205,6 +1206,76 @@ mod tests {
// custom header + caller UA present AND auth = real-token.
}

#[tokio::test]
async fn test_custom_headers_exclude_cloudfetch_but_preserve_link_headers() {
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};

let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;

let config = HttpClientConfig {
custom_headers: vec![
(
"X-Databricks-Driver-Test".to_string(),
"custom-header-sentinel".to_string(),
),
(
"x-storage-header".to_string(),
"connection-value".to_string(),
),
],
..HttpClientConfig::default()
};
let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap();
client.set_auth_provider(Arc::new(PersonalAccessToken::new("real-token".to_string())));

for request_type in [
RequestType::CreateSession,
RequestType::CloseSession,
RequestType::ExecuteStatement,
RequestType::ExecuteMetadataQuery,
RequestType::GetStatementStatus,
RequestType::CancelStatement,
RequestType::CloseStatement,
RequestType::GetResultChunks,
RequestType::TelemetryExport,
RequestType::AuthTokenRequest,
RequestType::AuthDiscovery,
RequestType::CloudFetchDownload,
] {
let mut request = client.inner().get(server.uri());
if request_type == RequestType::CloudFetchDownload {
request = request.header("x-storage-header", "link-value");
}
let request = request.build().unwrap();
let response = match request_type.category() {
RequestCategory::Auth | RequestCategory::CloudFetch => {
client.execute_without_auth(request, request_type).await
}
_ => client.execute(request, request_type).await,
}
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);

let requests = server.received_requests().await.unwrap();
let headers = &requests.last().unwrap().headers;
if request_type == RequestType::CloudFetchDownload {
assert!(!headers.contains_key("x-databricks-driver-test"));
assert_eq!(headers.get_all("x-storage-header").iter().count(), 1);
assert_eq!(headers["x-storage-header"], "link-value");
} else {
assert_eq!(
headers["x-databricks-driver-test"],
"custom-header-sentinel"
);
}
}
}

#[tokio::test]
async fn authenticated_requests_use_identity_encoding_by_default() {
use wiremock::matchers::{header, method, path};
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,10 +790,10 @@ pub struct HttpConfig {
/// map it as `retry_max_retries = max(0, total_attempts - 1)`.
pub retry_max_retries: u32,

/// Extra HTTP headers to send on every request. Lets wrappers
/// forward caller-supplied headers (the connector's `http_headers`,
/// which also carries the composed `User-Agent`) onto the kernel's
/// HTTP stack.
/// Extra HTTP headers applied by `execute` / `execute_without_auth`
/// (SEA, telemetry, M2M/OIDC auth) and the feature-flag GET, except
/// presigned CloudFetch downloads. A caller `User-Agent` becomes the
/// client-wide UA and is sent everywhere.
///
/// **`Authorization` / `x-databricks-org-id` are reserved:** a
/// caller entry for either name is **silently dropped (with a
Expand Down
59 changes: 57 additions & 2 deletions src/reader/cloudfetch/chunk_downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,63 @@ mod tests {
assert_eq!(downloader.speed_threshold_mbps, 0.1);
}

// Note: Full download tests require mocking the HTTP layer
// Integration tests should be added in a separate test module
#[tokio::test]
async fn test_download_excludes_connection_headers_and_preserves_link_headers() {
use arrow_ipc::writer::StreamWriter;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

let server = MockServer::start().await;
let batch = make_batch(0, 2);
let mut bytes = Vec::new();
{
let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
}
let byte_count = bytes.len() as i64;
Mock::given(method("GET"))
.and(path("/chunk"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(bytes))
.expect(1)
.mount(&server)
.await;

let http_client = Arc::new(
DatabricksHttpClient::with_default_retry(HttpClientConfig {
custom_headers: vec![
(
"X-Databricks-Driver-Test".to_string(),
"custom-header-sentinel".to_string(),
),
("User-Agent".to_string(), "MyConnector/1.0".to_string()),
],
..HttpClientConfig::default()
})
.unwrap(),
);
let downloader = ChunkDownloader::new(http_client, CompressionCodec::None, 0.0);
let link = CloudFetchLink {
url: format!("{}/chunk", server.uri()),
row_count: 2,
byte_count,
http_headers: HashMap::from([(
"x-storage-header".to_string(),
"link-value".to_string(),
)]),
..create_test_link()
};

let batches = downloader.download(&link, None).await.unwrap();
assert_eq!(batches, vec![batch]);
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
let headers = &requests[0].headers;
assert!(!headers.contains_key("x-databricks-driver-test"));
assert_eq!(headers.get_all("x-storage-header").iter().count(), 1);
assert_eq!(headers["x-storage-header"], "link-value");
assert_eq!(headers["user-agent"], "MyConnector/1.0");
}

use arrow_array::Int32Array;
use arrow_schema::{DataType, Field, Schema};
Expand Down
Loading