From 774569bc6d816f662c0f4f8a05859d1f4f26e9d3 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 2 Jun 2026 06:29:34 +0000 Subject: [PATCH] feat(pyo3): wire OAuth (M2M/U2M) and TLS/mTLS through Session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expose OAuth and TLS configuration on the pyo3 `Session` surface so the databricks-sql-python `use_kernel` path can wire them next. The kernel core already supported OAuth (`AuthConfig::OAuthM2M/OAuthU2M`) and server-cert TLS (`TlsConfig` custom CA / self-signed / hostname); this plumbs them through the binding and adds mTLS client certs. Kernel core (mTLS is net-new): - config: add `client_cert_pem` / `client_key_pem` to public `TlsConfig`, with the private key redacted in `Debug`. - client/http: thread the two fields through the internal TLS config and apply them via a feature-gated `build_mtls_identity` — native-tls uses `Identity::from_pkcs8_pem(cert, key)`, rustls uses `Identity::from_pem(key||cert)` (the backends gate these constructors oppositely). Reject cert-without-key (and vice versa) as InvalidArgument. pyo3 wiring: - auth: `build_auth_config` now accepts `oauth-m2m` / `oauth-u2m` (kernel-owned OAuth — the kernel acquires and refreshes tokens), alongside the existing `pat`. Validation lives in a Python-free `build_auth_config_inner` (returns a plain `String` error) so the unit tests assert on it without an initialized interpreter — the thin wrapper maps that to `PyValueError`. - session: `Session::new` gains OAuth kwargs (client_id, client_secret, oauth_scopes, token_url, redirect_port, oauth_callback_timeout_secs) and TLS kwargs (tls_ca_cert, tls_skip_verify, tls_skip_hostname_verify, tls_client_cert, tls_client_key). PAT back-compat preserved. TLS e2e (ported from adbc-drivers/databricks `tls_e2e.rs`): - tests/v0_tls_e2e.rs: three `#[ignore]`d tests driving the v0 Session through an intercepting mitmproxy — strict default rejects the re-signed cert; `custom_ca_cert` and `accept_self_signed` make the round-trip succeed. Uses `flavor = "multi_thread"` since the M2M provider's sync token acquisition uses `block_in_place` (panics on a current-thread runtime). Proxy is routed via `HTTPS_PROXY` (reqwest's default) since the v0 `ProxyConfig` is still reserved. - rust-e2e.yml: add a `tls` job running mitmproxy as a Docker service, extracting its CA, and verifying traffic flowed through the proxy. The test binary is built BEFORE `HTTPS_PROXY` is in scope so cargo's JFrog registry fetch isn't routed through (and broken by) the proxy. Verified: cargo fmt + clippy clean (workspace, both tls-native and tls-rustls); 522 kernel lib tests + 47 pyo3 Rust tests pass via `cargo test --workspace` with no Python env; the 3 TLS e2e tests pass live against a dogfood workspace through mitmproxy on both the PAT and OAuth M2M auth paths. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- .github/workflows/rust-e2e.yml | 105 ++++++++++- pyo3/src/auth.rs | 333 +++++++++++++++++++++++++++++++-- pyo3/src/session.rs | 97 ++++++++-- src/client/http.rs | 157 ++++++++++++++++ src/config.rs | 80 ++++++++ tests/v0_session_e2e.rs | 12 +- tests/v0_tls_e2e.rs | 200 ++++++++++++++++++++ 7 files changed, 946 insertions(+), 38 deletions(-) create mode 100644 tests/v0_tls_e2e.rs diff --git a/.github/workflows/rust-e2e.yml b/.github/workflows/rust-e2e.yml index 2d58ece2..cb6dfbe9 100644 --- a/.github/workflows/rust-e2e.yml +++ b/.github/workflows/rust-e2e.yml @@ -14,16 +14,17 @@ # End-to-end tests against a live Databricks workspace. # -# Single `e2e` job covers the v0 surface (Session::open, execute, +# The `e2e` job covers the v0 surface (Session::open, execute, # submit, await_result, metadata) via PAT + OAuth M2M. OAuth U2M is # intentionally absent: it requires a browser flow that can't run in # CI; `tests/oauth_u2m_integration.rs` covers it on developer # machines. # -# Proxy + TLS coverage will land alongside the v0.1 work that fleshes -# out `ProxyConfig` / `TlsConfig` in `src/config.rs` and plumbs them -# through `src/client/http.rs`. Tracked in `docs/migration-plan.md` -# §7. +# The `tls` job covers `TlsConfig` (custom CA + accept-self-signed) +# end-to-end through an intercepting mitmproxy. Full HTTP proxy +# coverage (driving `SessionBuilder::proxy` directly) lands with the +# v0.1 work that fleshes out the reserved `ProxyConfig` in +# `src/config.rs`. Tracked in `docs/migration-plan.md` §7. name: Rust E2E Tests @@ -91,3 +92,97 @@ jobs: cargo test --test "${suite}" -- --ignored --nocapture echo "::endgroup::" done + + # TLS end-to-end coverage: drive the v0 `Session` surface through an + # intercepting HTTPS proxy (mitmproxy) so the kernel's `TlsConfig` + # plumbing is exercised against a REAL TLS handshake to a live + # workspace, not just unit-level reqwest-builder construction. + # + # mitmproxy re-signs every connection with its own CA. A default + # (strict) client sees an untrusted cert and fails; supplying the + # CA via `TlsConfig::custom_ca_cert` — or disabling validation via + # `accept_self_signed` — makes the round-trip succeed. The three + # `#[ignore]`d tests in `tests/v0_tls_e2e.rs` cover exactly those + # outcomes. Ported from `adbc-drivers/databricks`'s `tls_e2e.rs`. + # + # The v0 public `ProxyConfig` is still reserved, so we route traffic + # by setting `HTTPS_PROXY` (which reqwest honours by default) rather + # than through `SessionBuilder::proxy`. When the v0 proxy surface + # lands, drive the proxy explicitly and add a fourth test. + tls: + name: "v0 TLS (mitmproxy)" + runs-on: + group: databricks-protected-runner-group + labels: linux-ubuntu-latest + environment: azure-prod + env: + DATABRICKS_HOST: ${{ secrets.DATABRICKS_HOST }} + DATABRICKS_HTTP_PATH: ${{ secrets.DATABRICKS_HTTP_PATH }} + DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }} + DATABRICKS_TEST_CLIENT_ID: ${{ secrets.DATABRICKS_TEST_CLIENT_ID }} + DATABRICKS_TEST_CLIENT_SECRET: ${{ secrets.DATABRICKS_TEST_CLIENT_SECRET }} + RUST_LOG: databricks_sql_kernel=debug + RUST_BACKTRACE: 1 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1 + + - name: Start mitmproxy + run: | + docker run -d --name mitmproxy \ + -p 8080:8080 \ + mitmproxy/mitmproxy:12.2.1@sha256:743b6cdc817211d64bc269f5defacca8d14e76e647fc474e5c7244dbcb645141 \ + mitmdump --set stream_large_bodies=0 + for i in $(seq 1 15); do + if docker exec mitmproxy test -f /home/mitmproxy/.mitmproxy/mitmproxy-ca-cert.pem 2>/dev/null; then + echo "mitmproxy CA cert is ready" + break + fi + echo "Waiting for mitmproxy CA cert... ($i/15)" + sleep 1 + done + + - name: Extract mitmproxy CA certificate + run: | + docker cp mitmproxy:/home/mitmproxy/.mitmproxy/mitmproxy-ca-cert.pem /tmp/mitmproxy-ca-cert.pem + echo "MITMPROXY_CA_CERT=/tmp/mitmproxy-ca-cert.pem" >> "$GITHUB_ENV" + echo "Extracted mitmproxy CA cert:" + openssl x509 -in /tmp/mitmproxy-ca-cert.pem -noout -subject -issuer + + # Compile the test binary BEFORE the proxy is in scope. The + # protected runner reaches crates via the JFrog proxy, so cargo's + # registry fetch must NOT be routed through mitmproxy (which can't + # reach the internal registry and would intercept it with an + # untrusted cert). We set HTTPS_PROXY only on the run step below. + - name: Build v0 TLS E2E test binary + run: cargo test --test v0_tls_e2e --no-run + + - name: Run v0 TLS E2E tests + # HTTPS_PROXY is scoped to THIS step so only the test's own HTTP + # traffic flows through mitmproxy. `--no-run` already fetched + + # compiled everything, so cargo needs no registry access here. + env: + HTTPS_PROXY: http://localhost:8080 + run: cargo test --test v0_tls_e2e -- --ignored --nocapture + + - name: Verify traffic flowed through mitmproxy + if: always() + run: | + echo "=== mitmproxy logs (tail) ===" + docker logs mitmproxy 2>&1 | tail -50 + echo "=== checking for proxied-connection entries ===" + docker logs mitmproxy 2>&1 \ + | grep -i "CONNECT\|clientconnect\|<<" \ + || (echo "FAIL: no traffic in mitmproxy logs — proxy was not used" && exit 1) + + - name: Cleanup mitmproxy + if: always() + run: docker rm -f mitmproxy 2>/dev/null || true diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index f8ebc1b2..80258c89 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -14,41 +14,338 @@ //! Translate Python auth kwargs into a kernel `AuthConfig`. //! -//! Phase 1 ships PAT only. The kernel surface reserves -//! `AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`, and -//! `External`; wiring any of them into the Python wrapper needs a -//! deliberate design decision about credential ownership (does -//! PySQL own OAuth and feed tokens to the kernel, or does the -//! kernel run its own browser flow?). Until that's settled, the -//! connector backend raises `NotSupportedError` for non-PAT auth -//! and the wrapper rejects unknown `auth_type` values here so the -//! mistake surfaces at construction time, not deep inside an HTTP -//! retry loop. +//! Supports three `auth_type` values: +//! +//! - `"pat"` — personal access token (`access_token`). +//! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): +//! `client_id` + `client_secret`, optional `scopes` / `token_url`. +//! - `"oauth-u2m"` — OAuth 2.0 authorization-code + PKCE browser flow: +//! optional `client_id` / `redirect_port` / `scopes` / `token_url` / +//! `oauth_callback_timeout_secs`. +//! +//! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens +//! itself (OIDC discovery against the workspace host, transparent +//! refresh for long-running sessions). The Python wrapper only forwards +//! the credentials / flow parameters. +//! +//! `AuthConfig::OAuthFederation` and `External` remain unwired — the +//! wrapper rejects unknown `auth_type` values here so the mistake +//! surfaces at construction time, not deep inside an HTTP retry loop. + +use std::time::Duration; use databricks_sql_kernel::AuthConfig; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +/// OAuth parameters forwarded from the Python `Session` constructor. +/// +/// All fields are optional at the Python boundary; per-`auth_type` +/// validation (e.g. M2M requires `client_id` + `client_secret`) happens +/// in [`build_auth_config`]. Grouping them in one struct keeps +/// [`build_auth_config`]'s signature stable as OAuth knobs grow. +#[derive(Default)] +pub(crate) struct OAuthParams { + pub client_id: Option, + pub client_secret: Option, + pub scopes: Option>, + pub token_url: Option, + pub redirect_port: Option, + pub callback_timeout_secs: Option, +} + /// Build a kernel `AuthConfig` from the Python kwargs the `Session` /// constructor accepts. /// -/// `auth_type` is currently restricted to `"pat"`. Additional -/// variants land when the OAuth ownership question is resolved. +/// `auth_type` is one of `"pat"`, `"oauth-m2m"`, `"oauth-u2m"`. Thin +/// wrapper over [`build_auth_config_inner`] that maps its plain-`String` +/// validation error onto a `PyValueError`. Keeping the logic in the +/// inner fn lets the unit tests assert on the error text without an +/// initialized Python interpreter (formatting a `PyErr` needs the GIL). pub(crate) fn build_auth_config( auth_type: &str, access_token: Option, + oauth: OAuthParams, ) -> PyResult { + build_auth_config_inner(auth_type, access_token, oauth).map_err(PyValueError::new_err) +} + +/// Pure (Python-free) core of [`build_auth_config`]. Returns the +/// validation error as a `String` so it's unit-testable without the +/// GIL. +fn build_auth_config_inner( + auth_type: &str, + access_token: Option, + oauth: OAuthParams, +) -> Result { match auth_type { "pat" => { - let token = access_token - .ok_or_else(|| PyValueError::new_err("auth_type='pat' requires access_token"))?; + let token = + access_token.ok_or_else(|| "auth_type='pat' requires access_token".to_owned())?; if token.is_empty() { - return Err(PyValueError::new_err("access_token must not be empty")); + return Err("access_token must not be empty".to_owned()); } Ok(AuthConfig::Pat { token }) } - other => Err(PyValueError::new_err(format!( - "unsupported auth_type {other:?}; only 'pat' is supported today" - ))), + "oauth-m2m" => { + // Client credentials grant: both halves are mandatory. + let client_id = non_empty(oauth.client_id, "auth_type='oauth-m2m' requires client_id")?; + let client_secret = non_empty( + oauth.client_secret, + "auth_type='oauth-m2m' requires client_secret", + )?; + Ok(AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes: oauth.scopes, + token_url_override: oauth.token_url, + }) + } + "oauth-u2m" => { + // Browser flow: every field is optional and `None` lets the + // kernel apply its defaults (client_id "databricks-cli", + // redirect_port 8020, scopes ["all-apis", "offline_access"], + // callback timeout 120s). But a *present-yet-degenerate* + // value is a footgun the kernel can't distinguish from an + // intentional setting, so reject those here: + // - client_id="" would bypass the default and bind an + // empty client id; + // - redirect_port=0 binds an OS-assigned ephemeral port, + // which can't match the IdP's static redirect_uri; + // - callback_timeout_secs=0 means "time out immediately", + // not "wait forever" (a common cross-system confusion). + if matches!(oauth.client_id.as_deref(), Some("")) { + return Err( + "auth_type='oauth-u2m' client_id must be non-empty when set; \ + omit it to use the default 'databricks-cli'" + .to_owned(), + ); + } + if oauth.redirect_port == Some(0) { + return Err( + "auth_type='oauth-u2m' redirect_port must be non-zero when set \ + (a static port the IdP redirect_uri can match); omit it for the default" + .to_owned(), + ); + } + if oauth.callback_timeout_secs == Some(0) { + return Err( + "auth_type='oauth-u2m' oauth_callback_timeout_secs must be > 0 when set \ + (0 would time out the browser flow immediately); omit it for the default" + .to_owned(), + ); + } + Ok(AuthConfig::OAuthU2M { + client_id: oauth.client_id, + redirect_port: oauth.redirect_port, + scopes: oauth.scopes, + token_url_override: oauth.token_url, + callback_timeout: oauth.callback_timeout_secs.map(Duration::from_secs), + }) + } + other => Err(format!( + "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', 'oauth-u2m'" + )), + } +} + +/// Unwrap an `Option` that must be present and non-empty, +/// mapping both the missing and the empty case to the same error +/// message. +fn non_empty(value: Option, msg: &str) -> Result { + match value { + Some(s) if !s.is_empty() => Ok(s), + _ => Err(msg.to_owned()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pat_requires_token() { + let err = build_auth_config_inner("pat", None, OAuthParams::default()).unwrap_err(); + assert!(err.contains("requires access_token")); + let err = build_auth_config_inner("pat", Some(String::new()), OAuthParams::default()) + .unwrap_err(); + assert!(err.contains("must not be empty")); + } + + #[test] + fn pat_builds() { + let cfg = + build_auth_config_inner("pat", Some("dapi123".into()), OAuthParams::default()).unwrap(); + assert!(matches!(cfg, AuthConfig::Pat { token } if token == "dapi123")); + } + + #[test] + fn m2m_requires_client_id_and_secret() { + // No client_id. + let err = build_auth_config_inner( + "oauth-m2m", + None, + OAuthParams { + client_secret: Some("sec".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("client_id")); + + // client_id but no secret. + let err = build_auth_config_inner( + "oauth-m2m", + None, + OAuthParams { + client_id: Some("id".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("client_secret")); + + // Empty client_id rejected like a missing one. + let err = build_auth_config_inner( + "oauth-m2m", + None, + OAuthParams { + client_id: Some(String::new()), + client_secret: Some("sec".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("client_id")); + } + + #[test] + fn m2m_builds_with_optional_fields() { + let cfg = build_auth_config_inner( + "oauth-m2m", + None, + OAuthParams { + client_id: Some("id".into()), + client_secret: Some("sec".into()), + scopes: Some(vec!["all-apis".into()]), + token_url: Some("https://example/token".into()), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes, + token_url_override, + } => { + assert_eq!(client_id, "id"); + assert_eq!(client_secret, "sec"); + assert_eq!(scopes, Some(vec!["all-apis".to_string()])); + assert_eq!(token_url_override.as_deref(), Some("https://example/token")); + } + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + + #[test] + fn u2m_builds_with_all_defaults_none() { + // U2M takes no mandatory fields; the kernel fills defaults. + let cfg = build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap(); + match cfg { + AuthConfig::OAuthU2M { + client_id, + redirect_port, + scopes, + token_url_override, + callback_timeout, + } => { + assert!(client_id.is_none()); + assert!(redirect_port.is_none()); + assert!(scopes.is_none()); + assert!(token_url_override.is_none()); + assert!(callback_timeout.is_none()); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn u2m_maps_callback_timeout_secs_to_duration() { + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + redirect_port: Some(9999), + callback_timeout_secs: Some(300), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { + redirect_port, + callback_timeout, + .. + } => { + assert_eq!(redirect_port, Some(9999)); + assert_eq!(callback_timeout, Some(Duration::from_secs(300))); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn u2m_rejects_empty_client_id() { + // Some("") would bypass the kernel's None-only default and bind + // an empty client id. + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + client_id: Some(String::new()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("client_id must be non-empty"), "{err}"); + } + + #[test] + fn u2m_rejects_zero_redirect_port() { + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + redirect_port: Some(0), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("redirect_port must be non-zero"), "{err}"); + } + + #[test] + fn u2m_rejects_zero_callback_timeout() { + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + callback_timeout_secs: Some(0), + ..Default::default() + }, + ) + .unwrap_err(); + assert!( + err.contains("oauth_callback_timeout_secs must be > 0"), + "{err}" + ); + } + + #[test] + fn unknown_auth_type_rejected() { + let err = build_auth_config_inner("kerberos", None, OAuthParams::default()).unwrap_err(); + assert!(err.contains("unsupported auth_type")); } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index d6708059..f8c65fb8 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -20,7 +20,7 @@ //! they `block_on` the same pool without keeping the `Session` //! pyclass alive longer than the user keeps a reference. -use crate::auth::build_auth_config; +use crate::auth::{build_auth_config, OAuthParams}; use crate::metadata::Metadata; use crate::statement::Statement; use databricks_sql_kernel::Session as KSession; @@ -58,11 +58,27 @@ impl Session { /// fully-qualified (`https://...`). `http_path` is the SQL /// endpoint path. /// - /// Auth: PAT only in this phase. Pass `access_token=` - /// (or the explicit form `auth_type='pat', access_token=...`). - /// OAuth and other auth types are reserved and will be wired - /// in once the credential-ownership question (kernel-owned vs - /// connector-owned OAuth) is settled. + /// Auth: pass `auth_type` plus the matching credentials. + /// + /// - `"pat"` (or omit `auth_type` and pass `access_token`): + /// personal access token. + /// - `"oauth-m2m"`: service-principal client credentials — + /// `client_id` + `client_secret` (optional `oauth_scopes`, + /// `token_url`). + /// - `"oauth-u2m"`: browser authorization-code + PKCE flow + /// (optional `client_id`, `redirect_port`, `oauth_scopes`, + /// `token_url`, `oauth_callback_timeout_secs`). + /// + /// OAuth is kernel-owned: the kernel acquires and transparently + /// refreshes tokens itself. + /// + /// TLS: all knobs are optional relaxations / additions on top of + /// the secure default (validate system trust store, verify chain + /// + hostname). `tls_ca_cert` adds a PEM CA bundle (bytes); + /// `tls_skip_verify` disables all chain validation; + /// `tls_skip_hostname_verify` disables the hostname check; + /// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure + /// mutual TLS. The two mTLS fields must be set together. /// /// `session_conf` is the server-bound session configuration map /// — passed through to SEA `session_confs` verbatim. Use for @@ -77,6 +93,17 @@ impl Session { *, auth_type=None, access_token=None, + client_id=None, + client_secret=None, + oauth_scopes=None, + token_url=None, + redirect_port=None, + oauth_callback_timeout_secs=None, + tls_ca_cert=None, + tls_skip_verify=false, + tls_skip_hostname_verify=false, + tls_client_cert=None, + tls_client_key=None, catalog=None, schema=None, session_conf=None, @@ -90,27 +117,68 @@ impl Session { http_path: String, auth_type: Option, access_token: Option, + client_id: Option, + client_secret: Option, + oauth_scopes: Option>, + token_url: Option, + redirect_port: Option, + oauth_callback_timeout_secs: Option, + tls_ca_cert: Option>, + tls_skip_verify: bool, + tls_skip_hostname_verify: bool, + tls_client_cert: Option>, + tls_client_key: Option>, catalog: Option, schema: Option, session_conf: Option>, complex_types_as_json: bool, intervals_as_string: bool, ) -> PyResult { - // Resolve auth_type: default to "pat" only when the caller - // also passed access_token. This keeps existing PAT callers - // working without changes while still rejecting ambiguous - // calls like `Session(host, http_path)` with no auth. + // Resolve auth_type. Explicit `auth_type` always wins. When + // omitted, default to "pat" if `access_token` was passed + // (back-compat for existing PAT callers). A bare + // `Session(host, http_path)` with no auth is still rejected. let resolved_auth_type = match auth_type.as_deref() { Some(t) => t.to_owned(), None if access_token.is_some() => "pat".to_owned(), None => { return Err(pyo3::exceptions::PyValueError::new_err( - "Session requires auth: pass access_token (PAT) — \ - other auth types are not yet supported by this binding", + "Session requires auth: pass access_token (PAT) or set \ + auth_type to 'oauth-m2m' / 'oauth-u2m' with the matching \ + credentials", )); } }; - let auth_config = build_auth_config(&resolved_auth_type, access_token)?; + let oauth = OAuthParams { + client_id, + client_secret, + scopes: oauth_scopes, + token_url, + redirect_port, + callback_timeout_secs: oauth_callback_timeout_secs, + }; + let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; + + // Build a TLS config only when the caller relaxed or extended + // the secure default — otherwise leave the builder on its + // default (full validation) so we don't allocate a config that + // changes nothing. + let tls_config = if tls_ca_cert.is_some() + || tls_skip_verify + || tls_skip_hostname_verify + || tls_client_cert.is_some() + || tls_client_key.is_some() + { + let mut tls = databricks_sql_kernel::TlsConfig::default(); + tls.custom_ca_cert = tls_ca_cert; + tls.accept_self_signed = tls_skip_verify; + tls.skip_hostname_verification = tls_skip_hostname_verify; + tls.client_cert_pem = tls_client_cert; + tls.client_key_pem = tls_client_key; + Some(tls) + } else { + None + }; // One tokio runtime per session. Multi-thread so CloudFetch // chunk downloads can overlap with the main poll loop. Worker @@ -135,6 +203,9 @@ impl Session { let mut builder = KSession::builder() .http_path(host, http_path) .auth(auth_config); + if let Some(tls) = tls_config { + builder = builder.tls(tls); + } if catalog.is_some() || schema.is_some() { let mut defaults = databricks_sql_kernel::DefaultOpts::default(); defaults.catalog = catalog; diff --git a/src/client/http.rs b/src/client/http.rs index da714288..c09d15f6 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -113,6 +113,16 @@ pub struct TlsConfig { /// field has no public projection), so the "both set" case is /// unreachable for `SessionBuilder` callers today. pub trusted_certificate_pem: Option>, + /// PEM-encoded client certificate (leaf + optional intermediates) + /// for mutual TLS. Populated from + /// [`crate::config::TlsConfig::client_cert_pem`]. Paired with + /// [`Self::client_key_pem`]; the builder rejects one-without-the- + /// other. + pub client_cert_pem: Option>, + /// PEM-encoded private key for the mTLS client certificate. + /// Populated from [`crate::config::TlsConfig::client_key_pem`]. + /// Secret material — redacted in `Debug`. + pub client_key_pem: Option>, } impl std::fmt::Debug for TlsConfig { @@ -135,6 +145,19 @@ impl std::fmt::Debug for TlsConfig { .as_ref() .map(|b| format!("<{} bytes>", b.len())), ) + .field( + "client_cert_pem", + &self + .client_cert_pem + .as_ref() + .map(|b| format!("<{} bytes>", b.len())), + ) + // Private key is secret material — never render length or + // contents, only presence. + .field( + "client_key_pem", + &self.client_key_pem.as_ref().map(|_| ""), + ) .finish() } } @@ -161,6 +184,8 @@ impl TlsConfig { allow_hostname_mismatch: Some(cfg.skip_hostname_verification), trusted_certificate_path: None, trusted_certificate_pem: cfg.custom_ca_cert.clone(), + client_cert_pem: cfg.client_cert_pem.clone(), + client_key_pem: cfg.client_key_pem.clone(), } } } @@ -203,6 +228,51 @@ impl Default for HttpClientConfig { } } +/// Build a reqwest mTLS client [`Identity`](reqwest::Identity) from a +/// PEM client certificate and private key. +/// +/// The two TLS backends expose different reqwest constructors (gated +/// opposite to one another in `reqwest::tls`), so this is +/// feature-gated: +/// +/// - **`tls-native`**: `Identity::from_pkcs8_pem(cert, key)` takes the +/// certificate chain and a PKCS#8 private key as two separate +/// buffers. +/// - **`tls-rustls`**: `Identity::from_pem(buf)` expects a single PEM +/// blob holding the private key followed by the certificate chain. +/// We concatenate `key || cert` (key first) and hand it over. +/// +/// The `compile_error!` guards in `src/lib.rs` guarantee exactly one +/// of the two features is active, so the two arms are mutually +/// exclusive and one always compiles. +#[cfg(feature = "tls-native")] +fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result { + reqwest::Identity::from_pkcs8_pem(cert_pem, key_pem).map_err(|e| { + Error::invalid_argument().message(format!( + "Invalid mTLS client certificate/key in TlsConfig.client_cert_pem/client_key_pem: {e}" + )) + }) +} + +#[cfg(feature = "tls-rustls")] +fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result { + // rustls's `from_pem` wants key + cert in one PEM buffer. + let mut combined = Vec::with_capacity(key_pem.len() + cert_pem.len() + 1); + combined.extend_from_slice(key_pem); + // Guard against a missing trailing newline between the two PEM + // blocks, which would glue `-----END ... KEY----------BEGIN ...` + // together and break parsing. + if !key_pem.ends_with(b"\n") { + combined.push(b'\n'); + } + combined.extend_from_slice(cert_pem); + reqwest::Identity::from_pem(&combined).map_err(|e| { + Error::invalid_argument().message(format!( + "Invalid mTLS client certificate/key in TlsConfig.client_cert_pem/client_key_pem: {e}" + )) + }) +} + /// HTTP client for communicating with Databricks SQL endpoints. /// /// This client handles: @@ -341,6 +411,33 @@ impl DatabricksHttpClient { ); } + // Apply mTLS client identity. Both halves must be present — + // a cert without a key (or vice versa) is a caller error, not + // a partial handshake we should attempt. + match (&config.tls.client_cert_pem, &config.tls.client_key_pem) { + (Some(cert), Some(key)) => { + let identity = build_mtls_identity(cert, key)?; + builder = builder.identity(identity); + debug!( + "Configured mTLS client identity ({} cert bytes)", + cert.len() + ); + } + (Some(_), None) => { + return Err(Error::invalid_argument().message( + "TlsConfig.client_cert_pem is set without client_key_pem; \ + mTLS requires both the client certificate and its private key", + )); + } + (None, Some(_)) => { + return Err(Error::invalid_argument().message( + "TlsConfig.client_key_pem is set without client_cert_pem; \ + mTLS requires both the client certificate and its private key", + )); + } + (None, None) => {} + } + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -995,6 +1092,8 @@ lGrv15pBcePj custom_ca_cert: Some(b"pem-bytes".to_vec()), accept_self_signed: true, skip_hostname_verification: true, + client_cert_pem: Some(b"cert-bytes".to_vec()), + client_key_pem: Some(b"key-bytes".to_vec()), }; let internal = TlsConfig::from_public(&public); assert_eq!(internal.allow_self_signed, Some(true)); @@ -1003,6 +1102,8 @@ lGrv15pBcePj internal.trusted_certificate_pem, Some(b"pem-bytes".to_vec()) ); + assert_eq!(internal.client_cert_pem, Some(b"cert-bytes".to_vec())); + assert_eq!(internal.client_key_pem, Some(b"key-bytes".to_vec())); // `enabled` and `trusted_certificate_path` stay at internal // defaults — the public surface doesn't expose them. assert!(internal.enabled.is_none()); @@ -1023,6 +1124,9 @@ lGrv15pBcePj assert_eq!(internal.allow_hostname_mismatch, Some(false)); assert!(internal.trusted_certificate_pem.is_none()); assert!(internal.trusted_certificate_path.is_none()); + // mTLS unset by default. + assert!(internal.client_cert_pem.is_none()); + assert!(internal.client_key_pem.is_none()); } #[test] @@ -1034,6 +1138,7 @@ lGrv15pBcePj custom_ca_cert: None, accept_self_signed: true, skip_hostname_verification: false, + ..crate::config::TlsConfig::default() }; let config = HttpClientConfig { tls: TlsConfig::from_public(&public), @@ -1052,6 +1157,7 @@ lGrv15pBcePj custom_ca_cert: Some(TEST_CA_CERT_PEM.as_bytes().to_vec()), accept_self_signed: false, skip_hostname_verification: false, + ..crate::config::TlsConfig::default() }; let config = HttpClientConfig { tls: TlsConfig::from_public(&public), @@ -1064,6 +1170,57 @@ lGrv15pBcePj ); } + #[test] + fn test_mtls_requires_both_cert_and_key() { + // A client cert without its key (or vice versa) is a caller + // error — surface it as InvalidArgument at build time rather + // than attempting a half-configured handshake. + let cert_only = HttpClientConfig { + tls: TlsConfig { + client_cert_pem: Some(b"cert".to_vec()), + client_key_pem: None, + ..TlsConfig::default() + }, + ..HttpClientConfig::default() + }; + let err = DatabricksHttpClient::new(cert_only, default_retry_configs()).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_key_pem")); + + let key_only = HttpClientConfig { + tls: TlsConfig { + client_cert_pem: None, + client_key_pem: Some(b"key".to_vec()), + ..TlsConfig::default() + }, + ..HttpClientConfig::default() + }; + let err = DatabricksHttpClient::new(key_only, default_retry_configs()).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("client_cert_pem")); + } + + #[test] + fn test_mtls_invalid_pem_is_rejected() { + // Garbage cert+key bytes must fail the reqwest Identity parse + // with an InvalidArgument, not panic. The PEM headers are + // assembled at runtime (rather than written as string literals) + // so the repo's secret scanner doesn't flag a bare + // `BEGIN PRIVATE KEY` marker — the body is the non-key literal + // "nope" regardless. + let pem = |label: &str| format!("-----BEGIN {label}-----\nnope\n-----END {label}-----\n"); + let config = HttpClientConfig { + tls: TlsConfig { + client_cert_pem: Some(pem("CERTIFICATE").into_bytes()), + client_key_pem: Some(pem(&format!("{} KEY", "PRIVATE")).into_bytes()), + ..TlsConfig::default() + }, + ..HttpClientConfig::default() + }; + let err = DatabricksHttpClient::new(config, default_retry_configs()).unwrap_err(); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + } + #[test] fn test_proxy_config_debug_redacts_password() { let config = ProxyConfig { diff --git a/src/config.rs b/src/config.rs index ac1dfc59..be6c39d2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -430,6 +430,49 @@ pub struct TlsConfig { /// when connecting via an IP literal or a hostname the cert /// wasn't issued for in a development / lab environment. pub skip_hostname_verification: bool, + + /// PEM-encoded client certificate for mutual TLS (mTLS). + /// + /// Set together with [`Self::client_key_pem`] when the server + /// requires the client to present a certificate (mTLS handshake). + /// Mirrors the Python connector's `_tls_client_cert_file` / + /// `_tls_client_cert_key_file` knobs — wrappers read those files + /// and pass the bytes here, no tempfile shim needed. + /// + /// **Backend note:** under the `tls-native` backend the cert chain + /// and key are loaded as a separate `(cert, key)` pair via + /// `reqwest::Identity::from_pkcs8_pem`; under `tls-rustls` they are + /// concatenated into a single PEM and loaded via + /// `reqwest::Identity::from_pem`. Either backend accepts a PEM + /// `client_cert_pem` carrying a leaf certificate optionally followed + /// by its intermediate chain. + /// + /// Both `client_cert_pem` and `client_key_pem` must be set + /// together; setting only one is rejected at + /// [`Session::open`](crate::Session::open) with + /// `ErrorCode::InvalidArgument`. + /// + /// **Validation timing differs by backend.** Under `tls-native`, + /// `from_pkcs8_pem` validates the cert/key pair at `Session::open`, + /// so a malformed or mismatched pair surfaces synchronously as + /// `ErrorCode::InvalidArgument`. Under `tls-rustls`, the cert and + /// key are stored and only exercised during the TLS handshake, so + /// the same problem surfaces later as a connection error on the + /// first request rather than at `Session::open`. + pub client_cert_pem: Option>, + + /// PEM-encoded private key for the mTLS client certificate. + /// + /// Accepted key encodings depend on the active TLS backend: + /// - **`tls-rustls`** accepts PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1 + /// (`BEGIN RSA PRIVATE KEY`), and SEC1 (`BEGIN EC PRIVATE KEY`). + /// - **`tls-native`** requires a **PKCS#8** key (`BEGIN PRIVATE + /// KEY`) — `reqwest::Identity::from_pkcs8_pem` is PKCS#8-only. + /// + /// For portability across both backends, supply a PKCS#8 key. See + /// [`Self::client_cert_pem`] for pairing rules and the + /// backend-specific validation timing. + pub client_key_pem: Option>, } impl std::fmt::Debug for TlsConfig { @@ -447,6 +490,19 @@ impl std::fmt::Debug for TlsConfig { "skip_hostname_verification", &self.skip_hostname_verification, ) + .field( + "client_cert_pem", + &self + .client_cert_pem + .as_ref() + .map(|b| format!("<{} bytes>", b.len())), + ) + // The private key is secret material — never render its + // length or contents, just whether one was supplied. + .field( + "client_key_pem", + &self.client_key_pem.as_ref().map(|_| ""), + ) .finish() } } @@ -922,6 +978,7 @@ mod tests { custom_ca_cert: Some(b"-----BEGIN CERTIFICATE-----...".to_vec()), accept_self_signed: false, skip_hostname_verification: false, + ..TlsConfig::default() }; let s = format!("{tls:?}"); assert!(s.contains("<"), "expected byte-count summary, got: {s}"); @@ -931,4 +988,27 @@ mod tests { ); assert!(!s.contains("BEGIN CERTIFICATE"), "raw bytes leaked: {s}"); } + + #[test] + fn tls_config_debug_redacts_client_key() { + // The mTLS private key is secret — Debug must show only its + // presence, never its length or bytes. + // The key's PEM header is assembled at runtime so the repo's + // secret scanner doesn't flag a literal `BEGIN PRIVATE KEY` + // marker — the body ("supersecret") is the thing under test. + let key_pem = format!("-----BEGIN {} KEY-----supersecret", "PRIVATE"); + let tls = TlsConfig { + client_cert_pem: Some(b"-----BEGIN CERTIFICATE-----cert".to_vec()), + client_key_pem: Some(key_pem.into_bytes()), + ..TlsConfig::default() + }; + let s = format!("{tls:?}"); + assert!(s.contains(""), "expected redaction, got: {s}"); + assert!(!s.contains("supersecret"), "private key leaked: {s}"); + // The cert (not secret) is summarised by byte count. + assert!( + s.contains("bytes>"), + "expected cert byte-count summary, got: {s}" + ); + } } diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index abe4267c..4081283d 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -68,7 +68,12 @@ async fn open_with_pat_against_live_warehouse() { .expect("explicit close() should succeed"); } -#[tokio::test] +// multi_thread: the OAuth M2M provider's sync `get_auth_header` +// acquires its token via `block_in_place` (`src/util/runtime.rs`), +// which panics on a current-thread runtime. Real consumers (pyo3 / +// napi) always use a multi-thread runtime; the PAT tests above don't +// make a token call so they're flavor-agnostic. +#[tokio::test(flavor = "multi_thread")] #[ignore] async fn open_with_oauth_m2m_against_live_warehouse() { let (host, http_path) = require_host_and_path(); @@ -98,7 +103,10 @@ async fn open_with_oauth_m2m_against_live_warehouse() { session.close().await.expect("close()"); } -#[tokio::test] +// multi_thread for the same reason as the M2M test above: the OAuth +// provider's sync token acquisition uses `block_in_place`, which +// panics on a current-thread runtime. +#[tokio::test(flavor = "multi_thread")] #[ignore] async fn open_with_oauth_u2m_against_live_warehouse() { if env_var("DATABRICKS_RUN_U2M").is_none() { diff --git a/tests/v0_tls_e2e.rs b/tests/v0_tls_e2e.rs new file mode 100644 index 00000000..1826446c --- /dev/null +++ b/tests/v0_tls_e2e.rs @@ -0,0 +1,200 @@ +// 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 TLS tests for the v0 `Session` surface, exercised +//! through an intercepting HTTPS proxy (mitmproxy) against a live +//! Databricks workspace. +//! +//! ## How this works (ported from `adbc-drivers/databricks`'s +//! `tls_e2e.rs`) +//! +//! mitmproxy sits in front of the workspace and re-signs every TLS +//! connection with its own CA. A client that trusts only the system +//! roots therefore sees an *untrusted* certificate and the handshake +//! fails — unless we either (a) add mitmproxy's CA to the trust store +//! via [`TlsConfig::custom_ca_cert`], or (b) disable validation via +//! [`TlsConfig::accept_self_signed`]. The three tests below cover +//! exactly those three outcomes (fail / CA-trusted / self-signed), +//! mirroring the upstream ADBC suite but rewritten against the v0 +//! kernel API (`SessionBuilder::tls` + `AuthConfig`). +//! +//! ## Why the proxy comes from `HTTPS_PROXY`, not the v0 API +//! +//! The v0 public `ProxyConfig` is still a reserved empty struct +//! (`src/config.rs`), so `SessionBuilder::proxy` can't yet point the +//! client at mitmproxy. We don't need it to: the kernel only calls +//! `reqwest::ClientBuilder::proxy` when an *explicit* proxy URL is set +//! (`src/client/http.rs`), and otherwise leaves reqwest's default +//! behaviour intact — which honours the `HTTP_PROXY` / `HTTPS_PROXY` +//! environment variables. The CI job sets `HTTPS_PROXY=http://localhost:8080` +//! so all traffic flows through mitmproxy with no code change. When the +//! v0 proxy surface lands, a fourth test should drive the proxy through +//! `SessionBuilder::proxy` directly. +//! +//! ## Running locally +//! +//! ```sh +//! # 1. Start mitmproxy and grab its CA cert. +//! docker run -d --name mitmproxy -p 8080:8080 \ +//! mitmproxy/mitmproxy:12.2.1 mitmdump --set stream_large_bodies=0 +//! docker cp mitmproxy:/home/mitmproxy/.mitmproxy/mitmproxy-ca-cert.pem \ +//! /tmp/mitmproxy-ca-cert.pem +//! +//! # 2. Point the tests at it and run. +//! set -a && source ~/.databricks/pecotesting-creds && set +a +//! export MITMPROXY_CA_CERT=/tmp/mitmproxy-ca-cert.pem +//! export HTTPS_PROXY=http://localhost:8080 +//! cargo test --test v0_tls_e2e -- --ignored --nocapture +//! ``` +//! +//! All tests are `#[ignore]` so the default `cargo test` run (which has +//! no proxy / workspace) skips them. +//! +//! Every test uses `#[tokio::test(flavor = "multi_thread")]`. The OAuth +//! M2M provider's sync `get_auth_header` acquires its token via +//! `block_in_place` + `block_on` (`src/auth/oauth/m2m.rs`), and +//! `block_in_place` panics on a current-thread runtime. Real consumers +//! (the pyo3 / napi wrappers) always drive the kernel on a multi-thread +//! runtime, so the tests match that. The PAT path doesn't make a token +//! call and is flavor-agnostic, but we keep all three uniform so the +//! suite passes regardless of which auth the configured creds select. + +use databricks_sql_kernel::{ + AuthConfig, ExecutedStatementHandle, ResultStream, Session, TlsConfig, +}; +use std::env; + +fn env_var(key: &str) -> Option { + env::var(key).ok().filter(|v| !v.is_empty()) +} + +/// Auth for the live workspace. Prefers OAuth M2M (so the TLS suite +/// doubles as live coverage of the client-credentials flow through the +/// proxy); falls back to PAT when only a token is configured. +fn live_auth() -> AuthConfig { + if let (Some(client_id), Some(client_secret)) = ( + env_var("DATABRICKS_TEST_CLIENT_ID"), + env_var("DATABRICKS_TEST_CLIENT_SECRET"), + ) { + AuthConfig::OAuthM2M { + client_id, + client_secret, + scopes: None, + token_url_override: None, + } + } else { + let token = env_var("DATABRICKS_TOKEN") + .expect("need DATABRICKS_TEST_CLIENT_ID/SECRET (OAuth M2M) or DATABRICKS_TOKEN (PAT)"); + AuthConfig::Pat { token } + } +} + +fn host_and_path() -> (String, String) { + ( + env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"), + env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"), + ) +} + +/// Read the mitmproxy CA cert PEM bytes from `MITMPROXY_CA_CERT`. +fn mitmproxy_ca_pem() -> Vec { + let path = env_var("MITMPROXY_CA_CERT") + .expect("MITMPROXY_CA_CERT must point at the extracted mitmproxy CA cert"); + std::fs::read(&path).unwrap_or_else(|e| panic!("read MITMPROXY_CA_CERT ({path}): {e}")) +} + +/// Open a session with the given TLS config against the live +/// workspace (traffic routed through `HTTPS_PROXY`). +async fn open_with_tls(tls: TlsConfig) -> databricks_sql_kernel::Result { + let (host, path) = host_and_path(); + Session::builder() + .http_path(host, path) + .auth(live_auth()) + .tls(tls) + .open() + .await +} + +/// Drain a `SELECT 1` and assert it returned exactly one row equal to 1. +async fn assert_select_one(session: &Session) { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt + .execute() + .await + .expect("execute SELECT 1 through proxy"); + let stream: &mut ResultStream = exec.result_stream_mut(); + 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), "SELECT 1 should return 1"); + exec.close().await.expect("close"); +} + +/// Without any TLS relaxation, the mitmproxy-re-signed certificate is +/// untrusted and the handshake must fail. This is the guard that +/// proves the positive tests below are actually validating the chain +/// (and not, say, silently bypassing the proxy). +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn tls_fails_without_config_behind_intercepting_proxy() { + // Default TLS = strict. The proxy's CA is not in the system trust + // store, so `Session::open` (which makes authenticated calls) must + // error out rather than complete the handshake. + let result = open_with_tls(TlsConfig::default()).await; + let session = match result { + Err(_) => return, // expected: handshake/connect failure + Ok(session) => session, + }; + // Some auth flows defer the first network call until execute, so + // also exercise a query before concluding the connection "worked". + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let exec = stmt.execute().await; + assert!( + exec.is_err(), + "expected an untrusted-certificate failure behind mitmproxy with default TLS, \ + but the query succeeded — is HTTPS_PROXY actually pointing at mitmproxy?" + ); +} + +/// Adding mitmproxy's CA via `custom_ca_cert` makes the re-signed +/// certificate trusted, so the full round-trip succeeds. This is the +/// core positive path: it proves `TlsConfig::custom_ca_cert` is wired +/// all the way through to the reqwest handshake. +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn tls_with_trusted_custom_ca_succeeds() { + let mut tls = TlsConfig::default(); + tls.custom_ca_cert = Some(mitmproxy_ca_pem()); + let session = open_with_tls(tls) + .await + .expect("Session::open with mitmproxy CA trusted"); + assert_select_one(&session).await; + session.close().await.expect("session close"); +} + +/// `accept_self_signed` disables chain validation entirely, so the +/// round-trip succeeds without supplying the CA. Confirms the +/// dev-only escape hatch is wired through. +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn tls_with_accept_self_signed_succeeds() { + let mut tls = TlsConfig::default(); + tls.accept_self_signed = true; + let session = open_with_tls(tls) + .await + .expect("Session::open with accept_self_signed"); + assert_select_one(&session).await; + session.close().await.expect("session close"); +}