From e2fd22d2758da21a8010a03119be23fa4e2d402c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 18 Nov 2026 08:24:04 +0000 Subject: [PATCH 1/2] fix(cloudfetch): exclude connection custom headers from downloads Preserve link-provided storage headers and custom headers on warehouse, telemetry, OAuth token and discovery requests. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 1 + src/client/http.rs | 122 +++++++++++++++++++++++++++++++++++---------- src/config.rs | 3 +- 3 files changed, 99 insertions(+), 27 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 3964deb0..bf1839ad 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -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. Server-provided storage headers and warehouse/OAuth custom headers 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 `?`. diff --git a/src/client/http.rs b/src/client/http.rs index cac2243b..f6afc796 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -285,7 +285,8 @@ pub struct HttpClientConfig { /// Databricks organization ID for multi-tenant workspace routing. /// When set, sent as the `x-databricks-org-id` header on all authenticated requests. pub org_id: Option, - /// Extra headers applied to every request, before the kernel's own + /// Extra headers applied to requests other than presigned CloudFetch + /// downloads, 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 @@ -864,34 +865,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 \ + // Custom headers still apply to OAuth requests through + // `execute_without_auth`, but not presigned storage downloads. + 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() { @@ -1205,6 +1204,77 @@ 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!(!headers.contains_key("authorization")); + 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}; diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..30a90835 100644 --- a/src/config.rs +++ b/src/config.rs @@ -790,7 +790,8 @@ 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 + /// Extra HTTP headers to send on warehouse and OAuth requests, not + /// presigned CloudFetch downloads. Lets wrappers /// forward caller-supplied headers (the connector's `http_headers`, /// which also carries the composed `User-Agent`) onto the kernel's /// HTTP stack. From 88e9740d38204b35eae5d3b8d716cbc46d9c3b0d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 18 Nov 2026 09:01:46 +0000 Subject: [PATCH 2/2] test(cloudfetch): cover downloader headers and clarify public docs Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 +- include/databricks_kernel.h | 6 ++- napi/index.d.ts | 7 +-- napi/src/database.rs | 7 +-- pyo3/src/session.rs | 19 ++++---- src/c_abi/session.rs | 12 +++-- src/client/http.rs | 21 ++++---- src/config.rs | 9 ++-- src/reader/cloudfetch/chunk_downloader.rs | 59 ++++++++++++++++++++++- 9 files changed, 101 insertions(+), 41 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index bf1839ad..d8ee4369 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -25,7 +25,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed -- Connection custom headers are no longer forwarded to presigned CloudFetch downloads. Server-provided storage headers and warehouse/OAuth custom headers are preserved. +- 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 `?`. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..e70e7c39 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -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); diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..fab78452 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -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 diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..bb6def26 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -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, - /// 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 diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..5bc8ed60 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -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 @@ -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, diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..16b2377a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -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, @@ -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 diff --git a/src/client/http.rs b/src/client/http.rs index f6afc796..e3015d28 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -283,14 +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, - /// Extra headers applied to requests other than presigned CloudFetch - /// downloads, 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)>, @@ -865,8 +867,8 @@ impl DatabricksHttpClient { // client's effective UA in `new()` (a caller UA replaces the // base, which then becomes reqwest's default UA header). // - // Custom headers still apply to OAuth requests through - // `execute_without_auth`, but not presigned storage downloads. + // 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(); @@ -1263,7 +1265,6 @@ mod tests { let headers = &requests.last().unwrap().headers; if request_type == RequestType::CloudFetchDownload { assert!(!headers.contains_key("x-databricks-driver-test")); - assert!(!headers.contains_key("authorization")); assert_eq!(headers.get_all("x-storage-header").iter().count(), 1); assert_eq!(headers["x-storage-header"], "link-value"); } else { diff --git a/src/config.rs b/src/config.rs index 30a90835..b3b11b21 100644 --- a/src/config.rs +++ b/src/config.rs @@ -790,11 +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 warehouse and OAuth requests, not - /// presigned CloudFetch downloads. 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 diff --git a/src/reader/cloudfetch/chunk_downloader.rs b/src/reader/cloudfetch/chunk_downloader.rs index f22de8b9..2234ca86 100644 --- a/src/reader/cloudfetch/chunk_downloader.rs +++ b/src/reader/cloudfetch/chunk_downloader.rs @@ -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};