diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6e29dc0c..6f421c57 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -12,7 +12,7 @@ by the struct it lives on. `ConnectionConfig` and `AuthConfig` are | [`AuthConfig`](#authconfig--authentication-required) | PAT / OAuth M2M / OAuth U2M *(required)* | | [`DefaultOpts`](#defaultopts--session-defaults-optional) | default catalog / schema, transactions | | [`HttpConfig`](#httpconfig--http-client-optional) | timeouts, connection pool, retries, headers | -| [`ProxyConfig`](#proxyconfig--httphttps-proxy-optional) | HTTP/HTTPS proxy | +| [`ProxyConfig`](#proxyconfig--httphttps-proxy-optional) | HTTP/HTTPS/SOCKS proxy | | [`TlsConfig`](#tlsconfig--tls--ssl-optional) | cert validation, custom CA, mTLS | | [`ResultConfig`](#resultconfig--result-handling-optional) | CloudFetch tuning, type rendering | | [`geospatial_result_representation`](#geospatial_result_representation--geospatial-result-encoding-optional) | GEOMETRY / GEOGRAPHY result encoding | @@ -178,13 +178,30 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). ## `ProxyConfig` — HTTP/HTTPS proxy (optional) When `url` is `None`, the kernel does not configure a proxy and -`reqwest`'s standard `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` env-var -behaviour applies. Setting `url` **overrides** those env vars. +`reqwest`'s standard `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` +env-var behaviour applies. Those variables are used only with the `http`, +`https`, `socks4`, `socks4a`, `socks5` and `socks5h` schemes. A value with +any other scheme, such as bare `socks://`, is ignored, so the kernel falls +back to `ALL_PROXY` or connects directly. Setting `url` **overrides** those +env vars, and an unsupported scheme in `url` fails with `InvalidArgument`. + +SOCKS: `socks5://` and `socks4://` resolve the target host locally; +`socks5h://` and `socks4a://` let the proxy resolve it. SOCKS5 credentials +use RFC 1929 username/password authentication. When credentials are set, +that is the only method offered, so a proxy that allows only +unauthenticated access rejects the connection. SOCKS4 has no password, and +the kernel does not yet send a SOCKS4 user ID, so a SOCKS4 proxy that checks +the user ID refuses the connection. An unreachable proxy fails the request +after the retry policy's attempts; a rejected SOCKS5 authentication fails it +at once, without resending the credentials. The kernel never falls back to a +direct connection. TLS is still negotiated with, and verified against, the target +host through the tunnel. Proxy URLs are logged and reported in errors with +userinfo replaced by `***`. | Field | Description | Default | |-------|-------------|---------| -| `url` | Proxy endpoint, e.g. `http://proxy.corp.example.com:8080`. Must be `http://` or `https://`. | `None` (env-var behaviour) | -| `username` | Proxy basic-auth username. Overrides credentials embedded in `url`. | `None` | +| `url` | Proxy endpoint, e.g. `http://proxy.corp.example.com:8080` or `socks5h://proxy.corp.example.com:1080`. Scheme must be `http`, `https`, `socks4`, `socks4a`, `socks5` or `socks5h`. | `None` (env-var behaviour) | +| `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` | diff --git a/Cargo.lock b/Cargo.lock index f1aee8c8..bc909a3e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,7 +115,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64", + "base64 0.22.1", "chrono", "half", "lexical-core", @@ -296,6 +296,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -654,7 +660,7 @@ dependencies = [ "arrow-schema", "arrow-select", "async-trait", - "base64", + "base64 0.22.1", "cbc 0.2.1", "chrono", "dashmap", @@ -663,6 +669,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper-util", "jsonwebtoken", "libc", "log", @@ -1245,16 +1252,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -1471,7 +1479,7 @@ version = "9.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" dependencies = [ - "base64", + "base64 0.22.1", "js-sys", "pem", "ring", @@ -1825,7 +1833,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http", @@ -1968,7 +1976,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -2287,7 +2295,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-core", "futures-util", @@ -3445,7 +3453,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" dependencies = [ "assert-json-diff", - "base64", + "base64 0.22.1", "deadpool", "futures", "http", diff --git a/Cargo.toml b/Cargo.toml index 1b7f8c0b..14e1e80a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,13 @@ arrow-ipc = "59" # (which `native-tls` pulls in on Linux) collides with Node's symbols at # module load time and segfaults the process before any Rust code runs. # `rustls` is pure Rust + ring and avoids the conflict entirely. -reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] } +# +# `socks` adds SOCKS4/4a/5/5h proxies. From 0.12.28 it is implemented by +# hyper-util (already a dependency) and pulls in no extra crate. +reqwest = { version = "0.12.28", default-features = false, features = ["json", "gzip", "stream", "socks"] } +# Enforce the SOCKS4/4a fix for consumers with their own lockfiles: hyper-util +# 0.1.20 writes a malformed SOCKS4 CONNECT request. +hyper-util = { version = "0.1.21", default-features = false } native-tls = { version = "0.2", optional = true } rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] } # Enforce TLS dependency minimums for consumers with their own lockfiles. diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ec9ccb7d..1313dae0 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,9 +20,14 @@ changes go in their respective binding's NEXT_CHANGELOG. `kernel_session_config_set_port` connect to `host:port`, so bindings no longer build it into the host. A non-default port is rejected with `InvalidArgument` if the host has credentials, a path, query or fragment. +- `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, + `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. ### Changed +- Proxy credentials are redacted from proxy URLs in errors, logs and `Debug` + output. + ### Updated ### Fixed diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index c7c29517..64db58f1 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -677,6 +677,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper-util", "jsonwebtoken", "libc", "lz4_flex", diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..81fd3747 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -640,9 +640,13 @@ impl DatabaseConfig { )); } if let Some(url) = &self.proxy.url { - if !(url.starts_with("http://") || url.starts_with("https://")) { + const SCHEMES: [&str; 6] = ["http", "https", "socks4", "socks4a", "socks5", "socks5h"]; + if !url + .split_once("://") + .is_some_and(|(scheme, _)| SCHEMES.contains(&scheme)) + { return Err(adbc_error( - "proxy URL must use http or https", + "proxy URL must use http, https, socks4, socks4a, socks5 or socks5h", Status::InvalidArguments, )); } @@ -1370,6 +1374,35 @@ mod tests { assert!(config.validate().is_ok()); } + #[test] + fn proxy_url_accepts_http_and_socks_schemes() { + for (url, accepted) in [ + ("http://proxy.example.com:8080", true), + ("https://proxy.example.com:8443", true), + ("socks4://proxy.example.com:1080", true), + ("socks4a://proxy.example.com:1080", true), + ("socks5://proxy.example.com:1080", true), + ("socks5h://proxy.example.com:1080", true), + ("socks://proxy.example.com:1080", false), + ("SOCKS5://proxy.example.com:1080", false), + ("ftp://proxy.example.com:21", false), + ("proxy.example.com:1080", false), + // SOCKS credentials still go through the username/password options. + ("socks5h://user:secret@proxy.example.com:1080", false), + ] { + let mut config = DatabaseConfig::default(); + set(&mut config, "adbc.databricks.proxy.url", url); + match config.validate() { + Ok(_) => assert!(accepted, "{url} must be rejected"), + Err(error) => { + assert!(!accepted, "{url} must be accepted: {}", error.message); + assert_eq!(error.status, Status::InvalidArguments, "{url}"); + assert!(!error.message.contains("secret"), "{url}"); + } + } + } + } + #[test] fn proxy_basic_auth_reaches_kernel_config() { let mut config = DatabaseConfig::default(); diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 871b21b8..effd6057 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -453,9 +453,10 @@ KernelStatusCode kernel_init_logging_callback(const char* level, * override. */ -/* Route traffic through an HTTP/HTTPS proxy. `url` is required (e.g. - * "http://proxy.corp:8080"); `username` / `password` / `bypass_hosts` - * (comma-separated) are optional — pass NULL to omit. */ +/* Route traffic through an HTTP/HTTPS or SOCKS proxy. `url` is required + * (e.g. "http://proxy.corp:8080" or "socks5h://proxy.corp:1080"; schemes + * http, https, socks4, socks4a, socks5, socks5h); `username` / `password` / + * `bypass_hosts` (comma-separated) are optional — pass NULL to omit. */ KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, const char* url, const char* username, const char* password, const char* bypass_hosts); diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 98dea798..dedcf797 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -115,7 +115,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64", + "base64 0.22.1", "chrono", "half", "lexical-core", @@ -257,6 +257,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -615,7 +621,7 @@ dependencies = [ "arrow-schema", "arrow-select", "async-trait", - "base64", + "base64 0.22.1", "cbc 0.2.1", "chrono", "dashmap", @@ -624,6 +630,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper-util", "jsonwebtoken", "libc", "lz4_flex", @@ -1167,16 +1174,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -1393,7 +1401,7 @@ version = "9.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" dependencies = [ - "base64", + "base64 0.22.1", "js-sys", "pem", "ring", @@ -1753,7 +1761,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http", @@ -1850,7 +1858,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -2138,7 +2146,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-core", "futures-util", @@ -3211,7 +3219,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" dependencies = [ "assert-json-diff", - "base64", + "base64 0.22.1", "deadpool", "futures", "http", diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index ac77df4a..ba2c9129 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -22,6 +22,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Updated +- Bundle the kernel's SOCKS proxy support. + ### Fixed --- diff --git a/napi/index.d.ts b/napi/index.d.ts index 13729932..73e17afd 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -156,13 +156,14 @@ export interface HeaderEntry { value: string } /** - * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * Programmatic HTTP/HTTPS/SOCKS proxy configuration, mirroring the kernel's * internal [`ProxyConfig`]. Supplied as a structured object rather than a * flattened URL so credentials never have to be percent-encoded into the URL * and the bypass-host list can be expressed. * * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must - * use the `http://` or `https://` scheme. + * use the `http://`, `https://`, `socks4://`, `socks4a://`, `socks5://` or + * `socks5h://` scheme. * - `username` / `password` — optional proxy basic-auth, applied via * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). * - `bypassHosts` — optional comma-separated host/domain list that should diff --git a/napi/src/database.rs b/napi/src/database.rs index 02ce1754..27897403 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -109,13 +109,14 @@ pub struct HeaderEntry { pub value: String, } -/// Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's +/// Programmatic HTTP/HTTPS/SOCKS proxy configuration, mirroring the kernel's /// internal [`ProxyConfig`]. Supplied as a structured object rather than a /// flattened URL so credentials never have to be percent-encoded into the URL /// and the bypass-host list can be expressed. /// /// - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must -/// use the `http://` or `https://` scheme. +/// use the `http://`, `https://`, `socks4://`, `socks4a://`, `socks5://` or +/// `socks5h://` scheme. /// - `username` / `password` — optional proxy basic-auth, applied via /// `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). /// - `bypassHosts` — optional comma-separated host/domain list that should diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 8303b544..55bef07f 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -124,7 +124,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64", + "base64 0.22.1", "chrono", "half", "lexical-core", @@ -268,6 +268,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -611,7 +617,7 @@ dependencies = [ "arrow-schema", "arrow-select", "async-trait", - "base64", + "base64 0.22.1", "cbc 0.2.1", "chrono", "dashmap", @@ -620,6 +626,7 @@ dependencies = [ "geo-traits", "hex", "hmac 0.13.0", + "hyper-util", "jsonwebtoken", "libc", "lz4_flex", @@ -1107,16 +1114,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -1333,7 +1341,7 @@ version = "9.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" dependencies = [ - "base64", + "base64 0.22.1", "js-sys", "pem", "ring", @@ -1609,7 +1617,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http", @@ -1706,7 +1714,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -2050,7 +2058,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-core", "futures-util", diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index aeac93ff..bf833a5d 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -21,6 +21,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Updated +- Bundle the kernel's SOCKS proxy support. + ### Fixed - Session runtime threads now block SIGPIPE. A TLS write after a peer reset no longer kills a Python process that restored the default action (`signal.signal(signal.SIGPIPE, signal.SIG_DFL)`); the write fails with `EPIPE` instead. diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b28eee7e..22b409c6 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1261,9 +1261,10 @@ unsafe fn optional_str(ptr: *const c_char, what: &str) -> Result, .map_err(|_| Error::invalid_argument().message(format!("{what} is not valid UTF-8"))) } -/// Configure an HTTP/HTTPS proxy. `url` is required (e.g. -/// `http://proxy:8080`); `username` / `password` / `bypass_hosts` are -/// optional (pass NULL to omit). Maps to the kernel's `ProxyConfig`. +/// Configure an HTTP/HTTPS or SOCKS proxy. `url` is required (e.g. +/// `http://proxy:8080` or `socks5h://proxy:1080`); `username` / +/// `password` / `bypass_hosts` are optional (pass NULL to omit). Maps to +/// the kernel's `ProxyConfig`. /// /// # Safety /// `config` must be a live config handle; `url` must be a NUL-terminated diff --git a/src/client/http.rs b/src/client/http.rs index 04571de7..1211e03e 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -24,8 +24,8 @@ use crate::auth::AuthProvider; use crate::client::retry::{ - calculate_backoff, is_certificate_verification_failure, RequestCategory, RequestType, - RetryConfig, RetryStrategy, + calculate_backoff, is_certificate_verification_failure, is_socks_authentication_failure, + RequestCategory, RequestType, RetryConfig, RetryStrategy, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -108,6 +108,36 @@ fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error err } +/// Proxy URL schemes accepted in [`ProxyConfig::url`]. `socks4` and `socks5` +/// resolve the target host locally; `socks4a` and `socks5h` let the proxy +/// resolve it. Bare `socks://` is rejected because drivers disagree on its +/// DNS mode. +const PROXY_URL_SCHEMES: &[&str] = &["http", "https", "socks4", "socks4a", "socks5", "socks5h"]; + +/// `url` with any `userinfo@` replaced by `***@`, for logs and errors. +/// +/// Everything up to the last `@` is treated as userinfo, so a credential +/// containing an unencoded `/`, `?` or `#` is still hidden. A `scheme://` +/// prefix is kept only when it is a syntactically valid scheme, so a `://` +/// inside unencoded credentials can't expose the part before it. +fn redact_proxy_url(url: &str) -> String { + let authority = url + .find("://") + .filter(|&i| is_uri_scheme(&url[..i])) + .map_or(0, |i| i + 3); + match url[authority..].rfind('@') { + Some(at) => format!("{}***{}", &url[..authority], &url[authority + at..]), + None => url.to_string(), + } +} + +/// RFC 3986 scheme syntax: a letter, then letters, digits, `+`, `-` or `.`. +fn is_uri_scheme(s: &str) -> bool { + let mut chars = s.chars(); + chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) +} + /// Configuration for HTTP proxy. /// /// When `url` is set, the driver uses the specified proxy for all requests, @@ -115,7 +145,9 @@ fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error /// is `None`, reqwest's default behavior applies (reads env vars automatically). #[derive(Clone, Default)] pub struct ProxyConfig { - /// Proxy URL (e.g., "http://proxy.corp.example.com:8080"). + /// Proxy URL (e.g., "http://proxy.corp.example.com:8080" or + /// "socks5h://proxy.corp.example.com:1080"). Accepted schemes are + /// `http`, `https`, `socks4`, `socks4a`, `socks5` and `socks5h`. /// When set, overrides HTTP_PROXY/HTTPS_PROXY environment variables. pub url: Option, /// Username for proxy authentication. @@ -132,7 +164,7 @@ pub struct ProxyConfig { impl std::fmt::Debug for ProxyConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ProxyConfig") - .field("url", &self.url) + .field("url", &self.url.as_deref().map(redact_proxy_url)) .field("username", &self.username) .field("password", &self.password.as_ref().map(|_| "[REDACTED]")) .field("bypass_hosts", &self.bypass_hosts) @@ -701,16 +733,23 @@ impl DatabricksHttpClient { // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme - if !proxy_url.starts_with("http://") && !proxy_url.starts_with("https://") { + let scheme_ok = proxy_url + .split_once("://") + .is_some_and(|(scheme, _)| PROXY_URL_SCHEMES.contains(&scheme)); + if !scheme_ok { return Err(Error::invalid_argument().message(format!( - "Proxy URL must use http:// or https:// scheme, got: '{}'", - proxy_url + "Proxy URL must use one of the {}:// schemes, got: '{}'", + PROXY_URL_SCHEMES.join("://, "), + redact_proxy_url(proxy_url) ))); } let mut proxy = Proxy::all(proxy_url).map_err(|e| { - Error::invalid_argument() - .message(format!("Invalid proxy URL '{}': {}", proxy_url, e)) + Error::invalid_argument().message(format!( + "Invalid proxy URL '{}': {}", + redact_proxy_url(proxy_url), + e + )) })?; // Add basic auth if credentials provided. @@ -724,6 +763,11 @@ impl DatabricksHttpClient { } else if config.proxy.password.is_some() { warn!("Proxy password provided without username; password will be ignored"); } + if proxy_url.starts_with("socks4") + && (config.proxy.username.is_some() || proxy_url.contains('@')) + { + warn!("SOCKS4 proxy credentials will be ignored: SOCKS4 has no password, and the user ID is not sent"); + } // Apply bypass_hosts list to the proxy. // Normalize by trimming whitespace around entries (e.g., "host1, host2"). @@ -740,7 +784,8 @@ impl DatabricksHttpClient { debug!( "HTTP client configured with proxy: {} (bypass_hosts: {:?})", - proxy_url, config.proxy.bypass_hosts + redact_proxy_url(proxy_url), + config.proxy.bypass_hosts ); } else { if config.proxy.username.is_some() { @@ -1144,7 +1189,10 @@ impl DatabricksHttpClient { error_message ); return Err(Error::network_error() - .with_retryable(!is_certificate_verification_failure(&e)) + .with_retryable( + !is_certificate_verification_failure(&e) + && !is_socks_authentication_failure(&e), + ) .message(format!( "HTTP request failed after {} attempts: {}", attempts, error_message @@ -1196,6 +1244,10 @@ mod revocation_support_tests { } } +#[cfg(test)] +#[path = "http_socks_tests.rs"] +mod socks_tests; + #[cfg(test)] mod tests { use super::*; @@ -1602,7 +1654,7 @@ mod tests { let result = DatabricksHttpClient::new(config, default_retry_configs()); assert!(result.is_err()); let err_msg = format!("{:?}", result.unwrap_err()); - assert!(err_msg.contains("http:// or https://")); + assert!(err_msg.contains("http://, https://")); } #[test] @@ -1624,13 +1676,77 @@ mod tests { } #[test] - fn test_http_client_rejects_invalid_proxy_scheme() { - let mut config = HttpClientConfig::default(); - config.proxy.url = Some("socks5://proxy.example.com:1080".to_string()); - let result = DatabricksHttpClient::new(config, default_retry_configs()); - assert!(result.is_err()); - let err_msg = format!("{:?}", result.unwrap_err()); - assert!(err_msg.contains("http:// or https://")); + fn test_http_client_proxy_scheme_table() { + let cases = [ + ("http://proxy.example.com:8080", true), + ("https://proxy.example.com:8443", true), + ("socks4://proxy.example.com:1080", true), + ("socks4a://proxy.example.com:1080", true), + ("socks5://proxy.example.com:1080", true), + ("socks5h://user:pass@proxy.example.com:1080", true), + ("socks://proxy.example.com:1080", false), + ("socks6://proxy.example.com:1080", false), + ("ftp://proxy.example.com:21", false), + ("SOCKS5://proxy.example.com:1080", false), + ]; + for (url, accepted) in cases { + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(url.to_string()); + match DatabricksHttpClient::new(config, default_retry_configs()) { + Ok(_) => assert!(accepted, "{url} must be rejected"), + Err(err) => { + assert!(!accepted, "{url} must be accepted: {err}"); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!( + err.message.contains( + "http://, https://, socks4://, socks4a://, socks5://, socks5h://" + ), + "{err}" + ); + } + } + } + } + + #[test] + fn test_proxy_url_errors_redact_userinfo() { + for url in [ + "socks://alice:s3cret@proxy.example.com:1080", + "alice:s3cret@proxy.example.com:1080", + "socks5h://alice:s3cret@", + "socks5h://alice:pa/ss#s3cret@proxy.example.com:1080", + "alice:s3cret://x@proxy.example.com:1080", + ] { + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(url.to_string()); + let err = DatabricksHttpClient::new(config, default_retry_configs()).unwrap_err(); + let text = format!("{err} {err:?}"); + assert!(!text.contains("s3cret"), "{text}"); + assert!(!text.contains("alice"), "{text}"); + assert!(text.contains("***@"), "{text}"); + } + } + + #[test] + fn test_redact_proxy_url() { + let cases = [ + ( + "socks5h://user:secret@proxy:1080", + "socks5h://***@proxy:1080", + ), + ("http://user@proxy:8080/", "http://***@proxy:8080/"), + ("http://proxy:8080", "http://proxy:8080"), + ("user:secret@proxy:1080", "***@proxy:1080"), + ("socks5://a:b@c@proxy:1080", "socks5://***@proxy:1080"), + // A `://` inside credentials without a scheme is not a scheme boundary. + ("user:pa://ss@proxy:1080", "***@proxy:1080"), + ("us er://x@proxy:1080", "***@proxy:1080"), + ("1x://x@proxy:1080", "***@proxy:1080"), + ("svn+ssh://u@proxy:1080", "svn+ssh://***@proxy:1080"), + ]; + for (url, expected) in cases { + assert_eq!(redact_proxy_url(url), expected, "{url}"); + } } #[test] @@ -1929,7 +2045,7 @@ lGrv15pBcePj #[test] fn test_proxy_config_debug_redacts_password() { let config = ProxyConfig { - url: Some("http://proxy:8080".to_string()), + url: Some("socks5h://urluser:urlsecret@proxy:1080".to_string()), username: Some("user".to_string()), password: Some("secret123".to_string()), bypass_hosts: None, @@ -1937,6 +2053,9 @@ lGrv15pBcePj let debug_output = format!("{:?}", config); assert!(debug_output.contains("[REDACTED]")); assert!(!debug_output.contains("secret123")); + assert!(debug_output.contains("socks5h://***@proxy:1080")); + assert!(!debug_output.contains("urlsecret")); + assert!(!debug_output.contains("urluser")); } // --- Retry integration tests (with wiremock) --- diff --git a/src/client/http_socks_tests.rs b/src/client/http_socks_tests.rs new file mode 100644 index 00000000..d1ee6233 --- /dev/null +++ b/src/client/http_socks_tests.rs @@ -0,0 +1,874 @@ +// 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. + +//! SOCKS proxy tests. A loopback SOCKS4/4a/5 fixture records what the proxy +//! saw (version, target, RFC 1929 outcome) and relays every CONNECT to +//! 127.0.0.1, so `*.socks.test` hosts are reachable only through the proxy. + +use super::tls_tests::download_cloudfetch_chunk; +use super::*; +use crate::client::retry::build_retry_configs; +use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; +use rustls::pki_types::PrivatePkcs8KeyDer; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio_rustls::TlsAcceptor; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +const PROXY_USER: &str = "proxy-user"; +const PROXY_PASSWORD: &str = "p@ss:w/rd#?"; +/// `PROXY_USER:PROXY_PASSWORD` as URL userinfo. +const ENCODED_USERINFO: &str = "proxy-user:p%40ss%3Aw%2Frd%23%3F"; + +#[derive(Clone, Debug, PartialEq)] +enum Target { + Ip(IpAddr), + Domain(String), +} + +#[derive(Clone, Debug, PartialEq)] +enum Auth { + None, + Accepted(String), + Rejected, + NotOffered, +} + +/// One SOCKS handshake. `target` is `None` when it ended at authentication. +#[derive(Clone, Debug)] +struct Event { + version: u8, + target: Option, + port: u16, + auth: Auth, +} + +#[derive(Clone, Default)] +struct FixtureOptions { + credentials: Option<(String, String)>, + refuse_connect: bool, +} + +struct SocksFixture { + addr: SocketAddr, + connections: Arc, + events: Arc>>, +} + +impl SocksFixture { + async fn start(options: FixtureOptions) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let connections = Arc::new(AtomicUsize::new(0)); + let events = Arc::new(Mutex::new(Vec::new())); + let (count, log) = (connections.clone(), events.clone()); + tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + count.fetch_add(1, Ordering::SeqCst); + let (log, options) = (log.clone(), options.clone()); + tokio::spawn(async move { + let _ = serve_socks(socket, &options, &log).await; + }); + } + }); + Self { + addr, + connections, + events, + } + } + + async fn with_credentials() -> Self { + Self::start(FixtureOptions { + credentials: Some((PROXY_USER.to_string(), PROXY_PASSWORD.to_string())), + ..Default::default() + }) + .await + } + + fn url(&self, scheme: &str) -> String { + format!("{scheme}://{}", self.addr) + } + + fn events(&self) -> Vec { + self.events.lock().unwrap().clone() + } + + fn connections(&self) -> usize { + self.connections.load(Ordering::SeqCst) + } +} + +async fn read_nul_terminated(stream: &mut TcpStream) -> std::io::Result { + let mut bytes = Vec::new(); + loop { + match stream.read_u8().await? { + 0 => return Ok(String::from_utf8_lossy(&bytes).into_owned()), + byte if bytes.len() < 255 => bytes.push(byte), + _ => return Err(std::io::ErrorKind::InvalidData.into()), + } + } +} + +async fn read_string(stream: &mut TcpStream) -> std::io::Result { + let mut bytes = vec![0; stream.read_u8().await? as usize]; + stream.read_exact(&mut bytes).await?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +async fn serve_socks( + mut client: TcpStream, + options: &FixtureOptions, + events: &Mutex>, +) -> std::io::Result<()> { + let version = client.read_u8().await?; + let record = |target, port, auth| { + events.lock().unwrap().push(Event { + version, + target, + port, + auth, + }) + }; + let (target, port, auth) = match version { + 4 => { + let _command = client.read_u8().await?; + let port = client.read_u16().await?; + let mut ip = [0; 4]; + client.read_exact(&mut ip).await?; + let _user_id = read_nul_terminated(&mut client).await?; + // SOCKS4a: 0.0.0.x (x != 0) means a host name follows. + let target = if ip[..3] == [0, 0, 0] && ip[3] != 0 { + Target::Domain(read_nul_terminated(&mut client).await?) + } else { + Target::Ip(Ipv4Addr::from(ip).into()) + }; + (target, port, Auth::None) + } + 5 => { + let mut methods = vec![0; client.read_u8().await? as usize]; + client.read_exact(&mut methods).await?; + let auth = match &options.credentials { + None if methods.contains(&0) => { + client.write_all(&[5, 0]).await?; + Auth::None + } + Some((user, password)) if methods.contains(&2) => { + client.write_all(&[5, 2]).await?; + let _version = client.read_u8().await?; + let offered_user = read_string(&mut client).await?; + let offered_password = read_string(&mut client).await?; + if (&offered_user, &offered_password) != (user, password) { + client.write_all(&[1, 1]).await?; + record(None, 0, Auth::Rejected); + return Ok(()); + } + client.write_all(&[1, 0]).await?; + Auth::Accepted(offered_user) + } + _ => { + client.write_all(&[5, 0xFF]).await?; + record(None, 0, Auth::NotOffered); + return Ok(()); + } + }; + let mut header = [0; 4]; + client.read_exact(&mut header).await?; + let target = match header[3] { + 1 => { + let mut ip = [0; 4]; + client.read_exact(&mut ip).await?; + Target::Ip(Ipv4Addr::from(ip).into()) + } + 3 => Target::Domain(read_string(&mut client).await?), + 4 => { + let mut ip = [0; 16]; + client.read_exact(&mut ip).await?; + Target::Ip(Ipv6Addr::from(ip).into()) + } + _ => return Err(std::io::ErrorKind::InvalidData.into()), + }; + (target, client.read_u16().await?, auth) + } + _ => return Ok(()), + }; + record(Some(target), port, auth); + + let upstream = if options.refuse_connect { + None + } else { + TcpStream::connect(("127.0.0.1", port)).await.ok() + }; + let (granted, refused): (&[u8], &[u8]) = if version == 4 { + (&[0, 90, 0, 0, 0, 0, 0, 0], &[0, 91, 0, 0, 0, 0, 0, 0]) + } else { + ( + &[5, 0, 0, 1, 0, 0, 0, 0, 0, 0], + &[5, 5, 0, 1, 0, 0, 0, 0, 0, 0], + ) + }; + let Some(mut upstream) = upstream else { + return client.write_all(refused).await; + }; + client.write_all(granted).await?; + tokio::io::copy_bidirectional(&mut client, &mut upstream).await?; + Ok(()) +} + +/// The default retry policy with millisecond backoff, so failure cases +/// still make every attempt but finish quickly. +fn fast_retry() -> HashMap { + build_retry_configs( + &RetryConfig { + min_wait: Duration::from_millis(1), + max_wait: Duration::from_millis(1), + overall_timeout: Duration::from_secs(10), + ..RetryConfig::default() + }, + &HashMap::new(), + ) +} + +fn max_attempts() -> usize { + RetryConfig::default().max_retries as usize + 1 +} + +fn proxy(url: impl Into) -> ProxyConfig { + ProxyConfig { + url: Some(url.into()), + ..Default::default() + } +} + +fn client_with(proxy: ProxyConfig, ca_pem: Option<&str>) -> DatabricksHttpClient { + let mut config = HttpClientConfig { + proxy, + ..HttpClientConfig::default() + }; + config.tls.trusted_certificate_pem = ca_pem.map(|pem| pem.as_bytes().to_vec()); + DatabricksHttpClient::new(config, fast_retry()).unwrap() +} + +async fn post_session(client: &DatabricksHttpClient, base: &str) -> Result { + let request = client + .inner() + .post(format!("{base}/api/2.0/sql/sessions")) + .build() + .unwrap(); + client + .execute_without_auth(request, RequestType::CreateSession) + .await + .map(|response| response.status().as_u16()) +} + +async fn session_server() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"session_id": "s"})), + ) + .mount(&server) + .await; + server +} + +async fn requests(server: &MockServer) -> usize { + server.received_requests().await.unwrap().len() +} + +/// A loopback address with nothing listening on it. +fn closed_port() -> SocketAddr { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() +} + +fn domain(name: &str) -> Option { + Some(Target::Domain(name.to_string())) +} + +fn assert_secret_free(error: &Error, secrets: &[&str]) { + let text = format!("{error} {error:?}"); + for secret in secrets { + assert!(!text.contains(secret), "{secret:?} leaked: {text}"); + } +} + +#[tokio::test] +async fn socks_schemes_route_through_the_proxy_with_their_dns_mode() { + let server = session_server().await; + let port = server.address().port(); + // (scheme, URL host, SOCKS version, target the proxy sees; `None` = a + // locally resolved loopback IP) + let cases = [ + ("socks5", "localhost", 5, None), + ("socks5h", "localhost", 5, domain("localhost")), + ("socks4", "127.0.0.1", 4, None), + ("socks4a", "localhost", 4, domain("localhost")), + ( + "socks5h", + "warehouse.socks.test", + 5, + domain("warehouse.socks.test"), + ), + ( + "socks4a", + "warehouse.socks.test", + 4, + domain("warehouse.socks.test"), + ), + ]; + for (count, (scheme, host, version, target)) in cases.into_iter().enumerate() { + let fixture = SocksFixture::start(FixtureOptions::default()).await; + let client = client_with(proxy(fixture.url(scheme)), None); + let status = post_session(&client, &format!("http://{host}:{port}")) + .await + .unwrap_or_else(|e| panic!("{scheme} {host}: {e}")); + assert_eq!(status, 200, "{scheme} {host}"); + assert_eq!(requests(&server).await, count + 1, "{scheme} {host}"); + let events = fixture.events(); + assert_eq!(events.len(), 1, "{scheme} {host}: {events:?}"); + assert_eq!(events[0].version, version, "{scheme} {host}"); + assert_eq!(events[0].port, port, "{scheme} {host}"); + match target { + Some(_) => assert_eq!(events[0].target, target, "{scheme} {host}"), + None => assert!( + matches!(events[0].target, Some(Target::Ip(ip)) if ip.is_loopback()), + "{scheme} {host}: {events:?}" + ), + } + } +} + +#[tokio::test] +async fn socks5_credentials_use_rfc1929_and_are_never_dropped() { + let server = session_server().await; + let base = format!("http://warehouse.socks.test:{}", server.address().port()); + // (URL userinfo, explicit username/password, accepted by the proxy) + type CredentialCase = ( + Option<&'static str>, + Option<(&'static str, &'static str)>, + bool, + ); + let cases: [CredentialCase; 6] = [ + (None, Some((PROXY_USER, PROXY_PASSWORD)), true), + (Some(ENCODED_USERINFO), None, true), + // Explicit credentials beat URL userinfo. + ( + Some("other-user:url-secret"), + Some((PROXY_USER, PROXY_PASSWORD)), + true, + ), + (None, Some((PROXY_USER, "wrong-secret")), false), + (Some("proxy-user:wrong-secret"), None, false), + (None, None, false), + ]; + let mut accepted_count = 0; + for (userinfo, explicit, accepted) in cases { + let fixture = SocksFixture::with_credentials().await; + let url = match userinfo { + Some(userinfo) => format!("socks5h://{userinfo}@{}", fixture.addr), + None => fixture.url("socks5h"), + }; + let mut config = proxy(url); + if let Some((user, password)) = explicit { + config.username = Some(user.to_string()); + config.password = Some(password.to_string()); + } + let client = client_with(config, None); + let result = post_session(&client, &base).await; + let events = fixture.events(); + let case = format!("{userinfo:?} {explicit:?}"); + if accepted { + accepted_count += 1; + assert_eq!(result.unwrap(), 200, "{case}"); + assert_eq!(events.len(), 1, "{case}: {events:?}"); + assert_eq!(events[0].auth, Auth::Accepted(PROXY_USER.into()), "{case}"); + assert_eq!(events[0].target, domain("warehouse.socks.test"), "{case}"); + } else { + let error = result.unwrap_err(); + assert_secret_free(&error, &["wrong-secret", PROXY_USER]); + let expected = if userinfo.is_none() && explicit.is_none() { + Auth::NotOffered + } else { + Auth::Rejected + }; + // One attempt that reached the proxy and stopped at + // authentication: a rejection is not retried, so the same + // credentials are never resent and nothing goes direct. + assert_eq!(events.len(), 1, "{case}: {error}"); + assert_eq!(fixture.connections(), 1, "{case}"); + assert!(!error.retryable, "{case}: {error}"); + assert!( + events + .iter() + .all(|e| e.auth == expected && e.target.is_none()), + "{case}: {events:?}" + ); + } + } + assert_eq!(requests(&server).await, accepted_count); +} + +#[tokio::test] +async fn dead_proxy_fails_closed_within_the_retry_budget() { + let server = session_server().await; + let base = format!("http://localhost:{}", server.address().port()); + let dead = closed_port(); + for scheme in ["socks4", "socks4a", "socks5", "socks5h"] { + let client = client_with(proxy(format!("{scheme}://user:dead-secret@{dead}")), None); + let started = Instant::now(); + let error = post_session(&client, &base).await.unwrap_err(); + // The retry policy ends the loop: either every attempt fails, or the + // 10 s overall timeout stops it first (a refused loopback connect takes + // about 2 s on Windows). The slack covers one more connect attempt. + assert!( + started.elapsed() < Duration::from_secs(20), + "{scheme}: {error}" + ); + assert!( + error + .message + .contains(&format!("after {} attempts", max_attempts())) + || error.message.contains("retry timeout exceeded"), + "{scheme}: {error}" + ); + assert_secret_free(&error, &["dead-secret"]); + } + assert_eq!(requests(&server).await, 0, "no direct fallback"); +} + +#[tokio::test] +async fn refused_connect_fails_closed_after_retries() { + let server = session_server().await; + let base = format!("http://localhost:{}", server.address().port()); + for scheme in ["socks4a", "socks5h"] { + let fixture = SocksFixture::start(FixtureOptions { + refuse_connect: true, + ..Default::default() + }) + .await; + let client = client_with(proxy(fixture.url(scheme)), None); + let error = post_session(&client, &base).await.unwrap_err(); + let events = fixture.events(); + assert_eq!(events.len(), max_attempts(), "{scheme}: {error}"); + assert!(events.iter().all(|e| e.target == domain("localhost"))); + assert!( + error + .message + .contains(&format!("after {} attempts", max_attempts())), + "{scheme}: {error}" + ); + } + assert_eq!(requests(&server).await, 0, "no direct fallback"); +} + +#[tokio::test] +async fn bypass_hosts_go_direct_and_other_hosts_use_the_proxy() { + let server = session_server().await; + let port = server.address().port(); + let fixture = SocksFixture::start(FixtureOptions::default()).await; + let mut config = proxy(fixture.url("socks5h")); + config.bypass_hosts = Some("localhost, .bypass.test".to_string()); + let client = client_with(config, None); + + post_session(&client, &format!("http://localhost:{port}")) + .await + .unwrap(); + assert!(fixture.events().is_empty(), "{:?}", fixture.events()); + + post_session(&client, &format!("http://warehouse.socks.test:{port}")) + .await + .unwrap(); + let events = fixture.events(); + assert_eq!(events.len(), 1, "{events:?}"); + assert_eq!(events[0].target, domain("warehouse.socks.test")); + assert_eq!(requests(&server).await, 2); +} + +#[tokio::test] +async fn cloudfetch_external_link_downloads_through_the_tunnel() { + use arrow_array::{ArrayRef, Int32Array, RecordBatch}; + use arrow_ipc::writer::StreamWriter; + + let expected = + RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(vec![7])) as ArrayRef)]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &expected.schema()).unwrap(); + writer.write(&expected).unwrap(); + writer.finish().unwrap(); + } + let storage = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/chunk.arrow")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc)) + .mount(&storage) + .await; + let storage_port = storage.address().port(); + let link = format!("http://storage.socks.test:{storage_port}/chunk.arrow"); + let sea = session_server().await; + let sea_port = sea.address().port(); + + // The warehouse request and the CloudFetch download share one client. + let fixture = SocksFixture::start(FixtureOptions::default()).await; + let client = client_with(proxy(fixture.url("socks5h")), None); + let status = post_session(&client, &format!("http://warehouse.socks.test:{sea_port}")) + .await + .unwrap(); + assert_eq!(status, 200); + let batch = download_cloudfetch_chunk(client, link.clone()) + .await + .unwrap() + .expect("chunk yields a batch"); + assert_eq!(batch, expected); + let targets: Vec<_> = fixture + .events() + .into_iter() + .map(|e| (e.target, e.port)) + .collect(); + assert_eq!( + targets, + [ + (domain("warehouse.socks.test"), sea_port), + (domain("storage.socks.test"), storage_port), + ] + ); + + // A dead proxy fails the download without a direct storage request. + let client = client_with(proxy(format!("socks5h://{}", closed_port())), None); + assert!(download_cloudfetch_chunk(client, link).await.is_err()); + assert_eq!(storage.received_requests().await.unwrap().len(), 1); +} + +struct TlsServer { + addr: SocketAddr, + ca_pem: String, + requests: Arc, +} + +/// HTTPS server on 127.0.0.1 with a certificate for `names`, issued by a +/// fresh test CA (`ca_pem`). +async fn tls_server(names: &[&str]) -> TlsServer { + 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, "SOCKS test CA"); + let ca_key = KeyPair::generate().unwrap(); + let ca_cert = ca_params.self_signed(&ca_key).unwrap(); + let issuer = Issuer::new(ca_params, ca_key); + let server_key = KeyPair::generate().unwrap(); + let names: Vec = names.iter().map(|n| n.to_string()).collect(); + let server_cert = CertificateParams::new(names) + .unwrap() + .signed_by(&server_key, &issuer) + .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![server_cert.der().clone()], + PrivatePkcs8KeyDer::from(server_key.serialize_der()).into(), + ) + .unwrap(); + let acceptor = TlsAcceptor::from(Arc::new(tls)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + let (acceptor, count) = (acceptor.clone(), count.clone()); + tokio::spawn(async move { + let Ok(mut stream) = acceptor.accept(socket).await else { + return; + }; + let mut buffer = [0; 4096]; + if stream.read(&mut buffer).await.unwrap_or(0) > 0 { + count.fetch_add(1, Ordering::SeqCst); + let _ = stream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await; + let _ = stream.shutdown().await; + } + }); + } + }); + TlsServer { + addr, + ca_pem: ca_cert.pem(), + requests, + } +} + +#[tokio::test] +async fn tls_through_the_tunnel_verifies_the_target_hostname() { + let server = tls_server(&["warehouse.socks.test", "localhost"]).await; + let port = server.addr.port(); + // socks5 resolves `localhost` locally, yet TLS still checks the name. + for (scheme, host) in [("socks5h", "warehouse.socks.test"), ("socks5", "localhost")] { + let fixture = SocksFixture::start(FixtureOptions::default()).await; + let client = client_with(proxy(fixture.url(scheme)), Some(&server.ca_pem)); + let status = post_session(&client, &format!("https://{host}:{port}")) + .await + .unwrap_or_else(|e| panic!("{scheme} {host}: {e}")); + assert_eq!(status, 200); + assert_eq!(fixture.events().len(), 1, "{scheme} {host}"); + } + assert_eq!(server.requests.load(Ordering::SeqCst), 2); + + // A certificate for another host is rejected through the tunnel, once. + let wrong = tls_server(&["wrong-host.invalid"]).await; + let fixture = SocksFixture::start(FixtureOptions::default()).await; + let client = client_with(proxy(fixture.url("socks5h")), Some(&wrong.ca_pem)); + let error = post_session( + &client, + &format!("https://warehouse.socks.test:{}", wrong.addr.port()), + ) + .await + .unwrap_err(); + assert_eq!(wrong.requests.load(Ordering::SeqCst), 0, "{error}"); + assert_eq!(fixture.events().len(), 1, "{error}"); + let message = error.message.to_ascii_lowercase(); + assert!( + [ + "notvalidforname", + "not valid for name", + "hostname mismatch", + "host name mismatch", + "name does not match", + "name mismatch", + ] + .iter() + .any(|cause| message.contains(cause)), + "expected a hostname-mismatch cause: {error}" + ); +} + +const ENV_CHILD: &str = "client::http::socks_tests::env_proxy_child"; +const PROXY_ENV_VARS: [&str; 9] = [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + "NO_PROXY", + "no_proxy", + "REQUEST_METHOD", +]; + +/// Requests `SOCKS_TEST_TARGETS` (space-separated `url=ok|err`) with proxy +/// env vars set. Run only by `env_proxies_*` in a child process, so those +/// vars never reach other tests in this binary. +#[tokio::test] +#[ignore = "child process of env_proxies_use_socks_with_no_proxy_and_explicit_precedence"] +async fn env_proxy_child() { + let Ok(targets) = std::env::var("SOCKS_TEST_TARGETS") else { + return; + }; + let ca = std::env::var("SOCKS_TEST_CA").unwrap(); + let explicit = std::env::var("SOCKS_TEST_EXPLICIT_PROXY").ok(); + let config = explicit.map(proxy).unwrap_or_default(); + let client = client_with(config, Some(&ca)); + for target in targets.split(' ') { + let (url, expected) = target.rsplit_once('=').unwrap(); + let result = post_session(&client, url).await; + assert_eq!(result.is_ok(), expected == "ok", "{url}: {result:?}"); + } +} + +struct EnvCase { + name: &'static str, + env: &'static [(&'static str, &'static str)], + explicit: Option<&'static str>, + credentials: bool, + /// (`W` = warehouse.socks.test, `L` = localhost, expected success) + targets: &'static [(&'static str, bool)], + /// What the fixture must see, in order; `None` = a local IP. + proxied: &'static [Option<&'static str>], +} + +#[tokio::test] +async fn env_proxies_use_socks_with_no_proxy_and_explicit_precedence() { + const W: &str = "warehouse.socks.test"; + let cases = [ + EnvCase { + name: "HTTPS_PROXY socks5h", + env: &[("HTTPS_PROXY", "socks5h://{F}")], + explicit: None, + credentials: false, + targets: &[("W", true)], + proxied: &[Some(W)], + }, + EnvCase { + name: "ALL_PROXY socks5h", + env: &[("ALL_PROXY", "socks5h://{F}")], + explicit: None, + credentials: false, + targets: &[("W", true)], + proxied: &[Some(W)], + }, + EnvCase { + name: "HTTPS_PROXY socks4a", + env: &[("HTTPS_PROXY", "socks4a://{F}")], + explicit: None, + credentials: false, + targets: &[("W", true)], + proxied: &[Some(W)], + }, + EnvCase { + name: "HTTPS_PROXY socks5 resolves locally", + env: &[("HTTPS_PROXY", "socks5://{F}")], + explicit: None, + credentials: false, + targets: &[("L", true)], + proxied: &[None], + }, + EnvCase { + name: "HTTPS_PROXY userinfo authenticates", + env: &[("HTTPS_PROXY", "socks5h://{U}@{F}")], + explicit: None, + credentials: true, + targets: &[("W", true)], + proxied: &[Some(W)], + }, + EnvCase { + name: "NO_PROXY host goes direct", + env: &[("HTTPS_PROXY", "socks5h://{F}"), ("NO_PROXY", "localhost")], + explicit: None, + credentials: false, + targets: &[("L", true), ("W", true)], + proxied: &[Some(W)], + }, + EnvCase { + name: "dead env proxy fails closed", + env: &[("HTTPS_PROXY", "socks5h://{D}")], + explicit: None, + credentials: false, + targets: &[("L", false)], + proxied: &[], + }, + EnvCase { + name: "explicit proxy beats env", + env: &[ + ("HTTPS_PROXY", "socks5h://{D}"), + ("ALL_PROXY", "socks5h://{D}"), + ], + explicit: Some("socks5h://{F}"), + credentials: false, + targets: &[("W", true)], + proxied: &[Some(W)], + }, + ]; + + let server = tls_server(&[W, "localhost"]).await; + let port = server.addr.port(); + let dead = closed_port().to_string(); + let mut expected_requests = 0; + for case in cases { + let fixture = if case.credentials { + SocksFixture::with_credentials().await + } else { + SocksFixture::start(FixtureOptions::default()).await + }; + let fill = |value: &str| { + value + .replace("{F}", &fixture.addr.to_string()) + .replace("{D}", &dead) + .replace("{U}", ENCODED_USERINFO) + }; + let targets: Vec = case + .targets + .iter() + .map(|(host, ok)| { + let host = if *host == "W" { W } else { "localhost" }; + format!("https://{host}:{port}={}", if *ok { "ok" } else { "err" }) + }) + .collect(); + expected_requests += case.targets.iter().filter(|(_, ok)| *ok).count(); + + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command.args([ENV_CHILD, "--exact", "--ignored", "--test-threads=1"]); + for var in PROXY_ENV_VARS { + command.env_remove(var); + } + command + .env("SOCKS_TEST_TARGETS", targets.join(" ")) + .env("SOCKS_TEST_CA", &server.ca_pem) + .env_remove("SOCKS_TEST_EXPLICIT_PROXY"); + for (name, value) in case.env { + command.env(name, fill(value)); + } + if let Some(explicit) = case.explicit { + command.env("SOCKS_TEST_EXPLICIT_PROXY", fill(explicit)); + } + let output = tokio::task::spawn_blocking(move || command.output().unwrap()) + .await + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success() && stdout.contains("1 passed"), + "{}: child failed\n{stdout}\n{stderr}", + case.name + ); + + let events = fixture.events(); + assert_eq!( + events.len(), + case.proxied.len(), + "{}: {events:?}", + case.name + ); + for (event, expected) in events.iter().zip(case.proxied) { + assert_eq!(event.port, port, "{}", case.name); + match expected { + Some(name) => assert_eq!(event.target, domain(name), "{}", case.name), + None => assert!( + matches!(event.target, Some(Target::Ip(ip)) if ip.is_loopback()), + "{}: {events:?}", + case.name + ), + } + if case.credentials { + assert_eq!( + event.auth, + Auth::Accepted(PROXY_USER.into()), + "{}", + case.name + ); + } + } + assert_eq!( + server.requests.load(Ordering::SeqCst), + expected_requests, + "{}", + case.name + ); + } +} diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index 977814e0..9e8ff53a 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -47,7 +47,7 @@ fn test_client(config: HttpClientConfig, overall_timeout: Duration) -> Databrick .unwrap() } -async fn download_cloudfetch_chunk( +pub(super) async fn download_cloudfetch_chunk( client: DatabricksHttpClient, url: String, ) -> Result> { diff --git a/src/client/retry.rs b/src/client/retry.rs index 1c0d21c5..3b59ccaf 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -247,9 +247,12 @@ impl RetryStrategy { /// Whether the given network/client error is retryable. pub fn is_retryable_error(&self, error: &reqwest::Error) -> bool { - // Certificate verification and permanent DNS failures cannot recover - // through retry, even though reqwest reports them as connect errors. - if is_certificate_verification_failure(error) || is_permanent_dns_resolution_failure(error) + // Certificate verification, permanent DNS and SOCKS authentication + // failures cannot recover through retry, even though reqwest reports + // them as connect errors. + if is_certificate_verification_failure(error) + || is_permanent_dns_resolution_failure(error) + || is_socks_authentication_failure(error) { return false; } @@ -420,6 +423,23 @@ fn error_chain_indicates_permanent_dns_failure(error: &(dyn std::error::Error + false } +/// Whether a SOCKS5 proxy rejected the client's authentication. Resending the +/// same credentials cannot succeed and may count toward a proxy's lockout. +/// hyper-util's SOCKS error types are private, so this matches the fixed +/// `Display` text of its authentication errors in the source chain. +pub(crate) fn is_socks_authentication_failure(error: &(dyn std::error::Error + 'static)) -> bool { + super::error_chain(error).any(|error| { + matches!( + error.to_string().strip_prefix("SOCKS error: "), + Some( + "credentials not accepted" + | "server does not support user/pass authentication" + | "server implements authentication incorrectly" + ) + ) + }) +} + // --- Backoff Calculator --- /// Calculate the backoff duration for a retry attempt. @@ -712,6 +732,43 @@ mod tests { } } + #[test] + fn socks_authentication_failures_are_detected_in_the_chain() { + #[derive(Debug)] + struct Wrapped(std::io::Error); + impl std::fmt::Display for Wrapped { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("error connecting to socks proxy") + } + } + impl std::error::Error for Wrapped { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.0) + } + } + for (cause, permanent) in [ + ("SOCKS error: credentials not accepted", true), + ( + "SOCKS error: server does not support user/pass authentication", + true, + ), + ( + "SOCKS error: server implements authentication incorrectly", + true, + ), + ("SOCKS error: io error during SOCKS handshake", false), + ("SOCKS error: failed to create underlying connection", false), + ("credentials not accepted", false), + ] { + let error = Wrapped(std::io::Error::other(cause)); + assert_eq!( + is_socks_authentication_failure(&error), + permanent, + "{cause}" + ); + } + } + // --- DNS-resolution detection tests --- #[test] diff --git a/src/config.rs b/src/config.rs index c83b9dc0..ddea3ce1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1037,12 +1037,12 @@ impl Default for HttpConfig { // ─── HTTP proxy ─────────────────────────────────────────────────────────── -/// Programmatic HTTP/HTTPS proxy configuration. +/// Programmatic HTTP/HTTPS or SOCKS proxy configuration. /// /// When [`url`](Self::url) is `None` (the default), the kernel does **not** /// configure a proxy explicitly and `reqwest`'s standard behaviour applies — -/// the `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` environment variables are -/// honoured automatically. Setting [`url`](Self::url) **overrides** those env +/// the `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` environment +/// variables (SOCKS URLs included) are honoured automatically. Setting [`url`](Self::url) **overrides** those env /// vars with the supplied proxy, routing all (`http://` and `https://`) /// traffic through it. /// @@ -1063,12 +1063,17 @@ impl Default for HttpConfig { #[derive(Clone, Default)] pub struct ProxyConfig { /// Proxy URL, e.g. `http://proxy.corp.example.com:8080` or - /// `http://user:pass@proxy:8080`. Must use the `http://` or - /// `https://` scheme. `None` ⇒ env-var behaviour (no override). + /// `socks5h://user:pass@proxy:1080`. The scheme must be `http`, + /// `https`, `socks4`, `socks4a`, `socks5` or `socks5h`; `socks5` and + /// `socks4` resolve the target locally, `socks5h` and `socks4a` at the + /// proxy. `None` ⇒ env-var behaviour (no override). pub url: Option, - /// Username for proxy basic-auth. Overrides any credentials - /// embedded in [`url`](Self::url) when set. + /// Username for proxy basic-auth (SOCKS5: RFC 1929). Overrides any + /// credentials embedded in [`url`](Self::url) when set. With SOCKS5 + /// credentials only username/password authentication is offered, so the + /// proxy can't downgrade to no authentication. SOCKS4 ignores credentials: + /// it has no password, and the user ID is not sent yet. pub username: Option, /// Password for proxy basic-auth. Secret material — redacted in diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index a4f84f73..5f7c106b 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -260,6 +260,39 @@ static void test_proxy_and_tls_setters(void) { kernel_session_config_free(config); } +/* A socks5h:// proxy passes the scheme check and a dead one fails the open + * at the SOCKS transport; + * bare socks:// fails the open with an error that names the accepted schemes + * and hides the userinfo. */ +static void test_socks_proxy_url(void) { + const char* urls[] = {"socks5h://127.0.0.1:1", "socks://user:s3cret@127.0.0.1:1"}; + for (int i = 0; i < 2; i++) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + (void)kernel_session_config_set_warehouse(config, "https://example.databricks.com", "wh123"); + (void)kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + (void)kernel_session_config_set_retry_config(config, 1, 1, 0, 0); + KernelStatusCode rc = kernel_session_config_set_proxy(config, urls[i], NULL, NULL, NULL); + CHECK(rc == KernelStatusCode_Success, "set_proxy(socks URL) succeeds"); + + kernel_session_t* session = NULL; + rc = kernel_session_open(config, &session); /* consumes config */ + CHECK(rc != KernelStatusCode_Success && session == NULL, "open through a dead/invalid SOCKS proxy fails"); + KernelError err; + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL, "SOCKS open failure populates last error"); + if (i == 1) { + CHECK(err.message != NULL && strstr(err.message, "socks5h://") != NULL, + "socks:// error names the accepted schemes"); + CHECK(err.message != NULL && strstr(err.message, "s3cret") == NULL, + "socks:// error redacts the proxy userinfo"); + } else { + CHECK(err.message != NULL && strstr(err.message, "error connecting to socks proxy") != NULL, + "socks5h:// reaches the SOCKS transport and fails connecting to the dead proxy"); + } + } +} + /* U2M + custom-header setters accept valid input; header requires args. */ static void test_u2m_and_header_setters(void) { KernelSessionConfig* config = NULL; @@ -447,6 +480,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_tls_certificate_revocation_setter(); + test_socks_proxy_url(); test_u2m_and_header_setters(); test_identity_federation_client_id_setter(); test_client_conf_setter(); diff --git a/tests/proxy_credential_logging.rs b/tests/proxy_credential_logging.rs new file mode 100644 index 00000000..824a9ff8 --- /dev/null +++ b/tests/proxy_credential_logging.rs @@ -0,0 +1,121 @@ +// 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 credentials (URL userinfo and explicit username/password) must not +//! appear in client errors or in `debug` logs, including the retry warnings +//! of a request through a dead SOCKS proxy. +//! +//! Its own test binary because it installs a global `tracing` subscriber +//! (see `presigned_url_logging.rs`). + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use databricks_sql_kernel::client::http::{DatabricksHttpClient, HttpClientConfig, ProxyConfig}; +use databricks_sql_kernel::client::retry::{build_retry_configs, RequestType, RetryConfig}; + +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl std::io::Write for CapturedLogs { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[tokio::test] +async fn proxy_credentials_stay_out_of_errors_and_logs() { + let logs = CapturedLogs::default(); + let writer = logs.clone(); + tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(), + ) + .expect("the only subscriber in this binary"); + + // Nothing listens on a port whose listener was dropped. + let dead = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap(); + let retry = RetryConfig { + min_wait: Duration::from_millis(1), + max_wait: Duration::from_millis(1), + overall_timeout: Duration::from_secs(10), + max_retries: 1, + override_retryable_codes: None, + }; + let secrets = ["url-user", "url-secret", "explicit-secret"]; + // (URL, explicit username/password) + let cases = [ + (format!("socks5h://url-user:url-secret@{dead}"), None), + ( + format!("socks5://url-user:url-secret@{dead}"), + Some(("explicit-user", "explicit-secret")), + ), + (format!("socks4a://url-user:url-secret@{dead}"), None), + (format!("http://url-user:url-secret@{dead}"), None), + // Rejected before any request. + (format!("socks://url-user:url-secret@{dead}"), None), + ("url-user:url-secret@proxy:1080".to_string(), None), + ]; + for (url, explicit) in cases { + let config = HttpClientConfig { + proxy: ProxyConfig { + url: Some(url.clone()), + username: explicit.map(|(user, _)| user.to_string()), + password: explicit.map(|(_, password)| password.to_string()), + bypass_hosts: None, + }, + ..HttpClientConfig::default() + }; + let error = + match DatabricksHttpClient::new(config, build_retry_configs(&retry, &HashMap::new())) { + Err(error) => error, + Ok(client) => { + let request = client + .inner() + .post("http://warehouse.example.test/api/2.0/sql/sessions") + .build() + .unwrap(); + client + .execute_without_auth(request, RequestType::CreateSession) + .await + .expect_err("dead proxy must fail") + } + }; + let text = format!("{error} {error:?}"); + for secret in secrets { + assert!(!text.contains(secret), "{url}: {secret} leaked: {text}"); + } + } + + let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap(); + assert!( + logs.contains(&format!("configured with proxy: socks5h://***@{dead}")), + "{logs}" + ); + assert!(logs.contains("before retry"), "{logs}"); + for secret in secrets { + assert!(!logs.contains(secret), "{secret} leaked: {logs}"); + } +}