diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index edcf6001..65f8c719 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -125,11 +125,18 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `HttpConfig` — HTTP client (optional) +`http2_enabled` covers all HTTPS traffic created by the session, including +authentication, SQL and result downloads. Telemetry clients are shared per host +and may reuse an earlier session's HTTP settings. An explicit proxy URL or nonempty +`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (including lowercase variants) forces +HTTP/1.1, including destinations that bypass the proxy. + | Field | Description | Default | |-------|-------------|---------| +| `http2_enabled` | HTTP/2 with HTTP/1.1 fallback; `false` forces HTTP/1.1. | `true` | | `request_timeout` | Per-request timeout (connect + body). | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | -| `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | +| `pool_max_idle_per_host` | Maximum idle connections retained per host. HTTP/1.1 concurrency can use multiple sockets; HTTP/2 multiplexes requests on a shared connection. This does not limit active requests or HTTP/2 streams. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | | `retry_max_wait` | Maximum backoff between retries; caps both the exponential backoff and a server `Retry-After`. | `60s` | | `retry_max_retries` | Max retries **after** the first attempt — a request is tried at most `retry_max_retries + 1` times. | `5` (→ 6 total attempts) | diff --git a/Cargo.lock b/Cargo.lock index b8867a94..a7fce602 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -655,14 +655,17 @@ dependencies = [ "arrow-select", "async-trait", "base64", + "bytes", "cbc 0.2.1", "chrono", "dashmap", "dirs", "futures", "geo-traits", + "h2", "hex", "hmac 0.13.0", + "http", "jsonwebtoken", "log", "lz4_flex", @@ -1059,9 +1062,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.15" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2288,6 +2291,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/Cargo.toml b/Cargo.toml index f428c382..04e89dc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ 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"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream", "http2"] } 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. @@ -150,6 +150,9 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-uti wiremock = "0.6" tempfile = "3" log = "0.4" +bytes = "1" +h2 = "0.4" +http = "1" # Generate JWT test keys in-process to avoid PEM fixtures and an external # `openssl` dependency. `ring` already backs runtime JWT signing. rsa = { version = "0.9", features = ["pem"] } @@ -195,7 +198,7 @@ tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring # guarantee — items 1 and 2 above are. [features] default = ["tls-native"] -tls-native = ["reqwest/native-tls", "dep:native-tls"] +tls-native = ["reqwest/native-tls-alpn", "dep:native-tls"] # `rustls-tls` alone is `reqwest/rustls-tls-webpki-roots` — the bundled Mozilla # root set only, which does NOT read the OS system trust store. `tls-native` # (native-tls → OpenSSL) DOES read `/etc/ssl/...`, so a `tls-rustls` build behind diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8577a424..4cdeef29 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,6 +16,13 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default when no + proxy is configured. Explicit or environment proxy configuration forces + HTTP/1.1 for the entire client. Set + `HttpConfig.http2_enabled` to `false`, or use + `kernel_session_config_set_http2_enabled(config, false)`, to force HTTP/1.1. + Rust ADBC exposes `adbc.databricks.http.http2_enabled`. + - Rust ADBC requests identify themselves as `RustADBCDatabricksDriver/` with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 37956eeb..7175b95d 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -1183,6 +1183,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -2115,10 +2130,12 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-tls", "hyper-util", "js-sys", @@ -2180,6 +2197,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -2189,6 +2219,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2646,6 +2687,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.20" diff --git a/adbc/README.md b/adbc/README.md index 7b5bac0f..ead93dce 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -98,7 +98,7 @@ The main database option families are: | Namespace | `adbc.databricks.catalog`, `adbc.databricks.schema` | | Attribution | `adbc.databricks.user_agent_entry` | | Session | `adbc.databricks.session_conf.`, `adbc.databricks.ssp_ansi_mode`, `adbc.databricks.ssp_timezone`, `adbc.databricks.query_tags` | -| HTTP | request/overall timeouts, idle pool size, retry limits/backoff, response compression, JSON custom headers | +| HTTP | HTTP/2 negotiation, request/overall timeouts, idle pool size, retry limits/backoff, response compression, JSON custom headers | | Proxy | URL, username, password, bypass hosts | | TLS/mTLS | CA file or PEM, client certificate/key file or PEM, self-signed and hostname-verification controls | | Logging | filter and file | @@ -107,6 +107,10 @@ The main database option families are: | Execution | `adbc.databricks.enable_direct_results` (default `true`); set `false` to use `wait_timeout=0s` and status polling | | Metadata | `adbc.databricks.metadata.escape_catalog_name` | +HTTPS requests negotiate HTTP/2 with HTTP/1.1 fallback by default. Set +`adbc.databricks.http.http2_enabled` to `false` to force HTTP/1.1 for session +HTTPS traffic. Configured proxies force HTTP/1.1, including bypassed destinations. + The optional user-agent entry is appended to the driver-owned identity as `RustADBCDatabricksDriver/ ()`. Set it through `adbc.databricks.user_agent_entry`; `User-Agent` is not accepted in the generic diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..baa67bee 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -399,6 +399,7 @@ impl DatabaseConfig { fn set_http(&mut self, key: &str, value: OptionValue) -> Result<()> { match key { + "adbc.databricks.http.http2_enabled" => self.http.http2_enabled = boolean(value, key)?, "adbc.databricks.http.request_timeout_ms" => { self.http.request_timeout = duration(value, key, false)? } @@ -1692,6 +1693,19 @@ mod tests { } } + #[test] + fn http2_default_and_opt_out_reach_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + assert!(config.resolve().unwrap().http.http2_enabled); + for enabled in [false, true] { + set(&mut config, "adbc.databricks.http.http2_enabled", enabled); + assert_eq!(config.resolve().unwrap().http.http2_enabled, enabled); + } + } + #[test] fn http_pool_and_custom_headers_reach_kernel_config() { let mut config = DatabaseConfig::default(); diff --git a/deny.toml b/deny.toml index 95be6715..9e34c816 100644 --- a/deny.toml +++ b/deny.toml @@ -38,17 +38,6 @@ ignore = [ # type, so exercising the RSA load+sign path in tests has value. # Re-evaluate when `rsa` ships a constant-time stable release. "RUSTSEC-2023-0071", - # RUSTSEC-2026-0258 — "h2 unbounded empty DATA frames". A DoS advisory - # in `h2 0.4.15`, pulled in transitively via `hyper` <- `reqwest` - # (`cargo tree -i h2`); not a direct dependency and unrelated to this - # crate's code. 0.4.15 is already the latest 0.4.x (a `cargo update -p - # h2` is a no-op), so it cannot be cleared by a bump; clearing it needs - # an upstream `hyper`/`reqwest` release that requires the fixed `h2`. - # The advisory concerns a server-side frame-flood; the kernel is an - # HTTP *client* to Databricks SEA, so the attack surface is not exercised - # here. Pre-existing on `main` (fires against the shared reqwest stack, - # not this PR). Re-evaluate when the reqwest/hyper stack picks up the fix. - "RUSTSEC-2026-0258", ] [licenses] diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..ef462902 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -361,6 +361,11 @@ KernelStatusCode kernel_session_config_set_enable_geospatial_support( KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, const char* name, const char* value); +/* Negotiate HTTP/2 for session HTTPS requests, with HTTP/1.1 fallback. + * Enabled by default. False or a configured proxy forces HTTP/1.1. */ +KernelStatusCode kernel_session_config_set_http2_enabled( + KernelSessionConfig* config, bool enabled); + /* Configure whether authenticated SEA responses may use HTTP compression. * Disabled by default. */ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b7eb6a6d..ec6e602d 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -997,9 +997,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.15" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2139,6 +2139,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index d5ca462e..fa7d598b 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,10 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.enableHttp2` selects HTTP/2 negotiation for HTTPS requests. + It defaults to enabled; set it to `false` to force HTTP/1.1. Configured proxies + force HTTP/1.1 for the entire kernel client. + ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..e67d33c3 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -518,6 +518,8 @@ export interface ConnectionOptions { * Whether SEA API responses may use HTTP compression. Defaults to false. */ seaResponseCompressionEnabled?: boolean + /** Negotiate HTTP/2 over HTTPS by default. False or a configured proxy forces HTTP/1.1. */ + enableHttp2?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's * built-in policy (1s/60s exponential backoff, 6 total attempts, 900s diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..9b2c30a3 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -388,6 +388,9 @@ pub struct ConnectionOptions { /// Whether SEA API responses may use HTTP compression. Defaults to false. pub sea_response_compression_enabled: Option, + /// Negotiate HTTP/2 over HTTPS by default. False or a configured proxy forces HTTP/1.1. + pub enable_http2: Option, + /// Retry/backoff tuning — all optional. An unset field keeps the kernel's /// built-in policy (1s/60s exponential backoff, 6 total attempts, 900s /// budget). Mirrors the pyo3 binding's `retry_*` kwargs so the Node.js @@ -624,6 +627,9 @@ fn build_tls_config(options: &ConnectionOptions) -> TlsConfig { /// strings. fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { let mut http = HttpConfig::default(); + if let Some(enabled) = options.enable_http2 { + http.http2_enabled = enabled; + } http.sea_response_compression_enabled = options.sea_response_compression_enabled.unwrap_or(false); http.pool_max_idle_per_host = options @@ -955,6 +961,7 @@ mod tests { client_key_pem: None, custom_headers: None, sea_response_compression_enabled: None, + enable_http2: None, retry_min_wait_secs: None, retry_max_wait_secs: None, retry_max_attempts: None, @@ -1574,6 +1581,18 @@ mod tests { assert_eq!(http.custom_headers[1].1, "Connector/2.0"); } + #[test] + fn http2_option_preserves_default_and_opt_out() { + for enabled in [None, Some(true), Some(false)] { + let mut options = base(); + options.enable_http2 = enabled; + assert_eq!( + build_http_config(&mut options).http2_enabled, + enabled.unwrap_or(true) + ); + } + } + #[test] fn sea_response_compression_option_maps_to_http_config() { let mut defaults = base(); diff --git a/osv-scanner.toml b/osv-scanner.toml index 02316c80..45640b57 100644 --- a/osv-scanner.toml +++ b/osv-scanner.toml @@ -49,25 +49,3 @@ id = "GHSA-h395-gr6q-cpjc" # ring-backed 10.x if one exists) before renewing. ignoreUntil = 2027-02-14 reason = "jsonwebtoken claim-validation bug (CVE-2026-25537) is in the decode path; the kernel only signs, never decodes/validates JWTs (verified: no decode/Validation calls in src/). Upgrade to 10.x deferred — it forces rust_crypto (rsa/RUSTSEC-2023-0071 in runtime) or aws_lc_rs (C dep). Re-review on expiry." - -[[IgnoredVulns]] -id = "RUSTSEC-2026-0258" -# "h2 unbounded empty DATA frames" — a DoS advisory in `h2 0.4.15`, pulled in -# transitively via `hyper` <- `reqwest` (`cargo tree -i h2`). Not a direct -# dependency and unrelated to this crate's code; pre-existing on `main` (fires -# against the shared reqwest/hyper stack, not this PR). -# -# Not reachable in the way the advisory describes: it concerns a SERVER -# accepting a flood of empty DATA frames; the kernel is an HTTP *client* to -# Databricks SEA and never runs an h2 server, so the affected entrypoint is -# not exposed. -# -# Cannot be cleared by a bump: 0.4.15 is already the latest 0.4.x -# (`cargo update -p h2` is a no-op); clearing it needs an upstream -# `reqwest`/`hyper` release that pulls the fixed `h2`. -# -# ignoreUntil forces periodic re-review: when it lapses OSV re-reports the -# finding, and someone must reconfirm the client-only posture (and re-check -# for a reqwest/hyper release carrying the fix) before renewing. -ignoreUntil = 2027-02-14 -reason = "h2 (RUSTSEC-2026-0258) DoS is a server-side empty-DATA-frame flood; the kernel is an HTTP client only and runs no h2 server. Transitive via reqwest/hyper, pre-existing on main, latest 0.4.x so no bump available. Re-review on expiry." diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index c908c554..80907079 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -795,6 +795,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -962,6 +968,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -1075,6 +1100,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -2051,6 +2077,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..0e330457 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,10 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session(enable_http2=False)` forces HTTP/1.1 for HTTPS requests. By default, + connections negotiate HTTP/2 with HTTP/1.1 fallback. Configured proxies force + HTTP/1.1 for the entire kernel client. + ### Changed ### Updated diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..2bbb5405 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -161,6 +161,7 @@ fn build_http_config( retry_max_attempts: Option, retry_overall_timeout_secs: Option, http_headers: Option>, + enable_http2: Option, ) -> PyResult> { // Zero means "keep the kernel default", matching the C ABI setter. Use a // float because databricks-sql-python's existing `_socket_timeout` accepts @@ -199,12 +200,16 @@ fn build_http_config( && retry_max_attempts.is_none() && retry_overall_timeout_secs.is_none() && !has_http_headers + && enable_http2.is_none() { return Ok(None); } let mut http = databricks_sql_kernel::HttpConfig::default(); http.sea_response_compression_enabled = sea_response_compression_enabled; + if let Some(enabled) = enable_http2 { + http.http2_enabled = enabled; + } if let Some(timeout) = request_timeout { http.request_timeout = timeout; } @@ -376,6 +381,7 @@ impl Session { tls_client_cert=None, tls_client_key=None, sea_response_compression_enabled=false, + enable_http2=None, request_timeout_secs=None, max_connections=None, retry_min_wait_secs=None, @@ -443,6 +449,7 @@ impl Session { tls_client_cert: Option>, tls_client_key: Option>, sea_response_compression_enabled: bool, + enable_http2: Option, request_timeout_secs: Option, max_connections: Option, retry_min_wait_secs: Option, @@ -543,10 +550,8 @@ impl Session { None }; - // Build an HttpConfig only when the caller tuned the request timeout, - // retry/backoff, or supplied custom headers; otherwise leave the - // builder on its defaults (120s request timeout, - // 1s/60s/5-retries, no extra headers). + // Leave the builder's HTTP defaults intact unless a timeout, pool, retry, + // header, compression or protocol option was supplied. // // `retry_max_attempts` is the **total** number of attempts // (matching the connector's `_retry_stop_after_attempts_count` @@ -569,6 +574,7 @@ impl Session { retry_max_attempts, retry_overall_timeout_secs, http_headers, + enable_http2, )?; let driver_system_configuration = build_driver_system_configuration( @@ -851,21 +857,33 @@ mod send_sync_tests { .is_ok()); } + #[test] + fn http2_kwarg_maps_to_http_config() { + for enabled in [None, Some(true), Some(false)] { + let http = build_http_config(false, None, None, None, None, None, None, None, enabled) + .unwrap(); + match enabled { + None => assert!(http.is_none()), + Some(enabled) => assert_eq!(http.unwrap().http2_enabled, enabled), + } + } + } + #[test] fn request_timeout_kwarg_maps_to_http_config() { let default = databricks_sql_kernel::HttpConfig::default(); assert!( - build_http_config(false, None, None, None, None, None, None, None) + build_http_config(false, None, None, None, None, None, None, None, None) .unwrap() .is_none() ); assert!( - build_http_config(false, Some(0.0), None, None, None, None, None, None) + build_http_config(false, Some(0.0), None, None, None, None, None, None, None) .unwrap() .is_none() ); - let http = build_http_config(false, Some(0.5), None, None, None, None, None, None) + let http = build_http_config(false, Some(0.5), None, None, None, None, None, None, None) .unwrap() .expect("positive request timeout should build an HTTP config"); assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); @@ -881,40 +899,64 @@ mod send_sync_tests { None, None, None, - None + None, + None, ) .is_err()); - let http = build_http_config(false, Some(one_ns), None, None, None, None, None, None) - .unwrap() - .expect("one-nanosecond request timeout should be accepted"); + let http = build_http_config( + false, + Some(one_ns), + None, + None, + None, + None, + None, + None, + None, + ) + .unwrap() + .expect("one-nanosecond request timeout should be accepted"); assert_eq!(http.request_timeout, std::time::Duration::from_nanos(1)); - assert!(build_http_config(false, Some(-1.0), None, None, None, None, None, None).is_err()); assert!( - build_http_config(false, Some(f64::NAN), None, None, None, None, None, None).is_err() + build_http_config(false, Some(-1.0), None, None, None, None, None, None, None).is_err() ); + assert!(build_http_config( + false, + Some(f64::NAN), + None, + None, + None, + None, + None, + None, + None + ) + .is_err()); } #[test] fn max_connections_kwarg_maps_to_http_config() { let default = databricks_sql_kernel::HttpConfig::default(); - let http = build_http_config(false, None, Some(17), None, None, None, None, None) + let http = build_http_config(false, None, Some(17), None, None, None, None, None, None) .unwrap() .expect("max connections should build an HTTP config"); assert_eq!(http.pool_max_idle_per_host, 17); assert_eq!(http.request_timeout, default.request_timeout); - assert!(build_http_config(false, None, Some(0), None, None, None, None, None).is_err()); + assert!( + build_http_config(false, None, Some(0), None, None, None, None, None, None).is_err() + ); } #[test] fn sea_response_compression_kwarg_maps_to_http_config() { assert!( - build_http_config(false, None, None, None, None, None, None, None) + build_http_config(false, None, None, None, None, None, None, None, None) .unwrap() .is_none() ); - let http = build_http_config(true, None, None, None, None, None, None, None) + let http = build_http_config(true, None, None, None, None, None, None, None, None) .unwrap() .expect("enabling SEA response compression should build an HTTP config"); assert!(http.sea_response_compression_enabled); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..65d933b5 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -152,6 +152,7 @@ pub struct KernelSessionConfig { custom_headers: Vec<(String, String)>, /// Whether authenticated SEA responses may use HTTP compression. sea_response_compression_enabled: bool, + http2_enabled: Option, /// Total request timeout (populated by `..._set_request_timeout`). `None` /// keeps [`HttpConfig::default`]'s 120-second timeout. request_timeout: Option, @@ -288,6 +289,7 @@ pub unsafe extern "C" fn kernel_session_config_new( tls: TlsSpec::default(), custom_headers: Vec::new(), sea_response_compression_enabled: false, + http2_enabled: None, request_timeout: None, max_connections: None, retry: None, @@ -610,6 +612,22 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( }) } +/// Negotiate HTTP/2 for HTTPS requests by default, with HTTP/1.1 fallback. +/// Setting `enabled` to `false` or configuring a proxy forces HTTP/1.1. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_http2_enabled( + config: *mut KernelSessionConfig, + enabled: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.http2_enabled = Some(enabled); + Ok(()) + }) +} + /// Configure whether authenticated SEA responses may use HTTP compression. /// The default is `false`. /// @@ -1514,12 +1532,16 @@ fn merge_http_config( request_timeout: Option, max_connections: Option, retry: Option, + http2_enabled: Option, ) -> HttpConfig { let mut http = HttpConfig { custom_headers, sea_response_compression_enabled, ..HttpConfig::default() }; + if let Some(enabled) = http2_enabled { + http.http2_enabled = enabled; + } if let Some(t) = request_timeout { http.request_timeout = t; } @@ -1651,6 +1673,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Result Result>, retry_configs: HashMap, } @@ -394,9 +395,21 @@ impl DatabricksHttpClient { /// Auth provider must be set separately via `set_auth_provider()` before /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). + /// + /// HTTPS connections negotiate HTTP/2 with HTTP/1.1 fallback unless a proxy is configured. + /// This constructor has no protocol opt-out; session-created clients honor + /// [`HttpConfig::http2_enabled`](crate::HttpConfig::http2_enabled). pub fn new( + config: HttpClientConfig, + retry_configs: HashMap, + ) -> Result { + Self::new_with_http2(config, retry_configs, true) + } + + pub(crate) fn new_with_http2( mut config: HttpClientConfig, retry_configs: HashMap, + http2_enabled: bool, ) -> Result { // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't @@ -478,8 +491,17 @@ impl DatabricksHttpClient { })?; } + // Use one HTTP/1.1 policy for every configured proxy, including bypassed + // destinations. This avoids reqwest's HTTPS-proxy ALPN/CONNECT mismatch. + let http2_enabled = + resolve_http2(http2_enabled, &config.proxy, |key| std::env::var_os(key)); + // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = Self::build_reqwest_client( + &config, + http2_enabled, + reqwest::redirect::Policy::default(), + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -494,12 +516,13 @@ impl DatabricksHttpClient { } else { "native-tls" }, - "DatabricksHttpClient initialised" + http2_enabled, "DatabricksHttpClient initialised" ); Ok(Self { client, config, + http2_enabled, auth_provider: OnceLock::new(), retry_configs, }) @@ -509,10 +532,11 @@ impl DatabricksHttpClient { /// /// Factored out of `new()` so tenant discovery can obtain a client that /// does NOT follow redirects (to read the first `/aad/auth` hop's - /// `Location`) while still honouring the workspace's TLS, proxy, timeout, - /// and user-agent configuration. + /// `Location`) while still honouring the workspace's protocol, TLS, proxy, + /// timeout and user-agent configuration. fn build_reqwest_client( config: &HttpClientConfig, + http2_enabled: bool, redirect: reqwest::redirect::Policy, ) -> Result { let mut builder = Client::builder() @@ -524,6 +548,10 @@ impl DatabricksHttpClient { .user_agent(&config.user_agent) .redirect(redirect); + if !http2_enabled { + builder = builder.http1_only(); + } + // Apply TLS configuration if config.tls.enabled == Some(false) { builder = builder.https_only(false); @@ -805,7 +833,11 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + self.http2_enabled, + reqwest::redirect::Policy::none(), + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; @@ -943,6 +975,13 @@ impl DatabricksHttpClient { match self.client.execute(request).await { Ok(response) => { let status = response.status(); + debug!( + request_type = ?request_type, + host = ?response.url().host_str(), + http_version = ?response.version(), + status = status.as_u16(), + "received HTTP response" + ); if status.is_success() { if attempts > 1 { @@ -1079,6 +1118,29 @@ impl DatabricksHttpClient { } } +fn resolve_http2( + requested: bool, + proxy: &ProxyConfig, + lookup: impl Fn(&str) -> Option, +) -> bool { + requested + && proxy.url.is_none() + && ![ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] + .iter() + .any(|key| lookup(key).is_some_and(|value| !value.is_empty())) +} + +#[cfg(test)] +#[path = "http2_tests.rs"] +mod http2_tests; + #[cfg(test)] #[path = "http_tls_tests.rs"] mod tls_tests; diff --git a/src/client/http2_tests.rs b/src/client/http2_tests.rs new file mode 100644 index 00000000..d791aa6c --- /dev/null +++ b/src/client/http2_tests.rs @@ -0,0 +1,327 @@ +// 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. + +use crate::auth::PersonalAccessToken; +use crate::client::{ + build_retry_configs, DatabricksHttpClient, HttpClientConfig, RequestType, RetryConfig, +}; +use crate::config::{AuthConfig, HttpConfig, TelemetryConfig, TlsConfig}; +use crate::Session; +use bytes::Bytes; +use http::Version; +use rustls::pki_types::PrivatePkcs8KeyDer; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use tokio::task::{JoinHandle, JoinSet}; +use tokio_rustls::TlsAcceptor; + +use super::{resolve_http2, ProxyConfig}; + +struct HttpsServer { + url: String, + certificate: Vec, + requests: mpsc::UnboundedReceiver, + acceptor: TlsAcceptor, + task: JoinHandle<()>, +} + +impl Drop for HttpsServer { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl HttpsServer { + async fn start(http2: bool) -> Self { + let identity = rcgen::generate_simple_self_signed(vec!["127.0.0.1".into()]).unwrap(); + let certificate = identity.cert.pem().into_bytes(); + let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![identity.cert.der().clone()], + PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der()).into(), + ) + .unwrap(); + if http2 { + tls.alpn_protocols.push(b"h2".to_vec()); + } + tls.alpn_protocols.push(b"http/1.1".to_vec()); + let acceptor = TlsAcceptor::from(Arc::new(tls)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("https://{}", listener.local_addr().unwrap()); + let (versions, received_versions) = mpsc::unbounded_channel(); + let proxy_acceptor = acceptor.clone(); + let task = tokio::spawn(async move { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept() => { + let socket = accepted.unwrap().0; + let acceptor = acceptor.clone(); + let versions = versions.clone(); + connections.spawn(async move { + let mut stream = acceptor.accept(socket).await.unwrap(); + if stream.get_ref().1.alpn_protocol() == Some(b"h2") { + let mut connection = h2::server::handshake(stream).await.unwrap(); + while let Some(request) = connection.accept().await { + let (request, mut response) = request.unwrap(); + versions.send(request.version()).unwrap(); + let redirect = request.uri().path() == "/redirect"; + let response_head = http::Response::builder() + .status(if redirect { 302 } else { 200 }) + .header("location", "https://example.invalid/authorize") + .body(()) + .unwrap(); + response.send_response(response_head, false).unwrap() + .send_data(Bytes::from_static(br#"{"session_id":"http2-test"}"#), true) + .unwrap(); + } + } else { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).await.unwrap_or(0) == 0 { + return; + } + request.push(byte[0]); + } + versions.send(Version::HTTP_11).unwrap(); + let redirect = request.starts_with(b"GET /redirect "); + let body = r#"{"session_id":"http2-test"}"#; + let response = format!( + "HTTP/1.1 {}\r\nLocation: https://example.invalid/authorize\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + if redirect { "302 Found" } else { "200 OK" }, body.len(), body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + let _ = stream.shutdown().await; + } + }); + } + Some(result) = connections.join_next(), if !connections.is_empty() => { + result.unwrap(); + } + } + } + }); + Self { + url, + certificate, + requests: received_versions, + acceptor: proxy_acceptor, + task, + } + } + + async fn assert_version(&mut self, expected: Version) { + let version = tokio::time::timeout(Duration::from_secs(5), self.requests.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(version, expected); + } + + fn client(&self, enabled: bool, proxy: Option) -> DatabricksHttpClient { + let mut config = HttpClientConfig { + read_timeout: Duration::from_secs(5), + ..HttpClientConfig::default() + }; + config.tls.trusted_certificate_pem = Some(self.certificate.clone()); + config.proxy.url = proxy; + let retries = RetryConfig { + max_retries: 0, + overall_timeout: Duration::from_secs(5), + ..RetryConfig::default() + }; + let client = DatabricksHttpClient::new_with_http2( + config, + build_retry_configs(&retries, &Default::default()), + enabled, + ) + .unwrap(); + client.set_auth_provider(Arc::new(PersonalAccessToken::new("test-token"))); + client + } +} + +#[tokio::test] +async fn https_negotiates_http2_with_http1_fallback_and_opt_out() { + assert!( + resolve_http2(true, &ProxyConfig::default(), |key| std::env::var_os(key)), + "unset HTTP(S)_PROXY/ALL_PROXY and lowercase equivalents to test direct HTTP/2" + ); + for (server_http2, enabled, expected) in [ + (true, true, Version::HTTP_2), + (false, true, Version::HTTP_11), + (true, false, Version::HTTP_11), + ] { + let mut server = HttpsServer::start(server_http2).await; + let client = server.client(enabled, None); + let request = client.inner().get(&server.url).build().unwrap(); + let response = client + .execute(request, RequestType::CreateSession) + .await + .unwrap(); + assert_eq!(response.version(), expected); + response.bytes().await.unwrap(); + server.assert_version(expected).await; + assert_eq!( + client + .first_redirect_location(&format!("{}/redirect", server.url)) + .await + .unwrap(), + Some("https://example.invalid/authorize".into()) + ); + server.assert_version(expected).await; + } +} + +#[tokio::test] +async fn session_http2_opt_out_reaches_the_first_request() { + assert!( + resolve_http2(true, &ProxyConfig::default(), |key| std::env::var_os(key)), + "unset HTTP(S)_PROXY/ALL_PROXY and lowercase equivalents to test direct HTTP/2" + ); + let mut server = HttpsServer::start(true).await; + let session = Session::builder() + .http_path(&server.url, "/sql/1.0/warehouses/test") + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .http(HttpConfig { + http2_enabled: false, + request_timeout: Duration::from_secs(5), + overall_timeout: Duration::from_secs(5), + retry_max_retries: 0, + ..HttpConfig::default() + }) + .tls(TlsConfig { + custom_ca_cert: Some(server.certificate.clone()), + ..TlsConfig::default() + }) + .telemetry(TelemetryConfig { + enabled: Some(false), + ..TelemetryConfig::default() + }) + .open() + .await + .unwrap(); + server.assert_version(Version::HTTP_11).await; + session.close().await.unwrap(); +} + +async fn tunnel( + mut downstream: S, + target: String, + sent_head: tokio::sync::oneshot::Sender, +) { + let mut head = Vec::new(); + let mut byte = [0]; + while !head.ends_with(b"\r\n\r\n") { + downstream.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + let mut upstream = tokio::net::TcpStream::connect(target).await.unwrap(); + downstream + .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") + .await + .unwrap(); + sent_head.send(String::from_utf8(head).unwrap()).unwrap(); + let _ = tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await; +} + +#[tokio::test] +async fn https_uses_http1_through_an_https_proxy() { + let mut server = HttpsServer::start(true).await; + let authority = server.url.strip_prefix("https://").unwrap().to_string(); + let target = authority.clone(); + let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_url = format!("https://{}", proxy.local_addr().unwrap()); + let (sent_head, received_head) = tokio::sync::oneshot::channel(); + let acceptor = server.acceptor.clone(); + let proxy_task = tokio::spawn(async move { + let downstream = proxy.accept().await.unwrap().0; + let downstream = acceptor.accept(downstream).await.unwrap(); + assert_ne!( + downstream.get_ref().1.alpn_protocol(), + Some(b"h2".as_slice()) + ); + tunnel(downstream, target, sent_head).await; + }); + let client = server.client(true, Some(proxy_url)); + let response = client.inner().get(&server.url).send().await.unwrap(); + assert_eq!(response.version(), Version::HTTP_11); + response.bytes().await.unwrap(); + server.assert_version(Version::HTTP_11).await; + let head = tokio::time::timeout(Duration::from_secs(5), received_head) + .await + .expect("proxy did not receive CONNECT") + .unwrap(); + assert!( + head.starts_with(&format!("CONNECT {authority} HTTP/1.1\r\n")), + "{head}" + ); + proxy_task.abort(); +} + +#[test] +fn resolves_http2_from_request_and_proxy_configuration() { + for (requested, url, bypass, expected) in [ + (true, None, None, true), + (false, None, None, false), + (true, Some("https://proxy:8080"), None, false), + (true, Some("http://proxy:8080"), Some("*"), false), + ] { + let proxy = ProxyConfig { + url: url.map(Into::into), + bypass_hosts: bypass.map(Into::into), + ..ProxyConfig::default() + }; + assert_eq!(resolve_http2(requested, &proxy, |_| None), expected); + } + let proxy = ProxyConfig::default(); + for key in [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + ] { + for (value, expected) in [ + (None, true), + (Some(""), true), + (Some("http://proxy:8080"), false), + ] { + assert_eq!( + resolve_http2(true, &proxy, |name| if name == key { + value.map(Into::into) + } else { + None + }), + expected, + "{key}={value:?}" + ); + } + } + assert!(resolve_http2(true, &proxy, |name| (name == "NO_PROXY") + .then(|| "*".into()))); +} diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..e4051747 100644 --- a/src/config.rs +++ b/src/config.rs @@ -748,6 +748,11 @@ impl std::fmt::Debug for AuthConfig { #[non_exhaustive] #[derive(Debug, Clone)] pub struct HttpConfig { + /// Negotiate HTTP/2 for HTTPS requests, with HTTP/1.1 fallback. + /// Defaults to `true`. Set to `false` to use HTTP/1.1 only. + /// A configured proxy forces HTTP/1.1 for every request on the client. + pub http2_enabled: bool, + /// Whether authenticated SEA requests may negotiate HTTP response compression. /// Defaults to `false` because inline Arrow results are already LZ4-compressed. pub sea_response_compression_enabled: bool, @@ -761,13 +766,11 @@ pub struct HttpConfig { /// Retrying stops once cumulative elapsed time exceeds this. pub overall_timeout: Duration, - /// Connection pool size (max idle warm sockets per remote host). - /// - /// Defaults to `100`, matching the JDBC driver's `HttpConnectionPoolSize` - /// default. Raise this for workloads that burst many concurrent - /// `executeStatement` calls or CloudFetch chunk downloads against a - /// single host; too low a value forces fresh TLS handshakes when the - /// pool fills. + /// Maximum idle connections retained per host, defaulting to `100`, + /// matching the JDBC driver's `HttpConnectionPoolSize`. + /// Higher values preserve more warm HTTP/1.1 connections between bursts. + /// HTTP/2 requests multiplex on a shared connection; this does not + /// limit active requests or HTTP/2 streams. pub pool_max_idle_per_host: usize, /// Minimum backoff wait between retry attempts. Also the floor for @@ -834,6 +837,7 @@ pub struct HttpConfig { impl Default for HttpConfig { fn default() -> Self { Self { + http2_enabled: true, sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), overall_timeout: Duration::from_secs(900), diff --git a/src/session.rs b/src/session.rs index 2c1bdd79..dabf5acf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,7 +368,12 @@ impl Session { let http_client_config = build_http_client_config(&config, org_id); let retry_configs = build_retry_configs_for_session(&config); let http_client = Arc::new( - DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { + DatabricksHttpClient::new_with_http2( + http_client_config, + retry_configs, + config.http.http2_enabled, + ) + .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f6b78c2c..7af3dcad 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -240,6 +240,8 @@ static void test_u2m_and_header_setters(void) { rc = kernel_session_config_set_sea_response_compression_enabled(config, true); CHECK(rc == KernelStatusCode_Success, "set_sea_response_compression_enabled succeeds"); + rc = kernel_session_config_set_http2_enabled(config, false); + CHECK(rc == KernelStatusCode_Success, "set_http2_enabled succeeds"); rc = kernel_session_config_set_custom_header(config, NULL, "v"); CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL name) → InvalidArgument"); rc = kernel_session_config_set_custom_header(config, "X-Foo", NULL);