diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2e6848a6..75a3443d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -102,6 +102,9 @@ jobs: - name: cargo clippy run: cargo clippy --all-targets -- -D warnings + - name: cargo clippy (proxy-negotiate) + run: cargo clippy --all-targets --features proxy-negotiate -- -D warnings + test: name: Unit + doc tests runs-on: @@ -131,6 +134,9 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + - name: cargo test (proxy-negotiate) + run: cargo test --lib --features proxy-negotiate + c-abi: name: C ABI smoke test runs-on: @@ -270,6 +276,10 @@ jobs: shell: pwsh run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings + - name: cargo clippy (tls-rustls, proxy-negotiate, Windows) + shell: pwsh + run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls,proxy-negotiate --all-targets -- -D warnings + - name: Test client behavior (tls-rustls, Windows) shell: pwsh # Two runs: the client:: suite, then the C ABI revocation open test, which is not under client::. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 97280556..a4cd1cad 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -224,6 +224,7 @@ userinfo replaced by `***`. | `username` | Proxy basic-auth (SOCKS5: RFC 1929) username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open (and lazily for Volume storage) and retries each request hop once with a fresh token on a proxy 407, including Volume PUT, GET and REMOVE storage requests. A second 407 fails the request; it never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Unix the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. Non-Linux platforms link through cross-krb5: GSS.framework on macOS (building needs libclang), SSPI on Windows, and system GSSAPI on other Unix (including BSDs, illumos and Android). C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/Cargo.lock b/Cargo.lock index 501a95b0..e9ab8f5a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "approx" version = "0.5.1" @@ -308,6 +314,26 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.118", +] + [[package]] name = "bit-vec" version = "0.9.1" @@ -403,7 +429,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" dependencies = [ "find-msvc-tools", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", ] [[package]] @@ -465,6 +500,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "cmov" version = "0.5.4" @@ -569,6 +615,19 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "cross-krb5" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d426da4c3f9df62d4dac801df95d980a8ba8c4b4f95d02b9b607dab079d6768" +dependencies = [ + "anyhow", + "bitflags", + "bytes", + "libgssapi", + "windows", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -663,6 +722,7 @@ dependencies = [ "base64 0.22.1", "cbc 0.2.1", "chrono", + "cross-krb5", "dashmap", "dirs", "futures", @@ -811,6 +871,12 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "equivalent" version = "1.0.2" @@ -1067,6 +1133,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "h2" version = "0.4.15" @@ -1456,6 +1528,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1560,6 +1641,37 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "libgssapi" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e440a6151f5ef06571612e4121709aed90cfc0c40f8161f9090c71656758086d" +dependencies = [ + "bitflags", + "bytes", + "libgssapi-sys", +] + +[[package]] +name = "libgssapi-sys" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5103ac4557eacd36ff678b654b943f8966d3db9688fbd180a0b4c5464759ce17" +dependencies = [ + "bindgen", + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -2075,6 +2187,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.118", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -2625,6 +2747,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -3296,6 +3424,27 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -3309,6 +3458,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -3337,6 +3497,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -3389,6 +3559,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index 334bd5e9..4796e89b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,6 +85,10 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } +# `tls-rustls`: loads the OS trust store, the same store reqwest's +# `rustls-tls-native-roots` loads, for the Windows revocation verifier (see +# `src/client/tls_revocation.rs`) and once per Negotiate client. +rustls-native-certs = { version = "0.8", optional = true } tokio = { version = "1", features = ["full", "sync"] } # Serialization @@ -168,13 +172,20 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption +# Kerberos/SPNEGO (`Proxy-Authorization: Negotiate`) proxy auth, behind the +# non-default `proxy-negotiate` feature. Non-Linux platforms use cross-krb5: +# GSS.framework on macOS (building needs libclang), SSPI on Windows, and +# system GSSAPI on other Unix, including BSDs, illumos and Android. Only Linux +# loads MIT GSSAPI (`libgssapi_krb5.so.2`) at run time instead +# (`src/client/gssapi_runtime.rs`), so Linux links no GSSAPI library and needs +# no GSSAPI headers to build. MIT. +[target.'cfg(not(target_os = "linux"))'.dependencies] +cross-krb5 = { version = "0.5", optional = true, default-features = false } + # Windows CryptoAPI for TLS certificate revocation (`src/client/tls_revocation.rs`). # `windows-sys` is already in the lock file; no new packages. [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } -# `tls-rustls` on Windows only. Loads the OS trust store for the revocation verifier (see -# `src/client/tls_revocation.rs`), the same store reqwest's `rustls-tls-native-roots` loads. -rustls-native-certs = { version = "0.8", optional = true } # `pthread_sigmask` for kernel-owned runtime threads (`src/util/runtime.rs`). # Already in the graph through tokio, so no new crate is added. @@ -249,6 +260,11 @@ tls-rustls = [ "dep:webpki-roots", "dep:rustls-native-certs", ] +# Kerberos token generation for `ProxyAuth::Negotiate`; without it `Negotiate` +# is rejected as unsupported. On Linux the feature adds no link dependency: +# MIT GSSAPI is loaded only when a token is needed (see `cross-krb5` above). +# `ProxyAuth::NegotiateCallback` works either way. +proxy-negotiate = ["dep:cross-krb5"] [lib] name = "databricks_sql_kernel" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 117940b2..a4c1c9af 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -25,6 +25,7 @@ changes go in their respective binding's NEXT_CHANGELOG. - Custom credentials providers: `AuthConfig::External` and the C ABI `kernel_session_config_set_auth_external` call the caller's provider for the auth headers of every request, so the host can refresh credentials. +- Kerberos (`Proxy-Authorization: Negotiate`) authentication to HTTP proxies via `ProxyConfig::auth` / `ProxyAuth::Negotiate` and the C ABI setter `kernel_session_config_set_proxy_negotiate`, behind the non-default cargo feature `proxy-negotiate`. On Linux it loads MIT Kerberos (`libgssapi_krb5.so.2`) only when used, so builds with the feature still run without it. - Volume `PUT`, `GET` and `REMOVE`: with `StatementSpec::volume` set, executing a statement the server marks as a Volume operation also runs its file transfer. Local paths, with symlinks resolved, must be inside the caller's @@ -45,6 +46,7 @@ changes go in their respective binding's NEXT_CHANGELOG. - Proxy credentials are redacted from proxy URLs in errors, logs and `Debug` output. +- `client::ProxyConfig`, the advanced HTTP-client proxy settings, has a new `auth` field. Code that builds it with a struct literal must add `..Default::default()`. - `Error` and `ResultManifest` have new public fields (`local_error`, `is_volume_operation`). Code that builds them with struct literals must set them. diff --git a/NOTICE b/NOTICE index 1a5bb418..97455f89 100644 --- a/NOTICE +++ b/NOTICE @@ -37,6 +37,11 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers +Package: cross-krb5 (optional, `proxy-negotiate` feature on non-Linux platforms; links GSS.framework on macOS, SSPI on Windows, or system GSSAPI on other Unix. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) +Project URL: https://github.com/estokes/cross-krb5 +Copyright: Copyright cross-krb5 Authors. + + Package: dashmap Project URL: https://github.com/xacrimon/dashmap Copyright: Copyright (c) 2025 Joel Wejdenstål diff --git a/adbc/NOTICE b/adbc/NOTICE index 1a5bb418..97455f89 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -37,6 +37,11 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers +Package: cross-krb5 (optional, `proxy-negotiate` feature on non-Linux platforms; links GSS.framework on macOS, SSPI on Windows, or system GSSAPI on other Unix. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) +Project URL: https://github.com/estokes/cross-krb5 +Copyright: Copyright cross-krb5 Authors. + + Package: dashmap Project URL: https://github.com/xacrimon/dashmap Copyright: Copyright (c) 2025 Joel Wejdenstål diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 79388598..b9dfd32c 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -507,6 +507,19 @@ KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, co const char* username, const char* password, const char* bypass_hosts); +/* Authenticate to the `set_proxy` proxy with Kerberos (`Proxy-Authorization: + * Negotiate` on CONNECT), using the ambient credential cache / logon session. + * Target name `service/host[@realm]`; NULL or "" selects the default: `HTTP`, + * the proxy host, the Kerberos default realm. Session open fails before any + * network I/O when no token can be created, the proxy also has Basic + * credentials or is not http(s)://, `set_proxy` was not called, or the kernel + * was built without the `proxy-negotiate` feature. The setting stays on the + * config (a later call replaces the target; there is no call that clears it), + * so use a new config for a session without Negotiate. */ +KernelStatusCode kernel_session_config_set_proxy_negotiate(KernelSessionConfig* config, + const char* service, const char* host, + const char* realm); + /* Add a PEM-encoded CA-certificate bundle (`pem`/`len` bytes) to the TLS * trust store on top of the system roots (corporate re-signing proxy / * on-prem CA). */ diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e2067760..0c3b6f34 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -27,6 +27,7 @@ changes go in the root `NEXT_CHANGELOG.md`. `is_volume_operation`. `KernelError` carries `local_os_error` and `local_path` for local file failures. A positive `request_timeout_secs` also sets the transfer idle limit. +- `Session` accepts `proxy_url`, `proxy_bypass_hosts` and `proxy_negotiate_token` (a callable returning a Kerberos token as `bytes`) to authenticate to an HTTP proxy with `Proxy-Authorization: Negotiate`. The wheel links no GSSAPI library. ### Changed - Allow pyarrow 24.x through 26.x on Python 3.10+ (`pyarrow>=23.0.1,<27`), diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 666c1347..7bc24fd0 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -264,6 +264,65 @@ fn build_http_config( Ok(Some(http)) } +/// Explicit proxy from the `proxy_*` kwargs; `None` keeps the kernel's +/// environment-variable proxy behaviour. `proxy_negotiate_token` is a +/// zero-argument callable returning one raw SPNEGO/Kerberos token +/// (`bytes`) for the proxy; the kernel calls it from a worker thread at +/// session open and once more if the proxy answers a `CONNECT` with 407. +/// If it raises or returns no token, the request fails closed. +fn build_proxy_config( + py: Python<'_>, + url: Option, + bypass_hosts: Option, + negotiate_token: Option>, +) -> PyResult> { + // The kernel ignores a bypass list without a proxy URL, so reject it here + // rather than drop it silently. + if url.is_none() && bypass_hosts.is_some() { + return Err(pyo3::exceptions::PyValueError::new_err( + "proxy_bypass_hosts requires proxy_url: without a proxy URL the bypass list is ignored", + )); + } + if url.is_none() && bypass_hosts.is_none() && negotiate_token.is_none() { + return Ok(None); + } + let mut proxy = databricks_sql_kernel::ProxyConfig::default(); + proxy.url = url; + proxy.bypass_hosts = bypass_hosts; + if let Some(callable) = negotiate_token { + if !callable.bind(py).is_callable() { + return Err(pyo3::exceptions::PyTypeError::new_err( + "proxy_negotiate_token must be a callable returning bytes", + )); + } + proxy.auth = databricks_sql_kernel::ProxyAuth::NegotiateCallback( + databricks_sql_kernel::NegotiateTokenCallback::new(move || { + // The kernel can ask for a token after the interpreter has + // started shutting down (background CloudFetch or telemetry + // requests that get a 407). `try_attach` returns `None` then + // instead of attaching during finalization, so fail closed. + // The error names no token bytes. + let attached = Python::try_attach(|py| { + let value = callable.call0(py).map_err(|e| e.to_string())?; + let value = value.bind(py); + let bytes = value + .cast::() + .map_err(|_| "proxy_negotiate_token must return bytes".to_string())?; + Ok(bytes.as_bytes().to_vec()) + }); + match attached { + Some(token) => token, + None => Err( + "Python interpreter is not running; no Negotiate token is available" + .to_string(), + ), + } + }), + ); + } + Ok(Some(proxy)) +} + #[allow(clippy::too_many_arguments)] fn build_driver_system_configuration( driver_name: Option, @@ -356,6 +415,17 @@ impl Session { /// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure /// mutual TLS. The two mTLS fields must be set together. /// + /// Proxy: `proxy_url` (`http://` or `https://`) overrides the + /// `HTTPS_PROXY` / `NO_PROXY` environment variables, with + /// `proxy_bypass_hosts` (comma-separated) as its bypass list. The bypass + /// list requires `proxy_url`: passing it alone raises `ValueError`. + /// `proxy_negotiate_token` (requires `proxy_url`) authenticates to it + /// with `Proxy-Authorization: Negotiate`: a zero-argument callable + /// returning one raw SPNEGO/Kerberos token as `bytes`, called at + /// session open and once more if the proxy answers 407. If it raises + /// or returns no token, the connection fails; it never falls back to + /// another proxy or a direct connection. + /// /// Retry/backoff: all optional, default to the kernel's built-in /// policy (1s/60s backoff, 6 total attempts, 900s budget) when /// unset. `retry_min_wait_secs` / `retry_max_wait_secs` bound the @@ -427,6 +497,9 @@ impl Session { tls_skip_hostname_verify=false, tls_client_cert=None, tls_client_key=None, + proxy_url=None, + proxy_bypass_hosts=None, + proxy_negotiate_token=None, sea_response_compression_enabled=false, request_timeout_secs=None, max_connections=None, @@ -496,6 +569,9 @@ impl Session { tls_skip_hostname_verify: bool, tls_client_cert: Option>, tls_client_key: Option>, + proxy_url: Option, + proxy_bypass_hosts: Option, + proxy_negotiate_token: Option>, sea_response_compression_enabled: bool, request_timeout_secs: Option, max_connections: Option, @@ -651,6 +727,9 @@ impl Session { None }; + let proxy_config = + build_proxy_config(py, proxy_url, proxy_bypass_hosts, proxy_negotiate_token)?; + // 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, @@ -729,6 +808,9 @@ impl Session { if let Some(tls) = tls_config { builder = builder.tls(tls); } + if let Some(proxy) = proxy_config { + builder = builder.proxy(proxy); + } if let Some(http) = http_config { builder = builder.http(http); } diff --git a/pyo3/tests/test_proxy_negotiate.py b/pyo3/tests/test_proxy_negotiate.py new file mode 100644 index 00000000..85d25645 --- /dev/null +++ b/pyo3/tests/test_proxy_negotiate.py @@ -0,0 +1,146 @@ +# 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. + +"""`proxy_negotiate_token`: Negotiate proxy auth from a Python callable. + +No network: a local stub proxy records each CONNECT's Proxy-Authorization +and answers 407, so no request reaches a warehouse. +""" + +from __future__ import annotations + +import base64 +import socket +import threading + +import pytest + +import databricks_sql_kernel as k + + +class StubProxy: + def __init__(self) -> None: + self.connects: list[str | None] = [] + self._sock = socket.socket() + self._sock.bind(("127.0.0.1", 0)) + self._sock.listen(16) + self.url = "http://127.0.0.1:%d" % self._sock.getsockname()[1] + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self) -> None: + while True: + try: + conn, _ = self._sock.accept() + except OSError: + return + with conn: + head = b"" + while b"\r\n\r\n" not in head: + chunk = conn.recv(4096) + if not chunk: + break + head += chunk + auth = None + for line in head.decode("latin-1").split("\r\n")[1:]: + name, _, value = line.partition(":") + if name.lower() == "proxy-authorization": + auth = value.strip() + self.connects.append(auth) + conn.sendall( + b"HTTP/1.1 407 Proxy Authentication Required\r\n" + b"Proxy-Authenticate: Negotiate\r\nContent-Length: 0\r\n\r\n" + ) + + def close(self) -> None: + self._sock.close() + + +@pytest.fixture +def proxy(): + stub = StubProxy() + yield stub + stub.close() + + +def open_session(proxy_url, token): + return k.Session( + host="warehouse.invalid", + http_path="/sql/1.0/warehouses/x", + access_token="not-a-real-token", + proxy_url=proxy_url, + proxy_negotiate_token=token, + retry_max_attempts=1, + ) + + +def negotiate(raw: bytes) -> str: + return "Negotiate " + base64.b64encode(raw).decode() + + +def test_token_rides_connect_and_regenerates_once_on_407(proxy): + calls = [] + + def token(): + calls.append(1) + return b"token-%d" % len(calls) + + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, token) + assert exc.value.code == "Unauthenticated", str(exc.value) + assert "407" in str(exc.value) + # Preemptive token, one fresh token after the 407, then fail closed. + assert proxy.connects == [negotiate(b"token-1"), negotiate(b"token-2")] + assert "dG9rZW4t" not in str(exc.value) + + +def test_raising_callable_fails_before_any_connect(proxy): + def token(): + raise RuntimeError("no Kerberos ticket") + + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, token) + assert exc.value.code == "Unauthenticated" + assert "no Kerberos ticket" in str(exc.value) + assert proxy.connects == [] + + +@pytest.mark.parametrize("value", [b"", "dG9r", None]) +def test_invalid_token_fails_before_any_connect(proxy, value): + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, lambda: value) + assert exc.value.code == "Unauthenticated" + assert proxy.connects == [] + + +def test_non_callable_token_is_a_type_error(proxy): + with pytest.raises(TypeError): + open_session(proxy.url, b"token") + + +@pytest.mark.parametrize("proxy_url", [None, "socks5://127.0.0.1:1080", "http://u:p@127.0.0.1:1"]) +def test_negotiate_needs_a_plain_http_proxy_url(proxy_url): + with pytest.raises(k.KernelError) as exc: + open_session(proxy_url, lambda: b"token") + assert exc.value.code == "InvalidArgument" + + +def test_bypass_hosts_without_proxy_url_is_a_value_error(): + # Rejected before any connect, so no proxy or warehouse is involved. + with pytest.raises(ValueError, match="proxy_bypass_hosts requires proxy_url"): + k.Session( + host="warehouse.invalid", + http_path="/sql/1.0/warehouses/x", + access_token="not-a-real-token", + proxy_bypass_hosts="localhost", + ) diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 0035724e..40adc0c7 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -47,8 +47,8 @@ use crate::kernel_error::{Error, Result}; use crate::util::runtime::block_on_in_runtime; use oauth2::basic::BasicClient; use oauth2::{ - AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, RefreshToken, - Scope, TokenResponse, TokenUrl, + AuthUrl, AuthorizationCode, ClientId, CsrfToken, HttpRequest, HttpResponse, PkceCodeChallenge, + RedirectUrl, RefreshToken, RequestTokenError, Scope, TokenResponse, TokenUrl, }; use std::sync::{Arc, Weak}; use std::time::Duration; @@ -62,6 +62,42 @@ const DEFAULT_CALLBACK_PORT: u16 = 8030; /// Default timeout for waiting for the OAuth callback. const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); +/// Send an `oauth2`-built token request once through the kernel client: +/// no retry ladder (error statuses reach `oauth2` as before), but a +/// Negotiate proxy 407 gets its fresh-token retry (D3). +pub(crate) async fn send_token_request( + http_client: &DatabricksHttpClient, + request: HttpRequest, +) -> Result { + let request = reqwest::Request::try_from(request).map_err(|e| { + Error::invalid_argument().message(format!("failed to build token request: {e}")) + })?; + let response = http_client.send_once(request).await?.map_err(|e| { + Error::network_error().message(format!("token request failed: {}", e.without_url())) + })?; + let status = response.status(); + let headers = response.headers().clone(); + let body = response.bytes().await.map_err(|e| { + Error::network_error().message(format!( + "failed to read token response: {}", + e.without_url() + )) + })?; + let mut http_response = HttpResponse::new(body.to_vec()); + *http_response.status_mut() = status; + *http_response.headers_mut() = headers; + Ok(http_response) +} + +/// A token-request failure for the user: `oauth2` shows a transport +/// failure only as "Request failed", so use the kernel's own message. +fn token_error_text(e: &RequestTokenError) -> String { + match e { + RequestTokenError::Request(e) => e.message.clone(), + other => other.to_string(), + } +} + /// Persist `token` to the on-disk cache, or do nothing when disk caching /// is disabled (`passphrase` is `None`). /// @@ -405,7 +441,7 @@ impl AuthProvider for AuthorizationCodeProvider { .exchange_refresh_token(&RefreshToken::new( refresh_token_str.clone(), )) - .request_async(http_client.inner()) + .request_async(&|request| send_token_request(&http_client, request)) .await { Ok(token_response) => { @@ -466,6 +502,7 @@ impl AuthProvider for AuthorizationCodeProvider { // browser flow remains reachable only for a // genuine first connect (no cached token), // below. + let e = token_error_text(&e); crate::klog::warn!("OAuth token refresh failed: {}", e); return Err(Error::unauthenticated().message(format!( "OAuth token refresh failed (refresh token expired or \ @@ -535,11 +572,14 @@ impl AuthProvider for AuthorizationCodeProvider { let token_response = oauth_client .exchange_code(AuthorizationCode::new(authorization_code)) .set_pkce_verifier(pkce_verifier) - .request_async(http_client.inner()) + .request_async(&|request| send_token_request(&http_client, request)) .await .map_err(|e| { Error::unauthenticated() - .message(format!("U2M authorization code exchange failed: {}", e)) + .message(format!( + "U2M authorization code exchange failed: {}", + token_error_text(&e) + )) .context("authorization code grant") })?; diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 17623032..84e27474 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -28,8 +28,8 @@ use super::{block_on_ffi, KernelStatusCode}; use crate::config::{ - AuthConfig, ConnectionConfig, GeospatialResultRepresentation, HttpConfig, ProxyConfig, - ResultConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, + AuthConfig, ConnectionConfig, GeospatialResultRepresentation, HttpConfig, ProxyAuth, + ProxyConfig, ResultConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, }; use crate::kernel_error::Error; use crate::logging::{LoggingOutcome, LoggingSink}; @@ -274,6 +274,9 @@ pub struct KernelSessionConfig { /// Programmatic HTTP proxy (populated by `..._set_proxy`). `None` ⇒ /// reqwest's env-var proxy behaviour. proxy: Option, + /// Negotiate proxy auth (populated by `..._set_proxy_negotiate`); + /// requires `proxy`. + proxy_negotiate: Option, /// TLS relaxations / custom trust (populated by the `..._set_tls_*` /// setters). Defaults to the kernel's strict validation. tls: TlsSpec, @@ -414,6 +417,7 @@ pub unsafe extern "C" fn kernel_session_config_new( session_conf: HashMap::new(), geospatial_result_representation: None, proxy: None, + proxy_negotiate: None, tls: TlsSpec::default(), custom_headers: Vec::new(), sea_response_compression_enabled: false, @@ -1451,6 +1455,36 @@ pub unsafe extern "C" fn kernel_session_config_set_proxy( }) } +/// Authenticate to the proxy set by `kernel_session_config_set_proxy` with +/// Kerberos (`Proxy-Authorization: Negotiate`), using the ambient +/// credential cache / logon session. The target is `service/host[@realm]`: +/// NULL or empty `service` means `HTTP`, `host` the proxy host and `realm` +/// the Kerberos default realm. Session open fails if the proxy has Basic +/// credentials, is not `http(s)://`, or the kernel lacks the +/// `proxy-negotiate` feature. Maps to `ProxyAuth::Negotiate`. The setting +/// stays on the config: a later call replaces the target, and no call clears +/// it, so use a new config for a session without Negotiate. +/// +/// # Safety +/// `config` must be a live config handle; the args, if non-null, must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_proxy_negotiate( + config: *mut KernelSessionConfig, + service: *const c_char, + host: *const c_char, + realm: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.proxy_negotiate = Some(ProxyAuth::Negotiate { + service: optional_str(service, "proxy negotiate service")?, + host: optional_str(host, "proxy negotiate host")?, + realm: optional_str(realm, "proxy negotiate realm")?, + }); + Ok(()) + }) +} + /// Add a PEM-encoded CA-certificate bundle (bytes) to the TLS trust store /// on top of the system roots — for a corporate re-signing proxy or an /// on-prem CA. Maps to `TlsConfig::custom_ca_cert`. @@ -1936,6 +1970,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result OmUint32; +type ReleaseCred = unsafe extern "C" fn(*mut OmUint32, *mut GssCred) -> OmUint32; +type ImportName = + unsafe extern "C" fn(*mut OmUint32, *mut Buffer, *mut Oid, *mut GssName) -> OmUint32; +type CanonicalizeName = + unsafe extern "C" fn(*mut OmUint32, GssName, *mut Oid, *mut GssName) -> OmUint32; +type ReleaseName = unsafe extern "C" fn(*mut OmUint32, *mut GssName) -> OmUint32; +type InitSecContext = unsafe extern "C" fn( + *mut OmUint32, + GssCred, + *mut GssCtx, + GssName, + *mut Oid, + OmUint32, + OmUint32, + *mut c_void, + *mut Buffer, + *mut *mut Oid, + *mut Buffer, + *mut OmUint32, + *mut OmUint32, +) -> OmUint32; +type DeleteSecContext = unsafe extern "C" fn(*mut OmUint32, *mut GssCtx, *mut Buffer) -> OmUint32; +type ReleaseBuffer = unsafe extern "C" fn(*mut OmUint32, *mut Buffer) -> OmUint32; +type DisplayStatus = unsafe extern "C" fn( + *mut OmUint32, + OmUint32, + c_int, + *mut Oid, + *mut OmUint32, + *mut Buffer, +) -> OmUint32; + +/// The GSSAPI functions this module calls. The library handle is never +/// closed, so the pointers stay valid for the life of the process. +struct Gss { + acquire_cred: AcquireCred, + release_cred: ReleaseCred, + import_name: ImportName, + canonicalize_name: CanonicalizeName, + release_name: ReleaseName, + init_sec_context: InitSecContext, + delete_sec_context: DeleteSecContext, + release_buffer: ReleaseBuffer, + display_status: DisplayStatus, +} + +/// The library, opened on first use and kept for the life of the process. A +/// failed load is not kept: the next Negotiate attempt tries again, so +/// installing MIT Kerberos takes effect without restarting the host. +static GSS: OnceLock = OnceLock::new(); + +fn library() -> Result<&'static Gss, String> { + if let Some(gss) = GSS.get() { + return Ok(gss); + } + let gss = load(LIBRARY)?; + // If a concurrent first load wins, its functions are kept and this copy + // is dropped; the extra library reference it took is harmless. + Ok(GSS.get_or_init(|| gss)) +} + +/// The text of the last `dlopen` / `dlsym` failure on this thread. +fn dl_error() -> String { + // SAFETY: `dlerror` returns NULL or a NUL-terminated string that stays + // valid until the next dl* call on this thread; it is copied at once. + unsafe { + let message = libc::dlerror(); + if message.is_null() { + "unknown error".to_string() + } else { + CStr::from_ptr(message).to_string_lossy().into_owned() + } + } +} + +fn load(library: &CStr) -> Result { + let name = library.to_string_lossy(); + // SAFETY: `library` is NUL-terminated. Loading runs the library's + // initializers, as linking it at load time did. + let handle = unsafe { libc::dlopen(library.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if handle.is_null() { + return Err(format!( + "MIT Kerberos (GSSAPI) is not installed or could not be loaded: {}. Install \ + libgssapi-krb5-2 (Debian, Ubuntu) or krb5-libs (RHEL, Fedora)", + dl_error() + )); + } + let symbol = |symbol: &CStr| { + // SAFETY: `handle` is a live handle and `symbol` is NUL-terminated. + let address = unsafe { libc::dlsym(handle, symbol.as_ptr()) }; + if address.is_null() { + Err(format!( + "{name} has no {}: {}", + symbol.to_string_lossy(), + dl_error() + )) + } else { + Ok(address) + } + }; + let resolve = || -> Result { + // SAFETY: each address is the MIT GSSAPI function of that name, and + // each target type is that function's C signature (RFC 2744). + unsafe { + Ok(Gss { + acquire_cred: std::mem::transmute::<*mut c_void, AcquireCred>(symbol( + c"gss_acquire_cred", + )?), + release_cred: std::mem::transmute::<*mut c_void, ReleaseCred>(symbol( + c"gss_release_cred", + )?), + import_name: std::mem::transmute::<*mut c_void, ImportName>(symbol( + c"gss_import_name", + )?), + canonicalize_name: std::mem::transmute::<*mut c_void, CanonicalizeName>(symbol( + c"gss_canonicalize_name", + )?), + release_name: std::mem::transmute::<*mut c_void, ReleaseName>(symbol( + c"gss_release_name", + )?), + init_sec_context: std::mem::transmute::<*mut c_void, InitSecContext>(symbol( + c"gss_init_sec_context", + )?), + delete_sec_context: std::mem::transmute::<*mut c_void, DeleteSecContext>(symbol( + c"gss_delete_sec_context", + )?), + release_buffer: std::mem::transmute::<*mut c_void, ReleaseBuffer>(symbol( + c"gss_release_buffer", + )?), + display_status: std::mem::transmute::<*mut c_void, DisplayStatus>(symbol( + c"gss_display_status", + )?), + }) + } + }; + resolve().inspect_err(|_| { + // SAFETY: nothing from this handle escapes when resolving fails. + unsafe { libc::dlclose(handle) }; + }) +} + +/// An OID over static bytes. GSSAPI takes `gss_OID` as non-const for +/// historical reasons but only reads it. +fn oid(bytes: &'static [u8]) -> Oid { + Oid { + length: bytes.len() as OmUint32, + elements: bytes.as_ptr() as *mut c_void, + } +} + +/// A buffer GSSAPI allocated, released on drop. +struct Output<'a> { + gss: &'a Gss, + buffer: Buffer, +} + +impl<'a> Output<'a> { + fn new(gss: &'a Gss) -> Self { + Output { + gss, + buffer: Buffer { + length: 0, + value: ptr::null_mut(), + }, + } + } + + fn bytes(&self) -> &[u8] { + if self.buffer.value.is_null() { + return &[]; + } + // SAFETY: GSSAPI filled `buffer` with `length` bytes at `value`; + // they stay valid until the buffer is released on drop. + unsafe { std::slice::from_raw_parts(self.buffer.value as *const u8, self.buffer.length) } + } +} + +impl Drop for Output<'_> { + fn drop(&mut self) { + if !self.buffer.value.is_null() { + let mut minor = 0; + // SAFETY: the buffer came from GSSAPI and is released once. + unsafe { (self.gss.release_buffer)(&mut minor, &mut self.buffer) }; + } + } +} + +/// A credential handle, released on drop. +struct Cred<'a> { + gss: &'a Gss, + handle: GssCred, +} + +impl Drop for Cred<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from `gss_acquire_cred` and is released once. + unsafe { (self.gss.release_cred)(&mut minor, &mut self.handle) }; + } + } +} + +/// A name handle, released on drop. +struct Name<'a> { + gss: &'a Gss, + handle: GssName, +} + +impl Drop for Name<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from GSSAPI and is released once. + unsafe { (self.gss.release_name)(&mut minor, &mut self.handle) }; + } + } +} + +/// A security context, deleted on drop (no output token). +struct Context<'a> { + gss: &'a Gss, + handle: GssCtx, +} + +impl Drop for Context<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from `gss_init_sec_context` and is + // deleted once; a NULL output token is allowed. + unsafe { (self.gss.delete_sec_context)(&mut minor, &mut self.handle, ptr::null_mut()) }; + } + } +} + +/// The parts of a status code's text (`gss_display_status` may return more +/// than one). +fn status_parts(gss: &Gss, code: OmUint32, kind: c_int) -> Vec { + let mut parts = Vec::new(); + let mut message_context: OmUint32 = 0; + // Bounded, in case a library never clears `message_context`. + for _ in 0..8 { + let mut minor = 0; + let mut text = Output::new(gss); + // SAFETY: all pointers are to live locals; a NULL mechanism selects + // the default one, as libgssapi does. + let major = unsafe { + (gss.display_status)( + &mut minor, + code, + kind, + ptr::null_mut(), + &mut message_context, + &mut text.buffer, + ) + }; + if major != GSS_S_COMPLETE && major != GSS_S_CONTINUE_NEEDED { + parts.push(format!("unknown GSSAPI status code {code}")); + break; + } + parts.push(String::from_utf8_lossy(text.bytes()).into_owned()); + if message_context == 0 { + break; + } + } + parts +} + +/// `Err` with libgssapi's message format when `major` is an error. +fn check(gss: &Gss, major: OmUint32, minor: OmUint32) -> Result<(), String> { + if major & GSS_ERROR_BITS == 0 { + return Ok(()); + } + let mut message = status_parts(gss, major, GSS_C_GSS_CODE).concat(); + for part in status_parts(gss, minor, GSS_C_MECH_CODE) { + message.push_str(&format!(" ({part})")); + } + Err(message) +} + +/// The first Kerberos token for `target` (`service/host[@realm]`), with the +/// ambient credentials (the credential cache). Loads the library on first +/// use. Blocking: GSSAPI may contact the KDC. +pub(crate) fn initial_token(target: &str) -> Result, String> { + let gss = library()?; + let mut mech = oid(KRB5_MECH); + let mech_ptr: *mut Oid = &mut mech; + let mut minor = 0; + + let mut mechs = OidSet { + count: 1, + elements: mech_ptr, + }; + let mut cred = Cred { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: all pointers are to live locals; a NULL desired name means + // the default principal, and NULL outputs are optional (RFC 2744). + let major = unsafe { + (gss.acquire_cred)( + &mut minor, + ptr::null_mut(), + GSS_C_INDEFINITE, + &mut mechs, + GSS_C_INITIATE, + &mut cred.handle, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + check(gss, major, minor)?; + + let mut input = Buffer { + length: target.len(), + value: target.as_ptr() as *mut c_void, + }; + let mut name_type = oid(KRB5_NT_PRINCIPAL_NAME); + let mut name = Name { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: `input` covers `target`'s bytes, which GSSAPI copies and does + // not write; the other pointers are to live locals. + let major = + unsafe { (gss.import_name)(&mut minor, &mut input, &mut name_type, &mut name.handle) }; + check(gss, major, minor)?; + + let mut canonical = Name { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: `name.handle` is a live name; the other pointers are to live locals. + let major = unsafe { + (gss.canonicalize_name)(&mut minor, name.handle, mech_ptr, &mut canonical.handle) + }; + check(gss, major, minor)?; + + let mut context = Context { + gss, + handle: ptr::null_mut(), + }; + let mut token = Output::new(gss); + // SAFETY: the credential and name handles are live; no channel bindings, + // no input token (the first call), and the optional outputs are NULL. + let major = unsafe { + (gss.init_sec_context)( + &mut minor, + cred.handle, + &mut context.handle, + canonical.handle, + mech_ptr, + GSS_C_MUTUAL_FLAG | GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG, + GSS_C_INDEFINITE, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + &mut token.buffer, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + check(gss, major, minor)?; + match token.bytes() { + [] => Err("expected token".to_string()), + bytes => Ok(bytes.to_vec()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_library_fails_with_an_install_hint() { + let err = load(c"libdatabricks-no-such-gssapi.so.2") + .err() + .expect("a library that does not exist must not load"); + assert!( + err.contains("MIT Kerberos (GSSAPI) is not installed"), + "{err}" + ); + assert!(err.contains("libdatabricks-no-such-gssapi.so.2"), "{err}"); + assert!(err.contains("libgssapi-krb5-2"), "{err}"); + assert!(err.contains("krb5-libs"), "{err}"); + } + + /// With the library present, a token for a principal in a realm that does + /// not exist fails, and the error carries the major and minor status text. + /// Skipped where MIT Kerberos is not installed. + #[test] + fn token_failure_reports_gssapi_status() { + if let Err(e) = library() { + eprintln!("skipped: {e}"); + return; + } + let err = initial_token("HTTP/proxy.invalid@DATABRICKS-KERNEL-TEST.INVALID") + .expect_err("no credentials or KDC exist for this realm"); + assert!(!err.is_empty()); + assert!( + err.contains(" ("), + "major status, then the minor in parentheses: {err}" + ); + assert!(!err.contains("unknown GSSAPI status code"), "{err}"); + } + + const TEST_REALM: &str = "KERNEL-TEST.INVALID"; + const CACHE_TEST_CHILD: &str = "DATABRICKS_KERNEL_GSSAPI_CACHE_TEST_CHILD"; + + /// DER with lengths sufficient for these small, synthetic tickets. + fn der(tag: u8, bytes: &[u8]) -> Vec { + let mut result = vec![tag]; + if bytes.len() < 128 { + result.push(bytes.len() as u8); + } else if bytes.len() < 256 { + result.extend([0x81, bytes.len() as u8]); + } else { + let length = u16::try_from(bytes.len()).expect("small test ticket"); + result.push(0x82); + result.extend(length.to_be_bytes()); + } + result.extend(bytes); + result + } + + fn der_integer(value: u8) -> Vec { + der(0x02, &[value]) + } + + fn fake_ticket(components: &[&[u8]]) -> Vec { + let names = components + .iter() + .flat_map(|name| der(0x1b, name)) + .collect::>(); + let principal = der( + 0x30, + &[der(0xa0, &der_integer(2)), der(0xa1, &der(0x30, &names))].concat(), + ); + // AES256 ciphertext is deliberately fake: an initiator copies the + // ticket into its AP-REQ without decrypting it. No real credentials. + let encrypted = der( + 0x30, + &[ + der(0xa0, &der_integer(18)), + der(0xa1, &der_integer(1)), + der(0xa2, &der(0x04, &[0x55; 96])), + ] + .concat(), + ); + der( + 0x61, + &der( + 0x30, + &[ + der(0xa0, &der_integer(5)), + der(0xa1, &der(0x1b, TEST_REALM.as_bytes())), + der(0xa2, &principal), + der(0xa3, &encrypted), + ] + .concat(), + ), + ) + } + + fn counted(bytes: &[u8]) -> Vec { + let mut result = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + result.extend(bytes); + result + } + + fn cache_principal(kind: u32, components: &[&[u8]]) -> Vec { + let mut result = kind.to_be_bytes().to_vec(); + result.extend(u32::try_from(components.len()).unwrap().to_be_bytes()); + result.extend(counted(TEST_REALM.as_bytes())); + for name in components { + result.extend(counted(name)); + } + result + } + + fn cached_credential(now: u32, server_kind: u32, server: &[&[u8]]) -> Vec { + let mut result = cache_principal(1, &[b"kernel-test"]); + result.extend(cache_principal(server_kind, server)); + result.extend(18_u16.to_be_bytes()); // AES256 session key type. + result.extend(counted(&[0x42; 32])); // Synthetic session key. + for time in [now - 60, now - 60, now + 36_000, 0] { + result.extend(time.to_be_bytes()); + } + result.push(0); // Not an SKEY ticket. + result.extend(0x40e1_0000_u32.to_be_bytes()); // Ticket flags. + result.extend(0_u32.to_be_bytes()); // No addresses. + result.extend(0_u32.to_be_bytes()); // No authdata. + result.extend(counted(&fake_ticket(server))); + result.extend(counted(&[])); // No second ticket. + result + } + + /// FILE v4 cache: a default client, a fake TGT and a cached HTTP ticket. + /// MIT can create an AP-REQ locally; the fake ticket needs no KDC or keytab. + fn write_test_cache(path: &std::path::Path) { + let now = u32::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(), + ) + .unwrap(); + let mut cache = Vec::new(); + cache.extend(0x0504_u16.to_be_bytes()); + cache.extend(12_u16.to_be_bytes()); // Header length. + cache.extend(1_u16.to_be_bytes()); // Time-offset header tag. + cache.extend(8_u16.to_be_bytes()); + cache.extend([0; 8]); // No clock offset. + cache.extend(cache_principal(1, &[b"kernel-test"])); + cache.extend(cached_credential( + now, + 2, + &[b"krbtgt", TEST_REALM.as_bytes()], + )); + cache.extend(cached_credential(now, 1, &[b"HTTP", b"proxy.test"])); + std::fs::write(path, cache).unwrap(); + } + + fn assert_ap_req(token: &[u8]) { + // RFC 2743 InitialContextToken: 0x60, DER length, krb5 OID, + // RFC 4121 TOK_ID 01 00, then the AP-REQ application tag (0x6e). + assert!(token.len() > 2, "missing GSSAPI token framing"); + assert!(token[0] == 0x60, "expected InitialContextToken"); + let (length, offset) = if token[1] < 128 { + (usize::from(token[1]), 2) + } else { + let count = usize::from(token[1] & 0x7f); + assert!(count > 0 && count <= std::mem::size_of::()); + let end = 2 + count; + assert!(token.len() >= end, "truncated DER length"); + let length = token[2..end] + .iter() + .fold(0_usize, |n, byte| (n << 8) | usize::from(*byte)); + (length, end) + }; + assert!( + token.len() - offset == length, + "incorrect GSSAPI token length" + ); + let prefix = [&[0x06, 0x09], KRB5_MECH, &[0x01, 0x00, 0x6e]].concat(); + assert!( + token[offset..].starts_with(&prefix), + "expected krb5 OID and AP-REQ TOK_ID" + ); + } + + fn check_cached_token_and_header() { + use crate::client::proxy_negotiate::NegotiateSource; + use crate::config::ProxyAuth; + use crate::kernel_error::ErrorCode; + use base64::Engine; + + let token = initial_token(&format!("HTTP/proxy.test@{TEST_REALM}")) + .expect("the cached service ticket must create a token without a KDC"); + assert_ap_req(&token); + let auth = ProxyAuth::Negotiate { + service: None, + host: None, + realm: Some(TEST_REALM.to_string()), + }; + let source = NegotiateSource::resolve(Some("http://proxy.test:3128"), None, None, &auth) + .unwrap() + .unwrap(); + let header = source + .header() + .expect("the cached service ticket must create a header"); + assert!(header.is_sensitive(), "Negotiate header must be sensitive"); + assert!( + format!("{header:?}") == "Sensitive", + "header Debug must hide the token" + ); + let encoded = header + .to_str() + .unwrap() + .strip_prefix("Negotiate ") + .expect("the header must use the Negotiate scheme"); + let header_token = base64::engine::general_purpose::STANDARD + .decode(encoded) + .unwrap(); + assert_ap_req(&header_token); + + // A missing service ticket fails against the unreachable local KDC. + // Check both the native error and the public wrapper, without ever + // printing tokens (even a failing assertion must not dump their bytes). + let missing_target = format!("HTTP/missing.test@{TEST_REALM}"); + let native_error = match initial_token(&missing_target) { + Ok(_) => panic!("a service ticket absent from the cache must fail"), + Err(error) => error, + }; + let error = NegotiateSource::Kerberos { + target: missing_target, + } + .header() + .unwrap_err(); + assert_eq!(error.code, ErrorCode::Unauthenticated); + assert!(!error.retryable); + for message in [ + native_error, + error.message.clone(), + error.to_string(), + format!("{error:?}"), + ] { + for token in [&token, &header_token] { + let encoded = base64::engine::general_purpose::STANDARD.encode(token); + assert!( + !message.contains(&encoded), + "base64 token leaked in an error" + ); + assert!( + !message.contains(String::from_utf8_lossy(token).as_ref()), + "raw token leaked in an error" + ); + } + } + } + + #[test] + fn cached_service_ticket_creates_sensitive_negotiate_header() { + if let Err(error) = library() { + eprintln!("skipped: {error}"); + return; + } + if std::env::var_os(CACHE_TEST_CHILD).is_some() { + check_cached_token_and_header(); + return; + } + let dir = tempfile::tempdir().unwrap(); + let cache = dir.path().join("ccache"); + let config = dir.path().join("krb5.conf"); + write_test_cache(&cache); + std::fs::write( + &config, + format!( + "[libdefaults]\n default_realm = {TEST_REALM}\n dns_lookup_kdc = false\n \ + dns_lookup_realm = false\n rdns = false\n dns_canonicalize_hostname = false\n \ + udp_preference_limit = 1\n[realms]\n {TEST_REALM} = {{\n kdc = 127.0.0.1:1\n }}\n" + ), + ) + .unwrap(); + // Only the child sees these environment settings. Other tests in the + // parent may create GSSAPI contexts concurrently using their own env. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "client::gssapi_runtime::tests::cached_service_ticket_creates_sensitive_negotiate_header", "--nocapture", "--test-threads=1"]) + .env(CACHE_TEST_CHILD, "1") + .env("KRB5CCNAME", format!("FILE:{}", cache.display())) + .env("KRB5_CONFIG", &config) + .output() + .expect("run the GSSAPI cache test in a child process"); + assert!( + output.status.success(), + "child GSSAPI test failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8_lossy(&output.stdout).contains("test result: ok. 1 passed;"), + "the child must run exactly one test, not silently match an empty filter" + ); + } + + #[test] + fn oids_match_rfc_1964() { + // 1.2.840.113554.1.2.2 and 1.2.840.113554.1.2.2.1, DER-encoded. + assert_eq!(KRB5_MECH.len(), 9); + assert_eq!(&KRB5_NT_PRINCIPAL_NAME[..9], KRB5_MECH); + assert_eq!(KRB5_NT_PRINCIPAL_NAME[9], 0x01); + } +} diff --git a/src/client/http.rs b/src/client/http.rs index 3841724d..5d96c6de 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -23,6 +23,7 @@ //! - Configurable timeouts use crate::auth::AuthProvider; +use crate::client::proxy_negotiate::{is_proxy_auth_required, next_redirect, NegotiateSource}; use crate::client::retry::{ calculate_backoff, is_certificate_verification_failure, is_socks_authentication_failure, RequestCategory, RequestType, RetryConfig, RetryStrategy, @@ -159,6 +160,8 @@ pub struct ProxyConfig { /// Comma-separated list of hosts/domains to bypass the proxy /// (e.g., "localhost,*.internal.corp,.example.com"). pub bypass_hosts: Option, + /// Proxy authentication scheme (Basic/none or Negotiate). + pub auth: crate::config::ProxyAuth, } impl std::fmt::Debug for ProxyConfig { @@ -168,6 +171,7 @@ impl std::fmt::Debug for ProxyConfig { .field("username", &self.username) .field("password", &self.password.as_ref().map(|_| "[REDACTED]")) .field("bypass_hosts", &self.bypass_hosts) + .field("auth", &self.auth) .finish() } } @@ -425,6 +429,143 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>> = std::sync::Mutex::new(Vec::new()); + +/// The token-independent, costly part of a Negotiate client's TLS setup. It +/// is loaded once per [`DatabricksHttpClient`] and shared by its first client +/// and every proxy-407 rebuild, so a rebuild only creates a client with the +/// new token instead of reloading the system trust store. It comes from the +/// same [`TlsConfig`] settings as reqwest's own setup, with the same result. +#[derive(Clone)] +struct ReusableTls { + /// The connector, built with the native-tls calls reqwest 0.12 makes for + /// these settings: system roots, custom CAs, mTLS identity, verification + /// flags and SNI. reqwest's `http2` and `native-tls-alpn` are off, so it + /// sets no ALPN. + #[cfg(feature = "tls-native")] + connector: native_tls::TlsConnector, + /// The OS trust store, which `rustls-tls-native-roots` otherwise reloads + /// on every build. reqwest still builds the rest of the rustls setup. + #[cfg(feature = "tls-rustls")] + system_roots: Vec, + /// With revocation on: the whole rustls config, as + /// [`super::tls_revocation::client_config`] builds it (session resumption + /// off, so clients share no session state). + #[cfg(all(windows, feature = "tls-rustls"))] + revocation: Option, +} + +impl std::fmt::Debug for ReusableTls { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ReusableTls") + } +} + +/// Built at the first Negotiate client build; `None` keeps reqwest's own setup. +type SharedTls = OnceLock>; + +impl ReusableTls { + /// `None` for a custom CA bundle that native-tls and reqwest would parse + /// differently: that client keeps reqwest's own TLS setup. + /// `revocation` is the effective mode; this backend rejects it at open. + #[cfg(feature = "tls-native")] + fn load(config: &TlsConfig, _revocation: Option) -> Result> { + let mut tls = native_tls::TlsConnector::builder(); + tls.danger_accept_invalid_hostnames(config.allow_hostname_mismatch.unwrap_or(false)) + .danger_accept_invalid_certs(config.allow_self_signed.unwrap_or(false)) + .use_sni(true) + .disable_built_in_roots(false); + let file = match &config.trusted_certificate_path { + Some(path) => Some(std::fs::read(path).map_err(|e| { + Error::invalid_argument() + .message(format!("Failed to read TLS certificate '{path}': {e}")) + })?), + None => None, + }; + for pem in file.iter().chain(&config.trusted_certificate_pem) { + // reqwest reads only `CERTIFICATE` blocks and OpenSSL also reads + // other labels, so the same count means the same certificates. + let (Ok(certs), Ok(expected)) = ( + native_tls::Certificate::stack_from_pem(pem), + reqwest::Certificate::from_pem_bundle(pem), + ) else { + return Ok(None); + }; + if certs.len() != expected.len() { + return Ok(None); + } + for cert in certs { + tls.add_root_certificate(cert); + } + } + if let (Some(cert), Some(key)) = (&config.client_cert_pem, &config.client_key_pem) { + tls.identity(native_tls::Identity::from_pkcs8(cert, key).map_err(|e| { + Error::invalid_argument().message(format!( + "Invalid mTLS client certificate/key in TlsConfig.client_cert_pem/client_key_pem: {e}" + )) + })?); + } + let connector = tls.build().map_err(|e| { + Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) + })?; + Ok(Some(Self { connector })) + } + + /// `revocation` is the effective mode (Windows only; rejected at open elsewhere). + #[cfg(feature = "tls-rustls")] + fn load(config: &TlsConfig, revocation: Option) -> Result> { + #[cfg(windows)] + if let Some(accept_undetermined) = revocation { + let config = super::tls_revocation::client_config(config, accept_undetermined)?; + return Ok(Some(Self { + system_roots: Vec::new(), + revocation: Some(config), + })); + } + let _ = (config, revocation); + let loaded = rustls_native_certs::load_native_certs(); + let mut store = rustls::RootCertStore::empty(); + let (mut system_roots, mut invalid) = (Vec::new(), 0); + for cert in loaded.certs { + // Like reqwest, skip certificates rustls cannot use as roots. + if store.add(cert.clone()).is_err() { + invalid += 1; + continue; + } + system_roots.push(reqwest::Certificate::from_der(&cert).map_err(|e| { + Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) + })?); + } + if system_roots.is_empty() && invalid > 0 { + return Err(Error::invalid_argument().message( + "Failed to create HTTP client: zero valid certificates found in native root store", + )); + } + Ok(Some(Self { + system_roots, + #[cfg(windows)] + revocation: None, + })) + } + + fn apply(&self, builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder { + #[cfg(all(windows, feature = "tls-rustls"))] + if let Some(config) = &self.revocation { + return builder.use_preconfigured_tls(config.clone()); + } + #[cfg(feature = "tls-native")] + let builder = builder.use_preconfigured_tls(self.connector.clone()); + #[cfg(feature = "tls-rustls")] + let builder = self.system_roots.iter().cloned().fold( + builder.tls_built_in_native_certs(false), + reqwest::ClientBuilder::add_root_certificate, + ); + builder + } +} + /// HTTP client for communicating with Databricks SQL endpoints. /// /// This client handles: @@ -449,6 +590,11 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, + /// With Negotiate, the TLS setup shared by every client build. + negotiate_tls: Arc, config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, @@ -461,6 +607,10 @@ 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). + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which creates it off the async workers within the request timeout. pub fn new( config: HttpClientConfig, retry_configs: HashMap, @@ -471,6 +621,10 @@ impl DatabricksHttpClient { /// Like [`Self::new`], with a revocation policy applied to every connection this client /// makes. The policy is kept outside [`TlsConfig`], so that struct keeps its published /// shape. + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which bounds token creation by the request timeout. pub(crate) fn with_revocation( mut config: HttpClientConfig, retry_configs: HashMap, @@ -563,11 +717,13 @@ impl DatabricksHttpClient { // Follow redirects for normal traffic (reqwest's default policy). // `read_timeout` is a historical name; reqwest applies it as the // total deadline from connect through response-body completion. + let negotiate_tls = Arc::new(SharedTls::new()); let client = Self::build_reqwest_client( &config, - reqwest::redirect::Policy::default(), + Self::redirect_policy(&config), revocation, Some(config.read_timeout), + Self::shared_tls(&config, &negotiate_tls), )?; // Surface which TLS backend was compiled in so oncall debugging @@ -588,6 +744,8 @@ impl DatabricksHttpClient { Ok(Self { client, + negotiate_client: std::sync::RwLock::new(None), + negotiate_tls, config, auth_provider: OnceLock::new(), retry_configs, @@ -595,6 +753,39 @@ impl DatabricksHttpClient { }) } + /// [`Self::with_revocation`] for async callers: with Negotiate the first + /// token is created off the async workers (GSSAPI may contact the KDC; a + /// token callback may block), within the request timeout + /// (`read_timeout`), like a token rebuilt after a 407. Default proxy auth + /// builds inline. + /// + /// A token call that times out keeps its blocking thread until it + /// returns: a GSSAPI or callback call cannot be cancelled. + pub(crate) async fn with_revocation_async( + config: HttpClientConfig, + retry_configs: HashMap, + revocation: Option, + ) -> Result { + if matches!(config.proxy.auth, crate::config::ProxyAuth::Default) { + return Self::with_revocation(config, retry_configs, revocation); + } + let budget = config.read_timeout; + let task = tokio::task::spawn_blocking(move || { + Self::with_revocation(config, retry_configs, revocation) + }); + match tokio::time::timeout(budget, task).await { + Ok(joined) => joined.map_err(|e| { + Error::internal().message(format!("Negotiate token task failed: {e}")) + })?, + Err(_) => Err(Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + )) + .with_retryable(false)), + } + } + /// Build a `reqwest::Client` from `config` with the given redirect policy /// and total request timeout. /// @@ -602,11 +793,14 @@ impl DatabricksHttpClient { /// 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. + /// + /// `tls` (Negotiate only) is loaded at the first build and reused after. fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, revocation: Option, timeout: Option, + tls: Option<&SharedTls>, ) -> Result { check_revocation_support(&config.tls, revocation)?; let mut builder = Client::builder() @@ -738,6 +932,15 @@ impl DatabricksHttpClient { (None, None) => {} } + // Negotiate: validated before any I/O; the token is created per + // client build (preemptive) and rides only on the proxy CONNECT. + let negotiate = NegotiateSource::resolve( + config.proxy.url.as_deref(), + config.proxy.username.as_deref(), + config.proxy.password.as_deref(), + &config.proxy.auth, + )?; + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -760,9 +963,13 @@ impl DatabricksHttpClient { )) })?; + if let Some(ref negotiate) = negotiate { + proxy = proxy.custom_http_auth(negotiate.header()?); + debug!("HTTP proxy auth: Negotiate configured ({negotiate:?})"); + } // Add basic auth if credentials provided. // Explicit username/password override any credentials embedded in the URL. - if let Some(ref username) = config.proxy.username { + else if let Some(ref username) = config.proxy.username { if proxy_url.contains('@') { warn!("Proxy URL contains embedded credentials, but explicit username/password are also set; explicit credentials take precedence"); } @@ -809,16 +1016,28 @@ impl DatabricksHttpClient { // With revocation on, the verifier replaces reqwest's trust roots and identity. // Those were already validated above. `allow_self_signed` turns revocation off. + // With Negotiate it is part of the reused TLS setup below. + let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); #[cfg(all(windows, feature = "tls-rustls"))] - if let Some(accept_undetermined) = - revocation.filter(|_| config.tls.allow_self_signed != Some(true)) - { + if let Some(accept_undetermined) = revocation.filter(|_| tls.is_none()) { builder = builder.use_preconfigured_tls(super::tls_revocation::client_config( &config.tls, accept_undetermined, )?); } + // After the token, so a missing ticket still fails fast. + if let Some(shared) = tls { + if shared.get().is_none() { + #[cfg(test)] + TLS_LOADS.lock().unwrap().push(config.proxy.url.clone()); + let _ = shared.set(ReusableTls::load(&config.tls, revocation)?); + } + if let Some(Some(reusable)) = shared.get() { + builder = reusable.apply(builder); + } + } + builder.build().map_err(|e| { Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) }) @@ -828,6 +1047,10 @@ impl DatabricksHttpClient { /// /// Convenience method for tests and simple use cases where custom retry /// configuration is not needed. + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which bounds token creation by the request timeout. pub fn with_default_retry(config: HttpClientConfig) -> Result { use crate::client::retry::build_retry_configs; let retry_configs = @@ -851,7 +1074,39 @@ impl DatabricksHttpClient { config: &HttpClientConfig, revocation: Option, ) -> Result { - Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), revocation, None) + Self::build_reqwest_client( + config, + reqwest::redirect::Policy::none(), + revocation, + None, + None, + ) + } + + /// Storage client construction for async callers. Default proxy auth keeps + /// the inline build; Negotiate token creation runs off the async workers, + /// bounded by the request timeout. A timed-out blocking call cannot be + /// cancelled and keeps its thread until it returns. + pub(crate) async fn storage_client_async( + config: &HttpClientConfig, + revocation: Option, + ) -> Result { + if matches!(config.proxy.auth, crate::config::ProxyAuth::Default) { + return Self::storage_client(config, revocation); + } + let (config, budget) = (config.clone(), config.read_timeout); + let task = tokio::task::spawn_blocking(move || Self::storage_client(&config, revocation)); + match tokio::time::timeout(budget, task).await { + Ok(joined) => joined.map_err(|e| { + Error::internal().message(format!("Negotiate token task failed: {e}")) + })?, + Err(_) => Err(Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + )) + .with_retryable(false)), + } } /// Returns the client configuration. @@ -870,6 +1125,183 @@ impl DatabricksHttpClient { &self.client } + /// The client new requests go through: the Negotiate rebuild, if any. + pub(crate) fn current_client(&self) -> Client { + self.negotiate_client + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| self.client.clone()) + } + + /// Negotiate clients follow no redirects: [`Self::send_once`] follows + /// them hop by hop so a proxy 407 is retried at the failing hop. + fn redirect_policy(config: &HttpClientConfig) -> reqwest::redirect::Policy { + match config.proxy.auth { + crate::config::ProxyAuth::Default => reqwest::redirect::Policy::default(), + _ => reqwest::redirect::Policy::none(), + } + } + + /// The shared TLS setup to build with: only with Negotiate. + fn shared_tls<'a>(config: &HttpClientConfig, tls: &'a SharedTls) -> Option<&'a SharedTls> { + (!matches!(config.proxy.auth, crate::config::ProxyAuth::Default)).then_some(tls) + } + + /// Rebuild the client with a fresh Negotiate token after a proxy 407. + async fn rebuild_negotiate_client(&self) -> Result { + self.build_negotiate_client(Self::redirect_policy(&self.config)) + .await + } + + /// Build a client with a fresh Negotiate token, off the async workers + /// (GSSAPI may contact the KDC; a token callback may block). It reuses + /// the client's TLS setup, so only the token is new. Callers bound it + /// with a timeout; a timed-out token call keeps its blocking thread until + /// it returns, because a GSSAPI or callback call cannot be cancelled. + async fn build_negotiate_client(&self, redirect: reqwest::redirect::Policy) -> Result { + let (config, tls) = (self.config.clone(), self.negotiate_tls.clone()); + let revocation = self.revocation; + tokio::task::spawn_blocking(move || { + Self::build_reqwest_client( + &config, + redirect, + revocation, + Some(config.read_timeout), + Some(&tls), + ) + }) + .await + .map_err(|e| Error::internal().message(format!("Negotiate token task failed: {e}")))? + } + + /// Send `request` once, without the retry ladder. The outer error is a + /// kernel failure; the inner result is the transport outcome. + /// + /// Without Negotiate this is `execute` on the client. With Negotiate (D3) + /// it follows redirects itself ([`next_redirect`]). A proxy 407 on a + /// hop's `CONNECT` gets one retry of that hop on a client rebuilt with a + /// fresh token, so hops that already reached their server are never + /// resent. A second 407 on the same hop fails closed. + /// + /// Like reqwest's own redirect handling, one deadline (the request's + /// timeout, else the client's) covers every hop, the token rebuild and + /// the final response body: each hop is sent with the remaining time. + /// + /// With Negotiate, plain-HTTP requests are refused (`InvalidArgument`, no + /// I/O), and so is a redirect to plain HTTP (`NetworkError`): the token + /// is only ever sent on a `CONNECT`. This applies to hosts on the bypass + /// list too: reqwest does not expose its bypass matching, and every + /// Databricks endpoint the kernel calls is `https://`. + /// + /// Limit: a request whose body cannot be cloned (a streaming body) gets + /// one plain attempt. It has no 407 retry, and a redirect on it comes back + /// to the caller unfollowed, because the Negotiate client does not follow + /// redirects itself. Kernel callers of this method send cloneable JSON + /// bodies (`sea.rs`) or none. Volume storage requests instead recreate their + /// streaming bodies and handle the proxy 407 retry in `volume.rs`. + pub(crate) async fn send_once( + &self, + request: Request, + ) -> Result> { + let mut client = self.current_client(); + if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { + return Ok(client.execute(request).await); + } + let budget = request + .timeout() + .copied() + .unwrap_or(self.config.read_timeout); + // An extreme timeout (e.g. `Duration::MAX`) must not overflow `Instant`. + let now = tokio::time::Instant::now(); + let deadline = now + .checked_add(budget) + .unwrap_or_else(|| now + Duration::from_secs(100 * 365 * 24 * 3600)); + // An exhausted budget fails the hop with reqwest's own timeout error. + let remaining = || deadline.saturating_duration_since(tokio::time::Instant::now()); + let mut rebuilt = false; + let mut previous = Vec::new(); + let mut hop = request; + loop { + // The token must ride only on CONNECT. reqwest forwards a plain-HTTP + // request to the proxy with the token and no tunnel, and a 407 there + // is an ordinary response that gets no fresh-token retry. So refuse + // plain-HTTP hops: the request itself, or an https -> http redirect. + if hop.url().scheme() != "https" { + let host = hop.url().host_str().unwrap_or("").to_string(); + return Err(if previous.is_empty() { + Error::invalid_argument().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP request to {host}" + )) + } else { + Error::network_error().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + redirect to plain HTTP at {host}" + )) + }); + } + let mut fresh_token = false; + let response = loop { + // A streaming body cannot be resent: one plain attempt. + let Some(mut attempt) = hop.try_clone() else { + *hop.timeout_mut() = Some(remaining()); + return Ok(client.execute(hop).await); + }; + *attempt.timeout_mut() = Some(remaining()); + match client.execute(attempt).await { + Ok(response) => break response, + Err(mut e) if is_proxy_auth_required(&e) => { + if fresh_token { + if let Some(url) = e.url_mut() { + url.set_query(None); + } + let mut causes = super::error_chain(&e) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + return Err(Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the proxy rejected a \ + fresh token (HTTP 407): {}", + causes.join(": ") + ))); + } + debug!("proxy 407; retrying this hop once with a fresh Negotiate token"); + client = tokio::time::timeout(remaining(), self.rebuild_negotiate_client()) + .await + .map_err(|_| { + Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no fresh token \ + within the {budget:?} request timeout" + )) + .with_retryable(false) + })??; + (rebuilt, fresh_token) = (true, true); + } + Err(e) => return Ok(Err(e)), + } + }; + if rebuilt { + // Its tunnel is up: later requests reuse its pool. Concurrent + // 407s each rebuild their own client and the last one to land + // here wins, so the other rebuilt clients' tunnels close after + // their requests. A later new tunnel then pays the one 407 per + // new tunnel that a replay-caching proxy costs anyway (each + // tunnel needs a token the proxy has not seen); coalescing the + // rebuilds would keep a few more pooled tunnels, not avoid it. + *self + .negotiate_client + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(client.clone()); + } + match next_redirect(&hop, &response, &mut previous)? { + Some(next) => hop = next, + None => return Ok(Ok(response)), + } + } + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -947,17 +1379,64 @@ impl DatabricksHttpClient { /// discovery is fatal to `Session::open` for a zero-config-tenant /// `azure-sp-m2m` caller; the recourse is to re-run with an explicit /// `azure_tenant_id` (which skips discovery entirely). A single hop is - /// sufficient for discovery, so no retry is attempted here. + /// sufficient for discovery, so no retry is attempted here. One request + /// timeout covers both token creation and the GET. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client( - &self.config, - reqwest::redirect::Policy::none(), - self.revocation, - Some(self.config.read_timeout), - )?; - let response = client.get(url).send().await.map_err(|e| { - Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) - })?; + let budget = self.config.read_timeout; + let now = tokio::time::Instant::now(); + let deadline = now + .checked_add(budget) + .unwrap_or_else(|| now + Duration::from_secs(100 * 365 * 24 * 3600)); + let redirect = reqwest::redirect::Policy::none(); + let client = if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { + Self::build_reqwest_client( + &self.config, + redirect, + self.revocation, + Some(self.config.read_timeout), + None, + )? + } else { + // As in `send_once`: the token rides only on CONNECT, so refuse a + // plain-HTTP probe rather than forward it to the proxy with the token. + if reqwest::Url::parse(url).map_or(true, |u| u.scheme() != "https") { + return Err(Error::invalid_argument().message( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP tenant-discovery probe", + )); + } + tokio::time::timeout_at(deadline, self.build_negotiate_client(redirect)) + .await + .map_err(|_| { + Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the \ + {budget:?} request timeout" + )) + .with_retryable(false) + })?? + }; + let negotiate = !matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default); + // Token creation and the probe share one budget, just as send_once's + // token rebuild and request hops do. + let response = client + .get(url) + .timeout(deadline.saturating_duration_since(tokio::time::Instant::now())) + .send() + .await + .map_err(|e| { + // The probe's client carries a fresh token, so a 407 fails closed + // as `send_once` does after its retry. + if negotiate && is_proxy_auth_required(&e) { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the proxy rejected a fresh token \ + (HTTP 407) on the tenant-discovery probe to {url}" + )) + } else { + Error::network_error() + .message(format!("Redirect-probe request to {url} failed: {e}")) + } + })?; Ok(response .headers() .get(reqwest::header::LOCATION) @@ -993,7 +1472,6 @@ impl DatabricksHttpClient { .body() .and_then(|b| b.as_bytes()) .map(|b| b.to_vec()); - loop { attempts += 1; @@ -1102,7 +1580,8 @@ impl DatabricksHttpClient { max_attempts ); - match self.client.execute(request).await { + // Negotiate's proxy 407 retry happens per hop inside `send_once`. + match self.send_once(request).await? { Ok(response) => { let status = response.status(); @@ -1285,6 +1764,10 @@ mod revocation_support_tests { } } +#[cfg(test)] +#[path = "http_negotiate_tests.rs"] +pub(crate) mod negotiate_tests; + #[cfg(test)] #[path = "http_socks_tests.rs"] mod socks_tests; @@ -2191,6 +2674,7 @@ lGrv15pBcePj username: Some("user".to_string()), password: Some("secret123".to_string()), bypass_hosts: None, + ..Default::default() }; let debug_output = format!("{:?}", config); assert!(debug_output.contains("[REDACTED]")); diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs new file mode 100644 index 00000000..5628a27a --- /dev/null +++ b/src/client/http_negotiate_tests.rs @@ -0,0 +1,1267 @@ +// 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. + +//! Negotiate proxy auth against a stub `CONNECT` proxy that, like a Kerberos +//! acceptor with a replay cache, rejects any token it has already seen +//! (`407 Negotiate, Basic`). The stub terminates the tunnel with its own TLS +//! origin. No KDC needed; the driver-test kernel nightly covers real tokens. + +use super::*; +use crate::auth::PersonalAccessToken; +use crate::config::{NegotiateTokenCallback, ProxyAuth}; +use crate::kernel_error::ErrorCode; +use std::collections::HashSet; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::TcpListener; + +#[derive(Default)] +pub(crate) struct Seen { + /// (`Proxy-Authorization` of each CONNECT, status the proxy answered). + pub(crate) connects: Vec<(Option, u16)>, + tokens: HashSet, + /// Header names of requests that came through a tunnel. + origin_headers: Vec, + /// ` ` and header names of each tunnelled request. + pub(crate) requests: Vec<(String, Vec)>, + /// Bytes received by the Volume route, which closes each tunnel after replying. + pub(crate) volume_bodies: Vec>, + volume_object: Vec, + /// When set, every origin answer waits here until all parties arrive. + gate: Option>, + /// Gate waits that gave up (a request never arrived, or a tunnel was reused). + gate_timeouts: usize, +} + +pub(crate) struct StubProxy { + pub(crate) url: String, + pub(crate) seen: Arc>, +} + +async fn read_head(stream: &mut S) -> Option { + let mut head = Vec::new(); + let mut byte = [0_u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).await.ok()? == 0 { + return None; + } + head.push(byte[0]); + } + Some(String::from_utf8_lossy(&head).into_owned()) +} + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().find_map(|line| { + let (n, v) = line.split_once(':')?; + n.eq_ignore_ascii_case(name).then(|| v.trim()) + }) +} + +async fn serve_origin( + mut stream: S, + seen: Arc>, + delay: Duration, +) { + while let Some(head) = read_head(&mut stream).await { + let names = head + .lines() + .skip(1) + .filter_map(|l| l.split_once(':').map(|(n, _)| n.to_ascii_lowercase())) + .collect::>(); + let mut line = head.lines().next().unwrap_or_default().split(' '); + let (method, path) = ( + line.next().unwrap_or_default(), + line.next().unwrap_or_default(), + ); + let length = header(&head, "content-length").map_or(0, |v| v.parse().unwrap()); + let mut body = vec![0_u8; length]; + if stream.read_exact(&mut body).await.is_err() { + return; + } + { + let mut seen = seen.lock().unwrap(); + seen.origin_headers.extend(names.clone()); + seen.requests.push((format!("{method} {path}"), names)); + } + let gate = seen.lock().unwrap().gate.clone(); + if let Some(gate) = gate { + if tokio::time::timeout(Duration::from_secs(10), gate.wait()) + .await + .is_err() + { + seen.lock().unwrap().gate_timeouts += 1; + } + } + tokio::time::sleep(delay).await; + if path.split('?').next() == Some("/volume") { + let payload = { + let mut seen = seen.lock().unwrap(); + if method == "PUT" { + seen.volume_object = body.clone(); + } else if method == "DELETE" { + seen.volume_object.clear(); + } + seen.volume_bodies.push(body); + if method == "GET" { + seen.volume_object.clone() + } else { + Vec::new() + } + }; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + if stream.write_all(head.as_bytes()).await.is_ok() { + let _ = stream.write_all(&payload).await; + } + // Every Volume request needs a new tunnel, deterministically + // replaying the current client's token on the next request. + return; + } + if path == "/slowbody" { + // Headers now, the body one more `delay` later. + let head = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n"; + if stream.write_all(head).await.is_err() || stream.flush().await.is_err() { + return; + } + tokio::time::sleep(delay).await; + if stream.write_all(b"ok").await.is_err() { + return; + } + continue; + } + let reply = match path { + "/rbody" => "HTTP/1.1 307 Redirect\r\nLocation: https://other.test/slowbody\r\n\ + Content-Length: 0\r\n\r\n" + .to_string(), + "/loop" => { + "HTTP/1.1 302 Found\r\nLocation: /loop\r\nContent-Length: 0\r\n\r\n".to_string() + } + "/downgrade" => "HTTP/1.1 302 Found\r\nLocation: http://other.test/final\r\n\ + Content-Length: 0\r\n\r\n" + .to_string(), + // `/r` redirects to another origin, so another tunnel. + redirect if redirect.starts_with("/r") => format!( + "HTTP/1.1 {} Redirect\r\nLocation: https://other.test/final\r\n\ + Content-Length: 0\r\n\r\n", + &redirect[2..] + ), + "/oidc/v1/token" => { + let token = r#"{"access_token":"at","token_type":"Bearer","expires_in":3600}"#; + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n\r\n{token}", + token.len() + ) + } + _ => "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok".to_string(), + }; + if stream.write_all(reply.as_bytes()).await.is_err() { + return; + } + } +} + +fn tls_acceptor() -> tokio_rustls::TlsAcceptor { + let key = rcgen::KeyPair::generate().unwrap(); + let cert = rcgen::CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let 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![cert.der().clone()], + rustls::pki_types::PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + ) + .unwrap(); + tokio_rustls::TlsAcceptor::from(Arc::new(tls)) +} + +impl StubProxy { + /// `reject_all`: answer every CONNECT with 407. `delay`: origin latency. + pub(crate) async fn start(reject_all: bool, delay: Duration) -> Self { + let acceptor = tls_acceptor(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Seen::default())); + let state = seen.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (acceptor, seen) = (acceptor.clone(), state.clone()); + tokio::spawn(async move { + let Some(head) = read_head(&mut socket).await else { + return; + }; + let auth = header(&head, "proxy-authorization").map(str::to_string); + let fresh = { + let mut seen = seen.lock().unwrap(); + let token = auth.as_deref().and_then(|a| a.strip_prefix("Negotiate ")); + let fresh = + !reject_all && token.is_some_and(|t| seen.tokens.insert(t.to_string())); + seen.connects.push((auth, if fresh { 200 } else { 407 })); + fresh + }; + if !fresh { + let reply = "HTTP/1.1 407 Proxy Authentication Required\r\n\ + Proxy-Authenticate: Negotiate\r\n\ + Proxy-Authenticate: Basic realm=\"stub\"\r\n\ + Content-Length: 0\r\n\r\n"; + let _ = socket.write_all(reply.as_bytes()).await; + return; + } + let established = b"HTTP/1.1 200 Connection established\r\n\r\n"; + if socket.write_all(established).await.is_ok() { + if let Ok(tls) = acceptor.accept(socket).await { + serve_origin(tls, seen, delay).await; + } + } + }); + } + }); + Self { url, seen } + } +} + +/// A directly reachable origin that counts connections: any direct +/// (non-proxied) attempt would land here. +pub(crate) async fn direct_origin() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("https://{}/probe", listener.local_addr().unwrap()); + let hits = Arc::new(AtomicUsize::new(0)); + let counter = hits.clone(); + tokio::spawn(async move { + while listener.accept().await.is_ok() { + counter.fetch_add(1, Ordering::SeqCst); + } + }); + (url, hits) +} + +/// Client whose token callback yields `tok-1`, `tok-2`, ... (or fails). +fn client(proxy: &StubProxy, calls: &Arc, fail: bool) -> Result { + slow_token_client(proxy, calls, fail, Duration::ZERO) +} + +/// As [`client`], but every token after the first takes `slow` to create. +fn slow_token_client( + proxy: &StubProxy, + calls: &Arc, + fail: bool, + slow: Duration, +) -> Result { + let calls = calls.clone(); + let callback = NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if fail { + return Err("no Kerberos credentials".to_string()); + } + if n > 1 { + std::thread::sleep(slow); + } + Ok(format!("tok-{n}").into_bytes()) + }); + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(callback); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + let client = DatabricksHttpClient::with_default_retry(config)?; + client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); + Ok(client) +} + +async fn get(client: &DatabricksHttpClient, url: &str) -> Result { + let request = client.inner().get(url).build().unwrap(); + let response = client + .execute(request, RequestType::GetStatementStatus) + .await?; + Ok(response.status().as_u16()) +} + +pub(crate) fn assert_negotiate_only(seen: &Seen) { + for (auth, _) in &seen.connects { + let auth = auth.as_deref().unwrap_or_default(); + assert!( + auth.starts_with("Negotiate "), + "non-Negotiate CONNECT: {auth:?}" + ); + } + assert!( + !seen + .origin_headers + .iter() + .any(|h| h == "proxy-authorization"), + "Proxy-Authorization reached the origin" + ); +} + +#[tokio::test] +async fn negotiate_token_is_preemptive_and_only_on_connect() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + for _ in 0..3 { + assert_eq!(get(&client, &origin).await.unwrap(), 200); + } + let seen = proxy.seen.lock().unwrap(); + // One token at client build, one tunnel reused by the pool. + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!( + seen.connects, + vec![(Some("Negotiate dG9rLTE=".to_string()), 200)] + ); + assert!(seen.origin_headers.iter().any(|h| h == "authorization")); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); +} + +/// Number of CONNECTs the proxy has answered with 407 so far. +fn replays(proxy: &StubProxy) -> usize { + let seen = proxy.seen.lock().unwrap(); + seen.connects.iter().filter(|(_, s)| *s == 407).count() +} + +/// Six concurrent requests on `client`. Each origin answer waits until all six +/// have reached their tunnels, so no tunnel can serve two of them and the +/// overlap does not depend on timing. +async fn gated_wave(proxy: &StubProxy, client: &DatabricksHttpClient, origin: &str) { + proxy.seen.lock().unwrap().gate = Some(Arc::new(tokio::sync::Barrier::new(6))); + let results = futures::future::join_all((0..6).map(|_| get(client, origin))).await; + assert_eq!( + proxy.seen.lock().unwrap().gate_timeouts, + 0, + "a wave did not reach the origin together: a request never arrived or a tunnel was reused" + ); + for result in results { + assert_eq!(result.unwrap(), 200); + } +} + +#[tokio::test] +async fn negotiate_survives_a_replay_cache_across_tunnels() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + + // Sequential sessions: each client build mints its own token. + for _ in 0..6 { + let client = client(&proxy, &calls, false).unwrap(); + assert_eq!(get(&client, &origin).await.unwrap(), 200); + } + // Concurrent tunnels within one client: every new tunnel after the first + // replays the client's token, gets 407 and retries once with a new one. + let client = client(&proxy, &calls, false).unwrap(); + let before = replays(&proxy); + gated_wave(&proxy, &client, &origin).await; + // The first tunnel takes the client's token; the other five replay it. + assert_eq!(replays(&proxy) - before, 5, "first wave"); + // A second wave goes through the promoted rebuilt client, whose token is + // spent. At most one of its requests can reuse the pooled tunnel, so at + // least five replay. + let before = replays(&proxy); + gated_wave(&proxy, &client, &origin).await; + assert!(replays(&proxy) - before >= 5, "second wave"); + + let seen = proxy.seen.lock().unwrap(); + assert_negotiate_only(&seen); + let rejected = seen.connects.iter().filter(|(_, s)| *s == 407).count(); + let accepted = seen.connects.len() - rejected; + // Every token was used for exactly one accepted tunnel: 7 preemptive + // ones plus one regenerated token per 407 (so at most one 407 each). + assert!(rejected >= 10, "rejected {rejected}"); + assert_eq!( + accepted, + 7 + rejected, + "accepted {accepted}, rejected {rejected}" + ); + assert_eq!(calls.load(Ordering::SeqCst), accepted); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + // Each of the 7 clients loaded its TLS setup once; its rebuilds reused it. + assert_eq!(tls_loads(&proxy.url), 7, "{rejected} rebuilds"); +} + +/// How many clients behind `proxy_url` loaded a [`ReusableTls`]. +fn tls_loads(proxy_url: &str) -> usize { + let loads = TLS_LOADS.lock().unwrap(); + loads + .iter() + .filter(|u| u.as_deref() == Some(proxy_url)) + .count() +} + +#[tokio::test] +async fn negotiate_second_407_fails_closed_without_downgrade() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = get(&client, &origin).await.unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{}", err.message); + assert!(!err.retryable); + assert!(err.message.contains("407"), "{}", err.message); + assert!( + !err.message.contains("dG9r"), + "token bytes in error: {}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + // Preemptive token, one regenerated token, then stop: no Basic, no + // direct connection, no generic retries. + assert_eq!(seen.connects.len(), 2); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); +} + +/// The tenant-discovery probe fails closed as `send_once` does: a 407 on its +/// fresh token is `Unauthenticated`, not a generic network error. +#[tokio::test] +async fn negotiate_probe_407_is_unauthenticated() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{}", err.message); + assert!(err.message.contains("407"), "{}", err.message); + assert!( + !err.message.contains("dG9r"), + "token bytes in error: {}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 1, "one CONNECT with the probe's token"); + assert_negotiate_only(&seen); +} + +/// The first token at session open is bounded by the request timeout: a +/// token call that never returns cannot stall `Session::open`. +#[tokio::test] +async fn negotiate_first_token_times_out() { + let mut config = HttpClientConfig::default(); + config.proxy.url = Some("http://127.0.0.1:9".to_string()); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| { + std::thread::sleep(Duration::from_secs(2)); + Ok(b"tok".to_vec()) + })); + config.read_timeout = Duration::from_millis(100); + let retry = crate::client::retry::build_retry_configs( + &RetryConfig::default(), + &std::collections::HashMap::new(), + ); + let started = std::time::Instant::now(); + let err = match DatabricksHttpClient::with_revocation_async(config, retry, None).await { + Ok(_) => panic!("a token slower than the request timeout must fail"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!( + !err.retryable, + "token timeouts must not start more blocking calls" + ); + assert!(err.message.contains("no token within"), "{}", err.message); + assert!( + started.elapsed() < Duration::from_secs(1), + "{:?}", + started.elapsed() + ); +} + +/// `Session::open` keeps the `Timeout` code of a first token slower than the +/// request timeout, instead of reporting a generic network error. +#[tokio::test] +async fn negotiate_session_open_reports_a_token_timeout() { + let proxy_config = crate::config::ProxyConfig { + url: Some("http://127.0.0.1:9".to_string()), + auth: ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| { + std::thread::sleep(Duration::from_secs(2)); + Ok(b"tok".to_vec()) + })), + ..Default::default() + }; + let started = std::time::Instant::now(); + let err = crate::session::Session::builder() + .connection(crate::config::ConnectionConfig::new( + "https://workspace.invalid", + "test_wh", + )) + .auth(crate::config::AuthConfig::Pat { + token: "dapi-test".to_string(), + identity_federation_client_id: None, + }) + .proxy(proxy_config) + .http(crate::config::HttpConfig { + request_timeout: Duration::from_millis(100), + ..Default::default() + }) + .open() + .await + .map(|_| ()) + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!( + !err.retryable, + "token timeouts must not start more blocking calls" + ); + assert!(err.message.contains("no token within"), "{}", err.message); + assert!( + started.elapsed() < Duration::from_secs(1), + "{:?}", + started.elapsed() + ); +} + +/// The probe shares its timeout between a new token and the GET rather than +/// letting each spend a full request timeout. +#[tokio::test] +async fn negotiate_probe_deadline_spans_token_and_request() { + let proxy = StubProxy::start(false, Duration::from_millis(1500)).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut client = slow_token_client(&proxy, &calls, false, Duration::from_secs(1)).unwrap(); + let budget = Duration::from_secs(2); + client.config.read_timeout = budget; + let started = tokio::time::Instant::now(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .expect_err("the token and origin delays together exceed the request timeout"); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message + .starts_with("Redirect-probe request to https://origin.test/aad/auth failed:"), + "{}", + err.message + ); + assert!(started.elapsed() < budget + Duration::from_millis(1500)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 1); + assert_eq!( + seen.requests.len(), + 1, + "the token was ready before the deadline" + ); + assert_negotiate_only(&seen); +} + +#[tokio::test] +async fn negotiate_probe_token_timeout_is_not_retryable() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut client = slow_token_client(&proxy, &calls, false, Duration::from_secs(2)).unwrap(); + client.config.read_timeout = Duration::from_millis(100); + let started = tokio::time::Instant::now(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Timeout); + assert!(!err.retryable); + assert_eq!( + err.message, + "Negotiate proxy authentication timed out: no token within the 100ms request timeout" + ); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); +} + +/// An extreme request timeout (`Duration::MAX`) does not overflow the +/// Negotiate deadline: the request still goes through. +#[tokio::test] +async fn negotiate_extreme_timeout_does_not_overflow() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let callback = { + let calls = calls.clone(); + NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + Ok(format!("tok-{n}").into_bytes()) + }) + }; + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(callback); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + config.read_timeout = Duration::MAX; + let client = DatabricksHttpClient::with_default_retry(config).unwrap(); + client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); + assert_eq!( + get(&client, "https://origin.test/probe").await.unwrap(), + 200 + ); + assert!(client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap() + .is_none()); +} + +#[tokio::test] +async fn negotiate_token_failure_fails_before_any_io() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let err = client(&proxy, &calls, true).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("no Kerberos credentials"), + "{}", + err.message + ); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); +} + +/// A slow first token (session open) or redirect-probe token is created off +/// the async workers: on a single-threaded runtime an unrelated task still +/// runs while the callback blocks, and the failure still fails closed. +#[tokio::test(flavor = "current_thread")] +async fn negotiate_slow_token_does_not_block_async_workers() { + // (case, the token call that is slow and then fails) + let cases = [("session open", 1), ("redirect probe", 2)]; + for (case, slow_call) in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let signalled = Arc::new(std::sync::atomic::AtomicBool::new(false)); + // The callback announces that it has started blocking; an async task + // answers over `signal` only once it runs, which needs the worker free. + let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel::<()>(); + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + let signal_rx = Mutex::new(signal_rx); + let callback = { + let (calls, signalled) = (calls.clone(), signalled.clone()); + NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if n != slow_call { + return Ok(format!("tok-{n}").into_bytes()); + } + let _ = entered_tx.send(()); + // Only a free async worker can run the signalling task. If the + // token is created on the worker, this expires instead. + let arrived = signal_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .is_ok(); + signalled.store(arrived, Ordering::SeqCst); + Err("no Kerberos credentials".to_string()) + }) + }; + let signaller = tokio::spawn(async move { + if entered_rx.recv().await.is_some() { + let _ = signal_tx.send(()); + } + }); + let proxy_config = crate::config::ProxyConfig { + url: Some(proxy.url.clone()), + auth: ProxyAuth::NegotiateCallback(callback), + ..Default::default() + }; + // The probe case builds its client (fast first token) up front. + let probe_client = (case == "redirect probe").then(|| { + let mut config = HttpClientConfig::default(); + config.proxy.url = proxy_config.url.clone(); + config.proxy.auth = proxy_config.auth.clone(); + DatabricksHttpClient::with_default_retry(config).unwrap() + }); + + let err = match probe_client { + None => crate::session::Session::builder() + .connection(crate::config::ConnectionConfig::new( + "https://workspace.invalid", + "test_wh", + )) + .auth(crate::config::AuthConfig::Pat { + token: "dapi-test".to_string(), + identity_federation_client_id: None, + }) + .proxy(proxy_config) + .open() + .await + .map(|_| ()) + .unwrap_err(), + Some(client) => client + .first_redirect_location("https://workspace.invalid/aad/auth") + .await + .unwrap_err(), + }; + signaller.abort(); + + assert!( + signalled.load(Ordering::SeqCst), + "{case}: no async task ran while the token was created (or the token was never created)" + ); + assert_eq!(calls.load(Ordering::SeqCst), slow_call, "{case}"); + assert_eq!( + err.code, + ErrorCode::Unauthenticated, + "{case}: {}", + err.message + ); + assert!( + err.message.contains("no Kerberos credentials"), + "{case}: {}", + err.message + ); + assert!(proxy.seen.lock().unwrap().connects.is_empty(), "{case}"); + } +} + +/// The CONNECTs of a request whose second tunnel replayed the first token. +/// (`tok-1` accepted, `tok-1` replayed, `tok-2` accepted.) +fn one_replay_407() -> Vec<(Option, u16)> { + let tok = |n: &str| Some(format!("Negotiate {n}")); + vec![ + (tok("dG9rLTE="), 200), + (tok("dG9rLTE="), 407), + (tok("dG9rLTI="), 200), + ] +} + +#[tokio::test] +async fn negotiate_redirect_retries_only_the_failed_hop() { + // A cross-origin redirect opens a second tunnel, which replays the + // spent token: only that hop is retried, the origin request is not. + let cases = [ + ("POST", "/r307", "POST /final"), + ("POST", "/r308", "POST /final"), + ("POST", "/r302", "GET /final"), + ("GET", "/r303", "GET /final"), + ]; + for (verb, path, final_hop) in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (_, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let request = client + .inner() + .request(verb.parse().unwrap(), format!("https://origin.test{path}")) + .body("{}") + .build() + .unwrap(); + let response = client + .execute(request, RequestType::ExecuteStatement) + .await + .unwrap_or_else(|e| panic!("{path}: {e}")); + assert_eq!(response.status().as_u16(), 200, "{path}"); + + let seen = proxy.seen.lock().unwrap(); + let hops = seen + .requests + .iter() + .map(|(r, _)| r.as_str()) + .collect::>(); + assert_eq!( + hops, + [format!("{verb} {path}").as_str(), final_hop], + "{path}" + ); + // Cross-origin hop: reqwest's rule drops the bearer token. + assert!(seen.requests[0].1.iter().any(|h| h == "authorization")); + assert!(!seen.requests[1].1.iter().any(|h| h == "authorization")); + assert_eq!(seen.connects, one_replay_407(), "{path}"); + assert_eq!(calls.load(Ordering::SeqCst), 2, "{path}"); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + } +} + +#[tokio::test] +async fn negotiate_redirects_stop_after_ten_hops() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = get(&client, "https://origin.test/loop").await.unwrap_err(); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message.contains("too many redirects"), + "{}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + // The original request plus 10 redirects, as reqwest's default policy. + assert_eq!(seen.requests.len(), 11); + assert_eq!(seen.connects.len(), 1, "same origin: one tunnel"); +} + +/// The token rides only on CONNECT, so a plain-HTTP request (which reqwest +/// would forward to the proxy, token attached, with no tunnel) is refused +/// before any I/O, and an https -> http redirect is refused before its hop. +#[tokio::test] +async fn negotiate_refuses_plain_http_hops() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + + let err = get(&client, "http://origin.test/plain").await.unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "{}", err.message); + assert!(err.message.contains("plain-HTTP"), "{}", err.message); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + + // The Azure tenant-discovery probe, which sends through its own client. + let err = client + .first_redirect_location("http://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "{}", err.message); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + + let err = get(&client, "https://origin.test/downgrade") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message.contains("redirect to plain HTTP"), + "{}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + assert_eq!( + seen.requests.len(), + 1, + "only the https hop: {:?}", + seen.requests + ); + assert_negotiate_only(&seen); +} + +#[tokio::test] +async fn negotiate_deadline_spans_redirects_token_and_body() { + // One request timeout covers every hop, the fresh-token rebuild after + // the cross-origin hop's 407, and the final body (as reqwest does for + // the redirects it follows itself). Each case would succeed if every + // hop restarted the timeout. + // Margins: the case must reach its timeout, with the second hop (and for + // the body case, its headers) at the origin before the deadline. The + // slack is 1200 ms for the redirect case and 800 ms for the body case, + // covering the new tunnel, TLS and client rebuild on a loaded runner, and + // the deadline still lands at least 800 ms before the request could + // finish. A per-hop restart would let each case finish within about 2x + // its budget, so the test still catches one. + let ms = Duration::from_millis; + let cases = [ + // (name, path, origin delay, token delay, timeout, origin hops) + // Hop 1 answers at 2000 ms, hop 2 would answer at about 4000 ms. + ("delayed redirect", "/r307", ms(2000), ms(0), ms(3200), 2), + // Hop 1 answers at 1600 ms, headers at about 3200 ms, body at 4800 ms. + ("delayed body", "/rbody", ms(1600), ms(0), ms(4000), 2), + ("slow fresh token", "/r307", ms(0), ms(1500), ms(500), 1), + ]; + for (name, path, delay, slow, timeout, hops) in cases { + let proxy = StubProxy::start(false, delay).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = slow_token_client(&proxy, &calls, false, slow).unwrap(); + let request = client + .inner() + .post(format!("https://origin.test{path}")) + .body("{}") + .timeout(timeout) + .build() + .unwrap(); + let started = tokio::time::Instant::now(); + let outcome = match client.send_once(request).await { + Ok(Ok(response)) => response.bytes().await.map(|_| ()).map_err(|e| { + assert!(e.is_timeout(), "{name}: {e}"); + "body timed out".to_string() + }), + Ok(Err(e)) => { + assert!(e.is_timeout(), "{name}: {e}"); + Err("hop timed out".to_string()) + } + Err(e) => { + assert_eq!(e.code, ErrorCode::Timeout, "{name}: {}", e.message); + assert!(!e.retryable, "{name}: token timeouts must not be retried"); + assert!(e.message.contains("fresh token"), "{name}: {}", e.message); + Err("token timed out".to_string()) + } + }; + let elapsed = started.elapsed(); + assert!(outcome.is_err(), "{name}: completed in {elapsed:?}"); + assert!(elapsed < timeout + ms(1500), "{name}: took {elapsed:?}"); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.requests.len(), hops, "{name}: {:?}", seen.requests); + assert_eq!(seen.connects[..2], one_replay_407()[..2], "{name}"); + assert_negotiate_only(&seen); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn negotiate_u2m_token_requests_regenerate_on_a_new_tunnel() { + use crate::auth::oauth::u2m::send_token_request; + use oauth2::basic::BasicClient; + use oauth2::{AuthUrl, AuthorizationCode, ClientId, RefreshToken, TokenResponse, TokenUrl}; + + // The token endpoint is another origin, so each grant opens a new tunnel + // after the client's token was spent on the first one. + let cases = ["refresh", "code"]; + for grant in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + assert_eq!( + get(&client, "https://origin.test/probe").await.unwrap(), + 200 + ); + + let oauth = BasicClient::new(ClientId::new("databricks-sql-connector".to_string())) + .set_auth_uri(AuthUrl::new("https://idp.test/oidc/v1/authorize".to_string()).unwrap()) + .set_token_uri(TokenUrl::new("https://idp.test/oidc/v1/token".to_string()).unwrap()); + let send = |request| send_token_request(&client, request); + let token = match grant { + "refresh" => oauth + .exchange_refresh_token(&RefreshToken::new("rt".to_string())) + .request_async(&send) + .await + .map(|t| t.access_token().secret().clone()), + _ => oauth + .exchange_code(AuthorizationCode::new("code".to_string())) + .request_async(&send) + .await + .map(|t| t.access_token().secret().clone()), + }; + assert_eq!(token.unwrap_or_else(|e| panic!("{grant}: {e:?}")), "at"); + + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects, one_replay_407(), "{grant}"); + let hops = seen + .requests + .iter() + .map(|(r, _)| r.as_str()) + .collect::>(); + assert_eq!(hops, ["GET /probe", "POST /oidc/v1/token"], "{grant}"); + assert_negotiate_only(&seen); + } +} + +/// Records each ClientHello (SNI, ALPN, cipher suites, signature schemes). +#[derive(Debug)] +struct HelloRecorder { + key: Arc, + seen: Arc>, +} + +impl rustls::server::ResolvesServerCert for HelloRecorder { + fn resolve( + &self, + hello: rustls::server::ClientHello<'_>, + ) -> Option> { + let alpn = hello + .alpn() + .map(|a| a.map(<[u8]>::to_vec).collect::>()); + self.seen.lock().unwrap().hellos.push(format!( + "sni {:?} alpn {alpn:?} suites {:?} schemes {:?}", + hello.server_name(), + hello.cipher_suites(), + hello.signature_schemes() + )); + Some(self.key.clone()) + } +} + +/// What a TLS origin behind a CONNECT proxy saw. +#[derive(Default, Debug, PartialEq)] +struct TlsSeen { + hellos: Vec, + /// Protocol version and whether a client certificate was presented. + sessions: Vec, + connects: Vec<(Option, u16)>, +} + +/// A CONNECT proxy that accepts unauthenticated CONNECTs (`Default`) and +/// fresh Negotiate tokens, except `tok-1` when `spend_first` (so the client +/// rebuilds), in front of a TLS origin with `cert` that asks for an optional +/// client certificate from `ca`. +async fn tls_probe_proxy( + cert: &rcgen::Certificate, + key: &rcgen::KeyPair, + ca: &rcgen::Certificate, + spend_first: bool, +) -> (String, Arc>) { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let signer = provider + .key_provider + .load_private_key(rustls::pki_types::PrivatePkcs8KeyDer::from(key.serialize_der()).into()) + .unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(ca.der().clone()).unwrap(); + let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider( + Arc::new(roots), + provider.clone(), + ) + .allow_unauthenticated() + .build() + .unwrap(); + let seen = Arc::new(Mutex::new(TlsSeen::default())); + let server = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_client_cert_verifier(verifier) + .with_cert_resolver(Arc::new(HelloRecorder { + key: Arc::new(rustls::sign::CertifiedKey::new( + vec![cert.der().clone()], + signer, + )), + seen: seen.clone(), + })); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let state = seen.clone(); + let spent = spend_first.then(|| "dG9rLTE=".to_string()); + let tokens = Arc::new(Mutex::new(spent.into_iter().collect::>())); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (acceptor, seen, tokens) = (acceptor.clone(), state.clone(), tokens.clone()); + tokio::spawn(async move { + let Some(head) = read_head(&mut socket).await else { + return; + }; + let auth = header(&head, "proxy-authorization").map(str::to_string); + let open = match auth.as_deref().and_then(|a| a.strip_prefix("Negotiate ")) { + Some(token) => tokens.lock().unwrap().insert(token.to_string()), + None => auth.is_none(), + }; + seen.lock() + .unwrap() + .connects + .push((auth, if open { 200 } else { 407 })); + if !open { + let reply = "HTTP/1.1 407 Proxy Authentication Required\r\n\ + Proxy-Authenticate: Negotiate\r\nContent-Length: 0\r\n\r\n"; + let _ = socket.write_all(reply.as_bytes()).await; + return; + } + let _ = socket + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await; + let Ok(tls) = acceptor.accept(socket).await else { + return; + }; + let session = tls.get_ref().1; + seen.lock().unwrap().sessions.push(format!( + "{:?} client cert {}", + session.protocol_version(), + session.peer_certificates().is_some() + )); + serve_origin(tls, Arc::new(Mutex::new(Seen::default())), Duration::ZERO).await; + }); + } + }); + (url, seen) +} + +#[tokio::test] +async fn negotiate_rebuild_keeps_the_tls_behavior() { + use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; + + // Per TLS setting, a Default-auth client (reqwest's own TLS setup), a + // Negotiate client and a Negotiate client rebuilt after a 407 (both on + // the reused setup) get the same outcome, offer the same ClientHello, + // negotiate the same version and present the same client certificate. + let mut ca_params = CertificateParams::new(Vec::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + (ca_params.distinguished_name).push(rcgen::DnType::CommonName, "Negotiate test CA"); + let ca_key = KeyPair::generate().unwrap(); + let ca = ca_params.self_signed(&ca_key).unwrap(); + let issuer = Issuer::new(ca_params, ca_key); + let leaf = |name: &str, expired: bool| { + let mut params = CertificateParams::new(vec![name.to_string()]).unwrap(); + (params.distinguished_name).push(rcgen::DnType::CommonName, name); + if expired { + params.not_before = rcgen::date_time_ymd(2000, 1, 1); + params.not_after = rcgen::date_time_ymd(2001, 1, 1); + } + let key = KeyPair::generate().unwrap(); + (params.signed_by(&key, &issuer).unwrap(), key) + }; + let self_signed = || { + let key = KeyPair::generate().unwrap(); + let params = CertificateParams::new(vec!["127.0.0.1".to_string()]).unwrap(); + (params.self_signed(&key).unwrap(), key) + }; + let (client_cert, client_key) = leaf("client", false); + let trust = TlsConfig { + trusted_certificate_pem: Some(ca.pem().into_bytes()), + ..TlsConfig::default() + }; + let cases = [ + // (name, server certificate, client TLS config, succeeds) + ("custom CA", leaf("127.0.0.1", false), trust.clone(), true), + ( + "unknown CA", + leaf("127.0.0.1", false), + TlsConfig::default(), + false, + ), + ( + "hostname mismatch", + leaf("wrong.invalid", false), + trust.clone(), + false, + ), + ( + "hostname mismatch allowed", + leaf("wrong.invalid", false), + TlsConfig { + allow_hostname_mismatch: Some(true), + ..trust.clone() + }, + true, + ), + ("expired", leaf("127.0.0.1", true), trust.clone(), false), + ("self-signed", self_signed(), trust.clone(), false), + ( + "self-signed allowed", + self_signed(), + TlsConfig { + allow_self_signed: Some(true), + ..TlsConfig::default() + }, + true, + ), + ( + "mTLS identity", + leaf("127.0.0.1", false), + TlsConfig { + client_cert_pem: Some(client_cert.pem().into_bytes()), + client_key_pem: Some(client_key.serialize_pem().into_bytes()), + ..trust.clone() + }, + true, + ), + ]; + for (name, (cert, key), tls, succeeds) in cases { + let mut runs = Vec::new(); + for via in ["default", "negotiate", "rebuilt"] { + let (url, seen) = tls_probe_proxy(&cert, &key, &ca, via == "rebuilt").await; + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(url.clone()); + config.tls = tls.clone(); + if via != "default" { + let calls = AtomicUsize::new(0); + config.proxy.auth = + ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(move || { + Ok(format!("tok-{}", calls.fetch_add(1, Ordering::SeqCst) + 1).into()) + })); + } + let client = DatabricksHttpClient::with_default_retry(config).unwrap(); + let request = client + .inner() + .get("https://127.0.0.1/probe") + .build() + .unwrap(); + let outcome = match client.send_once(request).await.unwrap() { + Ok(response) => Ok(response.status().as_u16()), + // Digits masked: rustls's expiry error names the current second. + Err(e) => Err(crate::client::error_chain(&e) + .map(ToString::to_string) + .collect::>() + .join(": ") + .replace(|c: char| c.is_ascii_digit(), "#")), + }; + assert_eq!(outcome.is_ok(), succeeds, "{name} via {via}: {outcome:?}"); + let mut seen = std::mem::take(&mut *seen.lock().unwrap()); + let connects = std::mem::take(&mut seen.connects); + let expected = match via { + "default" => vec![(None, 200)], + "negotiate" => vec![(Some("Negotiate dG9rLTE=".to_string()), 200)], + _ => one_replay_407()[1..].to_vec(), + }; + assert_eq!(connects, expected, "{name} via {via}"); + let loads = if via == "default" { 0 } else { 1 }; + assert_eq!(tls_loads(&url), loads, "{name} via {via}"); + assert!(!seen.hellos.is_empty(), "{name} via {via}"); + runs.push((via, outcome, seen)); + } + let (_, outcome, seen) = &runs[0]; + for (via, other_outcome, other_seen) in &runs[1..] { + assert_eq!(other_outcome, outcome, "{name}: {via} vs default"); + assert_eq!(other_seen, seen, "{name}: {via} vs default"); + } + if name == "mTLS identity" { + assert!(seen.sessions[0].ends_with("client cert true"), "{seen:?}"); + } + } +} + +/// The fresh-token retry keys on reqwest's text for hyper-util's private +/// `TunnelError::ProxyAuthRequired`. Pin it against a real CONNECT 407, so a +/// reqwest or hyper-util bump that rewords it fails here, not silently. +#[tokio::test] +async fn proxy_407_is_detected_from_the_real_tunnel_error() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, _) = direct_origin().await; + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(&proxy.url).unwrap()) + .build() + .unwrap(); + let err = client.get(&origin).send().await.unwrap_err(); + assert!( + is_proxy_auth_required(&err), + "a CONNECT 407 was not recognised: {err:?}" + ); + + // A proxy that is not listening is a plain connection error, not a 407. + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed_url = format!("http://{}", closed.local_addr().unwrap()); + drop(closed); + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(&closed_url).unwrap()) + .build() + .unwrap(); + let err = client.get(&origin).send().await.unwrap_err(); + assert!( + !is_proxy_auth_required(&err), + "a refused connection looked like a 407: {err:?}" + ); +} + +/// The native-tls setup is reused only when OpenSSL reads the same custom +/// CA certificates as reqwest (which skips non-`CERTIFICATE` PEM labels). +#[cfg(feature = "tls-native")] +#[test] +fn reusable_tls_keeps_reqwest_setup_when_parsers_disagree() { + let key = rcgen::KeyPair::generate().unwrap(); + let ca = rcgen::CertificateParams::new(vec!["ca.test".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap() + .pem(); + let relabelled = ca.replace("CERTIFICATE-----", "X509 CERTIFICATE-----"); + let cases = [ + ("one certificate", ca.clone(), true), + ("two certificates", format!("{ca}{ca}"), true), + ("X509 CERTIFICATE label", format!("{ca}{relabelled}"), false), + ]; + for (name, pem, reused) in cases { + let config = TlsConfig { + trusted_certificate_pem: Some(pem.into_bytes()), + ..TlsConfig::default() + }; + let tls = ReusableTls::load(&config, None).unwrap(); + assert_eq!(tls.is_some(), reused, "{name}"); + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index 65dff979..4c366362 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -31,7 +31,10 @@ //! [`transport`]: self::transport //! [`sea`]: self::sea +#[cfg(all(feature = "proxy-negotiate", target_os = "linux"))] +mod gssapi_runtime; pub mod http; +pub(crate) mod proxy_negotiate; pub mod retry; pub mod sea; #[cfg(all(windows, feature = "tls-rustls"))] diff --git a/src/client/proxy_negotiate.rs b/src/client/proxy_negotiate.rs new file mode 100644 index 00000000..638835bf --- /dev/null +++ b/src/client/proxy_negotiate.rs @@ -0,0 +1,492 @@ +// 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. + +//! `Proxy-Authorization: Negotiate` tokens for HTTP `CONNECT` proxies. + +use crate::config::{NegotiateTokenCallback, ProxyAuth}; +use crate::kernel_error::{Error, Result}; +use base64::Engine; +use reqwest::header::HeaderValue; + +/// Where Negotiate tokens come from. Never holds token bytes. +#[derive(Clone)] +pub(crate) enum NegotiateSource { + /// Platform GSSAPI / SSPI for this target name. + #[cfg(feature = "proxy-negotiate")] + Kerberos { + target: String, + }, + Callback(NegotiateTokenCallback), +} + +impl std::fmt::Debug for NegotiateSource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + #[cfg(feature = "proxy-negotiate")] + NegotiateSource::Kerberos { target } => write!(f, "Kerberos({target})"), + NegotiateSource::Callback(_) => f.write_str("Callback"), + } + } +} + +impl NegotiateSource { + /// Validate a proxy configuration and resolve its Negotiate source. + /// `Ok(None)` means [`ProxyAuth::Default`]. Does no I/O. + pub(crate) fn resolve( + url: Option<&str>, + username: Option<&str>, + password: Option<&str>, + auth: &ProxyAuth, + ) -> Result> { + let kerberos = match auth { + ProxyAuth::Default => return Ok(None), + ProxyAuth::Negotiate { + service, + host, + realm, + } => Some((service, host, realm)), + ProxyAuth::NegotiateCallback(_) => None, + }; + let invalid = |msg: &str| { + Err(Error::invalid_argument().message(format!("Negotiate proxy authentication {msg}"))) + }; + let Some(url) = url else { + return invalid("requires an explicit proxy URL (ProxyConfig.url)"); + }; + let parsed = match reqwest::Url::parse(url) { + Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => parsed, + Ok(_) => return invalid("supports only http:// and https:// proxy URLs"), + Err(e) => return invalid(&format!("has an invalid proxy URL: {e}")), + }; + if username.is_some() + || password.is_some() + || !parsed.username().is_empty() + || parsed.password().is_some() + { + return invalid("cannot be combined with Basic proxy credentials"); + } + let Some((service, host, realm)) = kerberos else { + let ProxyAuth::NegotiateCallback(callback) = auth else { + unreachable!("only the callback variant has no Kerberos target") + }; + return Ok(Some(NegotiateSource::Callback(callback.clone()))); + }; + let Some(proxy_host) = parsed.host_str() else { + return invalid("requires a proxy URL with a host"); + }; + // IPv6 literals keep their URL brackets in `host_str`. + let proxy_host = proxy_host.trim_start_matches('[').trim_end_matches(']'); + let target = target_name(service, host, realm, proxy_host)?; + #[cfg(feature = "proxy-negotiate")] + { + Ok(Some(NegotiateSource::Kerberos { target })) + } + #[cfg(not(feature = "proxy-negotiate"))] + { + Err(Error::not_implemented().message(format!( + "Negotiate proxy authentication (target {target}) is unsupported: the kernel was \ + built without the `proxy-negotiate` cargo feature" + ))) + } + } + + /// Create a fresh `Negotiate ` header value. Blocking: GSSAPI + /// may contact the KDC and a callback may block. + pub(crate) fn header(&self) -> Result { + let token = match self { + #[cfg(feature = "proxy-negotiate")] + NegotiateSource::Kerberos { target } => kerberos_token(target)?, + NegotiateSource::Callback(callback) => (callback.0)().map_err(|e| { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the token callback failed: {e}" + )) + })?, + }; + if token.is_empty() { + return Err(Error::unauthenticated().message( + "Negotiate proxy authentication failed: the token source returned no token", + )); + } + let encoded = base64::engine::general_purpose::STANDARD.encode(token); + let mut value = HeaderValue::try_from(format!("Negotiate {encoded}")).map_err(|_| { + Error::internal().message("Negotiate header is not a valid header value") + })?; + value.set_sensitive(true); + Ok(value) + } +} + +/// `/[@]`; blank overrides fall back to the defaults +/// (`HTTP` and the proxy host). +fn target_name( + service: &Option, + host: &Option, + realm: &Option, + proxy_host: &str, +) -> Result { + for (field, value) in [("service", service), ("host", host), ("realm", realm)] { + if value.as_deref().is_some_and(|v| v.contains('\0')) { + return Err(Error::invalid_argument().message(format!( + "Negotiate proxy authentication {field} must not contain NUL bytes" + ))); + } + } + let pick = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; + let mut target = format!( + "{}/{}", + pick(service).unwrap_or_else(|| "HTTP".to_string()), + pick(host).unwrap_or_else(|| proxy_host.to_string()) + ); + if let Some(realm) = pick(realm) { + target.push('@'); + target.push_str(&realm); + } + Ok(target) +} + +#[cfg(feature = "proxy-negotiate")] +fn kerberos_token(target: &str) -> Result> { + platform_token(target).map_err(|e| { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: no Kerberos token for {target}: {e}" + )) + }) +} + +/// Linux: MIT GSSAPI, loaded at run time only when a token is needed, so the +/// binary does not depend on it. A raw Kerberos token, accepted under +/// `Negotiate` by MIT and Heimdal acceptors. +#[cfg(all(feature = "proxy-negotiate", target_os = "linux"))] +fn platform_token(target: &str) -> std::result::Result, String> { + super::gssapi_runtime::initial_token(target) +} + +/// Non-Linux platforms, linked through cross-krb5: macOS (GSS.framework), +/// Windows (the SSPI Negotiate package), and system GSSAPI on other Unix +/// (including BSDs, illumos and Android). Unix sends a raw Kerberos token. +/// Ambient credentials (`None` principal); no delegation. +#[cfg(all( + feature = "proxy-negotiate", + not(target_os = "linux"), + any(unix, windows) +))] +fn platform_token(target: &str) -> std::result::Result, String> { + #[cfg(windows)] + let flags = cross_krb5::InitiateFlags::NEGOTIATE_TOKEN; + #[cfg(not(windows))] + let flags = cross_krb5::InitiateFlags::empty(); + let (_pending, token) = + cross_krb5::ClientCtx::new(flags, None, target, None).map_err(|e| format!("{e:#}"))?; + Ok(token.to_vec()) +} + +#[cfg(all(feature = "proxy-negotiate", not(any(unix, windows))))] +fn platform_token(_target: &str) -> std::result::Result, String> { + Err("Kerberos is not supported on this platform".to_string()) +} + +/// Whether a request failed because the proxy answered `CONNECT` with 407. +pub(crate) fn is_proxy_auth_required(error: &reqwest::Error) -> bool { + // hyper-util's `TunnelError::ProxyAuthRequired` is private; reqwest + // reports it as "tunnel error: proxy authorization required". + super::error_chain(error).any(|e| e.to_string().ends_with("proxy authorization required")) +} + +/// Redirect hops reqwest's default policy follows. +const MAX_REDIRECTS: usize = 10; + +/// The next request of a redirect chain, or `None` when `response` is final. +/// +/// Negotiate clients follow no redirects, so the kernel follows them hop by +/// hop and can retry a proxy 407 at the hop whose `CONNECT` failed. This +/// mirrors reqwest's default policy (tower-http `FollowRedirect` with +/// reqwest's `TowerRedirectPolicy`): 301/302 turn POST into GET, 303 turns +/// anything but HEAD into GET (both drop the body and its headers), +/// 307/308 resend as is. A hop to another host or port drops +/// `Authorization`, `Cookie`, `Proxy-Authorization` and `WWW-Authenticate`; +/// at most 10 hops. `previous` collects the URLs already sent. +pub(crate) fn next_redirect( + sent: &reqwest::Request, + response: &reqwest::Response, + previous: &mut Vec, +) -> Result> { + use reqwest::header::{ + AUTHORIZATION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, LOCATION, + PROXY_AUTHORIZATION, REFERER, TRANSFER_ENCODING, WWW_AUTHENTICATE, + }; + use reqwest::{Method, StatusCode}; + + let mut method = sent.method().clone(); + let keep_body = match response.status() { + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if method == Method::POST => { + method = Method::GET; + false + } + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => true, + StatusCode::SEE_OTHER => { + if method != Method::HEAD { + method = Method::GET; + } + false + } + StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => true, + _ => return Ok(None), + }; + let from = sent.url(); + let Some(next) = response + .headers() + .get(LOCATION) + .and_then(|v| std::str::from_utf8(v.as_bytes()).ok()) + .and_then(|location| from.join(location).ok()) + else { + return Ok(None); + }; + let mut shown = from.clone(); + shown.set_query(None); + previous.push(from.clone()); + if previous.len() > MAX_REDIRECTS { + return Err(Error::network_error().message(format!( + "error following redirect for url ({shown}): too many redirects" + ))); + } + if !matches!(next.scheme(), "http" | "https") { + return Err(Error::network_error().message(format!( + "error following redirect for url ({shown}): unsupported scheme {}", + next.scheme() + ))); + } + + let mut headers = sent.headers().clone(); + if !keep_body { + for name in [ + CONTENT_TYPE, + CONTENT_LENGTH, + CONTENT_ENCODING, + TRANSFER_ENCODING, + ] { + headers.remove(name); + } + } + if next.host_str() != from.host_str() + || next.port_or_known_default() != from.port_or_known_default() + { + for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE] { + headers.remove(name); + } + headers.remove("cookie2"); + } + if !(next.scheme() == "http" && from.scheme() == "https") { + let mut referer = from.clone(); + let _ = referer.set_username(""); + let _ = referer.set_password(None); + referer.set_fragment(None); + if let Ok(value) = HeaderValue::try_from(referer.as_str()) { + headers.insert(REFERER, value); + } + } + + // Keeps the body (and timeout); a streaming body cannot be resent. + let Some(mut request) = sent.try_clone() else { + return Ok(None); + }; + *request.method_mut() = method; + *request.url_mut() = next; + *request.headers_mut() = headers; + if !keep_body { + *request.body_mut() = None; + } + Ok(Some(request)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kernel_error::ErrorCode; + + fn callback() -> ProxyAuth { + ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| Ok(b"tok".to_vec()))) + } + + fn kerberos(service: Option<&str>, host: Option<&str>, realm: Option<&str>) -> ProxyAuth { + ProxyAuth::Negotiate { + service: service.map(str::to_string), + host: host.map(str::to_string), + realm: realm.map(str::to_string), + } + } + + #[test] + fn invalid_negotiate_configs_fail_before_io() { + let cases = [ + ("no url", None, None, None, callback()), + ("socks url", Some("socks5://p:1080"), None, None, callback()), + ( + "socks url kerberos", + Some("socks5h://p:1080"), + None, + None, + kerberos(None, None, None), + ), + ( + "basic username", + Some("http://p:3128"), + Some("u"), + None, + callback(), + ), + ( + "basic password", + Some("http://p:3128"), + None, + Some("x"), + kerberos(None, None, None), + ), + ( + "url userinfo", + Some("http://u:x@p:3128"), + None, + None, + callback(), + ), + ("bad url", Some("http://"), None, None, callback()), + ]; + for (name, url, user, pass, auth) in cases { + let err = NegotiateSource::resolve(url, user, pass, &auth).unwrap_err(); + assert_eq!( + err.code, + ErrorCode::InvalidArgument, + "{name}: {}", + err.message + ); + assert!(err.message.contains("Negotiate"), "{name}: {}", err.message); + } + } + + #[test] + fn default_auth_resolves_to_none() { + let resolved = + NegotiateSource::resolve(Some("http://p:3128"), Some("u"), None, &ProxyAuth::Default); + assert!(resolved.unwrap().is_none()); + } + + #[test] + fn target_names() { + let cases = [ + (None, None, None, "HTTP/proxy.corp"), + ( + Some("http"), + Some("fqdn.corp"), + Some("CORP.EXAMPLE"), + "http/fqdn.corp@CORP.EXAMPLE", + ), + (Some(" "), Some(""), Some(""), "HTTP/proxy.corp"), + (None, None, Some("R"), "HTTP/proxy.corp@R"), + ]; + for (service, host, realm, expected) in cases { + let to_owned = |v: Option<&str>| v.map(str::to_string); + let target = target_name( + &to_owned(service), + &to_owned(host), + &to_owned(realm), + "proxy.corp", + ) + .unwrap(); + assert_eq!(target, expected); + } + } + + #[test] + fn nul_in_kerberos_target_components_is_invalid_before_io() { + for (field, auth) in [ + ("service", kerberos(Some("HTTP\0suffix"), None, None)), + ("host", kerberos(None, Some("proxy.test\0suffix"), None)), + ("realm", kerberos(None, None, Some("REALM\0suffix"))), + ] { + let error = NegotiateSource::resolve(Some("http://proxy.test:3128"), None, None, &auth) + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert!(!error.retryable); + assert_eq!( + error.message, + format!("Negotiate proxy authentication {field} must not contain NUL bytes") + ); + } + } + + #[cfg(not(feature = "proxy-negotiate"))] + #[test] + fn kerberos_without_feature_is_unsupported() { + let err = NegotiateSource::resolve( + Some("http://p:3128"), + None, + None, + &kerberos(None, None, None), + ) + .unwrap_err(); + assert!(err.message.contains("unsupported"), "{}", err.message); + assert!(err.message.contains("proxy-negotiate"), "{}", err.message); + assert!(err.message.contains("HTTP/p"), "{}", err.message); + } + + #[cfg(feature = "proxy-negotiate")] + #[test] + fn kerberos_target_defaults_to_proxy_host() { + let source = NegotiateSource::resolve( + Some("http://[::1]:3128"), + None, + None, + &kerberos(None, None, None), + ) + .unwrap() + .unwrap(); + assert_eq!(format!("{source:?}"), "Kerberos(HTTP/::1)"); + } + + #[test] + fn callback_header_is_sensitive_and_base64() { + let source = NegotiateSource::resolve(Some("http://p:3128"), None, None, &callback()) + .unwrap() + .unwrap(); + let value = source.header().unwrap(); + assert_eq!(value.to_str().unwrap(), "Negotiate dG9r"); + assert!(value.is_sensitive()); + assert_eq!(format!("{value:?}"), "Sensitive"); + assert_eq!(format!("{source:?}"), "Callback"); + } + + #[test] + fn callback_failures_are_unauthenticated() { + let cases: [(&str, NegotiateTokenCallback); 2] = [ + ( + "error", + NegotiateTokenCallback::new(|| Err("no ticket".to_string())), + ), + ("empty", NegotiateTokenCallback::new(|| Ok(Vec::new()))), + ]; + for (name, callback) in cases { + let auth = ProxyAuth::NegotiateCallback(callback); + let source = NegotiateSource::resolve(Some("http://p:3128"), None, None, &auth) + .unwrap() + .unwrap(); + let err = source.header().unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{name}"); + assert!(!err.retryable, "{name}"); + } + } +} diff --git a/src/config.rs b/src/config.rs index 95f57401..ea7ccc7b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1136,6 +1136,10 @@ pub struct ProxyConfig { /// (e.g. `"localhost,*.internal.corp,.example.com"`). Only applied /// when [`url`](Self::url) is set. pub bypass_hosts: Option, + + /// Proxy authentication scheme. [`ProxyAuth::Default`] keeps Basic + /// credentials (from [`username`](Self::username) or the URL) or none. + pub auth: ProxyAuth, } impl std::fmt::Debug for ProxyConfig { @@ -1148,10 +1152,97 @@ impl std::fmt::Debug for ProxyConfig { .field("username", &self.username) .field("password", &self.password.as_ref().map(|_| "")) .field("bypass_hosts", &self.bypass_hosts) + .field("auth", &self.auth) .finish() } } +/// How the kernel authenticates to the HTTP proxy in [`ProxyConfig::url`]. +/// +/// Both Negotiate variants send `Proxy-Authorization: Negotiate ` on +/// the HTTP `CONNECT` to the proxy only, never to the warehouse or storage. +/// A token is created when each HTTP client is built (at session open, and +/// lazily for Volume storage); failure stops that operation before network +/// I/O. A proxy `CONNECT` answered with `407` gets one fresh-token retry per +/// request hop, including Volume PUT, GET and REMOVE storage requests. A +/// second `407` fails the request. Negotiate +/// never falls back to Basic, a direct connection or an environment proxy. +/// It needs an `http://` or `https://` [`ProxyConfig::url`] and no Basic +/// credentials. The token is only ever sent on a `CONNECT`, so with +/// Negotiate every request must be `https://`: a plain-HTTP request, or a +/// redirect to one, is refused, even to a host on the bypass list. +#[non_exhaustive] +#[derive(Clone, Default)] +pub enum ProxyAuth { + /// Basic credentials from the URL or `username` / `password`, or none. + #[default] + Default, + /// Kerberos via MIT GSSAPI on Linux (`libgssapi_krb5.so.2`, loaded only + /// when a token is needed). Non-Linux platforms link through cross-krb5: + /// GSS.framework on macOS, SSPI on Windows, and system GSSAPI on other + /// Unix (including BSDs, illumos and Android). Uses the caller's ambient + /// credentials (credential cache or logon + /// session). No password, keytab or delegation. The target is + /// `/[@]`, by default `HTTP/` in the + /// default realm. On Unix the token is a raw Kerberos token, + /// which MIT and Heimdal acceptors (such as squid's + /// `negotiate_kerberos_auth`) accept under `Negotiate`; a proxy that + /// accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends + /// SPNEGO (the SSPI Negotiate package). Requires the `proxy-negotiate` + /// cargo feature; without it, `Session::open` rejects this variant as + /// unsupported. + Negotiate { + /// Service part of the target name. Default `HTTP`. + service: Option, + /// Host part of the target name. Default: the proxy URL's host. + host: Option, + /// Realm of the target name. Default: the Kerberos default realm. + realm: Option, + }, + /// Tokens come from a caller-supplied callback (used by the Python + /// binding, which creates them with the same libraries as its Thrift + /// path). Needs no cargo feature. + NegotiateCallback(NegotiateTokenCallback), +} + +impl std::fmt::Debug for ProxyAuth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProxyAuth::Default => f.write_str("Default"), + ProxyAuth::Negotiate { + service, + host, + realm, + } => f + .debug_struct("Negotiate") + .field("service", service) + .field("host", host) + .field("realm", realm) + .finish(), + ProxyAuth::NegotiateCallback(_) => f.write_str("NegotiateCallback"), + } + } +} + +/// Callback returning one raw (not base64) SPNEGO or Kerberos token for the +/// proxy. It is called from a blocking thread, at most once per HTTP client +/// build plus once per proxy `407`, and must return a new token each time +/// (proxies reject replayed tokens). An `Err` or an empty token fails the +/// request closed; the message must not contain token bytes. +#[derive(Clone)] +pub struct NegotiateTokenCallback( + pub(crate) std::sync::Arc std::result::Result, String> + Send + Sync>, +); + +impl NegotiateTokenCallback { + /// Wrap a token-producing closure. + pub fn new( + f: impl Fn() -> std::result::Result, String> + Send + Sync + 'static, + ) -> Self { + Self(std::sync::Arc::new(f)) + } +} + // ─── TLS ──────────────────────────────────────────────────────────────────── /// TLS settings for the HTTP client. diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index 60264580..78572ff0 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -358,16 +358,25 @@ impl FeatureFlagResolver { } async fn fetch(&self, request: reqwest::RequestBuilder) -> Result { - let response = request.send().await.map_err(|error| { - let kernel_error = if error.is_timeout() { - Error::timeout() - } else { - Error::network_error() - }; - kernel_error.message(format!( - "connector-service feature-flag GET failed: {error}" - )) + // Sent once, outside the retry loop; `send_once` still gives a + // Negotiate proxy 407 its fresh-token retry. + let request = request.build().map_err(|error| { + Error::invalid_argument().message(format!("feature-flag request is invalid: {error}")) })?; + let response = self + .http_client + .send_once(request) + .await? + .map_err(|error| { + let kernel_error = if error.is_timeout() { + Error::timeout() + } else { + Error::network_error() + }; + kernel_error.message(format!( + "connector-service feature-flag GET failed: {error}" + )) + })?; let status = response.status(); if !status.is_success() { return Err(Error::from_http_status(status.as_u16()).message(format!( diff --git a/src/lib.rs b/src/lib.rs index cb525199..50c5cb11 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -136,8 +136,8 @@ pub mod c_abi; // === Public re-exports === pub use config::{ AuthConfig, ConnectionConfig, DefaultOpts, GeospatialResultRepresentation, HttpConfig, - LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, - TokenCacheConfig, TransportMode, + LoggingConfig, NegotiateTokenCallback, ProxyAuth, ProxyConfig, ResultConfig, SessionConfig, + TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; pub use kernel_error::{Error, ErrorCode, LocalFileError, Result}; /// The `tracing` target string stamped on every kernel log event. diff --git a/src/session.rs b/src/session.rs index cb79e993..0580f02d 100644 --- a/src/session.rs +++ b/src/session.rs @@ -383,14 +383,36 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); + // Invalid or unsupported Negotiate proxy settings keep their own + // error code, as does a failed Negotiate token (fail closed, D4). + let proxy = &http_client_config.proxy; + crate::client::proxy_negotiate::NegotiateSource::resolve( + proxy.url.as_deref(), + proxy.username.as_deref(), + proxy.password.as_deref(), + &proxy.auth, + )?; // The CloudFetch retry settings disable retries, so Volume transfers // use the SQL ones. let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( - DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) - .map_err(|e| { - Error::network_error().message(format!("Failed to construct HTTP client: {e}")) - })?, + DatabricksHttpClient::with_revocation_async( + http_client_config, + retry_configs, + revocation, + ) + .await + .map_err(|e| { + // A failed or timed-out Negotiate token keeps its own code. + if matches!( + e.code, + crate::kernel_error::ErrorCode::Unauthenticated + | crate::kernel_error::ErrorCode::Timeout + ) { + return e; + } + Error::network_error().message(format!("Failed to construct HTTP client: {e}")) + })?, ); let storage = Arc::new(crate::volume::Storage::new( http_client.config().clone(), @@ -1156,12 +1178,14 @@ fn build_proxy_config(proxy: Option<&ProxyConfig>) -> HttpProxyConfig { username, password, bypass_hosts, + auth, } = proxy.clone(); HttpProxyConfig { url, username, password, bypass_hosts, + auth, } } diff --git a/src/volume.rs b/src/volume.rs index 49fcf7cd..61897296 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -19,7 +19,9 @@ //! module makes the storage request that row describes. use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; +use crate::client::proxy_negotiate::is_proxy_auth_required; use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::config::ProxyAuth; use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, RecordBatch}; @@ -121,6 +123,8 @@ pub(crate) struct Storage { config: HttpClientConfig, revocation: Option, client: OnceCell, + /// The latest client whose fresh Negotiate token established a tunnel. + negotiate_client: std::sync::RwLock>, retry: RetryConfig, idle_limit: Option, cancellation: CancellationToken, @@ -139,6 +143,7 @@ impl Storage { config, revocation, client: OnceCell::new(), + negotiate_client: std::sync::RwLock::new(None), retry, idle_limit: idle_limit.filter(|limit| !limit.is_zero()), cancellation: CancellationToken::new(), @@ -166,12 +171,19 @@ impl Storage { self.cancellation.cancel(); } - async fn client(&self) -> Result<&Client> { - self.client - .get_or_try_init(|| async { - DatabricksHttpClient::storage_client(&self.config, self.revocation) + async fn client(&self) -> Result { + let initial = self + .client + .get_or_try_init(|| { + DatabricksHttpClient::storage_client_async(&self.config, self.revocation) }) - .await + .await?; + Ok(self + .negotiate_client + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| initial.clone())) } } @@ -276,19 +288,18 @@ impl VolumeState { input_bytes, ) .await?; - let client = self.storage.client().await?; + // Initial token failures (including timeouts) do not enter storage retries. + self.storage.client().await?; let retry = &self.storage.retry; let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, retry); let mut first_failure = None; let mut attempt = 0; loop { - let (error, retry_after) = match self - .attempt(client, &instruction, &local, options, &strategy) - .await - { - Ok(()) => return Ok(local), - Err(failure) => failure, - }; + let (error, retry_after) = + match self.attempt(&instruction, &local, options, &strategy).await { + Ok(()) => return Ok(local), + Err(failure) => failure, + }; let wait = calculate_backoff(retry, attempt, retry_after.as_deref()); // The retry budget runs from the first failure, so a long transfer that // is still making progress keeps the whole budget for a late failure. @@ -310,11 +321,10 @@ impl VolumeState { } } - /// One storage request. A failure carries the response's `Retry-After` - /// value. + /// One storage request, with one fresh-token retry of a rejected proxy + /// CONNECT. A failure carries the response's `Retry-After` value. async fn attempt( &self, - client: &Client, instruction: &Instruction, local: &Local, options: &VolumeOptions, @@ -323,25 +333,82 @@ impl VolumeState { let method = local.method(); let url = Url::parse(&instruction.url) .map_err(|_| (invalid("Invalid Volume storage URL"), None))?; - let (progress, mut progressed) = watch::channel(()); - let mut headers = instruction.headers.clone(); - let mut body = None; - if let Some((chunks, length)) = local.upload() { - headers.insert(CONTENT_LENGTH, length.into()); - body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { - progress.send_replace(()); - }))); + let negotiate = !matches!(self.storage.config.proxy.auth, ProxyAuth::Default); + // A plain-HTTP proxy request would carry the token without a CONNECT. + // As in send_once, refuse it even for hosts on the bypass list. + if negotiate && url.scheme() != "https" { + return Err(( + Error::invalid_argument().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP request to {}", + url.host_str().unwrap_or("") + )), + None, + )); } - let mut request = client.request(method.clone(), url).headers(headers); - if let Some(body) = body { - request = request.body(body); + let mut client = self.storage.client().await.map_err(|e| (e, None))?; + let mut fresh_token = false; + let response = loop { + // Recreate everything per send: a streaming PUT body cannot be cloned. + let (progress, mut progressed) = watch::channel(()); + let mut headers = instruction.headers.clone(); + let mut body = None; + if let Some((chunks, length)) = local.upload() { + headers.insert(CONTENT_LENGTH, length.into()); + body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { + progress.send_replace(()); + }))); + } + let mut request = client.request(method.clone(), url.clone()).headers(headers); + if let Some(body) = body { + request = request.body(body); + } + match self + .idle_bounded(&mut progressed, async { Ok(request.send().await) }) + .await + .map_err(|e| (e, None))? + { + Ok(response) => break response, + Err(mut error) if negotiate && is_proxy_auth_required(&error) => { + if fresh_token { + if let Some(url) = error.url_mut() { + url.set_query(None); + } + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + return Err(( + Error::unauthenticated() + .message(format!( + "Negotiate proxy authentication failed: the proxy rejected a \ + fresh token (HTTP 407): {}", + causes.join(": ") + )) + .with_retryable(false), + None, + )); + } + client = DatabricksHttpClient::storage_client_async( + &self.storage.config, + self.storage.revocation, + ) + .await + .map_err(|e| (e.with_retryable(false), None))?; + fresh_token = true; + } + Err(error) => return Err((storage_error(error, strategy), None)), + } + }; + if fresh_token { + // Its tunnel is up. Concurrent rebuilds each use their own token; + // the last successful send wins. Never hold the lock over an await. + *self + .storage + .negotiate_client + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(client); } - let response = self - .idle_bounded(&mut progressed, async { - request.send().await.map_err(|e| storage_error(e, strategy)) - }) - .await - .map_err(|e| (e, None))?; let status = response.status(); if status.is_success() || (method == Method::DELETE @@ -1030,14 +1097,25 @@ fn local_error(error: std::io::Error, path: &str) -> Error { #[cfg(test)] mod tests { use super::*; + use crate::client::http::negotiate_tests::{assert_negotiate_only, direct_origin, StubProxy}; + use crate::config::NegotiateTokenCallback; use crate::ErrorCode; use arrow_array::builder::{MapBuilder, StringBuilder}; use arrow_array::StringArray; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use tokio::io::AsyncReadExt; use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn storage(max_retries: u32, idle_limit: Option) -> Arc { + storage_with_config(HttpClientConfig::default(), max_retries, idle_limit) + } + + fn storage_with_config( + config: HttpClientConfig, + max_retries: u32, + idle_limit: Option, + ) -> Arc { let retry = RetryConfig { max_retries, min_wait: Duration::ZERO, @@ -1045,7 +1123,7 @@ mod tests { ..Default::default() }; Arc::new(Storage::new( - HttpClientConfig::default(), + config, None, retry, idle_limit, @@ -1120,6 +1198,278 @@ mod tests { unsafe { libc::geteuid() == 0 } } + fn negotiate_config(proxy: &StubProxy, calls: &Arc) -> HttpClientConfig { + let calls = calls.clone(); + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + Ok(format!("tok-{n}").into_bytes()) + })); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + config + } + + #[tokio::test] + async fn negotiate_storage_get_put_and_remove_survive_replayed_tokens() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let mut url = Url::parse(&origin).unwrap(); + url.set_path("/volume"); + url.set_query(Some("signature=presigned-secret")); + let calls = Arc::new(AtomicUsize::new(0)); + // No generic retries: every replay must be handled by the 407 retry. + let storage = storage_with_config(negotiate_config(&proxy, &calls), 0, None); + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + let destination = dir.path().join("destination"); + let payload = b"\0\xffvolume bytes".repeat(UPLOAD_CHUNK / 7 + 1); + std::fs::write(&source, &payload).unwrap(); + + // Spend the first token. The stub closes each Volume tunnel, so both + // GET and PUT below must recover from a replay on their next CONNECT. + run(&storage, remove(url.as_str()), dir.path()) + .await + .unwrap(); + run( + &storage, + instruction("PUT", url.as_str(), &source), + dir.path(), + ) + .await + .unwrap(); + run( + &storage, + instruction("GET", url.as_str(), &destination), + dir.path(), + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), payload); + + // Byte-backed uploads must also recreate their stream on the retry. + let bytes = Bytes::from_static(b"\xff\0stream payload"); + let state = storage.transfer_state(Some( + VolumeOptions::new(vec![dir.path().to_owned()], false).with_input_bytes(bytes.clone()), + )); + state + .complete( + Ok(Some(instruction( + "PUT", + url.as_str(), + Path::new("__input_stream__"), + ))), + true, + ) + .await + .unwrap(); + run( + &storage, + instruction("GET", url.as_str(), &destination), + dir.path(), + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), bytes); + run(&storage, remove(url.as_str()), dir.path()) + .await + .unwrap(); + + let seen = proxy.seen.lock().unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 6); + assert_eq!(seen.connects.len(), 11); + assert_eq!(seen.connects[0].1, 200); + for (i, pair) in seen.connects[1..].as_chunks::<2>().0.iter().enumerate() { + // Later requests use the promoted client, not the cached first one. + assert_eq!(pair[0].0, seen.connects[2 * i].0); + assert_eq!(pair[0].1, 407); + assert_eq!(pair[1].1, 200); + assert_ne!(pair[0].0, pair[1].0); + } + assert_eq!(seen.requests.len(), 6, "no origin operation is resent"); + assert!(seen.requests[1..5] + .iter() + .all(|(_, headers)| { headers.iter().any(|h| h == "x-test") })); + for i in [1, 3] { + assert!(seen.requests[i].1.iter().any(|h| h == "content-length")); + } + assert_eq!( + seen.volume_bodies, + vec![ + Vec::new(), + payload, + Vec::new(), + bytes.to_vec(), + Vec::new(), + Vec::new() + ] + ); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + assert!(storage.negotiate_client.read().unwrap().is_some()); + } + + #[tokio::test] + async fn negotiate_storage_second_407_fails_closed_and_redacts_secrets() { + for operation in ["GET", "PUT", "REMOVE"] { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let url = format!("{origin}?signature=presigned-secret&token=query-secret"); + let calls = Arc::new(AtomicUsize::new(0)); + // A second 407 must stop even when ordinary storage retries remain. + let storage = storage_with_config(negotiate_config(&proxy, &calls), 5, None); + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("local"); + if operation == "PUT" { + std::fs::write(&local, b"payload").unwrap(); + } + let batch = if operation == "REMOVE" { + remove(&url) + } else { + instruction(operation, &url, &local) + }; + let error = run(&storage, batch, dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::Unauthenticated, "{}", error.message); + assert!(!error.retryable); + assert!(error.message.starts_with( + "Negotiate proxy authentication failed: the proxy rejected a fresh token (HTTP 407): " + ), "{}", error.message); + for secret in [ + "?", + "signature", + "presigned-secret", + "query-secret", + "tok-", + "dG9r", + ] { + assert!(!error.message.contains(secret), "{}", error.message); + } + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 2); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(seen.requests.is_empty()); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + assert!(!local.exists() || operation == "PUT"); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn negotiate_storage_slow_first_token_does_not_block_async_workers() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let signalled = Arc::new(AtomicBool::new(false)); + let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel::<()>(); + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + let signal_rx = std::sync::Mutex::new(signal_rx); + let mut config = negotiate_config(&proxy, &calls); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new({ + let (calls, signalled) = (calls.clone(), signalled.clone()); + move || { + calls.fetch_add(1, Ordering::SeqCst); + let _ = entered_tx.send(()); + let arrived = signal_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .is_ok(); + signalled.store(arrived, Ordering::SeqCst); + Err("no Kerberos credentials".to_string()) + } + })); + let signaller = tokio::spawn(async move { + if entered_rx.recv().await.is_some() { + let _ = signal_tx.send(()); + } + }); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + let error = run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap_err(); + signaller.abort(); + assert!( + signalled.load(Ordering::SeqCst), + "the async worker was blocked" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(error.code, ErrorCode::Unauthenticated); + assert!(error.message.contains("no Kerberos credentials")); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + } + + #[tokio::test(flavor = "current_thread")] + async fn negotiate_storage_first_and_fresh_tokens_time_out() { + for slow_call in [1, 2] { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut config = negotiate_config(&proxy, &calls); + // The budget also covers building the storage client and scheduling the + // blocking call, so the fast token (and its client build) needs headroom on a + // loaded CI runner; the slow token still outlasts it by a wide margin. + config.read_timeout = Duration::from_secs(1); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new({ + let calls = calls.clone(); + move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if n == slow_call { + std::thread::sleep(Duration::from_secs(3)); + } + Ok(format!("tok-{n}").into_bytes()) + } + })); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + if slow_call == 2 { + run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap(); + } + let started = Instant::now(); + let error = run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::Timeout, "{}", error.message); + assert!( + !error.retryable, + "token timeouts must not start more blocking calls" + ); + assert_eq!( + error.message, + "Negotiate proxy authentication timed out: no token within the 1s request timeout" + ); + assert!( + started.elapsed() < Duration::from_millis(2500), + "{:?}", + started.elapsed() + ); + assert_eq!(calls.load(Ordering::SeqCst), slow_call); + assert_eq!( + proxy.seen.lock().unwrap().connects.len(), + if slow_call == 1 { 0 } else { 2 } + ); + } + } + + #[tokio::test] + async fn negotiate_storage_refuses_plain_http_without_io() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut config = negotiate_config(&proxy, &calls); + config.proxy.bypass_hosts = Some("127.0.0.1".to_string()); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + let url = origin.replacen("https://", "http://", 1) + "?signature=secret"; + let error = run(&storage, remove(&url), dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert!(error.message.contains("needs https://")); + assert!(!error.message.contains("signature")); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn put_get_and_remove_move_exact_bytes() { let payload = b"\0\xffvolume bytes".to_vec(); diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 425f24bc..be277cef 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -567,6 +567,35 @@ static void test_executed_null_handle_rejected(void) { CHECK(n == -1, "num_modified_rows(NULL exec) → -1"); } +/* Negotiate proxy setter; invalid combinations fail at open with + * InvalidArgument before any network I/O. */ +static void test_proxy_negotiate_setter(void) { + KernelStatusCode rc = kernel_session_config_set_proxy_negotiate(NULL, NULL, NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_proxy_negotiate(NULL config) → InvalidArgument"); + + const char* proxy_user[] = {"u", NULL}; + const char* expected[] = {"Basic", "set_proxy"}; + for (int i = 0; i < 2; i++) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); + (void)kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + rc = kernel_session_config_set_proxy_negotiate(config, "HTTP", "proxy.corp", "CORP.EXAMPLE"); + CHECK(rc == KernelStatusCode_Success, "set_proxy_negotiate succeeds"); + if (proxy_user[i] != NULL) { + (void)kernel_session_config_set_proxy(config, "http://192.0.2.1:3128", proxy_user[i], "p", NULL); + } + kernel_session_t* session = NULL; + rc = kernel_session_open(config, &session); + CHECK(rc == KernelStatusCode_InvalidArgument, "invalid Negotiate proxy open → InvalidArgument"); + KernelError err; + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL && + strstr(err.message, expected[i]) != NULL, + "invalid Negotiate proxy error names the cause"); + } +} + int main(void) { test_config_lifecycle(); test_null_guards(); @@ -578,6 +607,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_tls_certificate_revocation_setter(); + test_proxy_negotiate_setter(); test_socks_proxy_url(); test_u2m_and_header_setters(); test_identity_federation_client_id_setter(); diff --git a/tests/proxy_credential_logging.rs b/tests/proxy_credential_logging.rs index 824a9ff8..6db6de1e 100644 --- a/tests/proxy_credential_logging.rs +++ b/tests/proxy_credential_logging.rs @@ -85,6 +85,7 @@ async fn proxy_credentials_stay_out_of_errors_and_logs() { username: explicit.map(|(user, _)| user.to_string()), password: explicit.map(|(_, password)| password.to_string()), bypass_hosts: None, + ..ProxyConfig::default() }, ..HttpClientConfig::default() };