diff --git a/.github/workflows/rust-e2e.yml b/.github/workflows/rust-e2e.yml index cb6dfbe9..094bd44b 100644 --- a/.github/workflows/rust-e2e.yml +++ b/.github/workflows/rust-e2e.yml @@ -87,7 +87,7 @@ jobs: - name: Run v0 E2E tests run: | - for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e; do + for suite in v0_session_e2e v0_execute_e2e v0_async_execute_e2e v0_metadata_e2e v0_query_tags_headers_e2e; do echo "::group::cargo test --test ${suite}" cargo test --test "${suite}" -- --ignored --nocapture echo "::endgroup::" diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 97cad23c..f1c89219 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -88,10 +88,14 @@ pub struct ExecuteOptions { /// raises `InvalidArgument` — the caller's intent is ambiguous /// so we refuse to silently pick one over the other. /// + /// A **`null`** value emits a **bare key** (no colon) — e.g. + /// `{ production: null }` → `"production"` — matching the + /// connectors' `key`-only tag form. + /// /// See the struct-level "Tag-order caveat" for the /// HashMap-iteration-order vs `Object.keys`-iteration-order /// divergence and the byte-identical-Thrift-parity workaround. - pub query_tags: Option>, + pub query_tags: Option>>, /// Server-side cap on the number of rows this statement returns /// (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to /// `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. @@ -199,7 +203,7 @@ fn build_statement( session: &Session, sql: String, statement_conf: Option>, - query_tags: Option>, + query_tags: Option>>, row_limit: Option, query_timeout_secs: Option, positional_params: Vec, @@ -220,6 +224,7 @@ fn build_statement( } // Fold the `queryTags` convenience map into the conf overlay. Empty map is // a no-op; a dual definition with `statementConf["query_tags"]` rejects. + // A `null` JS value maps to `None` → a bare key on the wire. if let Some(tags) = query_tags { stmt.spec().query_tags(tags).map_err(napi_err_from_kernel)?; } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 3ea345d9..12bc503e 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -91,6 +91,13 @@ impl Session { /// CloudFetch requests; token-endpoint (auth) calls keep a fixed /// fast-fail policy. /// + /// `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. + /// /// `session_conf` is the server-bound session configuration map /// — passed through to SEA `session_confs` verbatim. Use for /// `ANSI_MODE`, `TIMEZONE`, `STATEMENT_TIMEOUT`, query-tag @@ -119,6 +126,7 @@ impl Session { retry_max_wait_secs=None, retry_max_attempts=None, retry_overall_timeout_secs=None, + http_headers=None, catalog=None, schema=None, session_conf=None, @@ -147,6 +155,7 @@ impl Session { retry_max_wait_secs: Option, retry_max_attempts: Option, retry_overall_timeout_secs: Option, + http_headers: Option>, catalog: Option, schema: Option, session_conf: Option>, @@ -199,8 +208,9 @@ impl Session { None }; - // Build an HttpConfig only when the caller tuned retry/backoff; - // otherwise leave the builder on its defaults (1s/60s/5-retries). + // Build an HttpConfig only when the caller tuned retry/backoff + // or supplied custom headers; otherwise leave the builder on its + // defaults (1s/60s/5-retries, no extra headers). // // `retry_max_attempts` is the **total** number of attempts // (matching the connector's `_retry_stop_after_attempts_count` @@ -209,10 +219,17 @@ impl Session { // `max(0, attempts - 1)` here — centralising the off-by-one so // 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. + let has_http_headers = http_headers.as_ref().is_some_and(|h| !h.is_empty()); let http_config = if retry_min_wait_secs.is_some() || retry_max_wait_secs.is_some() || retry_max_attempts.is_some() || retry_overall_timeout_secs.is_some() + || has_http_headers { let mut http = databricks_sql_kernel::HttpConfig::default(); if let Some(s) = retry_min_wait_secs { @@ -227,6 +244,9 @@ impl Session { if let Some(s) = retry_overall_timeout_secs { http.overall_timeout = std::time::Duration::from_secs(s); } + if let Some(headers) = http_headers { + http.custom_headers = headers; + } Some(http) } else { None diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index b7019bc9..404f0939 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -30,6 +30,7 @@ use databricks_sql_kernel::{ Statement as KStatement, }; use pyo3::prelude::*; +use std::collections::HashMap; use std::sync::Arc; use tokio::runtime::Runtime; @@ -65,6 +66,32 @@ impl Statement { Ok(()) } + /// Set per-statement query tags. + /// + /// ``tags`` is a ``dict[str, str | None]`` — a ``None`` value emits + /// a bare key (no colon) on the wire, matching the connector's + /// ``Dict[str, Optional[str]]`` contract. The kernel serialises to + /// the SEA ``query_tags`` conf shape and merges it into the + /// per-statement conf overlay. + /// + /// Raises ``KernelError(code='InvalidArgument')`` if a ``query_tags`` + /// entry was already set explicitly via the statement conf (the + /// kernel refuses an ambiguous double-definition). An empty ``tags`` + /// dict is a no-op. + fn set_query_tags( + &mut self, + py: Python<'_>, + tags: HashMap>, + ) -> PyResult<()> { + let inner = alive_mut!(self, "Statement"); + inner + .stmt + .spec() + .query_tags(tags) + .map_err(|e| to_py_err(py, e))?; + Ok(()) + } + /// Bind a positional parameter. /// /// ``ordinal`` is 1-based on the SEA wire. ``value_str`` is the diff --git a/src/client/http.rs b/src/client/http.rs index c09d15f6..44def560 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -208,6 +208,14 @@ 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 + /// `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 (appended to the base UA, then + /// removed from this list). Populated from + /// [`crate::config::HttpConfig::custom_headers`]; see its docs for + /// the full precedence / reserved-name rules. + pub custom_headers: Vec<(String, String)>, } impl Default for HttpClientConfig { @@ -224,6 +232,7 @@ impl Default for HttpClientConfig { proxy: ProxyConfig::default(), tls: TlsConfig::default(), org_id: None, + custom_headers: Vec::new(), } } } @@ -309,9 +318,66 @@ impl DatabricksHttpClient { /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). pub fn new( - config: HttpClientConfig, + mut config: HttpClientConfig, retry_configs: HashMap, ) -> Result { + // Fold any caller-supplied `User-Agent` custom header into the + // effective UA, and remove it from `custom_headers` so it isn't + // re-applied per-request. **`User-Agent` is never replaced** — + // the kernel's base UA carries the `DatabricksJDBCDriverOSS/...` + // token the SEA server keys on to enable the + // `INLINE_OR_EXTERNAL_LINKS` result disposition; a caller UA that + // replaced it would break result fetching (HTTP 400 + // "not a supported disposition"). Instead we APPEND the caller's + // UA as a suffix: `" "`. This preserves the + // disposition gating and honors partner attribution (the + // connector's composed `PyDatabricksSqlConnector/x (entry)` UA + // rides along after the base token). + // Last UA wins if a caller somehow set several. + if let Some(caller_ua) = config + .custom_headers + .iter() + .rfind(|(n, _)| n.eq_ignore_ascii_case("user-agent")) + .map(|(_, v)| v.clone()) + { + config + .custom_headers + .retain(|(n, _)| !n.eq_ignore_ascii_case("user-agent")); + let caller_ua = caller_ua.trim(); + // Guard against a pathologically large UA on every request. + // 1 KiB is far above any legitimate `product/version (entry)` + // string; truncate (don't reject) so an over-long entry + // degrades gracefully rather than failing the session. + const MAX_UA_SUFFIX: usize = 1024; + if caller_ua.len() > MAX_UA_SUFFIX { + warn!( + len = caller_ua.len(), + "caller User-Agent suffix exceeds {MAX_UA_SUFFIX} bytes; truncating" + ); + } + let caller_ua = &caller_ua[..caller_ua.len().min(MAX_UA_SUFFIX)]; + if !caller_ua.is_empty() { + config.user_agent = format!("{} {}", config.user_agent, caller_ua); + } + } + + // Validate the remaining custom headers up front so a malformed + // name/value fails at session-open rather than on every request + // build (where it would surface as a confusing per-request + // error). Reserved names are still dropped at request time; we + // only reject structurally-invalid headers here. + for (name, value) in &config.custom_headers { + reqwest::header::HeaderName::try_from(name.as_str()).map_err(|e| { + Error::invalid_argument() + .message(format!("invalid custom HTTP header name {name:?}: {e}")) + })?; + reqwest::header::HeaderValue::try_from(value.as_str()).map_err(|e| { + Error::invalid_argument().message(format!( + "invalid custom HTTP header value for {name:?}: {e}" + )) + })?; + } + let mut builder = Client::builder() .connect_timeout(config.connect_timeout) .timeout(config.read_timeout) @@ -616,6 +682,38 @@ impl DatabricksHttpClient { // Build a fresh request for this attempt let mut req_builder = self.client.request(method.clone(), url.clone()); + // Caller-supplied custom headers go on FIRST, so the + // kernel's own auth / routing headers (set last, below) take + // precedence — matching the Thrift connector, where + // `auth_provider.add_headers` runs after the custom-header + // dict. We SKIP any custom header named `Authorization` or + // `x-databricks-org-id` (case-insensitive) so a stray caller + // header can't sit alongside the kernel's (reqwest appends + // same-named headers rather than replacing, which for those + // two would send a duplicate and could confuse the server). + // `User-Agent` is NOT in this map — it was folded into the + // client's base UA in `new()` (appended, never replacing, + // to preserve the disposition-gating JDBC token). + // + // Note: this loop runs for BOTH `execute` and + // `execute_without_auth`, so custom headers (and the merged + // 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 \ + managed by the kernel and cannot be overridden" + ); + continue; + } + req_builder = req_builder.header(name, value); + } + for (name, value) in headers.iter() { req_builder = req_builder.header(name, value); } @@ -830,6 +928,89 @@ mod tests { assert_eq!(header, "Bearer test-token"); } + #[tokio::test] + async fn test_custom_headers_applied_with_auth_winning() { + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + + // Expect: our benign custom header present; the caller's + // User-Agent is APPENDED to the kernel's base UA (never + // replacing it — the base token gates the SEA result + // disposition); Authorization is the kernel's real token (NOT + // the caller's bogus one). + Mock::given(method("GET")) + .and(path("/probe")) + .and(header("x-custom-header", "custom-value")) + .and(header( + "user-agent", + "KernelBase/9.9 MyConnector/1.0 (entry)", + )) + .and(header("authorization", "Bearer real-token")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let config = HttpClientConfig { + // Fixed base UA so the merged-UA assertion is deterministic + // (the real default embeds the crate version). + user_agent: "KernelBase/9.9".to_string(), + custom_headers: vec![ + ("x-custom-header".to_string(), "custom-value".to_string()), + ( + "User-Agent".to_string(), + "MyConnector/1.0 (entry)".to_string(), + ), + // Caller attempt to override auth — must be ignored; the + // kernel's real token wins. + ( + "Authorization".to_string(), + "Bearer caller-bogus".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()))); + + let req = client + .inner() + .request(reqwest::Method::GET, format!("{}/probe", server.uri())) + .build() + .unwrap(); + let resp = client + .execute(req, RequestType::GetStatementStatus) + .await + .expect("request should succeed against the mock"); + assert_eq!(resp.status().as_u16(), 200); + // If the matchers above didn't all match, wiremock returns the + // default 404 and the status assert fails — so a 200 confirms + // custom header + caller UA present AND auth = real-token. + } + + #[test] + fn test_malformed_custom_header_rejected_at_construction() { + // A structurally-invalid header name must fail at `new()` + // (session-open) rather than on the first request build. + let bad_name = HttpClientConfig { + custom_headers: vec![("Bad Header Name".to_string(), "v".to_string())], + ..HttpClientConfig::default() + }; + let err = DatabricksHttpClient::new(bad_name, default_retry_configs()).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("header name"), "{}", err.message); + + // An invalid header value (control char) is likewise rejected. + let bad_value = HttpClientConfig { + custom_headers: vec![("X-Custom".to_string(), "bad\nvalue".to_string())], + ..HttpClientConfig::default() + }; + let err = DatabricksHttpClient::new(bad_value, default_retry_configs()).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("header value"), "{}", err.message); + } + #[tokio::test] #[should_panic(expected = "Auth provider can only be set once")] async fn test_set_auth_provider_twice_panics() { diff --git a/src/config.rs b/src/config.rs index 494cccaf..5d0ba400 100644 --- a/src/config.rs +++ b/src/config.rs @@ -416,6 +416,38 @@ pub struct HttpConfig { /// `_retry_stop_after_attempts_count`, the JDBC driver, …) should /// 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. + /// + /// **`Authorization` / `x-databricks-org-id` are reserved:** a + /// caller entry for either name is **silently dropped (with a + /// `warn!`)** — it never reaches the wire. The kernel always adds + /// its own `Authorization` (from the auth provider) and, when set, + /// `x-databricks-org-id`, so auth and multi-tenant routing can't be + /// hijacked by a caller header. (This mirrors the Thrift connector, + /// where `auth_provider.add_headers` runs after the custom-header + /// dict and overwrites those names.) + /// + /// **`User-Agent` is special-cased:** rather than replacing the + /// kernel's base UA, a caller `User-Agent` here is **appended** to + /// it (`" "`) — it is folded into the + /// effective UA at client construction and removed from this list. + /// The base UA carries the `DatabricksJDBCDriverOSS/...` token the + /// SEA server keys on to enable the `INLINE_OR_EXTERNAL_LINKS` + /// result disposition; replacing it would break result fetching. + /// Appending preserves that gating and still surfaces the caller's + /// identity (e.g. the connector's `PyDatabricksSqlConnector/x (entry)`). + /// + /// **All other headers are sent as supplied.** A `Vec` (not a map) + /// so order is preserved. No de-duplication is performed: duplicate + /// names are applied via `reqwest`'s `HeaderMap::append`, so each + /// entry is emitted on the wire in insertion order (the receiver + /// sees every value, not just the last) — pass a name once unless + /// you specifically intend multiple header lines. + pub custom_headers: Vec<(String, String)>, } impl Default for HttpConfig { @@ -430,6 +462,7 @@ impl Default for HttpConfig { retry_min_wait: Duration::from_secs(1), retry_max_wait: Duration::from_secs(60), retry_max_retries: 5, + custom_headers: Vec::new(), } } } diff --git a/src/session.rs b/src/session.rs index 49e8f550..60da5460 100644 --- a/src/session.rs +++ b/src/session.rs @@ -588,6 +588,7 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option) -> H proxy: HttpProxyConfig::default(), tls: HttpTlsConfig::from_public(&config.tls), org_id, + custom_headers: config.http.custom_headers.clone(), ..HttpClientConfig::default() }; // Touch the still-reserved proxy config so a future field addition diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 2b180abe..e13f55b1 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -284,12 +284,21 @@ impl StatementSpec { /// Merge a `query_tags` map into the per-statement conf overlay. /// - /// Serialises `tags` to the comma-separated `key:value` wire shape - /// the SEA server expects under the `query_tags` conf key (the same - /// shape NodeJS Thrift's `serializeQueryTags` produces: backslashes - /// in keys are doubled; backslash / colon / comma in values are - /// backslash-escaped) and inserts it into `statement_conf` under - /// `"query_tags"`. + /// Serialises `tags` to the comma-separated wire shape the SEA + /// server expects under the `query_tags` conf key, matching the + /// connectors' serialisers (NodeJS Thrift's `serializeQueryTags` + /// and the Python connector's `serialize_query_tags`): + /// - backslashes in keys are doubled (colon/comma in keys are NOT + /// escaped); + /// - backslash / colon / comma in values are backslash-escaped; + /// - a **`None`** value emits a **bare key** with no colon (e.g. + /// `{"production": None}` → `"production"`), matching the Python + /// connector's `Dict[str, Optional[str]]` contract. This is + /// distinct from `Some("")`, which emits `key:` (a present but + /// empty value) — `None` means "no value", `Some("")` means + /// "empty value". + /// + /// Then inserts the result into `statement_conf` under `"query_tags"`. /// /// - An **empty** `tags` map is a no-op (returns `Ok(self)`), /// matching the "empty map means not-supplied" convention. @@ -299,7 +308,7 @@ impl StatementSpec { /// ambiguous intent the kernel refuses to silently resolve. Set /// the explicit `statement_conf` map (via [`Self::statement_conf`]) /// before calling this so the conflict is detected. - pub fn query_tags(&mut self, tags: HashMap) -> Result<&mut Self> { + pub fn query_tags(&mut self, tags: HashMap>) -> Result<&mut Self> { if tags.is_empty() { return Ok(self); } @@ -347,18 +356,25 @@ impl StatementSpec { /// non-deterministic; the SEA server treats conf values as /// order-insensitive, so the result is functionally equivalent to the /// Thrift output regardless of key order. -fn serialize_query_tags(tags: &HashMap) -> String { +fn serialize_query_tags(tags: &HashMap>) -> String { tags.iter() .map(|(k, v)| { let esc_key = k.replace('\\', "\\\\"); - let esc_val = v - .chars() - .flat_map(|c| match c { - '\\' | ':' | ',' => vec!['\\', c], - other => vec![other], - }) - .collect::(); - format!("{esc_key}:{esc_val}") + match v { + // `None` → bare key, no colon. Matches the Python + // connector's serializer for a `None`-valued tag. + None => esc_key, + Some(v) => { + let esc_val = v + .chars() + .flat_map(|c| match c { + '\\' | ':' | ',' => vec!['\\', c], + other => vec![other], + }) + .collect::(); + format!("{esc_key}:{esc_val}") + } + } }) .collect::>() .join(",") @@ -454,7 +470,7 @@ mod tests { fn query_tags_serialised_into_query_tags_key() { let mut s = StatementSpec::new(); let mut tags = HashMap::new(); - tags.insert("team".to_string(), "platform".to_string()); + tags.insert("team".to_string(), Some("platform".to_string())); s.query_tags(tags).unwrap(); assert_eq!( s.statement_conf.get("query_tags").map(String::as_str), @@ -469,7 +485,7 @@ mod tests { conf.insert("query_tags".to_string(), "explicit:value".to_string()); s.statement_conf(conf); let mut tags = HashMap::new(); - tags.insert("team".to_string(), "platform".to_string()); + tags.insert("team".to_string(), Some("platform".to_string())); let err = s.query_tags(tags).unwrap_err(); assert_eq!(err.code, ErrorCode::InvalidArgument); assert!( @@ -507,11 +523,19 @@ mod tests { /// byte shape produced by the kernel-side serializer against the /// algorithm Thrift uses, so a regression on either side fails this /// test. + /// One tag with a present value. + fn tag(k: &str, v: &str) -> HashMap> { + let mut m = HashMap::new(); + m.insert(k.to_string(), Some(v.to_string())); + m + } + #[test] fn serialize_query_tags_matches_thrift_byte_shape_single_tag() { - let mut tags = HashMap::new(); - tags.insert("team".to_string(), "platform".to_string()); - assert_eq!(serialize_query_tags(&tags), "team:platform"); + assert_eq!( + serialize_query_tags(&tag("team", "platform")), + "team:platform" + ); } #[test] @@ -519,9 +543,10 @@ mod tests { // Per Thrift's `escapedValue.replace(/[\\:,]/g, c => '\\' + c)`: // input `v:1,v\2` // output `v\:1\,v\\2` - let mut tags = HashMap::new(); - tags.insert("k".to_string(), "v:1,v\\2".to_string()); - assert_eq!(serialize_query_tags(&tags), "k:v\\:1\\,v\\\\2"); + assert_eq!( + serialize_query_tags(&tag("k", "v:1,v\\2")), + "k:v\\:1\\,v\\\\2" + ); } #[test] @@ -532,9 +557,22 @@ mod tests { // Colons/commas in keys are NOT escaped on Thrift's path — only // in values. Pins this asymmetry so a future "uniformity" // refactor that escapes them in keys too gets caught. + assert_eq!(serialize_query_tags(&tag("k\\1", "v")), "k\\\\1:v"); + } + + #[test] + fn serialize_query_tags_none_value_emits_bare_key() { + // `None` value → bare key, no colon. Matches the Python + // connector's serializer for a `None`-valued tag + // (`Dict[str, Optional[str]]`). let mut tags = HashMap::new(); - tags.insert("k\\1".to_string(), "v".to_string()); - assert_eq!(serialize_query_tags(&tags), "k\\\\1:v"); + tags.insert("production".to_string(), None); + assert_eq!(serialize_query_tags(&tags), "production"); + + // A `None`-keyed backslash is still escaped in the bare key. + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), None); + assert_eq!(serialize_query_tags(&tags), "k\\\\1"); } #[test] @@ -548,15 +586,13 @@ mod tests { // can't assert a single byte string. Assert each pair is present // and the join uses `,`. SEA treats conf values as // order-insensitive, so this is functionally equivalent to the - // Thrift output regardless of order. + // Thrift output regardless of order. Mixes a valued tag with a + // bare-key (None) tag. let mut tags = HashMap::new(); - tags.insert("a".to_string(), "1".to_string()); - tags.insert("b".to_string(), "2".to_string()); + tags.insert("a".to_string(), Some("1".to_string())); + tags.insert("b".to_string(), None); let s = serialize_query_tags(&tags); let pairs: std::collections::HashSet<&str> = s.split(',').collect(); - assert!( - pairs == ["a:1", "b:2"].iter().copied().collect(), - "got: {s}", - ); + assert!(pairs == ["a:1", "b"].iter().copied().collect(), "got: {s}",); } } diff --git a/tests/v0_query_tags_headers_e2e.rs b/tests/v0_query_tags_headers_e2e.rs new file mode 100644 index 00000000..5f7242cd --- /dev/null +++ b/tests/v0_query_tags_headers_e2e.rs @@ -0,0 +1,192 @@ +// 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. + +//! End-to-end smoke tests for per-statement **query tags** and custom +//! **HTTP headers** against a live Databricks workspace. +//! +//! These are *smoke* tests: they assert the tagged / custom-header +//! request **succeeds** end-to-end. That proves the server accepts the +//! `query_tags` statement-conf and the custom headers — a malformed +//! `query_tags` conf, or a header that breaks the request, surfaces as +//! a failed execute here. +//! +//! Why not assert harder: +//! - **query tags**: `system.query.history` carries a `query_tags` +//! column, but its ingestion lag is minutes+ (empirically nothing +//! after 60s), so a synchronous assertion would be flaky/slow. The +//! exact wire serialisation is pinned by the unit tests in +//! `src/statement/spec.rs` (`serialize_query_tags_*`). +//! - **headers**: the server doesn't echo arbitrary request headers +//! back. The exact on-the-wire behaviour (custom header + caller +//! User-Agent sent; `Authorization` / `x-databricks-org-id` win) is +//! pinned by the wiremock test in `src/client/http.rs` +//! (`test_custom_headers_applied_with_auth_winning`). +//! +//! Run with: +//! +//! ```sh +//! set -a && source ~/.databricks/pecotesting-creds && set +a +//! cargo test --test v0_query_tags_headers_e2e -- --ignored +//! ``` + +use databricks_sql_kernel::{ + AuthConfig, ExecutedStatementHandle, HttpConfig, ResultStream, Session, +}; +use std::collections::HashMap; +use std::env; + +fn env_var(key: &str) -> Option { + env::var(key).ok().filter(|v| !v.is_empty()) +} + +fn host_path_token() -> (String, String, String) { + ( + env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"), + env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"), + env_var("DATABRICKS_TOKEN").expect("DATABRICKS_TOKEN required"), + ) +} + +async fn live_session() -> Session { + let (host, path, token) = host_path_token(); + Session::builder() + .http_path(host, path) + .auth(AuthConfig::Pat { token }) + .open() + .await + .expect("Session::open against live workspace") +} + +/// Open a session whose HTTP client sends the given custom headers on +/// every request. +// `HttpConfig` is `#[non_exhaustive]`, so it can't be built with a +// struct literal from this external test crate — the +// default-then-assign form is the only option, and the clippy lint +// that prefers a literal doesn't apply. +#[allow(clippy::field_reassign_with_default)] +async fn live_session_with_headers(headers: Vec<(String, String)>) -> Session { + let (host, path, token) = host_path_token(); + let mut http = HttpConfig::default(); + http.custom_headers = headers; + Session::builder() + .http_path(host, path) + .auth(AuthConfig::Pat { token }) + .http(http) + .open() + .await + .expect("Session::open against live workspace (custom headers)") +} + +/// Drain `SELECT 1` and assert exactly one row == 1. +async fn assert_select_one(stream: &mut ResultStream) { + stream.next_batch().await.unwrap().expect("one batch"); + let row = stream.next_row_in_batch().expect("one row"); + assert_eq!(row.get_i64(0).unwrap(), Some(1)); +} + +#[tokio::test] +#[ignore] +async fn query_tags_round_trip_succeeds() { + // A query carrying per-statement query tags must execute cleanly. + // The server validates the `query_tags` conf on receipt; a + // malformed serialisation would fail the execute. + let session = live_session().await; + let mut stmt = session.statement(); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), Some("platform".to_string())); + tags.insert("dashboard".to_string(), Some("abc123".to_string())); + stmt.spec().sql("SELECT 1 AS n"); + stmt.spec().query_tags(tags).expect("query_tags accepted"); + + let mut exec = stmt.execute().await.expect("execute with query tags"); + assert_select_one(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + +#[tokio::test] +#[ignore] +async fn query_tags_with_none_value_succeeds() { + // A `None`-valued tag serialises to a bare key (no colon). Confirm + // the server accepts that wire shape too. + let session = live_session().await; + let mut stmt = session.statement(); + let mut tags = HashMap::new(); + tags.insert("production".to_string(), None); + tags.insert("team".to_string(), Some("platform".to_string())); + stmt.spec().sql("SELECT 1 AS n"); + stmt.spec() + .query_tags(tags) + .expect("query_tags (with None value) accepted"); + + let mut exec = stmt.execute().await.expect("execute with bare-key tag"); + assert_select_one(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + +#[tokio::test] +#[ignore] +async fn custom_http_headers_round_trip_succeeds() { + // A session with custom headers (incl. a custom User-Agent, the + // way the connector forwards its composed UA) must execute cleanly. + // The kernel's own Authorization is applied last and wins; the + // custom headers ride alongside. A header that broke the request + // would surface as a failed execute here. + // A custom User-Agent here is APPENDED to the kernel's base UA (the + // kernel keeps its disposition-gating `DatabricksJDBCDriverOSS` + // token as a prefix), so we pass just the caller entry — the kernel + // prepends its base. Replacing the UA outright would break the SEA + // result disposition (HTTP 400), which is exactly the regression + // this exercises end-to-end. + let session = live_session_with_headers(vec![ + ("X-Custom-E2E-Header".to_string(), "kernel-e2e".to_string()), + ( + "User-Agent".to_string(), + "KernelE2E/1.0 (smoke-test)".to_string(), + ), + ]) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute with custom headers"); + assert_select_one(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + +#[tokio::test] +#[ignore] +async fn custom_authorization_header_is_dropped_and_real_auth_wins() { + // A caller-supplied `Authorization` custom header must be DROPPED — + // the kernel always applies the real PAT. If the bogus token leaked + // through (or replaced the real one), the server would reject with + // 401 and `SELECT 1` would fail. Success proves the reserved-header + // skip holds against a live server (the wiremock test pins the same + // behaviour at the unit level). + let session = live_session_with_headers(vec![( + "Authorization".to_string(), + "Bearer obviously-bogus-token".to_string(), + )]) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt + .execute() + .await + .expect("execute must succeed — the real PAT wins, the bogus Authorization is dropped"); + assert_select_one(exec.result_stream_mut()).await; + exec.close().await.expect("close"); + session.close().await.expect("session close"); +}